rzd-api 3.1.0__tar.gz → 3.2.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.
- {rzd_api-3.1.0/rzd_api.egg-info → rzd_api-3.2.0}/PKG-INFO +25 -3
- {rzd_api-3.1.0 → rzd_api-3.2.0}/README.md +24 -2
- {rzd_api-3.1.0 → rzd_api-3.2.0}/mcp_server/server.py +15 -1
- {rzd_api-3.1.0 → rzd_api-3.2.0}/pyproject.toml +1 -1
- {rzd_api-3.1.0 → rzd_api-3.2.0}/rzd_api/__init__.py +4 -0
- {rzd_api-3.1.0 → rzd_api-3.2.0}/rzd_api/api.py +147 -11
- {rzd_api-3.1.0 → rzd_api-3.2.0}/rzd_api/client.py +13 -0
- {rzd_api-3.1.0 → rzd_api-3.2.0}/rzd_api/models.py +15 -0
- {rzd_api-3.1.0 → rzd_api-3.2.0/rzd_api.egg-info}/PKG-INFO +25 -3
- {rzd_api-3.1.0 → rzd_api-3.2.0}/tests/test_current_contracts.py +125 -0
- {rzd_api-3.1.0 → rzd_api-3.2.0}/tests/test_mcp_output.py +32 -2
- {rzd_api-3.1.0 → rzd_api-3.2.0}/tests/test_mcp_protocol.py +5 -0
- {rzd_api-3.1.0 → rzd_api-3.2.0}/tests/test_mcp_server.py +2 -1
- {rzd_api-3.1.0 → rzd_api-3.2.0}/CREDITS.md +0 -0
- {rzd_api-3.1.0 → rzd_api-3.2.0}/LICENSE +0 -0
- {rzd_api-3.1.0 → rzd_api-3.2.0}/mcp_server/__init__.py +0 -0
- {rzd_api-3.1.0 → rzd_api-3.2.0}/mcp_server/serialization.py +0 -0
- {rzd_api-3.1.0 → rzd_api-3.2.0}/rzd_api/config.py +0 -0
- {rzd_api-3.1.0 → rzd_api-3.2.0}/rzd_api/exceptions.py +0 -0
- {rzd_api-3.1.0 → rzd_api-3.2.0}/rzd_api/py.typed +0 -0
- {rzd_api-3.1.0 → rzd_api-3.2.0}/rzd_api/query.py +0 -0
- {rzd_api-3.1.0 → rzd_api-3.2.0}/rzd_api.egg-info/SOURCES.txt +0 -0
- {rzd_api-3.1.0 → rzd_api-3.2.0}/rzd_api.egg-info/dependency_links.txt +0 -0
- {rzd_api-3.1.0 → rzd_api-3.2.0}/rzd_api.egg-info/entry_points.txt +0 -0
- {rzd_api-3.1.0 → rzd_api-3.2.0}/rzd_api.egg-info/requires.txt +0 -0
- {rzd_api-3.1.0 → rzd_api-3.2.0}/rzd_api.egg-info/top_level.txt +0 -0
- {rzd_api-3.1.0 → rzd_api-3.2.0}/setup.cfg +0 -0
- {rzd_api-3.1.0 → rzd_api-3.2.0}/tests/test_api.py +0 -0
- {rzd_api-3.1.0 → rzd_api-3.2.0}/tests/test_client.py +0 -0
- {rzd_api-3.1.0 → rzd_api-3.2.0}/tests/test_config_models.py +0 -0
- {rzd_api-3.1.0 → rzd_api-3.2.0}/tests/test_query.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: rzd-api
|
|
3
|
-
Version: 3.
|
|
3
|
+
Version: 3.2.0
|
|
4
4
|
Summary: Typed Python client and MCP server for the unofficial ticket.rzd.ru API
|
|
5
5
|
Author: drgod
|
|
6
6
|
License-Expression: MIT
|
|
@@ -56,6 +56,7 @@ endpoint и схема ответов могут изменяться без п
|
|
|
56
56
|
|
|
57
57
|
- поиск прямых поездов в одну сторону и туда-обратно;
|
|
58
58
|
- поиск станций по названию и синонимам;
|
|
59
|
+
- поиск ж/д вокзалов и аэропортов по названию города;
|
|
59
60
|
- календарь доступности и минимальные цены по датам;
|
|
60
61
|
- информация о вагонах, местах, схемах, изображениях и станциях маршрута;
|
|
61
62
|
- dataclass-модели с полным исходным объектом в `raw`;
|
|
@@ -113,6 +114,7 @@ with RzdClient() as client:
|
|
|
113
114
|
| `search_tickets(...)` | `list[TrainRoute]` или `RoundTripResult` |
|
|
114
115
|
| `search_tickets_detailed(...)` | `TrainSearchResult` или `RoundTripSearchResult` |
|
|
115
116
|
| `find_stations(query, ...)` | `list[Station]` |
|
|
117
|
+
| `get_city_transport_hubs(city, *, region_iso=None)` | `CityTransportHubs` |
|
|
116
118
|
| `resolve_station_code(station)` | код станции |
|
|
117
119
|
| `get_carriages(...)` | `CarriageResult` |
|
|
118
120
|
| `get_train_availability(...)` | `TrainAvailabilityResult` |
|
|
@@ -174,6 +176,22 @@ pricing endpoint не поддерживает маршруты с переса
|
|
|
174
176
|
прежний `/api/v1/suggests`; для ISDK задайте
|
|
175
177
|
`Config(station_search_url="https://ticket.rzd.ru/isdk/suggests")`.
|
|
176
178
|
|
|
179
|
+
`get_city_transport_hubs()` обращается к ISDK и возвращает два списка.
|
|
180
|
+
`railway_stations` содержит пассажирские ж/д узлы, для которых в ответе РЖД есть
|
|
181
|
+
код станции, связанный с карточкой города. `airports` содержит отдельные аэропорты
|
|
182
|
+
с кодами IATA, которые РЖД относит к городу, в том числе за его границами.
|
|
183
|
+
|
|
184
|
+
```python
|
|
185
|
+
with RzdClient() as client:
|
|
186
|
+
hubs = client.get_city_transport_hubs("Москва")
|
|
187
|
+
stations = [(station.name, station.code) for station in hubs.railway_stations]
|
|
188
|
+
airports = [(airport.name, airport.iata_code) for airport in hubs.airports]
|
|
189
|
+
```
|
|
190
|
+
|
|
191
|
+
Для одноимённых городов укажите `region_iso` из сообщения об ошибке, например
|
|
192
|
+
`"RU-IVA"` для Иванова. Если совпадений по названию нет, оба списка пусты.
|
|
193
|
+
Состав списков зависит от каталога РЖД.
|
|
194
|
+
|
|
177
195
|
### Конфигурация
|
|
178
196
|
|
|
179
197
|
```python
|
|
@@ -216,17 +234,21 @@ station-not-found и ambiguous-station.
|
|
|
216
234
|
docker run --rm -i \
|
|
217
235
|
--mount type=bind,src=/absolute/path/ca-bundle.pem,dst=/run/rzd-ca.pem,readonly \
|
|
218
236
|
-e RZD_CA_BUNDLE=/run/rzd-ca.pem \
|
|
219
|
-
-e MCP_TRANSPORT=stdio rzd-api:3.
|
|
237
|
+
-e MCP_TRANSPORT=stdio rzd-api:3.2.0
|
|
220
238
|
```
|
|
221
239
|
|
|
222
240
|
TLS/HTTP/transport errors остаются исключениями, а не пустым результатом поиска.
|
|
223
241
|
|
|
224
242
|
## MCP
|
|
225
243
|
|
|
226
|
-
Инструменты: `search_tickets`, `find_stations`, `get_carriages`,
|
|
244
|
+
Инструменты: `search_tickets`, `find_stations`, `get_city_transport_hubs`, `get_carriages`,
|
|
227
245
|
`get_train_availability`, `get_minimal_prices`, `get_car_scheme`,
|
|
228
246
|
`get_car_images`, `get_route_stations`.
|
|
229
247
|
|
|
248
|
+
Инструмент `get_city_transport_hubs` принимает `{"city": "Москва"}` и возвращает
|
|
249
|
+
объект со списками `railway_stations` и `airports`. Для одноимённых городов
|
|
250
|
+
можно передать `region_iso`.
|
|
251
|
+
|
|
230
252
|
Все tools по умолчанию исключают `raw` на всех уровнях ответа. Передайте
|
|
231
253
|
`include_raw=true`, если нужны исходные поля РЖД. Python-модели и их `to_dict()`
|
|
232
254
|
сохраняют полный `raw`. Списки не обрезаются молча.
|
|
@@ -11,6 +11,7 @@ endpoint и схема ответов могут изменяться без п
|
|
|
11
11
|
|
|
12
12
|
- поиск прямых поездов в одну сторону и туда-обратно;
|
|
13
13
|
- поиск станций по названию и синонимам;
|
|
14
|
+
- поиск ж/д вокзалов и аэропортов по названию города;
|
|
14
15
|
- календарь доступности и минимальные цены по датам;
|
|
15
16
|
- информация о вагонах, местах, схемах, изображениях и станциях маршрута;
|
|
16
17
|
- dataclass-модели с полным исходным объектом в `raw`;
|
|
@@ -68,6 +69,7 @@ with RzdClient() as client:
|
|
|
68
69
|
| `search_tickets(...)` | `list[TrainRoute]` или `RoundTripResult` |
|
|
69
70
|
| `search_tickets_detailed(...)` | `TrainSearchResult` или `RoundTripSearchResult` |
|
|
70
71
|
| `find_stations(query, ...)` | `list[Station]` |
|
|
72
|
+
| `get_city_transport_hubs(city, *, region_iso=None)` | `CityTransportHubs` |
|
|
71
73
|
| `resolve_station_code(station)` | код станции |
|
|
72
74
|
| `get_carriages(...)` | `CarriageResult` |
|
|
73
75
|
| `get_train_availability(...)` | `TrainAvailabilityResult` |
|
|
@@ -129,6 +131,22 @@ pricing endpoint не поддерживает маршруты с переса
|
|
|
129
131
|
прежний `/api/v1/suggests`; для ISDK задайте
|
|
130
132
|
`Config(station_search_url="https://ticket.rzd.ru/isdk/suggests")`.
|
|
131
133
|
|
|
134
|
+
`get_city_transport_hubs()` обращается к ISDK и возвращает два списка.
|
|
135
|
+
`railway_stations` содержит пассажирские ж/д узлы, для которых в ответе РЖД есть
|
|
136
|
+
код станции, связанный с карточкой города. `airports` содержит отдельные аэропорты
|
|
137
|
+
с кодами IATA, которые РЖД относит к городу, в том числе за его границами.
|
|
138
|
+
|
|
139
|
+
```python
|
|
140
|
+
with RzdClient() as client:
|
|
141
|
+
hubs = client.get_city_transport_hubs("Москва")
|
|
142
|
+
stations = [(station.name, station.code) for station in hubs.railway_stations]
|
|
143
|
+
airports = [(airport.name, airport.iata_code) for airport in hubs.airports]
|
|
144
|
+
```
|
|
145
|
+
|
|
146
|
+
Для одноимённых городов укажите `region_iso` из сообщения об ошибке, например
|
|
147
|
+
`"RU-IVA"` для Иванова. Если совпадений по названию нет, оба списка пусты.
|
|
148
|
+
Состав списков зависит от каталога РЖД.
|
|
149
|
+
|
|
132
150
|
### Конфигурация
|
|
133
151
|
|
|
134
152
|
```python
|
|
@@ -171,17 +189,21 @@ station-not-found и ambiguous-station.
|
|
|
171
189
|
docker run --rm -i \
|
|
172
190
|
--mount type=bind,src=/absolute/path/ca-bundle.pem,dst=/run/rzd-ca.pem,readonly \
|
|
173
191
|
-e RZD_CA_BUNDLE=/run/rzd-ca.pem \
|
|
174
|
-
-e MCP_TRANSPORT=stdio rzd-api:3.
|
|
192
|
+
-e MCP_TRANSPORT=stdio rzd-api:3.2.0
|
|
175
193
|
```
|
|
176
194
|
|
|
177
195
|
TLS/HTTP/transport errors остаются исключениями, а не пустым результатом поиска.
|
|
178
196
|
|
|
179
197
|
## MCP
|
|
180
198
|
|
|
181
|
-
Инструменты: `search_tickets`, `find_stations`, `get_carriages`,
|
|
199
|
+
Инструменты: `search_tickets`, `find_stations`, `get_city_transport_hubs`, `get_carriages`,
|
|
182
200
|
`get_train_availability`, `get_minimal_prices`, `get_car_scheme`,
|
|
183
201
|
`get_car_images`, `get_route_stations`.
|
|
184
202
|
|
|
203
|
+
Инструмент `get_city_transport_hubs` принимает `{"city": "Москва"}` и возвращает
|
|
204
|
+
объект со списками `railway_stations` и `airports`. Для одноимённых городов
|
|
205
|
+
можно передать `region_iso`.
|
|
206
|
+
|
|
185
207
|
Все tools по умолчанию исключают `raw` на всех уровнях ответа. Передайте
|
|
186
208
|
`include_raw=true`, если нужны исходные поля РЖД. Python-модели и их `to_dict()`
|
|
187
209
|
сохраняют полный `raw`. Списки не обрезаются молча.
|
|
@@ -65,6 +65,19 @@ def find_stations(
|
|
|
65
65
|
)
|
|
66
66
|
|
|
67
67
|
|
|
68
|
+
def get_city_transport_hubs(
|
|
69
|
+
city: str,
|
|
70
|
+
region_iso: str | None = None,
|
|
71
|
+
include_raw: bool = False,
|
|
72
|
+
) -> dict[str, Any]:
|
|
73
|
+
"""Get railway terminals and airports serving a city. Use region_iso for same-named cities."""
|
|
74
|
+
with RzdClient() as client:
|
|
75
|
+
return serialize(
|
|
76
|
+
client.get_city_transport_hubs(city, region_iso=region_iso),
|
|
77
|
+
include_raw=include_raw,
|
|
78
|
+
)
|
|
79
|
+
|
|
80
|
+
|
|
68
81
|
def get_carriages(
|
|
69
82
|
from_station: str,
|
|
70
83
|
to_station: str,
|
|
@@ -222,6 +235,7 @@ def create_mcp_app(*, host: str = "127.0.0.1", port: int = 8000) -> Any:
|
|
|
222
235
|
)
|
|
223
236
|
app.tool()(search_tickets)
|
|
224
237
|
app.tool()(find_stations)
|
|
238
|
+
app.tool()(get_city_transport_hubs)
|
|
225
239
|
app.tool()(get_carriages)
|
|
226
240
|
app.tool()(get_train_availability)
|
|
227
241
|
app.tool()(get_minimal_prices)
|
|
@@ -231,7 +245,7 @@ def create_mcp_app(*, host: str = "127.0.0.1", port: int = 8000) -> Any:
|
|
|
231
245
|
|
|
232
246
|
@app.custom_route("/health", methods=["GET"], include_in_schema=False)
|
|
233
247
|
async def health(_: Request) -> JSONResponse:
|
|
234
|
-
return JSONResponse({"status": "ok", "service": "rzd-api", "version": "3.
|
|
248
|
+
return JSONResponse({"status": "ok", "service": "rzd-api", "version": "3.2.0"})
|
|
235
249
|
|
|
236
250
|
return app
|
|
237
251
|
|
|
@@ -11,12 +11,14 @@ from .exceptions import (
|
|
|
11
11
|
RzdValidationError,
|
|
12
12
|
)
|
|
13
13
|
from .models import (
|
|
14
|
+
Airport,
|
|
14
15
|
CarGroup,
|
|
15
16
|
CarImage,
|
|
16
17
|
CarImagesResult,
|
|
17
18
|
Carriage,
|
|
18
19
|
CarriageResult,
|
|
19
20
|
CarScheme,
|
|
21
|
+
CityTransportHubs,
|
|
20
22
|
MinimalPrice,
|
|
21
23
|
MinimalPricingResult,
|
|
22
24
|
RoundTripResult,
|
|
@@ -32,12 +34,14 @@ from .models import (
|
|
|
32
34
|
)
|
|
33
35
|
|
|
34
36
|
__all__ = [
|
|
37
|
+
"Airport",
|
|
35
38
|
"CarGroup",
|
|
36
39
|
"CarImage",
|
|
37
40
|
"CarImagesResult",
|
|
38
41
|
"CarScheme",
|
|
39
42
|
"Carriage",
|
|
40
43
|
"CarriageResult",
|
|
44
|
+
"CityTransportHubs",
|
|
41
45
|
"Config",
|
|
42
46
|
"MinimalPrice",
|
|
43
47
|
"MinimalPricingResult",
|
|
@@ -5,14 +5,16 @@ from typing import Any
|
|
|
5
5
|
from urllib.parse import urlsplit, urlunsplit
|
|
6
6
|
|
|
7
7
|
from .config import Config
|
|
8
|
-
from .exceptions import RzdSchemaError
|
|
8
|
+
from .exceptions import RzdSchemaError, RzdValidationError
|
|
9
9
|
from .models import (
|
|
10
|
+
Airport,
|
|
10
11
|
CarGroup,
|
|
11
12
|
CarImage,
|
|
12
13
|
CarImagesResult,
|
|
13
14
|
Carriage,
|
|
14
15
|
CarriageResult,
|
|
15
16
|
CarScheme,
|
|
17
|
+
CityTransportHubs,
|
|
16
18
|
JsonObject,
|
|
17
19
|
MinimalPrice,
|
|
18
20
|
MinimalPricingResult,
|
|
@@ -37,6 +39,7 @@ class RzdApi:
|
|
|
37
39
|
parsed_base_url = urlsplit(self.base_url)
|
|
38
40
|
site_url = urlunsplit((parsed_base_url.scheme, parsed_base_url.netloc, "", "", ""))
|
|
39
41
|
self.b2b_base_url = (config.b2b_base_url or f"{site_url}/apib2b/p").rstrip("/")
|
|
42
|
+
self._isdk_suggest_url = f"{site_url}/isdk/suggests"
|
|
40
43
|
self.transport = transport or RzdTransport(config)
|
|
41
44
|
|
|
42
45
|
def get_train_routes(
|
|
@@ -191,17 +194,11 @@ class RzdApi:
|
|
|
191
194
|
transport_type: str,
|
|
192
195
|
group_results: bool,
|
|
193
196
|
) -> list[Station]:
|
|
194
|
-
payload = self.
|
|
195
|
-
"GET",
|
|
197
|
+
payload = self._get_station_suggestions(
|
|
196
198
|
self.config.station_search_url or f"{self.base_url}/suggests",
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
"GroupResults": str(group_results).lower(),
|
|
201
|
-
"RailwaySortPriority": "true",
|
|
202
|
-
"SynonymOn": 1,
|
|
203
|
-
"Language": self.config.language,
|
|
204
|
-
},
|
|
199
|
+
query=query,
|
|
200
|
+
transport_type=transport_type,
|
|
201
|
+
group_results=group_results,
|
|
205
202
|
)
|
|
206
203
|
nodes = self._suggestion_nodes(payload)
|
|
207
204
|
if not self._station_nodes_match_schema(nodes):
|
|
@@ -222,6 +219,145 @@ class RzdApi:
|
|
|
222
219
|
] = station
|
|
223
220
|
return list(unique.values())
|
|
224
221
|
|
|
222
|
+
def get_city_transport_hubs(self, *, city: str, region_iso: str | None) -> CityTransportHubs:
|
|
223
|
+
language = self.config.language
|
|
224
|
+
nodes = self._get_city_suggestions(city, language)
|
|
225
|
+
cities = self._matching_cities(city, region_iso, nodes)
|
|
226
|
+
russian_nodes = nodes
|
|
227
|
+
if language == "en" and nodes:
|
|
228
|
+
russian_nodes = self._get_city_suggestions(city, "ru")
|
|
229
|
+
cities = cities or self._matching_cities(city, region_iso, russian_nodes)
|
|
230
|
+
elif not cities and nodes:
|
|
231
|
+
cities = self._matching_cities(city, region_iso, self._get_city_suggestions(city, "en"))
|
|
232
|
+
if not cities:
|
|
233
|
+
return CityTransportHubs()
|
|
234
|
+
if len(cities) > 1:
|
|
235
|
+
regions = sorted({str(node.get("RegionISO") or "unknown") for node in cities.values()})
|
|
236
|
+
raise RzdValidationError(
|
|
237
|
+
f"Ambiguous city {city!r} ({', '.join(regions)}). Specify region_iso."
|
|
238
|
+
)
|
|
239
|
+
|
|
240
|
+
city_id, locality = next(iter(cities.items()))
|
|
241
|
+
# RZD matches more railway nodes when queried by the city's Russian name.
|
|
242
|
+
russian_name = next(
|
|
243
|
+
(
|
|
244
|
+
name
|
|
245
|
+
for node in russian_nodes
|
|
246
|
+
if "locality" in node["Types"]
|
|
247
|
+
and self._string(node, "CityId") == city_id
|
|
248
|
+
and (name := self._string(node, "Name", "NameRu"))
|
|
249
|
+
),
|
|
250
|
+
city,
|
|
251
|
+
)
|
|
252
|
+
if russian_name.casefold() != city.casefold():
|
|
253
|
+
nodes = self._get_city_suggestions(russian_name, language)
|
|
254
|
+
hubs = [
|
|
255
|
+
node
|
|
256
|
+
for node in nodes
|
|
257
|
+
if self._string(node, "CityId") == city_id and "locality" not in node["Types"]
|
|
258
|
+
]
|
|
259
|
+
railway_stations = self._city_railway_stations(locality, hubs)
|
|
260
|
+
airports: dict[str, Airport] = {}
|
|
261
|
+
for node in hubs:
|
|
262
|
+
if "avia" not in node["Types"]:
|
|
263
|
+
continue
|
|
264
|
+
iata_code = self._station_codes(node).get("Avia")
|
|
265
|
+
if iata_code is not None and not isinstance(iata_code, str):
|
|
266
|
+
raise RzdSchemaError("Station Codes.Avia must be a string.")
|
|
267
|
+
name = self._string(node, "Name", "NameRu")
|
|
268
|
+
if name and iata_code:
|
|
269
|
+
airports.setdefault(
|
|
270
|
+
iata_code,
|
|
271
|
+
Airport(
|
|
272
|
+
name=name,
|
|
273
|
+
iata_code=iata_code,
|
|
274
|
+
city_id=city_id,
|
|
275
|
+
node_id=self._string(node, "NodeId"),
|
|
276
|
+
raw=node,
|
|
277
|
+
),
|
|
278
|
+
)
|
|
279
|
+
return CityTransportHubs(
|
|
280
|
+
railway_stations=railway_stations, airports=list(airports.values())
|
|
281
|
+
)
|
|
282
|
+
|
|
283
|
+
def _get_city_suggestions(self, city: str, language: str) -> list[JsonObject]:
|
|
284
|
+
payload = self._get_station_suggestions(
|
|
285
|
+
self._isdk_suggest_url,
|
|
286
|
+
query=city,
|
|
287
|
+
transport_type="rail,suburban,avia",
|
|
288
|
+
group_results=False,
|
|
289
|
+
language=language,
|
|
290
|
+
)
|
|
291
|
+
endpoint = "ISDK suggests"
|
|
292
|
+
nodes = self._object_list(
|
|
293
|
+
self._object_payload(payload, endpoint), "transport_node_suggests", endpoint
|
|
294
|
+
)
|
|
295
|
+
if any(not isinstance(node.get("Types"), list) for node in nodes):
|
|
296
|
+
raise RzdSchemaError("ISDK suggestion Types must be a list.")
|
|
297
|
+
return nodes
|
|
298
|
+
|
|
299
|
+
def _get_station_suggestions(
|
|
300
|
+
self,
|
|
301
|
+
url: str,
|
|
302
|
+
*,
|
|
303
|
+
query: str,
|
|
304
|
+
transport_type: str,
|
|
305
|
+
group_results: bool,
|
|
306
|
+
language: str | None = None,
|
|
307
|
+
) -> JsonPayload:
|
|
308
|
+
return self.transport.request_json(
|
|
309
|
+
"GET",
|
|
310
|
+
url,
|
|
311
|
+
params={
|
|
312
|
+
"Query": query,
|
|
313
|
+
"TransportType": transport_type,
|
|
314
|
+
"GroupResults": str(group_results).lower(),
|
|
315
|
+
"RailwaySortPriority": "true",
|
|
316
|
+
"SynonymOn": 1,
|
|
317
|
+
"Language": language or self.config.language,
|
|
318
|
+
},
|
|
319
|
+
)
|
|
320
|
+
|
|
321
|
+
@classmethod
|
|
322
|
+
def _matching_cities(
|
|
323
|
+
cls, city: str, region_iso: str | None, nodes: list[JsonObject]
|
|
324
|
+
) -> dict[str, JsonObject]:
|
|
325
|
+
normalized_city = city.casefold().replace("ё", "е")
|
|
326
|
+
localities = {
|
|
327
|
+
city_id: node
|
|
328
|
+
for node in nodes
|
|
329
|
+
if "locality" in node["Types"]
|
|
330
|
+
and (name := cls._string(node, "Name", "NameRu"))
|
|
331
|
+
and name.casefold().replace("ё", "е") == normalized_city
|
|
332
|
+
and (region_iso is None or node.get("RegionISO") == region_iso)
|
|
333
|
+
and (city_id := cls._string(node, "CityId"))
|
|
334
|
+
}
|
|
335
|
+
cities = {
|
|
336
|
+
city_id: node
|
|
337
|
+
for city_id, node in localities.items()
|
|
338
|
+
if node.get("SubType") in ("Город", "City")
|
|
339
|
+
}
|
|
340
|
+
return cities or localities
|
|
341
|
+
|
|
342
|
+
@classmethod
|
|
343
|
+
def _city_railway_stations(cls, locality: JsonObject, hubs: list[JsonObject]) -> list[Station]:
|
|
344
|
+
# The city has a separate Stations list that also includes commuter stops.
|
|
345
|
+
codes = cls._station_codes(locality)
|
|
346
|
+
passenger_codes = set(str(codes.get("Cbdpr") or "").split(",")) - {""}
|
|
347
|
+
railway_codes = {
|
|
348
|
+
code
|
|
349
|
+
for key in ("Railway", "ForeignRailway", "Movista")
|
|
350
|
+
for code in str(codes.get(key) or "").split(",")
|
|
351
|
+
if code
|
|
352
|
+
}
|
|
353
|
+
stations: dict[str, Station] = {}
|
|
354
|
+
for station in cls._parse_station_nodes(
|
|
355
|
+
node for node in hubs if "railway" in node["Types"]
|
|
356
|
+
):
|
|
357
|
+
if str(station.codes.get("Cbdpr")) in passenger_codes or station.code in railway_codes:
|
|
358
|
+
stations.setdefault(station.code, station)
|
|
359
|
+
return list(stations.values())
|
|
360
|
+
|
|
225
361
|
def get_carriages(
|
|
226
362
|
self,
|
|
227
363
|
*,
|
|
@@ -18,6 +18,7 @@ from .models import (
|
|
|
18
18
|
CarImagesResult,
|
|
19
19
|
CarriageResult,
|
|
20
20
|
CarScheme,
|
|
21
|
+
CityTransportHubs,
|
|
21
22
|
MinimalPricingResult,
|
|
22
23
|
RoundTripResult,
|
|
23
24
|
RoundTripSearchResult,
|
|
@@ -178,6 +179,18 @@ class RzdClient:
|
|
|
178
179
|
self._station_cache.popitem(last=False)
|
|
179
180
|
return stations
|
|
180
181
|
|
|
182
|
+
def get_city_transport_hubs(
|
|
183
|
+
self, city: str, *, region_iso: str | None = None
|
|
184
|
+
) -> CityTransportHubs:
|
|
185
|
+
"""Find passenger railway terminals and airports serving a named city."""
|
|
186
|
+
self._ensure_open()
|
|
187
|
+
city = city.strip()
|
|
188
|
+
if len(city) < 2:
|
|
189
|
+
raise RzdValidationError("City name must contain at least two characters.")
|
|
190
|
+
return self._api.get_city_transport_hubs(
|
|
191
|
+
city=city, region_iso=region_iso.strip().upper() if region_iso else None
|
|
192
|
+
)
|
|
193
|
+
|
|
181
194
|
def get_train_availability(
|
|
182
195
|
self,
|
|
183
196
|
from_station: str | int,
|
|
@@ -29,6 +29,21 @@ class Station(ModelMixin):
|
|
|
29
29
|
country: str | None = None
|
|
30
30
|
|
|
31
31
|
|
|
32
|
+
@dataclass(slots=True)
|
|
33
|
+
class Airport(ModelMixin):
|
|
34
|
+
name: str
|
|
35
|
+
iata_code: str
|
|
36
|
+
city_id: str
|
|
37
|
+
node_id: str | None = None
|
|
38
|
+
raw: JsonObject = field(default_factory=dict)
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
@dataclass(slots=True)
|
|
42
|
+
class CityTransportHubs(ModelMixin):
|
|
43
|
+
railway_stations: list[Station] = field(default_factory=list)
|
|
44
|
+
airports: list[Airport] = field(default_factory=list)
|
|
45
|
+
|
|
46
|
+
|
|
32
47
|
@dataclass(slots=True)
|
|
33
48
|
class CarGroup(ModelMixin):
|
|
34
49
|
car_type: str | None
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: rzd-api
|
|
3
|
-
Version: 3.
|
|
3
|
+
Version: 3.2.0
|
|
4
4
|
Summary: Typed Python client and MCP server for the unofficial ticket.rzd.ru API
|
|
5
5
|
Author: drgod
|
|
6
6
|
License-Expression: MIT
|
|
@@ -56,6 +56,7 @@ endpoint и схема ответов могут изменяться без п
|
|
|
56
56
|
|
|
57
57
|
- поиск прямых поездов в одну сторону и туда-обратно;
|
|
58
58
|
- поиск станций по названию и синонимам;
|
|
59
|
+
- поиск ж/д вокзалов и аэропортов по названию города;
|
|
59
60
|
- календарь доступности и минимальные цены по датам;
|
|
60
61
|
- информация о вагонах, местах, схемах, изображениях и станциях маршрута;
|
|
61
62
|
- dataclass-модели с полным исходным объектом в `raw`;
|
|
@@ -113,6 +114,7 @@ with RzdClient() as client:
|
|
|
113
114
|
| `search_tickets(...)` | `list[TrainRoute]` или `RoundTripResult` |
|
|
114
115
|
| `search_tickets_detailed(...)` | `TrainSearchResult` или `RoundTripSearchResult` |
|
|
115
116
|
| `find_stations(query, ...)` | `list[Station]` |
|
|
117
|
+
| `get_city_transport_hubs(city, *, region_iso=None)` | `CityTransportHubs` |
|
|
116
118
|
| `resolve_station_code(station)` | код станции |
|
|
117
119
|
| `get_carriages(...)` | `CarriageResult` |
|
|
118
120
|
| `get_train_availability(...)` | `TrainAvailabilityResult` |
|
|
@@ -174,6 +176,22 @@ pricing endpoint не поддерживает маршруты с переса
|
|
|
174
176
|
прежний `/api/v1/suggests`; для ISDK задайте
|
|
175
177
|
`Config(station_search_url="https://ticket.rzd.ru/isdk/suggests")`.
|
|
176
178
|
|
|
179
|
+
`get_city_transport_hubs()` обращается к ISDK и возвращает два списка.
|
|
180
|
+
`railway_stations` содержит пассажирские ж/д узлы, для которых в ответе РЖД есть
|
|
181
|
+
код станции, связанный с карточкой города. `airports` содержит отдельные аэропорты
|
|
182
|
+
с кодами IATA, которые РЖД относит к городу, в том числе за его границами.
|
|
183
|
+
|
|
184
|
+
```python
|
|
185
|
+
with RzdClient() as client:
|
|
186
|
+
hubs = client.get_city_transport_hubs("Москва")
|
|
187
|
+
stations = [(station.name, station.code) for station in hubs.railway_stations]
|
|
188
|
+
airports = [(airport.name, airport.iata_code) for airport in hubs.airports]
|
|
189
|
+
```
|
|
190
|
+
|
|
191
|
+
Для одноимённых городов укажите `region_iso` из сообщения об ошибке, например
|
|
192
|
+
`"RU-IVA"` для Иванова. Если совпадений по названию нет, оба списка пусты.
|
|
193
|
+
Состав списков зависит от каталога РЖД.
|
|
194
|
+
|
|
177
195
|
### Конфигурация
|
|
178
196
|
|
|
179
197
|
```python
|
|
@@ -216,17 +234,21 @@ station-not-found и ambiguous-station.
|
|
|
216
234
|
docker run --rm -i \
|
|
217
235
|
--mount type=bind,src=/absolute/path/ca-bundle.pem,dst=/run/rzd-ca.pem,readonly \
|
|
218
236
|
-e RZD_CA_BUNDLE=/run/rzd-ca.pem \
|
|
219
|
-
-e MCP_TRANSPORT=stdio rzd-api:3.
|
|
237
|
+
-e MCP_TRANSPORT=stdio rzd-api:3.2.0
|
|
220
238
|
```
|
|
221
239
|
|
|
222
240
|
TLS/HTTP/transport errors остаются исключениями, а не пустым результатом поиска.
|
|
223
241
|
|
|
224
242
|
## MCP
|
|
225
243
|
|
|
226
|
-
Инструменты: `search_tickets`, `find_stations`, `get_carriages`,
|
|
244
|
+
Инструменты: `search_tickets`, `find_stations`, `get_city_transport_hubs`, `get_carriages`,
|
|
227
245
|
`get_train_availability`, `get_minimal_prices`, `get_car_scheme`,
|
|
228
246
|
`get_car_images`, `get_route_stations`.
|
|
229
247
|
|
|
248
|
+
Инструмент `get_city_transport_hubs` принимает `{"city": "Москва"}` и возвращает
|
|
249
|
+
объект со списками `railway_stations` и `airports`. Для одноимённых городов
|
|
250
|
+
можно передать `region_iso`.
|
|
251
|
+
|
|
230
252
|
Все tools по умолчанию исключают `raw` на всех уровнях ответа. Передайте
|
|
231
253
|
`include_raw=true`, если нужны исходные поля РЖД. Python-модели и их `to_dict()`
|
|
232
254
|
сохраняют полный `raw`. Списки не обрезаются молча.
|
|
@@ -11,6 +11,7 @@ from rzd_api import (
|
|
|
11
11
|
RoundTripSearchResult,
|
|
12
12
|
RzdClient,
|
|
13
13
|
RzdSchemaError,
|
|
14
|
+
RzdValidationError,
|
|
14
15
|
Station,
|
|
15
16
|
TrainSearchResult,
|
|
16
17
|
)
|
|
@@ -88,6 +89,130 @@ def test_station_deduplication_preserves_distinct_suburban_codes() -> None:
|
|
|
88
89
|
assert len(result) == 2
|
|
89
90
|
|
|
90
91
|
|
|
92
|
+
def test_city_transport_hubs_use_city_links_and_passenger_station_codes() -> None:
|
|
93
|
+
city = suggestion(
|
|
94
|
+
Types=["locality", "railway", "avia"],
|
|
95
|
+
RegionISO="RU-CU",
|
|
96
|
+
Codes={"Railway": "2060600", "Cbdpr": "5389,5390", "Avia": "CSY"},
|
|
97
|
+
)
|
|
98
|
+
airport = suggestion(Types=["avia"], SubType=None, NodeId="airport-node", Codes={"Avia": "CSY"})
|
|
99
|
+
station = suggestion(
|
|
100
|
+
Types=["railway"],
|
|
101
|
+
SubType=None,
|
|
102
|
+
NodeId="station-node",
|
|
103
|
+
Codes={"Railway": "2060620", "Cbdpr": "5389"},
|
|
104
|
+
)
|
|
105
|
+
api, transport = make_api(
|
|
106
|
+
{
|
|
107
|
+
"transport_node_suggests": [
|
|
108
|
+
suggestion(Types=["locality"], SubType="Деревня", CityId="village-node"),
|
|
109
|
+
city,
|
|
110
|
+
airport,
|
|
111
|
+
airport,
|
|
112
|
+
suggestion(Types=["avia"], CityId="other-city", Codes={"Avia": "OTHER"}),
|
|
113
|
+
station,
|
|
114
|
+
station,
|
|
115
|
+
{**station, "Types": ["boat"], "Codes": {"Railway": "999", "Cbdpr": "5390"}},
|
|
116
|
+
{**station, "Name": "Чебоксары Тур", "Codes": {"Railway": "2060699"}},
|
|
117
|
+
{**station, "Name": "Чебоксары-Сорт.", "Codes": {"Railway": "9", "Cbdpr": "9"}},
|
|
118
|
+
],
|
|
119
|
+
}
|
|
120
|
+
)
|
|
121
|
+
|
|
122
|
+
with RzdClient(_api=api) as client:
|
|
123
|
+
result = client.get_city_transport_hubs(" чЕбоксары ")
|
|
124
|
+
|
|
125
|
+
assert [(item.name, item.code) for item in result.railway_stations] == [
|
|
126
|
+
("Чебоксары", "2060620")
|
|
127
|
+
]
|
|
128
|
+
assert [(item.name, item.iata_code) for item in result.airports] == [("Чебоксары", "CSY")]
|
|
129
|
+
assert result.airports[0].node_id == "airport-node"
|
|
130
|
+
assert transport.calls[0]["url"] == "https://ticket.rzd.ru/isdk/suggests"
|
|
131
|
+
assert transport.calls[0]["params"]["Query"] == "чЕбоксары"
|
|
132
|
+
assert transport.calls[0]["params"]["TransportType"] == "rail,suburban,avia"
|
|
133
|
+
assert transport.calls[0]["params"]["GroupResults"] == "false"
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
def test_city_transport_hubs_disambiguates_by_region() -> None:
|
|
137
|
+
nodes = {
|
|
138
|
+
"transport_node_suggests": [
|
|
139
|
+
suggestion(Types=["locality", "railway"], RegionISO="RU-CU"),
|
|
140
|
+
suggestion(Types=["locality"], CityId="other-city", RegionISO="RU-ME", Codes={}),
|
|
141
|
+
suggestion(Types=["avia"], CityId="other-city", SubType=None, Codes={"Avia": "ABC"}),
|
|
142
|
+
],
|
|
143
|
+
}
|
|
144
|
+
api, _ = make_api(nodes, nodes, nodes, nodes)
|
|
145
|
+
|
|
146
|
+
with RzdClient(_api=api) as client:
|
|
147
|
+
with pytest.raises(RzdValidationError, match="RU-CU, RU-ME"):
|
|
148
|
+
client.get_city_transport_hubs("Чебоксары")
|
|
149
|
+
result = client.get_city_transport_hubs("Чебоксары", region_iso=" ru-me ")
|
|
150
|
+
missing = client.get_city_transport_hubs("Чебокс")
|
|
151
|
+
with pytest.raises(RzdValidationError, match="City name"):
|
|
152
|
+
client.get_city_transport_hubs(" ")
|
|
153
|
+
|
|
154
|
+
assert result.railway_stations == []
|
|
155
|
+
assert [item.iata_code for item in result.airports] == ["ABC"]
|
|
156
|
+
assert missing.to_dict() == {"railway_stations": [], "airports": []}
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
def test_city_transport_hubs_use_city_railway_code_without_suburban_codes() -> None:
|
|
160
|
+
city = suggestion(Types=["locality", "railway"], Codes={"Railway": "2060620"})
|
|
161
|
+
station = suggestion(Types=["railway"], SubType=None, Codes={"Railway": "2060620"})
|
|
162
|
+
api, _ = make_api({"transport_node_suggests": [city, station]})
|
|
163
|
+
|
|
164
|
+
with RzdClient(_api=api) as client:
|
|
165
|
+
result = client.get_city_transport_hubs("Чебоксары")
|
|
166
|
+
|
|
167
|
+
assert [item.code for item in result.railway_stations] == ["2060620"]
|
|
168
|
+
assert result.airports == []
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
@pytest.mark.parametrize(
|
|
172
|
+
("city", "language", "requests"),
|
|
173
|
+
[
|
|
174
|
+
("Cheboksary", "ru", [("Cheboksary", "ru"), ("Cheboksary", "en"), ("Чебоксары", "ru")]),
|
|
175
|
+
("Cheboksary", "en", [("Cheboksary", "en"), ("Cheboksary", "ru"), ("Чебоксары", "en")]),
|
|
176
|
+
("Чебоксары", "en", [("Чебоксары", "en"), ("Чебоксары", "ru")]),
|
|
177
|
+
],
|
|
178
|
+
)
|
|
179
|
+
def test_city_transport_hubs_query_russian_name_for_localized_results(
|
|
180
|
+
city: str, language: str, requests: list[tuple[str, str]]
|
|
181
|
+
) -> None:
|
|
182
|
+
payloads = []
|
|
183
|
+
for query, request_language in requests:
|
|
184
|
+
city_name = "Чебоксары" if request_language == "ru" else "Cheboksary"
|
|
185
|
+
locality = suggestion(Name=city_name, Types=["locality", "railway", "avia"])
|
|
186
|
+
nodes = [locality]
|
|
187
|
+
if query == "Чебоксары":
|
|
188
|
+
nodes.append(suggestion(Name=city_name, Types=["railway"], SubType=None))
|
|
189
|
+
payloads.append({"transport_node_suggests": nodes})
|
|
190
|
+
api, transport = make_api(*payloads)
|
|
191
|
+
api.config.language = language
|
|
192
|
+
|
|
193
|
+
with RzdClient(_api=api) as client:
|
|
194
|
+
result = client.get_city_transport_hubs(city)
|
|
195
|
+
|
|
196
|
+
assert [item.name for item in result.railway_stations] == [
|
|
197
|
+
"Чебоксары" if language == "ru" else "Cheboksary"
|
|
198
|
+
]
|
|
199
|
+
assert [
|
|
200
|
+
(call["params"]["Query"], call["params"]["Language"]) for call in transport.calls
|
|
201
|
+
] == requests
|
|
202
|
+
|
|
203
|
+
|
|
204
|
+
@pytest.mark.parametrize(
|
|
205
|
+
"airport",
|
|
206
|
+
[suggestion(Codes={"Avia": "ABC"}), suggestion(Types=["avia"], Codes={"Avia": ["ABC"]})],
|
|
207
|
+
)
|
|
208
|
+
def test_malformed_city_transport_hub_response_is_not_empty(airport: dict[str, Any]) -> None:
|
|
209
|
+
city = suggestion(Types=["locality", "avia"])
|
|
210
|
+
api, _ = make_api({"transport_node_suggests": [city, airport]})
|
|
211
|
+
|
|
212
|
+
with RzdClient(_api=api) as client, pytest.raises(RzdSchemaError):
|
|
213
|
+
client.get_city_transport_hubs("Чебоксары")
|
|
214
|
+
|
|
215
|
+
|
|
91
216
|
def test_search_preserves_partial_even_with_no_trains() -> None:
|
|
92
217
|
payload = {
|
|
93
218
|
"Trains": [],
|
|
@@ -8,7 +8,15 @@ import pytest
|
|
|
8
8
|
|
|
9
9
|
from mcp_server import server
|
|
10
10
|
from mcp_server.serialization import serialize
|
|
11
|
-
from rzd_api import
|
|
11
|
+
from rzd_api import (
|
|
12
|
+
Airport,
|
|
13
|
+
CarGroup,
|
|
14
|
+
CarriageResult,
|
|
15
|
+
CityTransportHubs,
|
|
16
|
+
Station,
|
|
17
|
+
TrainRoute,
|
|
18
|
+
TrainSearchResult,
|
|
19
|
+
)
|
|
12
20
|
|
|
13
21
|
|
|
14
22
|
def train() -> TrainRoute:
|
|
@@ -108,9 +116,31 @@ def test_mcp_search_can_return_completeness_without_raw(monkeypatch: pytest.Monk
|
|
|
108
116
|
assert "raw" not in compact
|
|
109
117
|
|
|
110
118
|
|
|
119
|
+
def test_mcp_city_transport_hubs_returns_both_lists(monkeypatch: pytest.MonkeyPatch) -> None:
|
|
120
|
+
result = CityTransportHubs(
|
|
121
|
+
railway_stations=[Station("Московский вокзал", "2004001", raw={"Name": "Санкт-Петербург"})],
|
|
122
|
+
airports=[Airport("Пулково", "LED", "city-id", raw={"Name": "Пулково"})],
|
|
123
|
+
)
|
|
124
|
+
|
|
125
|
+
def get_hubs(self: Any, city: str, *, region_iso: str | None) -> CityTransportHubs:
|
|
126
|
+
assert city == "Санкт-Петербург"
|
|
127
|
+
assert region_iso == "RU-SPE"
|
|
128
|
+
return result
|
|
129
|
+
|
|
130
|
+
monkeypatch.setattr(server.RzdClient, "get_city_transport_hubs", get_hubs)
|
|
131
|
+
compact = server.get_city_transport_hubs("Санкт-Петербург", region_iso="RU-SPE")
|
|
132
|
+
assert compact["railway_stations"][0]["code"] == "2004001"
|
|
133
|
+
assert compact["airports"][0]["iata_code"] == "LED"
|
|
134
|
+
assert '"raw":' not in json.dumps(compact)
|
|
135
|
+
assert (
|
|
136
|
+
server.get_city_transport_hubs("Санкт-Петербург", region_iso="RU-SPE", include_raw=True)
|
|
137
|
+
== result.to_dict()
|
|
138
|
+
)
|
|
139
|
+
|
|
140
|
+
|
|
111
141
|
def test_mcp_publishes_raw_opt_in_on_every_tool() -> None:
|
|
112
142
|
tools = anyio.run(server.create_mcp_app().list_tools)
|
|
113
|
-
assert len(tools) ==
|
|
143
|
+
assert len(tools) == 9
|
|
114
144
|
for tool in tools:
|
|
115
145
|
assert tool.inputSchema["properties"]["include_raw"]["default"] is False
|
|
116
146
|
search = next(tool for tool in tools if tool.name == "search_tickets")
|
|
@@ -23,11 +23,16 @@ def test_stdio_protocol_initialize_list_and_call() -> None:
|
|
|
23
23
|
tools = await session.list_tools()
|
|
24
24
|
call_result = await session.call_tool("find_stations", {"query": "x"})
|
|
25
25
|
assert call_result.isError is True
|
|
26
|
+
hubs_tool = next(tool for tool in tools.tools if tool.name == "get_city_transport_hubs")
|
|
27
|
+
assert hubs_tool.inputSchema["required"] == ["city"]
|
|
28
|
+
call_result = await session.call_tool("get_city_transport_hubs", {"city": "x"})
|
|
29
|
+
assert call_result.isError is True
|
|
26
30
|
return {tool.name for tool in tools.tools}
|
|
27
31
|
|
|
28
32
|
assert anyio.run(run) == {
|
|
29
33
|
"search_tickets",
|
|
30
34
|
"find_stations",
|
|
35
|
+
"get_city_transport_hubs",
|
|
31
36
|
"get_carriages",
|
|
32
37
|
"get_train_availability",
|
|
33
38
|
"get_minimal_prices",
|
|
@@ -80,6 +80,7 @@ def test_create_mcp_app_exposes_health_and_tools() -> None:
|
|
|
80
80
|
assert {tool.name for tool in tools} == {
|
|
81
81
|
"search_tickets",
|
|
82
82
|
"find_stations",
|
|
83
|
+
"get_city_transport_hubs",
|
|
83
84
|
"get_carriages",
|
|
84
85
|
"get_train_availability",
|
|
85
86
|
"get_minimal_prices",
|
|
@@ -90,7 +91,7 @@ def test_create_mcp_app_exposes_health_and_tools() -> None:
|
|
|
90
91
|
http_app = server.build_http_app(app, token=None, rate_limit=60)
|
|
91
92
|
response = request(http_app, path="/health")
|
|
92
93
|
assert response.status_code == 200
|
|
93
|
-
assert response.json() == {"status": "ok", "service": "rzd-api", "version": "3.
|
|
94
|
+
assert response.json() == {"status": "ok", "service": "rzd-api", "version": "3.2.0"}
|
|
94
95
|
|
|
95
96
|
|
|
96
97
|
class FakeRunApp:
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|