rzd-api 1.2.0__tar.gz → 2.0.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.
Files changed (40) hide show
  1. rzd_api-2.0.0/LICENSE +21 -0
  2. rzd_api-2.0.0/PKG-INFO +199 -0
  3. rzd_api-2.0.0/README.md +156 -0
  4. rzd_api-2.0.0/mcp_server/server.py +313 -0
  5. rzd_api-2.0.0/pyproject.toml +101 -0
  6. rzd_api-2.0.0/rzd_api/__init__.py +43 -0
  7. rzd_api-2.0.0/rzd_api/api.py +399 -0
  8. rzd_api-2.0.0/rzd_api/client.py +364 -0
  9. rzd_api-2.0.0/rzd_api/config.py +54 -0
  10. rzd_api-2.0.0/rzd_api/exceptions.py +60 -0
  11. rzd_api-2.0.0/rzd_api/models.py +84 -0
  12. rzd_api-2.0.0/rzd_api/py.typed +0 -0
  13. rzd_api-2.0.0/rzd_api/query.py +140 -0
  14. rzd_api-2.0.0/rzd_api.egg-info/PKG-INFO +199 -0
  15. {rzd_api-1.2.0 → rzd_api-2.0.0}/rzd_api.egg-info/SOURCES.txt +9 -1
  16. rzd_api-2.0.0/rzd_api.egg-info/requires.txt +18 -0
  17. rzd_api-2.0.0/tests/test_api.py +220 -0
  18. rzd_api-2.0.0/tests/test_client.py +276 -0
  19. rzd_api-2.0.0/tests/test_config_models.py +68 -0
  20. rzd_api-2.0.0/tests/test_mcp_protocol.py +33 -0
  21. rzd_api-2.0.0/tests/test_mcp_server.py +169 -0
  22. rzd_api-2.0.0/tests/test_query.py +154 -0
  23. rzd_api-1.2.0/PKG-INFO +0 -395
  24. rzd_api-1.2.0/README.md +0 -363
  25. rzd_api-1.2.0/mcp_server/server.py +0 -197
  26. rzd_api-1.2.0/pyproject.toml +0 -57
  27. rzd_api-1.2.0/rzd_api/__init__.py +0 -6
  28. rzd_api-1.2.0/rzd_api/api.py +0 -268
  29. rzd_api-1.2.0/rzd_api/client.py +0 -140
  30. rzd_api-1.2.0/rzd_api/config.py +0 -12
  31. rzd_api-1.2.0/rzd_api/query.py +0 -103
  32. rzd_api-1.2.0/rzd_api.egg-info/PKG-INFO +0 -395
  33. rzd_api-1.2.0/rzd_api.egg-info/requires.txt +0 -9
  34. rzd_api-1.2.0/tests/test_api.py +0 -114
  35. rzd_api-1.2.0/tests/test_client.py +0 -115
  36. {rzd_api-1.2.0 → rzd_api-2.0.0}/mcp_server/__init__.py +0 -0
  37. {rzd_api-1.2.0 → rzd_api-2.0.0}/rzd_api.egg-info/dependency_links.txt +0 -0
  38. {rzd_api-1.2.0 → rzd_api-2.0.0}/rzd_api.egg-info/entry_points.txt +0 -0
  39. {rzd_api-1.2.0 → rzd_api-2.0.0}/rzd_api.egg-info/top_level.txt +0 -0
  40. {rzd_api-1.2.0 → rzd_api-2.0.0}/setup.cfg +0 -0
rzd_api-2.0.0/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 drgod
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.
rzd_api-2.0.0/PKG-INFO ADDED
@@ -0,0 +1,199 @@
1
+ Metadata-Version: 2.4
2
+ Name: rzd-api
3
+ Version: 2.0.0
4
+ Summary: Typed Python client and MCP server for the unofficial ticket.rzd.ru API
5
+ Author: drgod
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://github.com/drGOD/rzd-api
8
+ Project-URL: Repository, https://github.com/drGOD/rzd-api
9
+ Project-URL: Issues, https://github.com/drGOD/rzd-api/issues
10
+ Keywords: rzd,railway,trains,tickets,api,mcp
11
+ Classifier: Development Status :: 4 - Beta
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: Programming Language :: Python :: 3
14
+ Classifier: Programming Language :: Python :: 3.10
15
+ Classifier: Programming Language :: Python :: 3.11
16
+ Classifier: Programming Language :: Python :: 3.12
17
+ Classifier: Programming Language :: Python :: 3.13
18
+ Classifier: Programming Language :: Python :: 3.14
19
+ Classifier: Programming Language :: Python :: 3 :: Only
20
+ Classifier: Topic :: Internet :: WWW/HTTP :: Dynamic Content
21
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
22
+ Classifier: Typing :: Typed
23
+ Requires-Python: >=3.10
24
+ Description-Content-Type: text/markdown
25
+ License-File: LICENSE
26
+ Requires-Dist: requests<3,>=2.31
27
+ Requires-Dist: urllib3<3,>=2
28
+ Provides-Extra: mcp
29
+ Requires-Dist: mcp<1.29,>=1.28.1; extra == "mcp"
30
+ Requires-Dist: uvicorn<0.52,>=0.51; extra == "mcp"
31
+ Provides-Extra: dev
32
+ Requires-Dist: build<2,>=1.3; extra == "dev"
33
+ Requires-Dist: mcp<1.29,>=1.28.1; extra == "dev"
34
+ Requires-Dist: mypy<2,>=1.18; extra == "dev"
35
+ Requires-Dist: pip-audit<3,>=2.9; extra == "dev"
36
+ Requires-Dist: pytest<10,>=9; extra == "dev"
37
+ Requires-Dist: pytest-cov<8,>=7; extra == "dev"
38
+ Requires-Dist: ruff<0.15,>=0.14; extra == "dev"
39
+ Requires-Dist: twine<7,>=6.2; extra == "dev"
40
+ Requires-Dist: types-requests<3,>=2.31; extra == "dev"
41
+ Requires-Dist: uvicorn<0.52,>=0.51; extra == "dev"
42
+ Dynamic: license-file
43
+
44
+ # RZD API 2.0
45
+
46
+ Типизированный Python-клиент и MCP-сервер для неофициального API
47
+ [`ticket.rzd.ru`](https://ticket.rzd.ru). Проект не связан с ОАО «РЖД»; внутренние
48
+ endpoint и схема ответов могут изменяться без предупреждения.
49
+
50
+ Поведение TLS намеренно сохранено от версии 1.x: проверка сертификата API РЖД
51
+ отключена. Не передавайте клиенту собственные секреты или учётные данные.
52
+
53
+ ## Возможности
54
+
55
+ - поиск прямых поездов в одну сторону и туда-обратно;
56
+ - поиск станций по названию и синонимам;
57
+ - информация о вагонах, местах и станциях маршрута;
58
+ - dataclass-модели с полным исходным объектом в `raw`;
59
+ - MCP через `stdio` и защищённый `streamable-http`;
60
+ - retries, раздельные таймауты и кэш поиска станций.
61
+
62
+ Требуется Python 3.10–3.14.
63
+
64
+ ## Установка
65
+
66
+ ```sh
67
+ pip install rzd-api
68
+ ```
69
+
70
+ С MCP-сервером:
71
+
72
+ ```sh
73
+ pip install "rzd-api[mcp]"
74
+ ```
75
+
76
+ ## Python API
77
+
78
+ ```python
79
+ from datetime import date, timedelta
80
+
81
+ from rzd_api import RoundTripResult, RzdClient
82
+
83
+ departure = date.today() + timedelta(days=14)
84
+ return_date = departure + timedelta(days=3)
85
+
86
+ with RzdClient() as client:
87
+ result = client.search_tickets(
88
+ "Москва",
89
+ "Санкт-Петербург",
90
+ departure,
91
+ return_date=return_date,
92
+ adults=1,
93
+ children=0,
94
+ )
95
+
96
+ if isinstance(result, RoundTripResult):
97
+ for train in result.forward:
98
+ print(train.number, train.departure_time, train.min_price)
99
+ for train in result.back:
100
+ print(train.number, train.departure_time, train.min_price)
101
+ ```
102
+
103
+ Все модели поддерживают `to_dict()` и содержат необработанный узел ответа в `raw`.
104
+
105
+ ### Методы `RzdClient`
106
+
107
+ | Метод | Результат |
108
+ |---|---|
109
+ | `search_tickets(...)` | `list[TrainRoute]` или `RoundTripResult` |
110
+ | `find_stations(query, ...)` | `list[Station]` |
111
+ | `resolve_station_code(station)` | код станции |
112
+ | `get_carriages(...)` | `CarriageResult` |
113
+ | `get_route_stations(object_id)` | `RouteStationsResult` |
114
+
115
+ `only_with_seats=True` фильтрует по доступности мест из `CarGroups`. Современный
116
+ pricing endpoint не поддерживает маршруты с пересадками и фильтр типа транспорта,
117
+ поэтому `include_transfers=True` и `transport_type="trains"|"suburban"` явно
118
+ возвращают `NotImplementedError`.
119
+
120
+ ### Конфигурация
121
+
122
+ ```python
123
+ from rzd_api import Config, RzdClient
124
+
125
+ config = Config(
126
+ language="ru",
127
+ connect_timeout=5,
128
+ read_timeout=20,
129
+ retry_total=3,
130
+ retry_backoff=0.5,
131
+ station_cache_ttl=3600,
132
+ station_cache_size=256,
133
+ proxy=None,
134
+ )
135
+ client = RzdClient(config)
136
+ ```
137
+
138
+ Ошибки наследуются от `RzdError`: validation, transport, HTTP, API, schema,
139
+ station-not-found и ambiguous-station.
140
+
141
+ ## MCP
142
+
143
+ Инструменты: `search_tickets`, `find_stations`, `get_carriages`,
144
+ `get_route_stations`.
145
+
146
+ Локальный stdio:
147
+
148
+ ```sh
149
+ rzd-mcp-server
150
+ ```
151
+
152
+ Streamable HTTP на loopback без токена:
153
+
154
+ ```sh
155
+ MCP_TRANSPORT=streamable-http MCP_HOST=127.0.0.1 rzd-mcp-server
156
+ ```
157
+
158
+ При привязке к non-loopback адресу требуется Bearer-токен минимум из 32 символов:
159
+
160
+ ```sh
161
+ export MCP_AUTH_TOKEN="replace-with-a-random-token-at-least-32-characters"
162
+ MCP_TRANSPORT=streamable-http MCP_HOST=0.0.0.0 rzd-mcp-server
163
+ ```
164
+
165
+ Endpoint MCP: `http://localhost:8000/mcp`; healthcheck: `/health`. Лимит по
166
+ умолчанию — 60 запросов в минуту, настраивается через
167
+ `MCP_RATE_LIMIT_PER_MINUTE`. Допустимые Host headers можно перечислить через
168
+ `MCP_ALLOWED_HOSTS`.
169
+
170
+ ## Docker
171
+
172
+ ```sh
173
+ export MCP_AUTH_TOKEN="replace-with-a-random-token-at-least-32-characters"
174
+ docker compose up -d
175
+ curl http://127.0.0.1:8000/health
176
+ ```
177
+
178
+ Контейнер запускается от UID 10001, без Linux capabilities, и публикует порт
179
+ только на loopback хоста.
180
+
181
+ ## Разработка
182
+
183
+ ```sh
184
+ python -m pip install -e ".[dev]"
185
+ make check
186
+ ```
187
+
188
+ Live smoke test является opt-in:
189
+
190
+ ```sh
191
+ RZD_LIVE_TEST=1 pytest tests/integration -m integration -v
192
+ ```
193
+
194
+ Переход с 1.x описан в [MIGRATION.md](MIGRATION.md), изменения релизов — в
195
+ [CHANGELOG.md](CHANGELOG.md).
196
+
197
+ ## Лицензия
198
+
199
+ MIT
@@ -0,0 +1,156 @@
1
+ # RZD API 2.0
2
+
3
+ Типизированный Python-клиент и MCP-сервер для неофициального API
4
+ [`ticket.rzd.ru`](https://ticket.rzd.ru). Проект не связан с ОАО «РЖД»; внутренние
5
+ endpoint и схема ответов могут изменяться без предупреждения.
6
+
7
+ Поведение TLS намеренно сохранено от версии 1.x: проверка сертификата API РЖД
8
+ отключена. Не передавайте клиенту собственные секреты или учётные данные.
9
+
10
+ ## Возможности
11
+
12
+ - поиск прямых поездов в одну сторону и туда-обратно;
13
+ - поиск станций по названию и синонимам;
14
+ - информация о вагонах, местах и станциях маршрута;
15
+ - dataclass-модели с полным исходным объектом в `raw`;
16
+ - MCP через `stdio` и защищённый `streamable-http`;
17
+ - retries, раздельные таймауты и кэш поиска станций.
18
+
19
+ Требуется Python 3.10–3.14.
20
+
21
+ ## Установка
22
+
23
+ ```sh
24
+ pip install rzd-api
25
+ ```
26
+
27
+ С MCP-сервером:
28
+
29
+ ```sh
30
+ pip install "rzd-api[mcp]"
31
+ ```
32
+
33
+ ## Python API
34
+
35
+ ```python
36
+ from datetime import date, timedelta
37
+
38
+ from rzd_api import RoundTripResult, RzdClient
39
+
40
+ departure = date.today() + timedelta(days=14)
41
+ return_date = departure + timedelta(days=3)
42
+
43
+ with RzdClient() as client:
44
+ result = client.search_tickets(
45
+ "Москва",
46
+ "Санкт-Петербург",
47
+ departure,
48
+ return_date=return_date,
49
+ adults=1,
50
+ children=0,
51
+ )
52
+
53
+ if isinstance(result, RoundTripResult):
54
+ for train in result.forward:
55
+ print(train.number, train.departure_time, train.min_price)
56
+ for train in result.back:
57
+ print(train.number, train.departure_time, train.min_price)
58
+ ```
59
+
60
+ Все модели поддерживают `to_dict()` и содержат необработанный узел ответа в `raw`.
61
+
62
+ ### Методы `RzdClient`
63
+
64
+ | Метод | Результат |
65
+ |---|---|
66
+ | `search_tickets(...)` | `list[TrainRoute]` или `RoundTripResult` |
67
+ | `find_stations(query, ...)` | `list[Station]` |
68
+ | `resolve_station_code(station)` | код станции |
69
+ | `get_carriages(...)` | `CarriageResult` |
70
+ | `get_route_stations(object_id)` | `RouteStationsResult` |
71
+
72
+ `only_with_seats=True` фильтрует по доступности мест из `CarGroups`. Современный
73
+ pricing endpoint не поддерживает маршруты с пересадками и фильтр типа транспорта,
74
+ поэтому `include_transfers=True` и `transport_type="trains"|"suburban"` явно
75
+ возвращают `NotImplementedError`.
76
+
77
+ ### Конфигурация
78
+
79
+ ```python
80
+ from rzd_api import Config, RzdClient
81
+
82
+ config = Config(
83
+ language="ru",
84
+ connect_timeout=5,
85
+ read_timeout=20,
86
+ retry_total=3,
87
+ retry_backoff=0.5,
88
+ station_cache_ttl=3600,
89
+ station_cache_size=256,
90
+ proxy=None,
91
+ )
92
+ client = RzdClient(config)
93
+ ```
94
+
95
+ Ошибки наследуются от `RzdError`: validation, transport, HTTP, API, schema,
96
+ station-not-found и ambiguous-station.
97
+
98
+ ## MCP
99
+
100
+ Инструменты: `search_tickets`, `find_stations`, `get_carriages`,
101
+ `get_route_stations`.
102
+
103
+ Локальный stdio:
104
+
105
+ ```sh
106
+ rzd-mcp-server
107
+ ```
108
+
109
+ Streamable HTTP на loopback без токена:
110
+
111
+ ```sh
112
+ MCP_TRANSPORT=streamable-http MCP_HOST=127.0.0.1 rzd-mcp-server
113
+ ```
114
+
115
+ При привязке к non-loopback адресу требуется Bearer-токен минимум из 32 символов:
116
+
117
+ ```sh
118
+ export MCP_AUTH_TOKEN="replace-with-a-random-token-at-least-32-characters"
119
+ MCP_TRANSPORT=streamable-http MCP_HOST=0.0.0.0 rzd-mcp-server
120
+ ```
121
+
122
+ Endpoint MCP: `http://localhost:8000/mcp`; healthcheck: `/health`. Лимит по
123
+ умолчанию — 60 запросов в минуту, настраивается через
124
+ `MCP_RATE_LIMIT_PER_MINUTE`. Допустимые Host headers можно перечислить через
125
+ `MCP_ALLOWED_HOSTS`.
126
+
127
+ ## Docker
128
+
129
+ ```sh
130
+ export MCP_AUTH_TOKEN="replace-with-a-random-token-at-least-32-characters"
131
+ docker compose up -d
132
+ curl http://127.0.0.1:8000/health
133
+ ```
134
+
135
+ Контейнер запускается от UID 10001, без Linux capabilities, и публикует порт
136
+ только на loopback хоста.
137
+
138
+ ## Разработка
139
+
140
+ ```sh
141
+ python -m pip install -e ".[dev]"
142
+ make check
143
+ ```
144
+
145
+ Live smoke test является opt-in:
146
+
147
+ ```sh
148
+ RZD_LIVE_TEST=1 pytest tests/integration -m integration -v
149
+ ```
150
+
151
+ Переход с 1.x описан в [MIGRATION.md](MIGRATION.md), изменения релизов — в
152
+ [CHANGELOG.md](CHANGELOG.md).
153
+
154
+ ## Лицензия
155
+
156
+ MIT
@@ -0,0 +1,313 @@
1
+ from __future__ import annotations
2
+
3
+ import hashlib
4
+ import ipaddress
5
+ import math
6
+ import os
7
+ import secrets
8
+ import sys
9
+ import threading
10
+ import time
11
+ from collections import defaultdict, deque
12
+ from collections.abc import Awaitable, Callable
13
+ from typing import Any
14
+
15
+ from rzd_api import RoundTripResult, RzdClient
16
+
17
+
18
+ def search_tickets(
19
+ from_station: str,
20
+ to_station: str,
21
+ departure_date: str,
22
+ return_date: str | None = None,
23
+ adults: int = 1,
24
+ children: int = 0,
25
+ only_with_seats: bool = True,
26
+ include_transfers: bool = False,
27
+ transport_type: str = "all",
28
+ ) -> dict[str, Any] | list[dict[str, Any]]:
29
+ """Search direct RZD routes by station name/code and departure date."""
30
+ with RzdClient() as client:
31
+ result = client.search_tickets(
32
+ from_station,
33
+ to_station,
34
+ departure_date,
35
+ return_date,
36
+ adults=adults,
37
+ children=children,
38
+ only_with_seats=only_with_seats,
39
+ include_transfers=include_transfers,
40
+ transport_type=transport_type,
41
+ )
42
+ if isinstance(result, RoundTripResult):
43
+ return result.to_dict()
44
+ return [route.to_dict() for route in result]
45
+
46
+
47
+ def find_stations(
48
+ query: str,
49
+ transport_type: str = "rail,suburban",
50
+ group_results: bool = True,
51
+ ) -> list[dict[str, Any]]:
52
+ """Find station candidates, including synonym matches."""
53
+ with RzdClient() as client:
54
+ return [
55
+ station.to_dict()
56
+ for station in client.find_stations(
57
+ query,
58
+ transport_type=transport_type,
59
+ group_results=group_results,
60
+ )
61
+ ]
62
+
63
+
64
+ def get_carriages(
65
+ from_station: str,
66
+ to_station: str,
67
+ departure_date: str,
68
+ departure_time: str,
69
+ train_number: str,
70
+ car_number: str = "01",
71
+ provider: str = "P1",
72
+ ) -> dict[str, Any]:
73
+ """Get typed carriage and seat availability details for a train."""
74
+ with RzdClient() as client:
75
+ return client.get_carriages(
76
+ from_station,
77
+ to_station,
78
+ departure_date,
79
+ departure_time,
80
+ train_number,
81
+ car_number=car_number,
82
+ provider=provider,
83
+ ).to_dict()
84
+
85
+
86
+ def get_route_stations(object_id: str) -> dict[str, Any]:
87
+ """Get all stations for an RZD route object."""
88
+ with RzdClient() as client:
89
+ return client.get_route_stations(object_id).to_dict()
90
+
91
+
92
+ def create_mcp_app(*, host: str = "127.0.0.1", port: int = 8000) -> Any:
93
+ try:
94
+ from mcp.server.fastmcp import FastMCP
95
+ from mcp.server.fastmcp.server import TransportSecuritySettings
96
+ from starlette.requests import Request
97
+ from starlette.responses import JSONResponse
98
+ except ImportError as exc:
99
+ raise RuntimeError(
100
+ "MCP support is not installed. Install it with: pip install 'rzd-api[mcp]'"
101
+ ) from exc
102
+
103
+ allowed_hosts = _allowed_hosts(host)
104
+ app = FastMCP(
105
+ "RZD API",
106
+ host=host,
107
+ port=port,
108
+ streamable_http_path="/mcp",
109
+ transport_security=TransportSecuritySettings(
110
+ enable_dns_rebinding_protection=True,
111
+ allowed_hosts=allowed_hosts,
112
+ allowed_origins=[f"http://{value}" for value in allowed_hosts],
113
+ ),
114
+ )
115
+ app.tool()(search_tickets)
116
+ app.tool()(find_stations)
117
+ app.tool()(get_carriages)
118
+ app.tool()(get_route_stations)
119
+
120
+ @app.custom_route("/health", methods=["GET"], include_in_schema=False)
121
+ async def health(_: Request) -> JSONResponse:
122
+ return JSONResponse({"status": "ok", "service": "rzd-api", "version": "2.0.0"})
123
+
124
+ return app
125
+
126
+
127
+ class BearerTokenMiddleware:
128
+ """Small ASGI bearer-token guard for MCP endpoints."""
129
+
130
+ def __init__(self, app: Any, token: str) -> None:
131
+ self.app = app
132
+ self.token = token
133
+
134
+ async def __call__(
135
+ self,
136
+ scope: dict[str, Any],
137
+ receive: Callable[[], Awaitable[dict[str, Any]]],
138
+ send: Callable[[dict[str, Any]], Awaitable[None]],
139
+ ) -> None:
140
+ if scope.get("type") != "http" or scope.get("path") == "/health":
141
+ await self.app(scope, receive, send)
142
+ return
143
+
144
+ headers = _headers(scope)
145
+ authorization = headers.get("authorization", "")
146
+ scheme, _, candidate = authorization.partition(" ")
147
+ if scheme.lower() != "bearer" or not secrets.compare_digest(candidate, self.token):
148
+ await _json_response(
149
+ send,
150
+ 401,
151
+ {"error": "unauthorized"},
152
+ [(b"www-authenticate", b"Bearer")],
153
+ )
154
+ return
155
+ await self.app(scope, receive, send)
156
+
157
+
158
+ class RateLimitMiddleware:
159
+ """In-memory sliding-window limiter keyed by token digest or client IP."""
160
+
161
+ def __init__(self, app: Any, limit_per_minute: int = 60) -> None:
162
+ self.app = app
163
+ self.limit = limit_per_minute
164
+ self._requests: defaultdict[str, deque[float]] = defaultdict(deque)
165
+ self._lock = threading.Lock()
166
+
167
+ async def __call__(
168
+ self,
169
+ scope: dict[str, Any],
170
+ receive: Callable[[], Awaitable[dict[str, Any]]],
171
+ send: Callable[[dict[str, Any]], Awaitable[None]],
172
+ ) -> None:
173
+ if self.limit == 0 or scope.get("type") != "http" or scope.get("path") == "/health":
174
+ await self.app(scope, receive, send)
175
+ return
176
+
177
+ now = time.monotonic()
178
+ key = self._key(scope)
179
+ retry_after = 0
180
+ with self._lock:
181
+ timestamps = self._requests[key]
182
+ while timestamps and now - timestamps[0] >= 60:
183
+ timestamps.popleft()
184
+ if len(timestamps) >= self.limit:
185
+ retry_after = max(1, math.ceil(60 - (now - timestamps[0])))
186
+ else:
187
+ timestamps.append(now)
188
+
189
+ if retry_after:
190
+ await _json_response(
191
+ send,
192
+ 429,
193
+ {"error": "rate_limit_exceeded", "retry_after": retry_after},
194
+ [(b"retry-after", str(retry_after).encode("ascii"))],
195
+ )
196
+ return
197
+ await self.app(scope, receive, send)
198
+
199
+ @staticmethod
200
+ def _key(scope: dict[str, Any]) -> str:
201
+ authorization = _headers(scope).get("authorization", "")
202
+ if authorization:
203
+ return "token:" + hashlib.sha256(authorization.encode()).hexdigest()
204
+ client = scope.get("client")
205
+ return f"ip:{client[0] if client else 'unknown'}"
206
+
207
+
208
+ def build_http_app(app: Any, *, token: str | None, rate_limit: int) -> Any:
209
+ asgi_app: Any = app.streamable_http_app()
210
+ asgi_app = RateLimitMiddleware(asgi_app, rate_limit)
211
+ if token:
212
+ asgi_app = BearerTokenMiddleware(asgi_app, token)
213
+ return asgi_app
214
+
215
+
216
+ def main() -> None:
217
+ try:
218
+ transport = os.getenv("MCP_TRANSPORT", "stdio")
219
+ if transport not in {"stdio", "streamable-http"}:
220
+ raise ValueError("MCP_TRANSPORT must be 'stdio' or 'streamable-http'.")
221
+
222
+ host = os.getenv("MCP_HOST", "127.0.0.1")
223
+ port = _positive_int(os.getenv("MCP_PORT", "8000"), "MCP_PORT", maximum=65535)
224
+ rate_limit = _positive_int(
225
+ os.getenv("MCP_RATE_LIMIT_PER_MINUTE", "60"),
226
+ "MCP_RATE_LIMIT_PER_MINUTE",
227
+ allow_zero=True,
228
+ )
229
+ token = os.getenv("MCP_AUTH_TOKEN") or None
230
+
231
+ if transport == "streamable-http":
232
+ if token and len(token) < 32:
233
+ raise ValueError("MCP_AUTH_TOKEN must contain at least 32 characters.")
234
+ if not _is_loopback(host) and not token:
235
+ raise ValueError("MCP_AUTH_TOKEN is required when MCP_HOST is not loopback.")
236
+
237
+ app = create_mcp_app(host=host, port=port)
238
+ if transport == "stdio":
239
+ app.run(transport="stdio")
240
+ return
241
+
242
+ import uvicorn
243
+
244
+ uvicorn.run(
245
+ build_http_app(app, token=token, rate_limit=rate_limit),
246
+ host=host,
247
+ port=port,
248
+ log_level=os.getenv("MCP_LOG_LEVEL", "info").lower(),
249
+ )
250
+ except (RuntimeError, ValueError) as exc:
251
+ print(str(exc), file=sys.stderr)
252
+ raise SystemExit(2) from exc
253
+
254
+
255
+ def _allowed_hosts(host: str) -> list[str]:
256
+ configured = os.getenv("MCP_ALLOWED_HOSTS")
257
+ if configured:
258
+ return [item.strip() for item in configured.split(",") if item.strip()]
259
+ hosts = ["127.0.0.1:*", "localhost:*", "[::1]:*"]
260
+ if host not in {"0.0.0.0", "::"} and not _is_loopback(host):
261
+ hosts.append(f"{host}:*")
262
+ return hosts
263
+
264
+
265
+ def _is_loopback(host: str) -> bool:
266
+ if host.casefold() == "localhost":
267
+ return True
268
+ try:
269
+ return ipaddress.ip_address(host).is_loopback
270
+ except ValueError:
271
+ return False
272
+
273
+
274
+ def _positive_int(
275
+ value: str,
276
+ name: str,
277
+ *,
278
+ maximum: int | None = None,
279
+ allow_zero: bool = False,
280
+ ) -> int:
281
+ try:
282
+ parsed = int(value)
283
+ except ValueError as exc:
284
+ raise ValueError(f"{name} must be an integer.") from exc
285
+ minimum = 0 if allow_zero else 1
286
+ if parsed < minimum or (maximum is not None and parsed > maximum):
287
+ raise ValueError(f"{name} must be between {minimum} and {maximum or 'unbounded'}.")
288
+ return parsed
289
+
290
+
291
+ def _headers(scope: dict[str, Any]) -> dict[str, str]:
292
+ return {
293
+ key.decode("latin-1").lower(): value.decode("latin-1")
294
+ for key, value in scope.get("headers", [])
295
+ }
296
+
297
+
298
+ async def _json_response(
299
+ send: Callable[[dict[str, Any]], Awaitable[None]],
300
+ status: int,
301
+ body: dict[str, Any],
302
+ extra_headers: list[tuple[bytes, bytes]],
303
+ ) -> None:
304
+ import json
305
+
306
+ content = json.dumps(body).encode("utf-8")
307
+ headers = [(b"content-type", b"application/json"), *extra_headers]
308
+ await send({"type": "http.response.start", "status": status, "headers": headers})
309
+ await send({"type": "http.response.body", "body": content})
310
+
311
+
312
+ if __name__ == "__main__":
313
+ main()