regiojet-mcp 0.1.0__tar.gz

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.
@@ -0,0 +1,60 @@
1
+ Metadata-Version: 2.3
2
+ Name: regiojet-mcp
3
+ Version: 0.1.0
4
+ Summary: MCP server for the RegioJet Affiliate API
5
+ Author: Petr Václavek
6
+ Author-email: Petr Václavek <petr@vaclavek.cloud>
7
+ Requires-Dist: fastmcp
8
+ Requires-Dist: httpx
9
+ Requires-Python: >=3.14
10
+ Description-Content-Type: text/markdown
11
+
12
+ # regiojet-mcp
13
+
14
+ MCP server (FastMCP) for the [RegioJet Affiliate API](https://app.swaggerhub.com/apis/regiojet/affiliate/1.1.0).
15
+ Read-only: find stations, search connections, inspect routes, prices and free seats.
16
+
17
+ ## Tools
18
+
19
+ | Tool | Description |
20
+ |---|---|
21
+ | `find_locations` | Resolve city/station names (any language, diacritics optional) to ids |
22
+ | `search_routes` | Connections between two locations on a date, paginated via `cursor` + `page` |
23
+ | `get_route_detail` | Sections (lines, platforms, transfers) and price per seat class |
24
+ | `get_free_seats` | Free seats per vehicle for a seat class |
25
+ | `list_tariffs`, `list_seat_classes`, `list_vehicle_standards`, `list_carriers`, `list_action_prices` | Reference data (cached) |
26
+ | `get_ticket` | Existing ticket by account code + ticket id |
27
+
28
+ Resources: `regiojet://tariffs`, `regiojet://seat-classes`.
29
+
30
+ ## Run
31
+
32
+ ```sh
33
+ uv sync
34
+ uv run regiojet-mcp # stdio
35
+ REGIOJET_MCP_TRANSPORT=http uv run regiojet-mcp # http on 127.0.0.1:8000
36
+ uv run fastmcp dev server.py # MCP Inspector
37
+ ```
38
+
39
+ Claude Code:
40
+
41
+ ```sh
42
+ claude mcp add regiojet -- uv run --directory /path/to/regiojet-mcp regiojet-mcp
43
+ ```
44
+
45
+ ## Configuration
46
+
47
+ | Env var | Default |
48
+ |---|---|
49
+ | `REGIOJET_BASE_URL` | `https://brn-ybus-pubapi.sa.cz/restapi` |
50
+ | `REGIOJET_USER` / `REGIOJET_PASSWORD` | unset (HTTP Basic auth for affiliate accounts) |
51
+ | `REGIOJET_LANG` | `en` |
52
+ | `REGIOJET_CURRENCY` | `EUR` |
53
+ | `REGIOJET_TIMEOUT` | `20` seconds |
54
+ | `REGIOJET_MCP_TRANSPORT` / `_HOST` / `_PORT` | `stdio` / `127.0.0.1` / `8000` |
55
+
56
+ ## Tests
57
+
58
+ ```sh
59
+ uv run pytest
60
+ ```
@@ -0,0 +1,49 @@
1
+ # regiojet-mcp
2
+
3
+ MCP server (FastMCP) for the [RegioJet Affiliate API](https://app.swaggerhub.com/apis/regiojet/affiliate/1.1.0).
4
+ Read-only: find stations, search connections, inspect routes, prices and free seats.
5
+
6
+ ## Tools
7
+
8
+ | Tool | Description |
9
+ |---|---|
10
+ | `find_locations` | Resolve city/station names (any language, diacritics optional) to ids |
11
+ | `search_routes` | Connections between two locations on a date, paginated via `cursor` + `page` |
12
+ | `get_route_detail` | Sections (lines, platforms, transfers) and price per seat class |
13
+ | `get_free_seats` | Free seats per vehicle for a seat class |
14
+ | `list_tariffs`, `list_seat_classes`, `list_vehicle_standards`, `list_carriers`, `list_action_prices` | Reference data (cached) |
15
+ | `get_ticket` | Existing ticket by account code + ticket id |
16
+
17
+ Resources: `regiojet://tariffs`, `regiojet://seat-classes`.
18
+
19
+ ## Run
20
+
21
+ ```sh
22
+ uv sync
23
+ uv run regiojet-mcp # stdio
24
+ REGIOJET_MCP_TRANSPORT=http uv run regiojet-mcp # http on 127.0.0.1:8000
25
+ uv run fastmcp dev server.py # MCP Inspector
26
+ ```
27
+
28
+ Claude Code:
29
+
30
+ ```sh
31
+ claude mcp add regiojet -- uv run --directory /path/to/regiojet-mcp regiojet-mcp
32
+ ```
33
+
34
+ ## Configuration
35
+
36
+ | Env var | Default |
37
+ |---|---|
38
+ | `REGIOJET_BASE_URL` | `https://brn-ybus-pubapi.sa.cz/restapi` |
39
+ | `REGIOJET_USER` / `REGIOJET_PASSWORD` | unset (HTTP Basic auth for affiliate accounts) |
40
+ | `REGIOJET_LANG` | `en` |
41
+ | `REGIOJET_CURRENCY` | `EUR` |
42
+ | `REGIOJET_TIMEOUT` | `20` seconds |
43
+ | `REGIOJET_MCP_TRANSPORT` / `_HOST` / `_PORT` | `stdio` / `127.0.0.1` / `8000` |
44
+
45
+ ## Tests
46
+
47
+ ```sh
48
+ uv run pytest
49
+ ```
@@ -0,0 +1,32 @@
1
+ [project]
2
+ name = "regiojet-mcp"
3
+ version = "0.1.0"
4
+ description = "MCP server for the RegioJet Affiliate API"
5
+ readme = "README.md"
6
+ requires-python = ">=3.14"
7
+ dependencies = [
8
+ "fastmcp",
9
+ "httpx",
10
+ ]
11
+
12
+ [[project.authors]]
13
+ name = "Petr Václavek"
14
+ email = "petr@vaclavek.cloud"
15
+
16
+ [project.scripts]
17
+ regiojet-mcp = "regiojet_mcp:main"
18
+
19
+ [build-system]
20
+ requires = ["uv_build>=0.12.18,<=0.13.5"]
21
+ build-backend = "uv_build"
22
+
23
+ [dependency-groups]
24
+ dev = [
25
+ "pytest",
26
+ "pytest-asyncio",
27
+ "respx",
28
+ ]
29
+
30
+ [tool.pytest.ini_options]
31
+ asyncio_mode = "auto"
32
+ testpaths = ["tests"]
@@ -0,0 +1,31 @@
1
+ [project]
2
+ name = "regiojet-mcp"
3
+ version = "0.1.0"
4
+ description = "MCP server for the RegioJet Affiliate API"
5
+ readme = "README.md"
6
+ authors = [
7
+ { name = "Petr Václavek", email = "petr@vaclavek.cloud" }
8
+ ]
9
+ requires-python = ">=3.14"
10
+ dependencies = [
11
+ "fastmcp",
12
+ "httpx",
13
+ ]
14
+
15
+ [project.scripts]
16
+ regiojet-mcp = "regiojet_mcp:main"
17
+
18
+ [build-system]
19
+ requires = ["uv_build>=0.12.18,<=0.13.5"]
20
+ build-backend = "uv_build"
21
+
22
+ [dependency-groups]
23
+ dev = [
24
+ "pytest",
25
+ "pytest-asyncio",
26
+ "respx",
27
+ ]
28
+
29
+ [tool.pytest.ini_options]
30
+ asyncio_mode = "auto"
31
+ testpaths = ["tests"]
@@ -0,0 +1,17 @@
1
+ import os
2
+
3
+ from .server import mcp
4
+
5
+ __all__ = ["main", "mcp"]
6
+
7
+
8
+ def main() -> None:
9
+ transport = os.getenv("REGIOJET_MCP_TRANSPORT", "stdio")
10
+ if transport == "stdio":
11
+ mcp.run()
12
+ else:
13
+ mcp.run(
14
+ transport=transport,
15
+ host=os.getenv("REGIOJET_MCP_HOST", "127.0.0.1"),
16
+ port=int(os.getenv("REGIOJET_MCP_PORT", "8000")),
17
+ )
@@ -0,0 +1,90 @@
1
+ import time
2
+ from typing import Any
3
+
4
+ import httpx
5
+ from fastmcp.exceptions import ToolError
6
+
7
+ from .config import Settings
8
+
9
+
10
+ class RegioJetClient:
11
+ """Thin async wrapper over the RegioJet Affiliate REST API."""
12
+
13
+ def __init__(self, settings: Settings, transport: httpx.AsyncBaseTransport | None = None):
14
+ self.settings = settings
15
+ auth = None
16
+ if settings.username and settings.password:
17
+ auth = httpx.BasicAuth(settings.username, settings.password)
18
+ self._http = httpx.AsyncClient(
19
+ base_url=settings.base_url,
20
+ auth=auth,
21
+ timeout=settings.timeout,
22
+ transport=transport,
23
+ headers={
24
+ "Accept": "application/json",
25
+ "X-Application-Origin": "AFF",
26
+ **settings.extra_headers,
27
+ },
28
+ )
29
+ self._cache: dict[tuple, tuple[float, Any]] = {}
30
+
31
+ async def aclose(self) -> None:
32
+ await self._http.aclose()
33
+
34
+ def _headers(self, lang: str | None, currency: str | None) -> dict[str, str]:
35
+ return {
36
+ "X-Lang": lang or self.settings.lang,
37
+ "X-Currency": currency or self.settings.currency,
38
+ }
39
+
40
+ async def request(
41
+ self,
42
+ method: str,
43
+ path: str,
44
+ *,
45
+ params: dict[str, Any] | None = None,
46
+ json: Any = None,
47
+ headers: dict[str, str] | None = None,
48
+ lang: str | None = None,
49
+ currency: str | None = None,
50
+ ) -> httpx.Response:
51
+ params = {k: v for k, v in (params or {}).items() if v is not None}
52
+ try:
53
+ resp = await self._http.request(
54
+ method,
55
+ path,
56
+ params=params,
57
+ json=json,
58
+ headers={**self._headers(lang, currency), **(headers or {})},
59
+ )
60
+ except httpx.HTTPError as e:
61
+ raise ToolError(f"RegioJet API unreachable: {e}") from e
62
+ if resp.is_error:
63
+ raise ToolError(f"RegioJet API error {resp.status_code}: {_error_message(resp)}")
64
+ return resp
65
+
66
+ async def get_json(self, path: str, **kwargs: Any) -> Any:
67
+ return (await self.request("GET", path, **kwargs)).json()
68
+
69
+ async def get_cached(self, path: str, *, params: dict[str, Any] | None = None, lang: str | None = None) -> Any:
70
+ """GET with in-memory TTL cache; for rarely changing /consts endpoints."""
71
+ key = (path, tuple(sorted((params or {}).items())), lang or self.settings.lang)
72
+ hit = self._cache.get(key)
73
+ now = time.monotonic()
74
+ if hit and now - hit[0] < self.settings.cache_ttl:
75
+ return hit[1]
76
+ data = await self.get_json(path, params=params, lang=lang)
77
+ self._cache[key] = (now, data)
78
+ return data
79
+
80
+
81
+ def _error_message(resp: httpx.Response) -> str:
82
+ try:
83
+ body = resp.json()
84
+ except ValueError:
85
+ return resp.text[:500] or resp.reason_phrase
86
+ if isinstance(body, dict):
87
+ msg = body.get("message") or resp.reason_phrase
88
+ fields = body.get("errorFields")
89
+ return f"{msg} {fields}" if fields else msg
90
+ return str(body)[:500]
@@ -0,0 +1,27 @@
1
+ import os
2
+ from dataclasses import dataclass, field
3
+
4
+ DEFAULT_BASE_URL = "https://brn-ybus-pubapi.sa.cz/restapi"
5
+
6
+
7
+ @dataclass(frozen=True)
8
+ class Settings:
9
+ base_url: str = DEFAULT_BASE_URL
10
+ username: str | None = None
11
+ password: str | None = None
12
+ lang: str = "en"
13
+ currency: str = "EUR"
14
+ timeout: float = 20.0
15
+ cache_ttl: float = 24 * 3600
16
+ extra_headers: dict[str, str] = field(default_factory=dict)
17
+
18
+ @classmethod
19
+ def from_env(cls) -> "Settings":
20
+ return cls(
21
+ base_url=os.getenv("REGIOJET_BASE_URL", DEFAULT_BASE_URL).rstrip("/"),
22
+ username=os.getenv("REGIOJET_USER") or None,
23
+ password=os.getenv("REGIOJET_PASSWORD") or None,
24
+ lang=os.getenv("REGIOJET_LANG", "en"),
25
+ currency=os.getenv("REGIOJET_CURRENCY", "EUR"),
26
+ timeout=float(os.getenv("REGIOJET_TIMEOUT", "20")),
27
+ )
@@ -0,0 +1,410 @@
1
+ import unicodedata
2
+ from datetime import date
3
+ from typing import Annotated, Any, Literal
4
+
5
+ from fastmcp import FastMCP
6
+ from fastmcp.exceptions import ToolError
7
+ from fastmcp.server.lifespan import lifespan
8
+ from pydantic import BaseModel, Field
9
+
10
+ from .client import RegioJetClient
11
+ from .config import Settings
12
+
13
+ Lang = Literal["cs", "de", "en", "es", "fr", "hu", "ru", "sk", "uk", "zh"]
14
+ Currency = Literal["CZK", "EUR"]
15
+ LocationType = Literal["CITY", "STATION"]
16
+
17
+ LangArg = Annotated[Lang | None, Field(description="Response language; defaults to server setting.")]
18
+ CurrencyArg = Annotated[Currency | None, Field(description="Price currency; defaults to server setting.")]
19
+ TariffsArg = Annotated[
20
+ list[str],
21
+ Field(description="Passenger tariff per traveller, e.g. ['REGULAR', 'REGULAR', 'CHILD_UNDER_12']. See list_tariffs."),
22
+ ]
23
+
24
+ READ_ONLY = {"readOnlyHint": True, "openWorldHint": True}
25
+
26
+ _client: RegioJetClient | None = None
27
+
28
+
29
+ def get_client() -> RegioJetClient:
30
+ global _client
31
+ if _client is None:
32
+ _client = RegioJetClient(Settings.from_env())
33
+ return _client
34
+
35
+
36
+ def set_client(client: RegioJetClient | None) -> None:
37
+ global _client
38
+ _client = client
39
+
40
+
41
+ @lifespan
42
+ async def client_lifespan(server):
43
+ try:
44
+ yield {}
45
+ finally:
46
+ if _client is not None:
47
+ await _client.aclose()
48
+ set_client(None)
49
+
50
+
51
+ mcp = FastMCP(
52
+ "RegioJet",
53
+ instructions=(
54
+ "Tools for RegioJet trains and buses (Czechia and Central Europe). Typical flow: "
55
+ "find_locations to resolve city/station IDs -> search_routes -> get_route_detail -> get_free_seats. "
56
+ "All times are ISO 8601 with local timezone offset."
57
+ ),
58
+ lifespan=client_lifespan,
59
+ )
60
+
61
+
62
+ # ---------- locations ----------
63
+
64
+
65
+ class LocationHit(BaseModel):
66
+ type: LocationType
67
+ id: int
68
+ name: str
69
+ city: str
70
+ country: str
71
+ station_types: list[str] = []
72
+
73
+
74
+ def _norm(s: str) -> str:
75
+ return "".join(c for c in unicodedata.normalize("NFKD", s) if not unicodedata.combining(c)).casefold()
76
+
77
+
78
+ def _match_score(query: str, names: list[str]) -> int | None:
79
+ """Lower is better; None = no match."""
80
+ best = None
81
+ for n in names:
82
+ n = _norm(n)
83
+ if n == query:
84
+ score = 0
85
+ elif n.startswith(query):
86
+ score = 1
87
+ elif query in n:
88
+ score = 2
89
+ else:
90
+ continue
91
+ best = score if best is None else min(best, score)
92
+ return best
93
+
94
+
95
+ @mcp.tool(annotations=READ_ONLY)
96
+ async def find_locations(
97
+ query: Annotated[str, Field(description="City or station name, any language, diacritics optional (e.g. 'Praha', 'Wien', 'Brno hl. n.').")],
98
+ station_type: Annotated[Literal["BUS_STATION", "TRAIN_STATION"] | None, Field(description="Only locations with this station type.")] = None,
99
+ limit: Annotated[int, Field(ge=1, le=100)] = 20,
100
+ lang: LangArg = None,
101
+ ) -> list[LocationHit]:
102
+ """Find RegioJet cities and stations by name. Use returned id+type as from/to in search_routes.
103
+
104
+ Prefer CITY ids for searching (covers all stations in the city); STATION ids are needed for route detail/seats.
105
+ """
106
+ q = _norm(query.strip())
107
+ if not q:
108
+ raise ToolError("query must not be empty")
109
+ countries = await get_client().get_cached(
110
+ "/consts/locations", params={"stationType": station_type} if station_type else None, lang=lang
111
+ )
112
+ scored: list[tuple[int, int, LocationHit]] = []
113
+ for country in countries:
114
+ for city in country.get("cities", []):
115
+ score = _match_score(q, [city["name"], *(city.get("aliases") or [])])
116
+ if score is not None:
117
+ hit = LocationHit(
118
+ type="CITY", id=city["id"], name=city["name"], city=city["name"],
119
+ country=country["country"], station_types=city.get("stationsTypes") or [],
120
+ )
121
+ scored.append((score, 0, hit))
122
+ for st in city.get("stations", []):
123
+ s_score = _match_score(q, [st["fullname"], st["name"], *(st.get("aliases") or [])])
124
+ if s_score is None and score is not None:
125
+ s_score = score + 1 # stations of a matching city
126
+ if s_score is not None:
127
+ hit = LocationHit(
128
+ type="STATION", id=st["id"], name=st["fullname"], city=city["name"],
129
+ country=country["country"], station_types=st.get("stationsTypes") or [],
130
+ )
131
+ scored.append((s_score, -st.get("significance", 0), hit))
132
+ scored.sort(key=lambda t: (t[0], t[2].type != "CITY", t[1], t[2].name))
133
+ return [h for *_, h in scored[:limit]]
134
+
135
+
136
+ # ---------- routes ----------
137
+
138
+
139
+ class RouteSummary(BaseModel):
140
+ id: str
141
+ departure_time: str
142
+ arrival_time: str
143
+ departure_station_id: int
144
+ arrival_station_id: int
145
+ travel_time: str | None = None
146
+ transfers: int
147
+ vehicle_types: list[str]
148
+ free_seats: int | None = None
149
+ price_from: float | None = None
150
+ price_to: float | None = None
151
+ bookable: bool
152
+ notices: list[str] = []
153
+
154
+
155
+ class RouteSearchResult(BaseModel):
156
+ routes: list[RouteSummary]
157
+ currency: str
158
+ cursor: str | None = Field(
159
+ None, description="Pass back to search_routes together with page=FORWARD/BACKWARD to get the next/previous page."
160
+ )
161
+
162
+
163
+ @mcp.tool(annotations=READ_ONLY)
164
+ async def search_routes(
165
+ from_id: Annotated[int, Field(description="Origin city or station id from find_locations.")],
166
+ from_type: LocationType,
167
+ to_id: Annotated[int, Field(description="Destination city or station id from find_locations.")],
168
+ to_type: LocationType,
169
+ departure_date: Annotated[date | None, Field(description="Departure date (YYYY-MM-DD). Defaults to today.")] = None,
170
+ tariffs: TariffsArg = ["REGULAR"],
171
+ page: Annotated[Literal["FORWARD", "BACKWARD"] | None, Field(description="Paginate relative to cursor.")] = None,
172
+ cursor: Annotated[str | None, Field(description="Cursor from a previous search_routes result.")] = None,
173
+ lang: LangArg = None,
174
+ currency: CurrencyArg = None,
175
+ ) -> RouteSearchResult:
176
+ """Search RegioJet connections between two locations on a date. Returns route ids for get_route_detail."""
177
+ headers = {}
178
+ if cursor:
179
+ if not page:
180
+ raise ToolError("page (FORWARD/BACKWARD) is required when cursor is given")
181
+ dep_from, _, dep_to = cursor.partition("|")
182
+ headers = {"X-Used-DepartureFromDateTime": dep_from, "X-Used-DepartureToDateTime": dep_to}
183
+ resp = await get_client().request(
184
+ "GET",
185
+ "/routes/search/simple",
186
+ params={
187
+ "fromLocationId": from_id,
188
+ "fromLocationType": from_type,
189
+ "toLocationId": to_id,
190
+ "toLocationType": to_type,
191
+ "departureDate": departure_date.isoformat() if departure_date else None,
192
+ "tariffs": tariffs,
193
+ "move": page if cursor else None,
194
+ },
195
+ headers=headers,
196
+ lang=lang,
197
+ currency=currency,
198
+ )
199
+ data = resp.json()
200
+ used_from = resp.headers.get("X-Used-DepartureFromDateTime")
201
+ used_to = resp.headers.get("X-Used-DepartureToDateTime")
202
+ routes = [
203
+ RouteSummary(
204
+ id=str(r["id"]),
205
+ departure_time=r["departureTime"],
206
+ arrival_time=r["arrivalTime"],
207
+ departure_station_id=r["departureStationId"],
208
+ arrival_station_id=r["arrivalStationId"],
209
+ travel_time=r.get("travelTime"),
210
+ transfers=r.get("transfersCount", 0),
211
+ vehicle_types=r.get("vehicleTypes") or [],
212
+ free_seats=r.get("freeSeatsCount"),
213
+ price_from=r.get("priceFrom"),
214
+ price_to=r.get("priceTo"),
215
+ bookable=r.get("bookable", False),
216
+ notices=[str(n) for n in r.get("notices") or []],
217
+ )
218
+ for r in data.get("routes", [])
219
+ ]
220
+ return RouteSearchResult(
221
+ routes=routes,
222
+ currency=currency or get_client().settings.currency,
223
+ cursor=f"{used_from}|{used_to}" if used_from and used_to else None,
224
+ )
225
+
226
+
227
+ def _trim_section(s: dict[str, Any]) -> dict[str, Any]:
228
+ line = s.get("line") or {}
229
+ return {
230
+ "section_id": s.get("id"),
231
+ "vehicle_type": s.get("vehicleType"),
232
+ "vehicle_standard": s.get("vehicleStandardKey"),
233
+ "line": line.get("code"),
234
+ "line_direction": f"{line.get('from')} -> {line.get('to')}" if line else None,
235
+ "departure_station_id": s.get("departureStationId"),
236
+ "departure": f"{s.get('departureCityName')} ({s.get('departureStationName')})",
237
+ "departure_time": s.get("departureTime"),
238
+ "departure_platform": s.get("departurePlatform"),
239
+ "arrival_station_id": s.get("arrivalStationId"),
240
+ "arrival": f"{s.get('arrivalCityName')} ({s.get('arrivalStationName')})",
241
+ "arrival_time": s.get("arrivalTime"),
242
+ "arrival_platform": s.get("arrivalPlatform"),
243
+ "free_seats": s.get("freeSeatsCount"),
244
+ "delay": s.get("delay"),
245
+ }
246
+
247
+
248
+ def _trim_price_class(p: dict[str, Any]) -> dict[str, Any]:
249
+ desc = (p.get("conditions") or {}).get("descriptions") or {}
250
+ return {
251
+ "seat_class": p.get("seatClassKey"),
252
+ "price": p.get("price"),
253
+ "credit_price": p.get("creditPrice"),
254
+ "free_seats": p.get("freeSeatsCount"),
255
+ "bookable": p.get("bookable"),
256
+ "tariffs": p.get("tariffs"),
257
+ "cancel_conditions": desc.get("cancelShort") or desc.get("cancel"),
258
+ "rebook_conditions": desc.get("rebookShort") or desc.get("rebook"),
259
+ }
260
+
261
+
262
+ @mcp.tool(annotations=READ_ONLY)
263
+ async def get_route_detail(
264
+ route_id: Annotated[str, Field(description="Route id from search_routes.")],
265
+ from_station_id: Annotated[int, Field(description="departure_station_id from search_routes (station, not city).")],
266
+ to_station_id: Annotated[int, Field(description="arrival_station_id from search_routes (station, not city).")],
267
+ tariffs: TariffsArg = ["REGULAR"],
268
+ lang: LangArg = None,
269
+ currency: CurrencyArg = None,
270
+ ) -> dict[str, Any]:
271
+ """Get a route's sections (trains/buses, lines, platforms, transfers) and price per seat class."""
272
+ r = await get_client().get_json(
273
+ f"/routes/{route_id}/simple",
274
+ params={"fromStationId": from_station_id, "toStationId": to_station_id, "tariffs": tariffs},
275
+ lang=lang,
276
+ currency=currency,
277
+ )
278
+ return {
279
+ "id": r.get("id"),
280
+ "from": f"{r.get('departureCityName')} ({r.get('departureStationName')})",
281
+ "to": f"{r.get('arrivalCityName')} ({r.get('arrivalStationName')})",
282
+ "departure_time": r.get("departureTime"),
283
+ "arrival_time": r.get("arrivalTime"),
284
+ "travel_time": r.get("travelTime"),
285
+ "currency": currency or get_client().settings.currency,
286
+ "price_from": r.get("priceFrom"),
287
+ "price_to": r.get("priceTo"),
288
+ "free_seats": r.get("freeSeatsCount"),
289
+ "bookable": r.get("bookable"),
290
+ "sections": [_trim_section(s) for s in r.get("sections") or []],
291
+ "transfers": r.get("transfersInfo"),
292
+ "price_classes": [_trim_price_class(p) for p in r.get("priceClasses") or []],
293
+ "notices": r.get("notices"),
294
+ }
295
+
296
+
297
+ class SectionRef(BaseModel):
298
+ section_id: int
299
+ from_station_id: int
300
+ to_station_id: int
301
+
302
+
303
+ @mcp.tool(annotations=READ_ONLY)
304
+ async def get_free_seats(
305
+ route_id: Annotated[str, Field(description="Route id from search_routes.")],
306
+ sections: Annotated[
307
+ list[SectionRef],
308
+ Field(description="Sections from get_route_detail (section_id, departure_station_id, arrival_station_id)."),
309
+ ],
310
+ seat_class: Annotated[str, Field(description="seat_class key from get_route_detail price_classes, e.g. 'TRAIN_LOW_COST', 'C0'.")],
311
+ tariffs: TariffsArg = ["REGULAR"],
312
+ include_seat_numbers: Annotated[bool, Field(description="List individual free seat numbers per vehicle.")] = True,
313
+ lang: LangArg = None,
314
+ ) -> list[dict[str, Any]]:
315
+ """Get free seats per vehicle (carriage/bus) offering the given seat class, for each section of a route."""
316
+ resp = await get_client().request(
317
+ "POST",
318
+ f"/routes/{route_id}/freeSeats",
319
+ json={
320
+ "sections": [
321
+ {"sectionId": s.section_id, "fromStationId": s.from_station_id, "toStationId": s.to_station_id}
322
+ for s in sections
323
+ ],
324
+ "tariffs": tariffs,
325
+ "seatClass": seat_class,
326
+ },
327
+ lang=lang,
328
+ )
329
+ out = []
330
+ for sec in resp.json():
331
+ vehicles = []
332
+ for v in sec.get("vehicles") or []:
333
+ if seat_class not in (v.get("seatClasses") or [seat_class]):
334
+ continue
335
+ free = [s for s in v.get("freeSeats") or [] if s.get("seatClass") in (None, seat_class)]
336
+ vehicle = {
337
+ "vehicle_number": v.get("vehicleNumber"),
338
+ "type": v.get("type"),
339
+ "vehicle_standard": v.get("vehicleStandardKey"),
340
+ "seat_classes": v.get("seatClasses"),
341
+ "free_seats_count": len(free),
342
+ "layout_url": v.get("layoutURL"),
343
+ }
344
+ if include_seat_numbers:
345
+ vehicle["free_seats"] = [s.get("index") for s in free]
346
+ vehicles.append(vehicle)
347
+ out.append({"section_id": sec.get("sectionId"), "vehicles": vehicles})
348
+ return out
349
+
350
+
351
+ # ---------- constants ----------
352
+
353
+
354
+ @mcp.tool(annotations=READ_ONLY)
355
+ async def list_tariffs(lang: LangArg = None) -> list[dict[str, Any]]:
356
+ """List passenger tariffs (adult, child, student, senior, ...). Use `key` in tariffs arguments."""
357
+ return await get_client().get_cached("/consts/tariffs", lang=lang)
358
+
359
+
360
+ @mcp.tool(annotations=READ_ONLY)
361
+ async def list_seat_classes(lang: LangArg = None) -> list[dict[str, Any]]:
362
+ """List seat classes (Low cost, Standard, Relax, Business, ...) with descriptions."""
363
+ return await get_client().get_cached("/consts/seatClasses", lang=lang)
364
+
365
+
366
+ @mcp.tool(annotations=READ_ONLY)
367
+ async def list_vehicle_standards(lang: LangArg = None) -> list[dict[str, Any]]:
368
+ """List vehicle standards (e.g. YELLOW, FUN_AND_RELAX) with descriptions."""
369
+ return await get_client().get_cached("/consts/vehicleStandards", lang=lang)
370
+
371
+
372
+ @mcp.tool(annotations=READ_ONLY)
373
+ async def list_carriers(lang: LangArg = None) -> list[dict[str, Any]]:
374
+ """List carriers operating RegioJet connections."""
375
+ return await get_client().get_cached("/consts/carriers", lang=lang)
376
+
377
+
378
+ @mcp.tool(annotations=READ_ONLY)
379
+ async def list_action_prices(active_only: bool = True, lang: LangArg = None) -> list[dict[str, Any]]:
380
+ """List marketing actions / promo prices."""
381
+ return await get_client().get_cached("/consts/actionPrices", params={"activeOnly": active_only}, lang=lang)
382
+
383
+
384
+ # ---------- tickets ----------
385
+
386
+
387
+ @mcp.tool(annotations=READ_ONLY)
388
+ async def get_ticket(
389
+ account_code: Annotated[str, Field(description="Customer account code (from the ticket e-mail/link).")],
390
+ ticket_id: int,
391
+ lang: LangArg = None,
392
+ currency: CurrencyArg = None,
393
+ ) -> dict[str, Any]:
394
+ """Get an existing ticket by account code and ticket id."""
395
+ return await get_client().get_json(f"/tickets/{account_code}/{ticket_id}", lang=lang, currency=currency)
396
+
397
+
398
+ # ---------- resources ----------
399
+
400
+
401
+ @mcp.resource("regiojet://tariffs", mime_type="application/json")
402
+ async def tariffs_resource() -> list[dict[str, Any]]:
403
+ """Passenger tariffs."""
404
+ return await get_client().get_cached("/consts/tariffs")
405
+
406
+
407
+ @mcp.resource("regiojet://seat-classes", mime_type="application/json")
408
+ async def seat_classes_resource() -> list[dict[str, Any]]:
409
+ """Seat classes."""
410
+ return await get_client().get_cached("/consts/seatClasses")