|
3 | 3 | from __future__ import annotations |
4 | 4 |
|
5 | 5 | import contextlib |
| 6 | +import json |
6 | 7 | import logging |
7 | 8 | import math |
| 9 | +from collections import deque |
8 | 10 | from collections.abc import AsyncIterator |
9 | | -from typing import TYPE_CHECKING, Any, Final |
| 11 | +from typing import TYPE_CHECKING, Any, Final, cast |
10 | 12 | from uuid import uuid4 |
11 | 13 |
|
12 | 14 | import anyio |
|
26 | 28 | from mcp.server.transport_security import RequestBodyLimitMiddleware as RequestBodyLimitMiddleware |
27 | 29 | from mcp.server.transport_security import TransportSecuritySettings |
28 | 30 | from mcp.shared._compat import resync_tracer |
29 | | -from mcp.shared.inbound import MCP_PROTOCOL_VERSION_HEADER |
| 31 | +from mcp.shared.inbound import MCP_PROTOCOL_VERSION_HEADER, has_modern_envelope |
30 | 32 | from mcp.shared.jsonrpc_dispatcher import JSONRPCDispatcher |
31 | 33 | from mcp.shared.transport_context import TransportContext |
32 | 34 |
|
|
42 | 44 | """Default maximum number of concurrent stateful Streamable HTTP sessions per session manager.""" |
43 | 45 |
|
44 | 46 |
|
| 47 | +async def _peek_modern_envelope(receive: Receive) -> tuple[Receive, bool]: |
| 48 | + """Read the POST body and report whether it is a request carrying the 2026-07-28 envelope. |
| 49 | +
|
| 50 | + Returns a `receive` that replays everything read, so the chosen handler sees the body untouched. |
| 51 | + The body is already complete and size-limited by `RequestBodyLimitMiddleware`. An unparseable |
| 52 | + body, a notification, a batch and `initialize` are not evidence of the modern era and stay on the |
| 53 | + legacy path, which owns their errors. |
| 54 | + """ |
| 55 | + messages: deque[Message] = deque() |
| 56 | + body = bytearray() |
| 57 | + while True: |
| 58 | + message = await receive() |
| 59 | + messages.append(message) |
| 60 | + if message["type"] != "http.request": |
| 61 | + break |
| 62 | + body.extend(message.get("body", b"")) |
| 63 | + if not message.get("more_body", False): |
| 64 | + break |
| 65 | + |
| 66 | + async def replay() -> Message: |
| 67 | + return messages.popleft() if messages else await receive() |
| 68 | + |
| 69 | + try: |
| 70 | + decoded: Any = json.loads(body) |
| 71 | + except (ValueError, RecursionError): |
| 72 | + return replay, False |
| 73 | + if not isinstance(decoded, dict): |
| 74 | + return replay, False |
| 75 | + request = cast("dict[str, Any]", decoded) |
| 76 | + if "id" not in request or request.get("method") == "initialize": |
| 77 | + return replay, False |
| 78 | + params: Any = request.get("params") |
| 79 | + return replay, isinstance(params, dict) and has_modern_envelope(cast("dict[str, Any]", params)) |
| 80 | + |
| 81 | + |
45 | 82 | class StreamableHTTPSessionManager: |
46 | 83 | """Manages StreamableHTTP sessions with optional resumability via event store. |
47 | 84 |
|
@@ -184,18 +221,27 @@ async def _handle_request(self, scope: Scope, receive: Receive, send: Send) -> N |
184 | 221 | if self._task_group is None: |
185 | 222 | raise RuntimeError("Task group is not initialized. Make sure to use run().") |
186 | 223 |
|
187 | | - # TODO(L49): header-only era-routing for now; body-primary classification |
188 | | - # is a follow-up. The legacy paths below own only the known |
189 | | - # initialize-handshake versions; anything else (including unknown |
190 | | - # values) goes to the modern entry so the classifier can validate it |
191 | | - # and return a structured rejection. 2025 paths below remain unchanged. |
| 224 | + # The legacy paths below own only the known initialize-handshake versions; |
| 225 | + # anything else (including unknown values) goes to the modern entry so |
| 226 | + # the classifier can validate it and return a structured rejection. A |
| 227 | + # request that carries the 2026-07-28 `_meta` envelope goes there too, |
| 228 | + # whatever its header says, so the classifier answers a header that |
| 229 | + # disagrees with the envelope (or is absent) with HeaderMismatch rather |
| 230 | + # than the legacy path serving it as a 2025 request. |
192 | 231 | header = MCP_PROTOCOL_VERSION_HEADER.encode("ascii") |
193 | 232 | pv = next((v.decode("latin-1") for k, v in scope["headers"] if k == header), None) |
194 | 233 | if pv is not None and pv not in HANDSHAKE_PROTOCOL_VERSIONS: |
195 | 234 | await handle_modern_request( |
196 | 235 | self.app, self.security_settings, self.json_response, self._lifespan_state, scope, receive, send |
197 | 236 | ) |
198 | 237 | return |
| 238 | + if scope["method"] == "POST": |
| 239 | + receive, carries_modern_envelope = await _peek_modern_envelope(receive) |
| 240 | + if carries_modern_envelope: |
| 241 | + await handle_modern_request( |
| 242 | + self.app, self.security_settings, self.json_response, self._lifespan_state, scope, receive, send |
| 243 | + ) |
| 244 | + return |
199 | 245 |
|
200 | 246 | # Dispatch to the appropriate handler |
201 | 247 | if self.stateless: |
|
0 commit comments