sbb-mcp 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +200 -0
- package/dist/formatters.d.ts +6 -0
- package/dist/formatters.js +162 -0
- package/dist/formatters.js.map +1 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.js +162 -0
- package/dist/index.js.map +1 -0
- package/dist/transport/index.d.ts +9 -0
- package/dist/transport/index.js +9 -0
- package/dist/transport/index.js.map +1 -0
- package/dist/transport/smapi-auth.d.ts +2 -0
- package/dist/transport/smapi-auth.js +39 -0
- package/dist/transport/smapi-auth.js.map +1 -0
- package/dist/transport/smapi-client.d.ts +22 -0
- package/dist/transport/smapi-client.js +82 -0
- package/dist/transport/smapi-client.js.map +1 -0
- package/dist/transport/smapi-journey.d.ts +18 -0
- package/dist/transport/smapi-journey.js +81 -0
- package/dist/transport/smapi-journey.js.map +1 -0
- package/dist/transport/smapi-mock.d.ts +5 -0
- package/dist/transport/smapi-mock.js +144 -0
- package/dist/transport/smapi-mock.js.map +1 -0
- package/dist/transport/smapi-prices.d.ts +13 -0
- package/dist/transport/smapi-prices.js +71 -0
- package/dist/transport/smapi-prices.js.map +1 -0
- package/dist/transport/smapi-types.d.ts +153 -0
- package/dist/transport/smapi-types.js +2 -0
- package/dist/transport/smapi-types.js.map +1 -0
- package/package.json +60 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 SwissTrip
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,200 @@
|
|
|
1
|
+
# sbb-mcp
|
|
2
|
+
|
|
3
|
+
MCP server for **Swiss Federal Railways** (SBB/CFF/FFS) -- real-time train schedules, prices, and ticket purchase links for any AI assistant.
|
|
4
|
+
|
|
5
|
+
Works with Claude Desktop, Claude Code, Cursor, Windsurf, VS Code Copilot, and any MCP-compatible AI client.
|
|
6
|
+
|
|
7
|
+
## Features
|
|
8
|
+
|
|
9
|
+
- **Search stations** -- find any Swiss train station by name
|
|
10
|
+
- **Train connections** -- real-time schedules with departure/arrival times, platforms, transfers
|
|
11
|
+
- **Ticket prices** -- 1st/2nd class with Half-Fare (Halbtax) and GA travelcard support
|
|
12
|
+
- **Purchase links** -- direct deep links to buy tickets on SBB.ch
|
|
13
|
+
- **Pagination** -- browse earlier/later connections
|
|
14
|
+
- **Trip details** -- intermediate stops, occupancy, platform changes
|
|
15
|
+
- **Mock mode** -- works without credentials for testing and demos
|
|
16
|
+
|
|
17
|
+
## Quick Start
|
|
18
|
+
|
|
19
|
+
### Claude Desktop
|
|
20
|
+
|
|
21
|
+
Add to your `claude_desktop_config.json`:
|
|
22
|
+
|
|
23
|
+
```json
|
|
24
|
+
{
|
|
25
|
+
"mcpServers": {
|
|
26
|
+
"sbb": {
|
|
27
|
+
"command": "npx",
|
|
28
|
+
"args": ["-y", "sbb-mcp"],
|
|
29
|
+
"env": {
|
|
30
|
+
"SMAPI_CLIENT_ID": "your-client-id",
|
|
31
|
+
"SMAPI_CLIENT_SECRET": "your-secret",
|
|
32
|
+
"SMAPI_SCOPE": "your-scope",
|
|
33
|
+
"SMAPI_CONTRACT_ID": "your-contract-id"
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
### Claude Code
|
|
41
|
+
|
|
42
|
+
```bash
|
|
43
|
+
claude mcp add sbb -- npx -y sbb-mcp
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
### Cursor
|
|
47
|
+
|
|
48
|
+
Add to `.cursor/mcp.json`:
|
|
49
|
+
|
|
50
|
+
```json
|
|
51
|
+
{
|
|
52
|
+
"mcpServers": {
|
|
53
|
+
"sbb": {
|
|
54
|
+
"command": "npx",
|
|
55
|
+
"args": ["-y", "sbb-mcp"],
|
|
56
|
+
"env": {
|
|
57
|
+
"SMAPI_CLIENT_ID": "your-client-id",
|
|
58
|
+
"SMAPI_CLIENT_SECRET": "your-secret",
|
|
59
|
+
"SMAPI_SCOPE": "your-scope",
|
|
60
|
+
"SMAPI_CONTRACT_ID": "your-contract-id"
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
```
|
|
66
|
+
|
|
67
|
+
### Windsurf
|
|
68
|
+
|
|
69
|
+
Add to `~/.codeium/windsurf/mcp_config.json`:
|
|
70
|
+
|
|
71
|
+
```json
|
|
72
|
+
{
|
|
73
|
+
"mcpServers": {
|
|
74
|
+
"sbb": {
|
|
75
|
+
"command": "npx",
|
|
76
|
+
"args": ["-y", "sbb-mcp"],
|
|
77
|
+
"env": {
|
|
78
|
+
"SMAPI_CLIENT_ID": "your-client-id",
|
|
79
|
+
"SMAPI_CLIENT_SECRET": "your-secret",
|
|
80
|
+
"SMAPI_SCOPE": "your-scope",
|
|
81
|
+
"SMAPI_CONTRACT_ID": "your-contract-id"
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
```
|
|
87
|
+
|
|
88
|
+
### VS Code Copilot
|
|
89
|
+
|
|
90
|
+
Add to `.vscode/mcp.json`:
|
|
91
|
+
|
|
92
|
+
```json
|
|
93
|
+
{
|
|
94
|
+
"servers": {
|
|
95
|
+
"sbb": {
|
|
96
|
+
"command": "npx",
|
|
97
|
+
"args": ["-y", "sbb-mcp"],
|
|
98
|
+
"env": {
|
|
99
|
+
"SMAPI_CLIENT_ID": "your-client-id",
|
|
100
|
+
"SMAPI_CLIENT_SECRET": "your-secret",
|
|
101
|
+
"SMAPI_SCOPE": "your-scope",
|
|
102
|
+
"SMAPI_CONTRACT_ID": "your-contract-id"
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
```
|
|
108
|
+
|
|
109
|
+
### Demo Mode (No Credentials)
|
|
110
|
+
|
|
111
|
+
Run without any environment variables to use mock data:
|
|
112
|
+
|
|
113
|
+
```bash
|
|
114
|
+
npx sbb-mcp
|
|
115
|
+
```
|
|
116
|
+
|
|
117
|
+
This lets you test the MCP server with realistic Swiss station data without SBB API credentials.
|
|
118
|
+
|
|
119
|
+
## Tools
|
|
120
|
+
|
|
121
|
+
### search_stations
|
|
122
|
+
|
|
123
|
+
Search for Swiss train stations by name.
|
|
124
|
+
|
|
125
|
+
**Input:**
|
|
126
|
+
- `query` (string, required) -- Station name, e.g. "Zurich", "Bern", "Interlaken"
|
|
127
|
+
- `limit` (number, optional) -- Max results (default: 10)
|
|
128
|
+
|
|
129
|
+
**Example:** "Find stations matching Luzern"
|
|
130
|
+
|
|
131
|
+
### search_connections
|
|
132
|
+
|
|
133
|
+
Find train connections between two stations.
|
|
134
|
+
|
|
135
|
+
**Input:**
|
|
136
|
+
- `from` (string, required) -- Origin station name or ID
|
|
137
|
+
- `to` (string, required) -- Destination station name or ID
|
|
138
|
+
- `date` (string, optional) -- Travel date YYYY-MM-DD
|
|
139
|
+
- `time` (string, optional) -- Departure time HH:MM
|
|
140
|
+
- `arrival_time` (boolean, optional) -- Treat time as arrival time
|
|
141
|
+
|
|
142
|
+
**Example:** "Show me trains from Zurich to Bern tomorrow at 9am"
|
|
143
|
+
|
|
144
|
+
### get_trip_details
|
|
145
|
+
|
|
146
|
+
Get detailed stop-by-stop information for a connection.
|
|
147
|
+
|
|
148
|
+
**Input:**
|
|
149
|
+
- `trip_id` (string, required) -- Trip ID from search_connections
|
|
150
|
+
|
|
151
|
+
### get_more_connections
|
|
152
|
+
|
|
153
|
+
Load earlier or later trains for a previous search.
|
|
154
|
+
|
|
155
|
+
**Input:**
|
|
156
|
+
- `collection_id` (string, required) -- Collection ID from search_connections
|
|
157
|
+
- `direction` ("next" | "previous") -- Later or earlier trains
|
|
158
|
+
|
|
159
|
+
### get_prices
|
|
160
|
+
|
|
161
|
+
Get ticket prices with reduction card support.
|
|
162
|
+
|
|
163
|
+
**Input:**
|
|
164
|
+
- `trip_ids` (string[], required) -- Trip IDs from search_connections
|
|
165
|
+
- `traveler_type` ("ADULT" | "CHILD", default: "ADULT")
|
|
166
|
+
- `reduction_card` ("HALF_FARE" | "GA" | "NONE", default: "HALF_FARE")
|
|
167
|
+
|
|
168
|
+
**Example:** "How much is a ticket from Zurich to Zermatt with Half-Fare card?"
|
|
169
|
+
|
|
170
|
+
### get_ticket_link
|
|
171
|
+
|
|
172
|
+
Get a direct purchase link to buy the ticket on SBB.ch.
|
|
173
|
+
|
|
174
|
+
**Input:**
|
|
175
|
+
- `trip_id` (string, required) -- Trip ID to purchase
|
|
176
|
+
- `traveler_type` ("ADULT" | "CHILD", default: "ADULT")
|
|
177
|
+
- `reduction_card` ("HALF_FARE" | "GA" | "NONE", default: "HALF_FARE")
|
|
178
|
+
|
|
179
|
+
## Environment Variables
|
|
180
|
+
|
|
181
|
+
| Variable | Required | Description |
|
|
182
|
+
|----------|----------|-------------|
|
|
183
|
+
| `SMAPI_CLIENT_ID` | Yes* | OAuth 2.0 client ID from SBB Developer Portal |
|
|
184
|
+
| `SMAPI_CLIENT_SECRET` | Yes* | OAuth 2.0 client secret |
|
|
185
|
+
| `SMAPI_SCOPE` | Yes* | OAuth scope |
|
|
186
|
+
| `SMAPI_CONTRACT_ID` | Yes* | SBB business contract ID |
|
|
187
|
+
| `SMAPI_ENV` | No | `int` (default) or `prod` |
|
|
188
|
+
| `SMAPI_TENANT_ID` | No | Azure AD tenant (defaults to SBB tenant) |
|
|
189
|
+
|
|
190
|
+
*Without credentials, the server runs in mock mode with realistic demo data.
|
|
191
|
+
|
|
192
|
+
## About
|
|
193
|
+
|
|
194
|
+
Built on the official SBB Swiss Mobility API (SMAPI) with OSDM-compliant journey planning and pricing. Covers the entire Swiss public transport network including SBB, BLS, SOB, and regional operators.
|
|
195
|
+
|
|
196
|
+
**SBB** (Schweizerische Bundesbahnen) / **CFF** (Chemins de fer federaux suisses) / **FFS** (Ferrovie federali svizzere) -- Swiss Federal Railways operates one of the densest rail networks in the world with over 10,000 daily connections.
|
|
197
|
+
|
|
198
|
+
## License
|
|
199
|
+
|
|
200
|
+
MIT
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import type { SmapiPlace, SmapiTrip, SmapiTripsCollection, SmapiPriceResult } from './transport/smapi-types.js';
|
|
2
|
+
export declare function formatStations(stations: SmapiPlace[]): string;
|
|
3
|
+
export declare function formatConnections(collection: SmapiTripsCollection): string;
|
|
4
|
+
export declare function formatTripDetails(trip: SmapiTrip): string;
|
|
5
|
+
export declare function formatPrices(results: SmapiPriceResult[]): string;
|
|
6
|
+
export declare function formatTicketLink(tripId: string, deepLink?: string): string;
|
|
@@ -0,0 +1,162 @@
|
|
|
1
|
+
function formatTime(iso) {
|
|
2
|
+
const d = new Date(iso);
|
|
3
|
+
return d.toLocaleTimeString('de-CH', {
|
|
4
|
+
hour: '2-digit',
|
|
5
|
+
minute: '2-digit',
|
|
6
|
+
timeZone: 'Europe/Zurich',
|
|
7
|
+
});
|
|
8
|
+
}
|
|
9
|
+
function formatDate(iso) {
|
|
10
|
+
const d = new Date(iso);
|
|
11
|
+
return d.toLocaleDateString('de-CH', {
|
|
12
|
+
weekday: 'short',
|
|
13
|
+
day: '2-digit',
|
|
14
|
+
month: '2-digit',
|
|
15
|
+
year: 'numeric',
|
|
16
|
+
timeZone: 'Europe/Zurich',
|
|
17
|
+
});
|
|
18
|
+
}
|
|
19
|
+
function parseDuration(iso) {
|
|
20
|
+
const match = iso.match(/PT(?:(\d+)H)?(?:(\d+)M)?/);
|
|
21
|
+
if (!match)
|
|
22
|
+
return iso;
|
|
23
|
+
const h = match[1] ? `${match[1]}h` : '';
|
|
24
|
+
const m = match[2] ? `${match[2]}m` : '';
|
|
25
|
+
return `${h}${h && m ? ' ' : ''}${m}` || '0m';
|
|
26
|
+
}
|
|
27
|
+
function durationMinutes(iso) {
|
|
28
|
+
const match = iso.match(/PT(?:(\d+)H)?(?:(\d+)M)?/);
|
|
29
|
+
if (!match)
|
|
30
|
+
return 0;
|
|
31
|
+
return (parseInt(match[1] || '0') * 60) + parseInt(match[2] || '0');
|
|
32
|
+
}
|
|
33
|
+
export function formatStations(stations) {
|
|
34
|
+
if (stations.length === 0) {
|
|
35
|
+
return 'No stations found.';
|
|
36
|
+
}
|
|
37
|
+
const lines = [`Found ${stations.length} station(s):`, ''];
|
|
38
|
+
lines.push('| Station | ID | Coordinates |');
|
|
39
|
+
lines.push('|---|---|---|');
|
|
40
|
+
for (const s of stations) {
|
|
41
|
+
const coords = s.geoPosition
|
|
42
|
+
? `${s.geoPosition.latitude.toFixed(4)}, ${s.geoPosition.longitude.toFixed(4)}`
|
|
43
|
+
: '-';
|
|
44
|
+
lines.push(`| ${s.name} | \`${s.id}\` | ${coords} |`);
|
|
45
|
+
}
|
|
46
|
+
return lines.join('\n');
|
|
47
|
+
}
|
|
48
|
+
function formatLegSummary(leg) {
|
|
49
|
+
if (leg.type === 'timed') {
|
|
50
|
+
const tl = leg;
|
|
51
|
+
const line = tl.service.publishedLineName || 'Train';
|
|
52
|
+
const platform = tl.board.platform ? ` Pl.${tl.board.platform}` : '';
|
|
53
|
+
return `${line}${platform}`;
|
|
54
|
+
}
|
|
55
|
+
if (leg.type === 'transfer') {
|
|
56
|
+
const tr = leg;
|
|
57
|
+
return `Walk ${parseDuration(tr.duration)}`;
|
|
58
|
+
}
|
|
59
|
+
return 'Transfer';
|
|
60
|
+
}
|
|
61
|
+
export function formatConnections(collection) {
|
|
62
|
+
const trips = collection.trips;
|
|
63
|
+
if (trips.length === 0) {
|
|
64
|
+
return 'No connections found.';
|
|
65
|
+
}
|
|
66
|
+
const first = trips[0];
|
|
67
|
+
const date = formatDate(first.startTime);
|
|
68
|
+
const lines = [
|
|
69
|
+
`**${first.origin.name} -> ${first.destination.name}** | ${date}`,
|
|
70
|
+
`Collection ID: \`${collection.id}\` (use with get_more_connections)`,
|
|
71
|
+
'',
|
|
72
|
+
'| Dep | Arr | Duration | Transfers | Route | Trip ID |',
|
|
73
|
+
'|-----|-----|----------|-----------|-------|---------|',
|
|
74
|
+
];
|
|
75
|
+
for (const trip of trips) {
|
|
76
|
+
const dep = formatTime(trip.startTime);
|
|
77
|
+
const arr = formatTime(trip.endTime);
|
|
78
|
+
const dur = parseDuration(trip.duration);
|
|
79
|
+
const route = trip.legs.map(formatLegSummary).join(' > ');
|
|
80
|
+
lines.push(`| ${dep} | ${arr} | ${dur} | ${trip.transfers} | ${route} | \`${trip.id}\` |`);
|
|
81
|
+
}
|
|
82
|
+
lines.push('');
|
|
83
|
+
lines.push(`*Use \`get_prices\` with trip IDs to see ticket prices. Use \`get_more_connections\` to see earlier/later trains.*`);
|
|
84
|
+
return lines.join('\n');
|
|
85
|
+
}
|
|
86
|
+
export function formatTripDetails(trip) {
|
|
87
|
+
const lines = [
|
|
88
|
+
`**Trip Details** | ${formatDate(trip.startTime)}`,
|
|
89
|
+
`${trip.origin.name} -> ${trip.destination.name} | ${parseDuration(trip.duration)} | ${trip.transfers} transfer(s)`,
|
|
90
|
+
`Status: ${trip.tripStatus}`,
|
|
91
|
+
'',
|
|
92
|
+
];
|
|
93
|
+
for (let i = 0; i < trip.legs.length; i++) {
|
|
94
|
+
const leg = trip.legs[i];
|
|
95
|
+
if (leg.type === 'timed') {
|
|
96
|
+
const tl = leg;
|
|
97
|
+
const line = tl.service.publishedLineName || 'Train';
|
|
98
|
+
const operator = tl.service.operatorName || '';
|
|
99
|
+
const boardPlatform = tl.board.platform ? ` | Platform ${tl.board.platform}` : '';
|
|
100
|
+
const alightPlatform = tl.alight.platform ? ` | Platform ${tl.alight.platform}` : '';
|
|
101
|
+
lines.push(`### Leg ${i + 1}: ${line} ${operator}`.trim());
|
|
102
|
+
lines.push(`- **${formatTime(tl.board.departureTime)}** ${tl.board.stopPlace.name}${boardPlatform}`);
|
|
103
|
+
if (tl.intermediateStops?.length) {
|
|
104
|
+
for (const stop of tl.intermediateStops) {
|
|
105
|
+
const time = stop.arrivalTime ? formatTime(stop.arrivalTime) : '';
|
|
106
|
+
lines.push(` - ${time} ${stop.stopPlace.name}`);
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
lines.push(`- **${formatTime(tl.alight.arrivalTime)}** ${tl.alight.stopPlace.name}${alightPlatform}`);
|
|
110
|
+
if (tl.occupancy) {
|
|
111
|
+
const occ = [];
|
|
112
|
+
if (tl.occupancy.firstClass)
|
|
113
|
+
occ.push(`1st: ${tl.occupancy.firstClass}`);
|
|
114
|
+
if (tl.occupancy.secondClass)
|
|
115
|
+
occ.push(`2nd: ${tl.occupancy.secondClass}`);
|
|
116
|
+
if (occ.length)
|
|
117
|
+
lines.push(` Occupancy: ${occ.join(', ')}`);
|
|
118
|
+
}
|
|
119
|
+
lines.push(` Duration: ${parseDuration(tl.duration)}`);
|
|
120
|
+
}
|
|
121
|
+
else if (leg.type === 'transfer') {
|
|
122
|
+
const tr = leg;
|
|
123
|
+
lines.push(`### Transfer: Walk ${parseDuration(tr.duration)}`);
|
|
124
|
+
}
|
|
125
|
+
lines.push('');
|
|
126
|
+
}
|
|
127
|
+
lines.push(`*Use \`get_prices\` with trip ID \`${trip.id}\` to see ticket prices.*`);
|
|
128
|
+
return lines.join('\n');
|
|
129
|
+
}
|
|
130
|
+
export function formatPrices(results) {
|
|
131
|
+
if (results.length === 0) {
|
|
132
|
+
return 'No price information available.';
|
|
133
|
+
}
|
|
134
|
+
const lines = ['**Ticket Prices**', ''];
|
|
135
|
+
lines.push('| Trip ID | 2nd Class | 1st Class |');
|
|
136
|
+
lines.push('|---------|-----------|-----------|');
|
|
137
|
+
for (const r of results) {
|
|
138
|
+
const second = r.prices.find(p => p.class === '2');
|
|
139
|
+
const first = r.prices.find(p => p.class === '1');
|
|
140
|
+
const secondStr = second ? `CHF ${second.amount.toFixed(2)}` : '-';
|
|
141
|
+
const firstStr = first ? `CHF ${first.amount.toFixed(2)}` : '-';
|
|
142
|
+
lines.push(`| \`${r.tripId}\` | ${secondStr} | ${firstStr} |`);
|
|
143
|
+
}
|
|
144
|
+
lines.push('');
|
|
145
|
+
lines.push('*Prices are estimates. Use `get_ticket_link` to get the purchase link with final pricing.*');
|
|
146
|
+
return lines.join('\n');
|
|
147
|
+
}
|
|
148
|
+
export function formatTicketLink(tripId, deepLink) {
|
|
149
|
+
if (!deepLink) {
|
|
150
|
+
return `No ticket link available for trip \`${tripId}\`. The trip may have expired or is not bookable online.`;
|
|
151
|
+
}
|
|
152
|
+
return [
|
|
153
|
+
'**Buy Ticket on SBB**',
|
|
154
|
+
'',
|
|
155
|
+
`Trip: \`${tripId}\``,
|
|
156
|
+
'',
|
|
157
|
+
`[Purchase on SBB.ch](${deepLink})`,
|
|
158
|
+
'',
|
|
159
|
+
'*Opens the SBB webshop with this connection pre-selected. Complete your purchase there.*',
|
|
160
|
+
].join('\n');
|
|
161
|
+
}
|
|
162
|
+
//# sourceMappingURL=formatters.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"formatters.js","sourceRoot":"","sources":["../src/formatters.ts"],"names":[],"mappings":"AAUA,SAAS,UAAU,CAAC,GAAW;IAC7B,MAAM,CAAC,GAAG,IAAI,IAAI,CAAC,GAAG,CAAC,CAAA;IACvB,OAAO,CAAC,CAAC,kBAAkB,CAAC,OAAO,EAAE;QACnC,IAAI,EAAE,SAAS;QACf,MAAM,EAAE,SAAS;QACjB,QAAQ,EAAE,eAAe;KAC1B,CAAC,CAAA;AACJ,CAAC;AAED,SAAS,UAAU,CAAC,GAAW;IAC7B,MAAM,CAAC,GAAG,IAAI,IAAI,CAAC,GAAG,CAAC,CAAA;IACvB,OAAO,CAAC,CAAC,kBAAkB,CAAC,OAAO,EAAE;QACnC,OAAO,EAAE,OAAO;QAChB,GAAG,EAAE,SAAS;QACd,KAAK,EAAE,SAAS;QAChB,IAAI,EAAE,SAAS;QACf,QAAQ,EAAE,eAAe;KAC1B,CAAC,CAAA;AACJ,CAAC;AAED,SAAS,aAAa,CAAC,GAAW;IAChC,MAAM,KAAK,GAAG,GAAG,CAAC,KAAK,CAAC,0BAA0B,CAAC,CAAA;IACnD,IAAI,CAAC,KAAK;QAAE,OAAO,GAAG,CAAA;IACtB,MAAM,CAAC,GAAG,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,GAAG,KAAK,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,CAAA;IACxC,MAAM,CAAC,GAAG,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,GAAG,KAAK,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,CAAA;IACxC,OAAO,GAAG,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,GAAG,CAA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import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
|
|
3
|
+
import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
|
|
4
|
+
import { z } from 'zod';
|
|
5
|
+
import { isSmapiConfigured, searchPlaces, searchTrips, getTrip, paginateTrips, getTripPrices, getTripOffers, mockSearchPlaces, mockSearchTrips, mockGetTripPrices, mockGetTripOffers, } from './transport/index.js';
|
|
6
|
+
import { formatStations, formatConnections, formatTripDetails, formatPrices, formatTicketLink, } from './formatters.js';
|
|
7
|
+
const useMock = !isSmapiConfigured();
|
|
8
|
+
const server = new McpServer({
|
|
9
|
+
name: 'sbb-mcp',
|
|
10
|
+
version: '0.1.0',
|
|
11
|
+
description: 'Swiss Federal Railways (SBB/CFF/FFS) — real-time train schedules, prices, and ticket purchase links for Switzerland',
|
|
12
|
+
});
|
|
13
|
+
// ─── Tool 1: search_stations ────────────────────────────────────────────────
|
|
14
|
+
server.tool('search_stations', 'Search for Swiss train stations, addresses, or points of interest by name. Returns station IDs needed for other tools.', {
|
|
15
|
+
query: z.string().describe('Station name to search for (e.g. "Zurich", "Bern", "Interlaken")'),
|
|
16
|
+
limit: z.number().min(1).max(20).default(10).describe('Maximum number of results'),
|
|
17
|
+
}, async ({ query, limit }) => {
|
|
18
|
+
const stations = useMock
|
|
19
|
+
? await mockSearchPlaces({ name: query })
|
|
20
|
+
: await searchPlaces({ name: query, type: 'STOP', numberOfResults: limit });
|
|
21
|
+
return { content: [{ type: 'text', text: formatStations(stations) }] };
|
|
22
|
+
});
|
|
23
|
+
// ─── Tool 2: search_connections ─────────────────────────────────────────────
|
|
24
|
+
server.tool('search_connections', 'Find train connections between two Swiss stations. Returns schedules with departure/arrival times, duration, transfers, and trip IDs for pricing.', {
|
|
25
|
+
from: z.string().describe('Origin station name or ID (e.g. "Zurich HB" or "8503000")'),
|
|
26
|
+
to: z.string().describe('Destination station name or ID (e.g. "Bern" or "8507000")'),
|
|
27
|
+
date: z.string().optional().describe('Travel date in YYYY-MM-DD format (default: today)'),
|
|
28
|
+
time: z.string().optional().describe('Departure time in HH:MM format (default: now)'),
|
|
29
|
+
arrival_time: z.boolean().optional().describe('If true, the time parameter is treated as desired arrival time'),
|
|
30
|
+
}, async ({ from, to, date, time, arrival_time }) => {
|
|
31
|
+
// Resolve station names to IDs if needed
|
|
32
|
+
let fromId = from;
|
|
33
|
+
let toId = to;
|
|
34
|
+
if (!/^\d{7}$/.test(from)) {
|
|
35
|
+
const stations = useMock
|
|
36
|
+
? await mockSearchPlaces({ name: from })
|
|
37
|
+
: await searchPlaces({ name: from, type: 'STOP', numberOfResults: 1 });
|
|
38
|
+
if (stations.length === 0) {
|
|
39
|
+
return { content: [{ type: 'text', text: `No station found matching "${from}". Try a different name.` }] };
|
|
40
|
+
}
|
|
41
|
+
fromId = stations[0].id;
|
|
42
|
+
}
|
|
43
|
+
if (!/^\d{7}$/.test(to)) {
|
|
44
|
+
const stations = useMock
|
|
45
|
+
? await mockSearchPlaces({ name: to })
|
|
46
|
+
: await searchPlaces({ name: to, type: 'STOP', numberOfResults: 1 });
|
|
47
|
+
if (stations.length === 0) {
|
|
48
|
+
return { content: [{ type: 'text', text: `No station found matching "${to}". Try a different name.` }] };
|
|
49
|
+
}
|
|
50
|
+
toId = stations[0].id;
|
|
51
|
+
}
|
|
52
|
+
// Build datetime
|
|
53
|
+
let departureTime;
|
|
54
|
+
let arrivalTime;
|
|
55
|
+
if (date || time) {
|
|
56
|
+
const d = date || new Date().toISOString().split('T')[0];
|
|
57
|
+
const t = time || '08:00';
|
|
58
|
+
const dt = new Date(`${d}T${t}:00+02:00`).toISOString();
|
|
59
|
+
if (arrival_time) {
|
|
60
|
+
arrivalTime = dt;
|
|
61
|
+
}
|
|
62
|
+
else {
|
|
63
|
+
departureTime = dt;
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
const collection = useMock
|
|
67
|
+
? await mockSearchTrips({ origin: fromId, destination: toId, departureTime })
|
|
68
|
+
: await searchTrips({
|
|
69
|
+
origin: fromId,
|
|
70
|
+
destination: toId,
|
|
71
|
+
...(departureTime && { departureTime }),
|
|
72
|
+
...(arrivalTime && { arrivalTime }),
|
|
73
|
+
});
|
|
74
|
+
return { content: [{ type: 'text', text: formatConnections(collection) }] };
|
|
75
|
+
});
|
|
76
|
+
// ─── Tool 3: get_trip_details ───────────────────────────────────────────────
|
|
77
|
+
server.tool('get_trip_details', 'Get detailed information about a specific train connection including all intermediate stops, platforms, and occupancy. Use a trip ID from search_connections results.', {
|
|
78
|
+
trip_id: z.string().describe('Trip ID from search_connections results'),
|
|
79
|
+
}, async ({ trip_id }) => {
|
|
80
|
+
if (useMock) {
|
|
81
|
+
return {
|
|
82
|
+
content: [{
|
|
83
|
+
type: 'text',
|
|
84
|
+
text: `Detailed trip information is available with live API access. In mock mode, use search_connections to see trip summaries.`,
|
|
85
|
+
}],
|
|
86
|
+
};
|
|
87
|
+
}
|
|
88
|
+
const trip = await getTrip(trip_id, 'REAL_BOARDING_ALIGHTING');
|
|
89
|
+
return { content: [{ type: 'text', text: formatTripDetails(trip) }] };
|
|
90
|
+
});
|
|
91
|
+
// ─── Tool 4: get_more_connections ───────────────────────────────────────────
|
|
92
|
+
server.tool('get_more_connections', 'Load earlier or later train connections for a previous search. Use the collection ID from search_connections results.', {
|
|
93
|
+
collection_id: z.string().describe('Collection ID from search_connections results'),
|
|
94
|
+
direction: z.enum(['next', 'previous']).describe('"next" for later trains, "previous" for earlier trains'),
|
|
95
|
+
}, async ({ collection_id, direction }) => {
|
|
96
|
+
if (useMock) {
|
|
97
|
+
// Generate new mock trips with offset times
|
|
98
|
+
const offset = direction === 'next' ? 3 * 60 * 60 * 1000 : -3 * 60 * 60 * 1000;
|
|
99
|
+
const baseTime = new Date(Date.now() + offset).toISOString();
|
|
100
|
+
const collection = await mockSearchTrips({
|
|
101
|
+
origin: '8503000',
|
|
102
|
+
destination: '8507000',
|
|
103
|
+
departureTime: baseTime,
|
|
104
|
+
});
|
|
105
|
+
return { content: [{ type: 'text', text: formatConnections(collection) }] };
|
|
106
|
+
}
|
|
107
|
+
const collection = await paginateTrips(collection_id, direction);
|
|
108
|
+
return { content: [{ type: 'text', text: formatConnections(collection) }] };
|
|
109
|
+
});
|
|
110
|
+
// ─── Tool 5: get_prices ────────────────────────────────────────────────────
|
|
111
|
+
server.tool('get_prices', 'Get ticket prices for one or more train connections. Supports Half-Fare card (Halbtax) and GA travelcard discounts.', {
|
|
112
|
+
trip_ids: z.array(z.string()).min(1).max(10).describe('Trip IDs from search_connections results'),
|
|
113
|
+
traveler_type: z.enum(['ADULT', 'CHILD']).default('ADULT').describe('Traveler type'),
|
|
114
|
+
reduction_card: z.enum(['HALF_FARE', 'GA', 'NONE']).default('HALF_FARE').describe('Swiss reduction card (most travelers have Half-Fare)'),
|
|
115
|
+
}, async ({ trip_ids, traveler_type, reduction_card }) => {
|
|
116
|
+
if (useMock) {
|
|
117
|
+
const prices = await mockGetTripPrices(trip_ids);
|
|
118
|
+
return { content: [{ type: 'text', text: formatPrices(prices) }] };
|
|
119
|
+
}
|
|
120
|
+
const travelers = [{
|
|
121
|
+
id: 'traveler-1',
|
|
122
|
+
type: traveler_type,
|
|
123
|
+
reductionCard: reduction_card,
|
|
124
|
+
}];
|
|
125
|
+
const prices = await getTripPrices(trip_ids, travelers);
|
|
126
|
+
return { content: [{ type: 'text', text: formatPrices(prices) }] };
|
|
127
|
+
});
|
|
128
|
+
// ─── Tool 6: get_ticket_link ───────────────────────────────────────────────
|
|
129
|
+
server.tool('get_ticket_link', 'Get a direct purchase link to buy a train ticket on SBB.ch. Only call this when the user wants to buy a specific ticket.', {
|
|
130
|
+
trip_id: z.string().describe('Trip ID to purchase'),
|
|
131
|
+
traveler_type: z.enum(['ADULT', 'CHILD']).default('ADULT').describe('Traveler type'),
|
|
132
|
+
reduction_card: z.enum(['HALF_FARE', 'GA', 'NONE']).default('HALF_FARE').describe('Swiss reduction card'),
|
|
133
|
+
}, async ({ trip_id, traveler_type, reduction_card }) => {
|
|
134
|
+
const travelers = [{
|
|
135
|
+
id: 'traveler-1',
|
|
136
|
+
type: traveler_type,
|
|
137
|
+
reductionCard: reduction_card,
|
|
138
|
+
}];
|
|
139
|
+
if (useMock) {
|
|
140
|
+
const result = await mockGetTripOffers(trip_id, travelers);
|
|
141
|
+
return { content: [{ type: 'text', text: formatTicketLink(trip_id, result.affiliateDeepLink) }] };
|
|
142
|
+
}
|
|
143
|
+
const result = await getTripOffers(trip_id, travelers);
|
|
144
|
+
return { content: [{ type: 'text', text: formatTicketLink(trip_id, result.affiliateDeepLink) }] };
|
|
145
|
+
});
|
|
146
|
+
// ─── Start server ───────────────────────────────────────────────────────────
|
|
147
|
+
async function main() {
|
|
148
|
+
const transport = new StdioServerTransport();
|
|
149
|
+
await server.connect(transport);
|
|
150
|
+
if (useMock) {
|
|
151
|
+
console.error('[sbb-mcp] Running in MOCK mode (no SMAPI credentials configured)');
|
|
152
|
+
console.error('[sbb-mcp] Set SMAPI_CLIENT_ID, SMAPI_CLIENT_SECRET, SMAPI_SCOPE for live data');
|
|
153
|
+
}
|
|
154
|
+
else {
|
|
155
|
+
console.error('[sbb-mcp] Connected to SBB SMAPI');
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
main().catch((err) => {
|
|
159
|
+
console.error('[sbb-mcp] Fatal error:', err);
|
|
160
|
+
process.exit(1);
|
|
161
|
+
});
|
|
162
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";AAEA,OAAO,EAAE,SAAS,EAAE,MAAM,yCAAyC,CAAA;AACnE,OAAO,EAAE,oBAAoB,EAAE,MAAM,2CAA2C,CAAA;AAChF,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAA;AAEvB,OAAO,EACL,iBAAiB,EACjB,YAAY,EACZ,WAAW,EACX,OAAO,EACP,aAAa,EACb,aAAa,EACb,aAAa,EACb,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,CAAA"}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
export { isSmapiConfigured } from './smapi-auth.js';
|
|
2
|
+
export { searchPlaces } from './smapi-journey.js';
|
|
3
|
+
export { searchTrips } from './smapi-journey.js';
|
|
4
|
+
export { getTrip } from './smapi-journey.js';
|
|
5
|
+
export { paginateTrips } from './smapi-journey.js';
|
|
6
|
+
export { getTripPrices } from './smapi-prices.js';
|
|
7
|
+
export { getTripOffers } from './smapi-prices.js';
|
|
8
|
+
export { mockSearchPlaces, mockSearchTrips, mockGetTripPrices, mockGetTripOffers, } from './smapi-mock.js';
|
|
9
|
+
export type { SmapiPlace, SmapiTrip, SmapiTripsCollection, SmapiTripSearchParams, SmapiPlaceSearchParams, SmapiPriceResult, SmapiOfferResult, SmapiTraveler, SmapiReductionCard, SmapiTimedLeg, SmapiTransferLeg, SmapiTripLeg, } from './smapi-types.js';
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
export { isSmapiConfigured } from './smapi-auth.js';
|
|
2
|
+
export { searchPlaces } from './smapi-journey.js';
|
|
3
|
+
export { searchTrips } from './smapi-journey.js';
|
|
4
|
+
export { getTrip } from './smapi-journey.js';
|
|
5
|
+
export { paginateTrips } from './smapi-journey.js';
|
|
6
|
+
export { getTripPrices } from './smapi-prices.js';
|
|
7
|
+
export { getTripOffers } from './smapi-prices.js';
|
|
8
|
+
export { mockSearchPlaces, mockSearchTrips, mockGetTripPrices, mockGetTripOffers, } from './smapi-mock.js';
|
|
9
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/transport/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iBAAiB,EAAE,MAAM,iBAAiB,CAAA;AACnD,OAAO,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAA;AACjD,OAAO,EAAE,WAAW,EAAE,MAAM,oBAAoB,CAAA;AAChD,OAAO,EAAE,OAAO,EAAE,MAAM,oBAAoB,CAAA;AAC5C,OAAO,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAA;AAClD,OAAO,EAAE,aAAa,EAAE,MAAM,mBAAmB,CAAA;AACjD,OAAO,EAAE,aAAa,EAAE,MAAM,mBAAmB,CAAA;AACjD,OAAO,EACL,gBAAgB,EAChB,eAAe,EACf,iBAAiB,EACjB,iBAAiB,GAClB,MAAM,iBAAiB,CAAA"}
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
// OAuth 2.0 Client Credentials flow for SBB SMAPI
|
|
2
|
+
// Token endpoint: Microsoft Azure AD
|
|
3
|
+
// Tokens cached in-memory with 55-min TTL (5-min safety margin on 60-min expiry)
|
|
4
|
+
let cachedToken = null;
|
|
5
|
+
export function isSmapiConfigured() {
|
|
6
|
+
return !!(process.env.SMAPI_CLIENT_ID &&
|
|
7
|
+
process.env.SMAPI_CLIENT_SECRET &&
|
|
8
|
+
process.env.SMAPI_SCOPE);
|
|
9
|
+
}
|
|
10
|
+
export async function getAccessToken() {
|
|
11
|
+
// Return cached token if still valid (55-min TTL)
|
|
12
|
+
if (cachedToken && Date.now() < cachedToken.expiresAt) {
|
|
13
|
+
return cachedToken.token;
|
|
14
|
+
}
|
|
15
|
+
const tenantId = process.env.SMAPI_TENANT_ID || '2cda5d11-f0ac-46b3-967d-af1b2e1bd01a';
|
|
16
|
+
const tokenUrl = `https://login.microsoftonline.com/${tenantId}/oauth2/v2.0/token`;
|
|
17
|
+
const body = new URLSearchParams({
|
|
18
|
+
grant_type: 'client_credentials',
|
|
19
|
+
client_id: process.env.SMAPI_CLIENT_ID,
|
|
20
|
+
client_secret: process.env.SMAPI_CLIENT_SECRET,
|
|
21
|
+
scope: process.env.SMAPI_SCOPE,
|
|
22
|
+
});
|
|
23
|
+
const res = await fetch(tokenUrl, {
|
|
24
|
+
method: 'POST',
|
|
25
|
+
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
|
|
26
|
+
body: body.toString(),
|
|
27
|
+
});
|
|
28
|
+
if (!res.ok) {
|
|
29
|
+
const text = await res.text();
|
|
30
|
+
throw new Error(`SMAPI token request failed: ${res.status} ${text}`);
|
|
31
|
+
}
|
|
32
|
+
const data = await res.json();
|
|
33
|
+
cachedToken = {
|
|
34
|
+
token: data.access_token,
|
|
35
|
+
expiresAt: Date.now() + 55 * 60 * 1000, // 55 minutes
|
|
36
|
+
};
|
|
37
|
+
return cachedToken.token;
|
|
38
|
+
}
|
|
39
|
+
//# sourceMappingURL=smapi-auth.js.map
|