From f0c1c200a395a6ec7eba462801454f58537fa8fb Mon Sep 17 00:00:00 2001 From: Andre Vegas <8179406+andrevegas@users.noreply.github.com> Date: Tue, 17 Nov 2026 16:49:14 -0500 Subject: [PATCH 1/2] Route Streamable HTTP era from the request envelope, not only the header StreamableHTTPSessionManager chose the protocol era from the MCP-Protocol-Version header alone, so a request carrying the 2026-07-28 `_meta` envelope with a 2025-era or missing header was served by the legacy path: tools/list answered 200 with a 2025-shaped result and modern-only methods such as server/discover answered 200 with -32601. The 2026-07-28 transport requires 400 with HeaderMismatch (-32020) when the header does not match the envelope. Peek at the POST body (already buffered and size-limited by RequestBodyLimitMiddleware) and send requests that carry the envelope to the modern entry, whose classifier already produces HeaderMismatch. The body is replayed untouched. Unparseable bodies, notifications, batches and `initialize` stay on the legacy path, as in the stdio runner. Share the era predicate as mcp.shared.inbound.has_modern_envelope so stdio and HTTP use one definition. Refs #3863 Co-Authored-By: Claude Sonnet 5.5 --- src/mcp/server/runner.py | 22 +-- src/mcp/server/streamable_http_manager.py | 60 ++++++- src/mcp/shared/inbound.py | 17 ++ tests/server/test_runner.py | 16 +- tests/server/test_streamable_http_manager.py | 163 ++++++++++++++++++- 5 files changed, 243 insertions(+), 35 deletions(-) diff --git a/src/mcp/server/runner.py b/src/mcp/server/runner.py index 26e8efbe57..fa2012e319 100644 --- a/src/mcp/server/runner.py +++ b/src/mcp/server/runner.py @@ -64,7 +64,7 @@ from mcp.shared._stream_protocols import ReadStream, WriteStream from mcp.shared.dispatcher import CallOptions, DispatchContext, Dispatcher, OnNotify, OnRequest from mcp.shared.exceptions import MCPError, NoBackChannelError -from mcp.shared.inbound import InboundLadderRejection, classify_inbound_request +from mcp.shared.inbound import InboundLadderRejection, classify_inbound_request, has_modern_envelope from mcp.shared.jsonrpc_dispatcher import JSONRPCDispatcher, handler_exception_to_error_data from mcp.shared.message import MessageMetadata, ServerMessageMetadata, SessionMessage from mcp.shared.transport_context import TransportContext @@ -501,22 +501,6 @@ async def serve_loop( ) -def _has_modern_envelope(params: Mapping[str, Any] | None) -> bool: - """Whether `params._meta` carries the reserved protocol-version key. - - The `io.modelcontextprotocol/protocolVersion` key exists only in - 2026-07-28+ envelopes and its prefix is spec-reserved, so legacy traffic - never mints it (a bare `_meta` is not evidence - legacy requests carry - `progressToken` there). The version key alone is the signal, not the full - required pair, so a half-built envelope still routes modern and gets the - classifier's INVALID_PARAMS naming the missing key. - """ - if not params: - return False - meta = params.get("_meta") - return isinstance(meta, Mapping) and PROTOCOL_VERSION_META_KEY in meta - - def _initialize_after_modern_data(params: Mapping[str, Any] | None) -> dict[str, Any]: """Error data for an `initialize` arriving on a modern-locked connection. @@ -626,7 +610,7 @@ async def serve_dual_era_loop( try: async with _replay_from_opening_request(read_stream) as (opening, replayed): opens_modern = ( - opening is not None and opening.method != "initialize" and _has_modern_envelope(opening.params) + opening is not None and opening.method != "initialize" and has_modern_envelope(opening.params) ) if opens_modern: await _serve_modern_stream( @@ -738,7 +722,7 @@ async def _serve_legacy_stream( async def on_request( dctx: DispatchContext[TransportContext], method: str, params: Mapping[str, Any] | None ) -> dict[str, Any]: - if method != "initialize" and _has_modern_envelope(params): + if method != "initialize" and has_modern_envelope(params): raise MCPError( code=INVALID_REQUEST, message="this connection serves the handshake protocol era; " diff --git a/src/mcp/server/streamable_http_manager.py b/src/mcp/server/streamable_http_manager.py index a7efac3fbc..9ff1412838 100644 --- a/src/mcp/server/streamable_http_manager.py +++ b/src/mcp/server/streamable_http_manager.py @@ -3,10 +3,12 @@ from __future__ import annotations import contextlib +import json import logging import math +from collections import deque from collections.abc import AsyncIterator -from typing import TYPE_CHECKING, Any, Final +from typing import TYPE_CHECKING, Any, Final, cast from uuid import uuid4 import anyio @@ -26,7 +28,7 @@ from mcp.server.transport_security import RequestBodyLimitMiddleware as RequestBodyLimitMiddleware from mcp.server.transport_security import TransportSecuritySettings from mcp.shared._compat import resync_tracer -from mcp.shared.inbound import MCP_PROTOCOL_VERSION_HEADER +from mcp.shared.inbound import MCP_PROTOCOL_VERSION_HEADER, has_modern_envelope from mcp.shared.jsonrpc_dispatcher import JSONRPCDispatcher from mcp.shared.transport_context import TransportContext @@ -42,6 +44,41 @@ """Default maximum number of concurrent stateful Streamable HTTP sessions per session manager.""" +async def _peek_modern_envelope(receive: Receive) -> tuple[Receive, bool]: + """Read the POST body and report whether it is a request carrying the 2026-07-28 envelope. + + Returns a `receive` that replays everything read, so the chosen handler sees the body untouched. + The body is already complete and size-limited by `RequestBodyLimitMiddleware`. An unparseable + body, a notification, a batch and `initialize` are not evidence of the modern era and stay on the + legacy path, which owns their errors. + """ + messages: deque[Message] = deque() + body = bytearray() + while True: + message = await receive() + messages.append(message) + if message["type"] != "http.request": + break + body.extend(message.get("body", b"")) + if not message.get("more_body", False): + break + + async def replay() -> Message: + return messages.popleft() if messages else await receive() + + try: + decoded: Any = json.loads(body) + except (ValueError, RecursionError): + return replay, False + if not isinstance(decoded, dict): + return replay, False + request = cast("dict[str, Any]", decoded) + if "id" not in request or request.get("method") == "initialize": + return replay, False + params: Any = request.get("params") + return replay, isinstance(params, dict) and has_modern_envelope(cast("dict[str, Any]", params)) + + class StreamableHTTPSessionManager: """Manages StreamableHTTP sessions with optional resumability via event store. @@ -184,11 +221,13 @@ async def _handle_request(self, scope: Scope, receive: Receive, send: Send) -> N if self._task_group is None: raise RuntimeError("Task group is not initialized. Make sure to use run().") - # TODO(L49): header-only era-routing for now; body-primary classification - # is a follow-up. The legacy paths below own only the known - # initialize-handshake versions; anything else (including unknown - # values) goes to the modern entry so the classifier can validate it - # and return a structured rejection. 2025 paths below remain unchanged. + # The legacy paths below own only the known initialize-handshake versions; + # anything else (including unknown values) goes to the modern entry so + # the classifier can validate it and return a structured rejection. A + # request that carries the 2026-07-28 `_meta` envelope goes there too, + # whatever its header says, so the classifier answers a header that + # disagrees with the envelope (or is absent) with HeaderMismatch rather + # than the legacy path serving it as a 2025 request. header = MCP_PROTOCOL_VERSION_HEADER.encode("ascii") pv = next((v.decode("latin-1") for k, v in scope["headers"] if k == header), None) if pv is not None and pv not in HANDSHAKE_PROTOCOL_VERSIONS: @@ -196,6 +235,13 @@ async def _handle_request(self, scope: Scope, receive: Receive, send: Send) -> N self.app, self.security_settings, self.json_response, self._lifespan_state, scope, receive, send ) return + if scope["method"] == "POST": + receive, carries_modern_envelope = await _peek_modern_envelope(receive) + if carries_modern_envelope: + await handle_modern_request( + self.app, self.security_settings, self.json_response, self._lifespan_state, scope, receive, send + ) + return # Dispatch to the appropriate handler if self.stateless: diff --git a/src/mcp/shared/inbound.py b/src/mcp/shared/inbound.py index e33d6f502f..003d6703e0 100644 --- a/src/mcp/shared/inbound.py +++ b/src/mcp/shared/inbound.py @@ -51,6 +51,7 @@ "encode_header_value", "find_duplicated_routing_header", "find_invalid_x_mcp_header", + "has_modern_envelope", "mcp_param_headers", "unsupported_protocol_version_rejection", "validate_mcp_param_headers", @@ -351,6 +352,22 @@ class InboundLadderRejection: _ROUTING_HEADER_NAMES: Final = frozenset({MCP_PROTOCOL_VERSION_HEADER, MCP_METHOD_HEADER, MCP_NAME_HEADER}) +def has_modern_envelope(params: Mapping[str, Any] | None) -> bool: + """Whether `params._meta` carries the reserved protocol-version key. + + The `io.modelcontextprotocol/protocolVersion` key exists only in + 2026-07-28+ envelopes and its prefix is spec-reserved, so legacy traffic + never mints it (a bare `_meta` is not evidence - legacy requests carry + `progressToken` there). The version key alone is the signal, not the full + required pair, so a half-built envelope still routes modern and gets the + classifier's INVALID_PARAMS naming the missing key. + """ + if not params: + return False + meta = params.get("_meta") + return isinstance(meta, Mapping) and PROTOCOL_VERSION_META_KEY in meta + + def find_duplicated_routing_header(headers: Iterable[tuple[str, str]]) -> str | None: """Name of a routing header supplied more than once in raw header lines, or `None`. diff --git a/tests/server/test_runner.py b/tests/server/test_runner.py index 1e2ab741b7..db397b06dc 100644 --- a/tests/server/test_runner.py +++ b/tests/server/test_runner.py @@ -65,7 +65,6 @@ from mcp.server.runner import ( ServerRunner, _extract_meta, - _has_modern_envelope, _initialize_after_modern_data, _NoServerRequestsDispatchContext, aclose_shielded, @@ -78,6 +77,7 @@ from mcp.shared._context_streams import create_context_streams from mcp.shared.dispatcher import CallOptions from mcp.shared.exceptions import MCPError, NoBackChannelError +from mcp.shared.inbound import has_modern_envelope from mcp.shared.jsonrpc_dispatcher import JSONRPCDispatcher from mcp.shared.message import MessageMetadata, SessionMessage from mcp.shared.peer import dump_params @@ -1931,15 +1931,15 @@ def test_has_modern_envelope_keys_on_the_protocol_version_key(): never mints it (bare `_meta` / `progressToken` is not evidence), and a half-built envelope still routes modern so the classifier - not the legacy path - names its missing required key.""" - assert not _has_modern_envelope(None) - assert not _has_modern_envelope({}) - assert not _has_modern_envelope({"_meta": None}) - assert not _has_modern_envelope({"_meta": {"progressToken": 1}}) + assert not has_modern_envelope(None) + assert not has_modern_envelope({}) + assert not has_modern_envelope({"_meta": None}) + assert not has_modern_envelope({"_meta": {"progressToken": 1}}) version_only = {PROTOCOL_VERSION_META_KEY: LATEST_MODERN_VERSION} - assert _has_modern_envelope({"_meta": version_only}) + assert has_modern_envelope({"_meta": version_only}) pair_only = {k: v for k, v in _modern_envelope().items() if k != CLIENT_INFO_META_KEY} - assert _has_modern_envelope({"_meta": pair_only}) - assert _has_modern_envelope(_modern_params()) + assert has_modern_envelope({"_meta": pair_only}) + assert has_modern_envelope(_modern_params()) def test_initialize_after_modern_data_arms(): diff --git a/tests/server/test_streamable_http_manager.py b/tests/server/test_streamable_http_manager.py index 1b8f9264f1..05419ff127 100644 --- a/tests/server/test_streamable_http_manager.py +++ b/tests/server/test_streamable_http_manager.py @@ -12,15 +12,17 @@ import httpx2 import pytest from mcp_types import ( + HEADER_MISMATCH, INTERNAL_ERROR, INVALID_REQUEST, + PARSE_ERROR, CallToolRequestParams, CallToolResult, ListToolsResult, PaginatedRequestParams, TextContent, ) -from mcp_types.version import LATEST_HANDSHAKE_VERSION +from mcp_types.version import LATEST_HANDSHAKE_VERSION, LATEST_MODERN_VERSION from starlette.applications import Starlette from starlette.routing import Mount from starlette.types import ASGIApp, Message, Receive, Scope, Send @@ -36,7 +38,9 @@ DEFAULT_MAX_SESSIONS, DEFAULT_SESSION_IDLE_TIMEOUT, StreamableHTTPSessionManager, + _peek_modern_envelope, ) +from tests.interaction._connect import base_headers, initialize_via_http, mounted_app from tests.interaction.transports import StreamingASGITransport # The in-process app is mounted at this origin purely so URLs are well-formed; nothing listens here. @@ -1065,3 +1069,160 @@ async def test_anonymous_session_accepts_anonymous_requests( session_id = await _open_session(manager, None) assert await _request_session(manager, session_id, None) != 404 + + +def _era_routing_server() -> Server: + async def list_tools(ctx: ServerRequestContext, params: PaginatedRequestParams | None) -> ListToolsResult: + return ListToolsResult(tools=[], ttl_ms=0, cache_scope="public") + + return Server("era-routing", on_list_tools=list_tools) + + +def _modern_params() -> dict[str, Any]: + return { + "_meta": { + "io.modelcontextprotocol/protocolVersion": LATEST_MODERN_VERSION, + "io.modelcontextprotocol/clientCapabilities": {}, + } + } + + +def _rpc_body(method: str, params: dict[str, Any]) -> dict[str, Any]: + return {"jsonrpc": "2.0", "id": 1, "method": method, "params": params} + + +def _rpc_message(response: httpx2.Response) -> dict[str, Any]: + """Decode the JSON-RPC reply, whether it travelled as JSON or as a single SSE event.""" + if response.headers["content-type"].startswith("text/event-stream"): + data = next(line[len("data:") :] for line in response.text.splitlines() if line.startswith("data:")) + return json.loads(data) + return response.json() + + +@pytest.mark.anyio +@pytest.mark.parametrize("stateless", [True, False]) +@pytest.mark.parametrize("method", ["tools/list", "server/discover"]) +@pytest.mark.parametrize("header_version", [LATEST_HANDSHAKE_VERSION, None]) +async def test_modern_envelope_with_a_missing_or_2025_version_header_is_a_header_mismatch( + stateless: bool, method: str, header_version: str | None +) -> None: + """The envelope, not the header, decides the era: a header that disagrees is HeaderMismatch.""" + headers = base_headers() | {"mcp-method": method} + if header_version is not None: + headers["mcp-protocol-version"] = header_version + async with mounted_app(_era_routing_server(), stateless_http=stateless) as (http, _): + response = await http.post("/mcp", json=_rpc_body(method, _modern_params()), headers=headers) + + assert response.status_code == 400 + assert _rpc_message(response)["error"]["code"] == HEADER_MISMATCH + + +@pytest.mark.anyio +async def test_modern_envelope_with_a_matching_header_is_still_served() -> None: + headers = base_headers() | {"mcp-protocol-version": LATEST_MODERN_VERSION, "mcp-method": "tools/list"} + async with mounted_app(_era_routing_server(), stateless_http=True) as (http, _): + response = await http.post("/mcp", json=_rpc_body("tools/list", _modern_params()), headers=headers) + + assert response.status_code == 200 + assert _rpc_message(response)["result"]["resultType"] == "complete" + + +@pytest.mark.anyio +@pytest.mark.parametrize("params", [{}, {"_meta": {"progressToken": "p1"}}]) +async def test_2025_request_without_an_envelope_is_served_as_legacy(params: dict[str, Any]) -> None: + """A bare `_meta` (progress tokens) is not era evidence; the body reaches the legacy handler intact.""" + headers = base_headers() | {"mcp-protocol-version": LATEST_HANDSHAKE_VERSION} + async with mounted_app(_era_routing_server(), stateless_http=True) as (http, _): + response = await http.post("/mcp", json=_rpc_body("tools/list", params), headers=headers) + + assert response.status_code == 200 + result = _rpc_message(response)["result"] + assert result["tools"] == [] + assert "resultType" not in result + + +@pytest.mark.anyio +async def test_stateful_2025_session_is_unaffected_by_the_body_peek() -> None: + async with mounted_app(_era_routing_server()) as (http, _): + session_id = await initialize_via_http(http) + headers = base_headers(session_id=session_id) | {"mcp-protocol-version": LATEST_HANDSHAKE_VERSION} + response = await http.post("/mcp", json=_rpc_body("tools/list", {}), headers=headers) + + assert response.status_code == 200 + assert _rpc_message(response)["result"]["tools"] == [] + + +@pytest.mark.anyio +async def test_unparseable_2025_body_keeps_its_legacy_parse_error() -> None: + headers = base_headers() | {"mcp-protocol-version": LATEST_HANDSHAKE_VERSION} + async with mounted_app(_era_routing_server(), stateless_http=True) as (http, _): + response = await http.post("/mcp", content=b"{not json", headers=headers) + + assert response.status_code == 400 + assert _rpc_message(response)["error"]["code"] == PARSE_ERROR + + +@pytest.mark.anyio +@pytest.mark.parametrize( + ("body", "status"), + [ + pytest.param( + {"jsonrpc": "2.0", "method": "notifications/initialized", "params": _modern_params()}, + 202, + id="notification", + ), + pytest.param( + { + "jsonrpc": "2.0", + "id": 1, + "method": "initialize", + "params": { + "protocolVersion": LATEST_HANDSHAKE_VERSION, + "capabilities": {}, + "clientInfo": {"name": "client", "version": "1"}, + **_modern_params(), + }, + }, + 200, + id="initialize", + ), + pytest.param([_rpc_body("tools/list", _modern_params())], 400, id="batch"), + ], +) +async def test_messages_that_are_not_modern_requests_stay_on_the_legacy_path(body: Any, status: int) -> None: + """Notifications, `initialize` and batches are not routed on the envelope, even if they carry one.""" + headers = base_headers() | {"mcp-protocol-version": LATEST_HANDSHAKE_VERSION} + async with mounted_app(_era_routing_server(), stateless_http=True) as (http, _): + response = await http.post("/mcp", json=body, headers=headers) + + assert response.status_code == status + assert "-32020" not in response.text + + +@pytest.mark.anyio +async def test_peek_replays_every_message_then_defers_to_the_underlying_receive() -> None: + messages: list[Message] = [ + {"type": "http.request", "body": b'{"jsonrpc":"2.0","id":1,', "more_body": True}, + {"type": "http.request", "body": b'"method":"ping"}', "more_body": False}, + {"type": "http.disconnect"}, + ] + pending = iter(messages) + + async def receive() -> Message: + return next(pending) + + replay, carries_modern_envelope = await _peek_modern_envelope(receive) + + assert carries_modern_envelope is False + assert [await replay(), await replay(), await replay()] == messages + + +@pytest.mark.anyio +async def test_peek_stops_at_a_disconnect_without_a_body() -> None: + async def receive() -> Message: + return {"type": "http.disconnect"} + + replay, carries_modern_envelope = await _peek_modern_envelope(receive) + + assert carries_modern_envelope is False + assert await replay() == {"type": "http.disconnect"} From 72bd9f348a1f2cb0bb9f4d83a834ac19e453ef59 Mon Sep 17 00:00:00 2001 From: Andre Vegas <8179406+andrevegas@users.noreply.github.com> Date: Tue, 17 Nov 2026 16:49:14 -0500 Subject: [PATCH 2/2] Judge an enveloped initialize against its header, and update the routing docs An `initialize` carrying the reserved 2026-07-28 version key with a 2025-era or missing header was still served by the legacy handshake, so the same body got a successful handshake or a modern rejection depending only on the header. A handshake never carries the reserved key, so route it like any other enveloped request and let the modern entry answer HeaderMismatch. Ordinary legacy `initialize` requests are unchanged and covered by tests. Document that routing now also considers the 2026-07-28 envelope. Refs #3863 Co-Authored-By: Claude Sonnet 5.5 --- docs/run/deploy.md | 2 +- docs/run/legacy-clients.md | 4 +-- src/mcp/server/streamable_http_manager.py | 7 ++-- tests/server/test_streamable_http_manager.py | 34 ++++++++++---------- 4 files changed, 24 insertions(+), 23 deletions(-) diff --git a/docs/run/deploy.md b/docs/run/deploy.md index 5e891fe3ba..46f1ad130a 100644 --- a/docs/run/deploy.md +++ b/docs/run/deploy.md @@ -70,7 +70,7 @@ Four processes, one socket. And now the question every deployment has to answer: For a client speaking the **2026-07-28** protocol, no. A modern request is one self-contained POST: no `initialize` handshake before it, no `Mcp-Session-Id` on the response, nothing for a second request to come back *to*. Route it to any worker. -That is not a mode you switch on. `stateless_http=True` looks like it should be, but the transport routes on the `MCP-Protocol-Version` request header, hands a modern request to the modern handler, and **returns**. The line that reads `stateless_http` comes *after* that return. It isn't that the flag is ignored on the 2026-07-28 path; it is never reached. `stateless_http` is a knob for the **legacy** leg only, and the modern path is sessionless by construction. +That is not a mode you switch on. `stateless_http=True` looks like it should be, but the transport routes on the `MCP-Protocol-Version` request header (and the request's `_meta` envelope), hands a modern request to the modern handler, and **returns**. The line that reads `stateless_http` comes *after* that return. It isn't that the flag is ignored on the 2026-07-28 path; it is never reached. `stateless_http` is a knob for the **legacy** leg only, and the modern path is sessionless by construction. For a legacy client on spec version 2025-11-25 or earlier, the answer depends on that flag: diff --git a/docs/run/legacy-clients.md b/docs/run/legacy-clients.md index 15809fd608..550b006bd1 100644 --- a/docs/run/legacy-clients.md +++ b/docs/run/legacy-clients.md @@ -4,7 +4,7 @@ MCP has two protocol eras: the `initialize`-handshake era, up to spec version `2 This page is about the server side of that split, and the answer fits in one sentence: **the `streamable_http_app()` you already deploy serves both.** -The SDK routes every request by its `MCP-Protocol-Version` header. A request naming `2026-07-28` goes to the modern handler. A request naming a handshake-era version, or carrying no header at all (which is how a pre-2026 client's `initialize` arrives), goes to the transport those clients expect: `initialize` handshake, sessions and all. It happens per request, before your code, on the one app. +The SDK routes every request by its `MCP-Protocol-Version` header and its body. A request naming `2026-07-28`, or carrying the 2026-07-28 `_meta` envelope, goes to the modern handler; if such a request's header is missing or names another version, it is rejected with `400` and `HeaderMismatch` (`-32020`). Any other request naming a handshake-era version, or carrying no header at all (which is how a pre-2026 client's `initialize` arrives), goes to the transport those clients expect: `initialize` handshake, sessions and all. It happens per request, before your code, on the one app. So a legacy client is not something you build *for*. It is something that connects *to* the server you already wrote. You configure nothing. @@ -163,7 +163,7 @@ Two lines, no `if`, no version check, and you are done. That is the entire list ## Recap -* One `streamable_http_app()` serves both protocol eras. The SDK routes each request by its `MCP-Protocol-Version` header; there is nothing to configure and no era knob to look for. +* One `streamable_http_app()` serves both protocol eras. The SDK routes each request by its `MCP-Protocol-Version` header and, for requests carrying the 2026-07-28 envelope, its body; there is nothing to configure and no era knob to look for. * A legacy client costs you a session: an in-process `Mcp-Session-Id` record with no distributed store behind it. More than one worker means **sticky routing**, or the wrong worker answers `404 Session not found`. **[Deploy & scale](deploy.md)** has the multi-worker story. * `stateless_http=True` is the one knob, and it is **legacy-leg-only**. It buys free load balancing for legacy clients at the price of both server-to-client channels on that leg: server-initiated requests raise `NoBackChannelError` (a top-level error at the client, not an `is_error` result), and notifications are dropped. * A `2026-07-28` connection is sessionless either way. `stateless_http` never touches it. diff --git a/src/mcp/server/streamable_http_manager.py b/src/mcp/server/streamable_http_manager.py index 9ff1412838..319647db11 100644 --- a/src/mcp/server/streamable_http_manager.py +++ b/src/mcp/server/streamable_http_manager.py @@ -49,8 +49,9 @@ async def _peek_modern_envelope(receive: Receive) -> tuple[Receive, bool]: Returns a `receive` that replays everything read, so the chosen handler sees the body untouched. The body is already complete and size-limited by `RequestBodyLimitMiddleware`. An unparseable - body, a notification, a batch and `initialize` are not evidence of the modern era and stay on the - legacy path, which owns their errors. + body, a notification and a batch are not routed on the envelope and stay on the legacy path, + which owns their errors. `initialize` is routed like any other request: a handshake never carries + the reserved version key, so an enveloped one is judged against its header by the modern entry. """ messages: deque[Message] = deque() body = bytearray() @@ -73,7 +74,7 @@ async def replay() -> Message: if not isinstance(decoded, dict): return replay, False request = cast("dict[str, Any]", decoded) - if "id" not in request or request.get("method") == "initialize": + if "id" not in request: return replay, False params: Any = request.get("params") return replay, isinstance(params, dict) and has_modern_envelope(cast("dict[str, Any]", params)) diff --git a/tests/server/test_streamable_http_manager.py b/tests/server/test_streamable_http_manager.py index 05419ff127..f72ea95adc 100644 --- a/tests/server/test_streamable_http_manager.py +++ b/tests/server/test_streamable_http_manager.py @@ -1101,7 +1101,7 @@ def _rpc_message(response: httpx2.Response) -> dict[str, Any]: @pytest.mark.anyio @pytest.mark.parametrize("stateless", [True, False]) -@pytest.mark.parametrize("method", ["tools/list", "server/discover"]) +@pytest.mark.parametrize("method", ["tools/list", "server/discover", "initialize"]) @pytest.mark.parametrize("header_version", [LATEST_HANDSHAKE_VERSION, None]) async def test_modern_envelope_with_a_missing_or_2025_version_header_is_a_header_mismatch( stateless: bool, method: str, header_version: str | None @@ -1171,26 +1171,11 @@ async def test_unparseable_2025_body_keeps_its_legacy_parse_error() -> None: 202, id="notification", ), - pytest.param( - { - "jsonrpc": "2.0", - "id": 1, - "method": "initialize", - "params": { - "protocolVersion": LATEST_HANDSHAKE_VERSION, - "capabilities": {}, - "clientInfo": {"name": "client", "version": "1"}, - **_modern_params(), - }, - }, - 200, - id="initialize", - ), pytest.param([_rpc_body("tools/list", _modern_params())], 400, id="batch"), ], ) async def test_messages_that_are_not_modern_requests_stay_on_the_legacy_path(body: Any, status: int) -> None: - """Notifications, `initialize` and batches are not routed on the envelope, even if they carry one.""" + """Notifications and batches are not routed on the envelope, even if they carry one.""" headers = base_headers() | {"mcp-protocol-version": LATEST_HANDSHAKE_VERSION} async with mounted_app(_era_routing_server(), stateless_http=True) as (http, _): response = await http.post("/mcp", json=body, headers=headers) @@ -1226,3 +1211,18 @@ async def receive() -> Message: assert carries_modern_envelope is False assert await replay() == {"type": "http.disconnect"} + + +@pytest.mark.anyio +async def test_legacy_initialize_without_an_envelope_still_completes_the_handshake() -> None: + headers = base_headers() | {"mcp-protocol-version": LATEST_HANDSHAKE_VERSION} + params = { + "protocolVersion": LATEST_HANDSHAKE_VERSION, + "capabilities": {}, + "clientInfo": {"name": "client", "version": "1"}, + } + async with mounted_app(_era_routing_server(), stateless_http=True) as (http, _): + response = await http.post("/mcp", json=_rpc_body("initialize", params), headers=headers) + + assert response.status_code == 200 + assert _rpc_message(response)["result"]["protocolVersion"] == LATEST_HANDSHAKE_VERSION