Skip to main content

Typed Python client and MCP server for the unofficial ticket.rzd.ru API

Project description

RZD API 2.0

Типизированный Python-клиент и MCP-сервер для неофициального API ticket.rzd.ru. Проект не связан с ОАО «РЖД»; внутренние endpoint и схема ответов могут изменяться без предупреждения.

Поведение TLS намеренно сохранено от версии 1.x: проверка сертификата API РЖД отключена. Не передавайте клиенту собственные секреты или учётные данные.

Возможности

  • поиск прямых поездов в одну сторону и туда-обратно;
  • поиск станций по названию и синонимам;
  • информация о вагонах, местах и станциях маршрута;
  • dataclass-модели с полным исходным объектом в raw;
  • MCP через stdio и защищённый streamable-http;
  • retries, раздельные таймауты и кэш поиска станций.

Требуется Python 3.10–3.14.

Установка

pip install rzd-api

С MCP-сервером:

pip install "rzd-api[mcp]"

Python API

from datetime import date, timedelta

from rzd_api import RoundTripResult, RzdClient

departure = date.today() + timedelta(days=14)
return_date = departure + timedelta(days=3)

with RzdClient() as client:
    result = client.search_tickets(
        "Москва",
        "Санкт-Петербург",
        departure,
        return_date=return_date,
        adults=1,
        children=0,
    )

    if isinstance(result, RoundTripResult):
        for train in result.forward:
            print(train.number, train.departure_time, train.min_price)
        for train in result.back:
            print(train.number, train.departure_time, train.min_price)

Все модели поддерживают to_dict() и содержат необработанный узел ответа в raw.

Методы RzdClient

Метод Результат
search_tickets(...) list[TrainRoute] или RoundTripResult
find_stations(query, ...) list[Station]
resolve_station_code(station) код станции
get_carriages(...) CarriageResult
get_route_stations(object_id) RouteStationsResult

only_with_seats=True фильтрует по доступности мест из CarGroups. Современный pricing endpoint не поддерживает маршруты с пересадками и фильтр типа транспорта, поэтому include_transfers=True и transport_type="trains"|"suburban" явно возвращают NotImplementedError.

Конфигурация

from rzd_api import Config, RzdClient

config = Config(
    language="ru",
    connect_timeout=5,
    read_timeout=20,
    retry_total=3,
    retry_backoff=0.5,
    station_cache_ttl=3600,
    station_cache_size=256,
    proxy=None,
)
client = RzdClient(config)

Ошибки наследуются от RzdError: validation, transport, HTTP, API, schema, station-not-found и ambiguous-station.

MCP

Инструменты: search_tickets, find_stations, get_carriages, get_route_stations.

Локальный stdio:

rzd-mcp-server

Streamable HTTP на loopback без токена:

MCP_TRANSPORT=streamable-http MCP_HOST=127.0.0.1 rzd-mcp-server

При привязке к non-loopback адресу требуется Bearer-токен минимум из 32 символов:

export MCP_AUTH_TOKEN="replace-with-a-random-token-at-least-32-characters"
MCP_TRANSPORT=streamable-http MCP_HOST=0.0.0.0 rzd-mcp-server

Endpoint MCP: http://localhost:8000/mcp; healthcheck: /health. Лимит по умолчанию — 60 запросов в минуту, настраивается через MCP_RATE_LIMIT_PER_MINUTE. Допустимые Host headers можно перечислить через MCP_ALLOWED_HOSTS.

Docker

export MCP_AUTH_TOKEN="replace-with-a-random-token-at-least-32-characters"
docker compose up -d
curl http://127.0.0.1:8000/health

Контейнер запускается от UID 10001, без Linux capabilities, и публикует порт только на loopback хоста.

Разработка

python -m pip install -e ".[dev]"
make check

Live smoke test является opt-in:

RZD_LIVE_TEST=1 pytest tests/integration -m integration -v

Переход с 1.x описан в MIGRATION.md, изменения релизов — в CHANGELOG.md.

Лицензия

MIT

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

rzd_api-2.0.0.tar.gz (27.8 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

rzd_api-2.0.0-py3-none-any.whl (20.1 kB view details)

Uploaded Python 3

File details

Details for the file rzd_api-2.0.0.tar.gz.

File metadata

  • Download URL: rzd_api-2.0.0.tar.gz
  • Upload date:
  • Size: 27.8 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.14

File hashes

Hashes for rzd_api-2.0.0.tar.gz
Algorithm Hash digest
SHA256 d507fca0ef246e3b87425113c69735d6d765c5ea9acc64df578f47a94bb0f39d
MD5 b116f3a34a30dede47d3bc5c5ee7b4f6
BLAKE2b-256 9ef3ac2c93b07e160faae49ec6a5e47f8c5f32c93433d8c6f2c53143437f2cc2

See more details on using hashes here.

Provenance

The following attestation bundles were made for rzd_api-2.0.0.tar.gz:

Publisher: publish.yml on drGOD/rzd-api

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file rzd_api-2.0.0-py3-none-any.whl.

File metadata

  • Download URL: rzd_api-2.0.0-py3-none-any.whl
  • Upload date:
  • Size: 20.1 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.14

File hashes

Hashes for rzd_api-2.0.0-py3-none-any.whl
Algorithm Hash digest
SHA256 11f52ac100416b1ee12dd1f9e7f9ee812f53a87cfffa7759eaa542ecc727ebdd
MD5 7472800f3b194c920a285ccd7955305b
BLAKE2b-256 09189898825c03741dc2731f2a8a328e434bffca8a2574d2a4a4ef0044370517

See more details on using hashes here.

Provenance

The following attestation bundles were made for rzd_api-2.0.0-py3-none-any.whl:

Publisher: publish.yml on drGOD/rzd-api

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page