From 56de8cceb681aa28ea16b7df696a939dca29d6e9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?K=C3=BCr=C5=9Fat=20Y=C4=B1lmaz?= <141324500+DevKursat@users.noreply.github.com> Date: Wed, 18 Nov 2026 23:29:28 +0300 Subject: [PATCH] fix(server): route POST requests carrying 2026-07-28 _meta envelope to modern handler --- src/mcp/server/runner.py | 17 ++---- src/mcp/server/streamable_http_manager.py | 54 +++++++++++++++++++- src/mcp/shared/inbound.py | 16 ++++++ tests/server/test_streamable_http_manager.py | 44 ++++++++++++++++ 4 files changed, 116 insertions(+), 15 deletions(-) diff --git a/src/mcp/server/runner.py b/src/mcp/server/runner.py index 26e8efbe57..d96f38c0f8 100644 --- a/src/mcp/server/runner.py +++ b/src/mcp/server/runner.py @@ -502,19 +502,10 @@ 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 + """Whether `params._meta` carries the reserved protocol-version key.""" + from mcp.shared.inbound import has_modern_envelope + + return has_modern_envelope(params) def _initialize_after_modern_data(params: Mapping[str, Any] | None) -> dict[str, Any]: diff --git a/src/mcp/server/streamable_http_manager.py b/src/mcp/server/streamable_http_manager.py index a7efac3fbc..99b4f8c30f 100644 --- a/src/mcp/server/streamable_http_manager.py +++ b/src/mcp/server/streamable_http_manager.py @@ -3,10 +3,11 @@ from __future__ import annotations import contextlib +import json import logging import math 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 +27,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 @@ -197,6 +198,14 @@ async def _handle_request(self, scope: Scope, receive: Receive, send: Send) -> N ) return + if scope["method"] == "POST": + raw_body, receive = await _buffer_and_replay_body(receive) + if _body_has_modern_envelope(raw_body): + 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: await self._handle_stateless_request(pv, scope, receive, send) @@ -395,6 +404,47 @@ async def _discard_session(self, session_id: str, transport: StreamableHTTPServe await transport.terminate() +def _body_has_modern_envelope(raw_body: bytes) -> bool: + """Return True when a POST body carries a non-initialize 2026-07-28+ _meta envelope.""" + try: + decoded: Any = json.loads(raw_body) + except (ValueError, RecursionError): + return False + if not isinstance(decoded, dict): + return False + payload = cast("dict[str, Any]", decoded) + if payload.get("method") == "initialize": + return False + raw_params: Any = payload.get("params") + return isinstance(raw_params, dict) and has_modern_envelope(cast("dict[str, Any]", raw_params)) + + +async def _buffer_and_replay_body(receive: Receive) -> tuple[bytes, Receive]: + """Read the ASGI request body once and return `(body_bytes, replay_receive)`.""" + buffered: list[Message] = [] + chunks: list[bytes] = [] + while True: + message = await receive() + buffered.append(message) + if message["type"] != "http.request": + break + chunks.append(message.get("body", b"")) + if not message.get("more_body", False): + break + + idx = 0 + + async def replay() -> Message: + nonlocal idx + if idx < len(buffered): + msg = buffered[idx] + idx += 1 + return msg + return await receive() + + return b"".join(chunks), replay + + def _error_response(message: str, status_code: int, code: int = INVALID_REQUEST) -> Response: """A JSON-RPC error body (no request id) with the given HTTP status.""" body = JSONRPCError(jsonrpc="2.0", id=None, error=ErrorData(code=code, message=message)) diff --git a/src/mcp/shared/inbound.py b/src/mcp/shared/inbound.py index e33d6f502f..f3dded25d8 100644 --- a/src/mcp/shared/inbound.py +++ b/src/mcp/shared/inbound.py @@ -593,3 +593,19 @@ def validate_mcp_param_headers( message=f"{header_name} header does not match the request body's {argument!r} argument", ) return None + + +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 diff --git a/tests/server/test_streamable_http_manager.py b/tests/server/test_streamable_http_manager.py index 1b8f9264f1..e6bae64278 100644 --- a/tests/server/test_streamable_http_manager.py +++ b/tests/server/test_streamable_http_manager.py @@ -1065,3 +1065,47 @@ async def test_anonymous_session_accepts_anonymous_requests( session_id = await _open_session(manager, None) assert await _request_session(manager, session_id, None) != 404 + + +@pytest.mark.anyio +@pytest.mark.parametrize("version_header", [LATEST_HANDSHAKE_VERSION, None]) +async def test_modern_envelope_routes_to_modern_handler_regardless_of_header( + version_header: str | None, +) -> None: + """A 2026-07-28 _meta envelope must not fall back to legacy when the header is missing or 2025-era.""" + from mcp_types import HEADER_MISMATCH, PROTOCOL_VERSION_META_KEY + from mcp_types.version import LATEST_MODERN_VERSION + + from mcp.shared.inbound import MCP_METHOD_HEADER, MCP_PROTOCOL_VERSION_HEADER + + app = Server("test-modern-routing") + manager = StreamableHTTPSessionManager(app=app, stateless=True, json_response=True) + body = { + "jsonrpc": "2.0", + "id": 1, + "method": "tools/list", + "params": { + "_meta": { + PROTOCOL_VERSION_META_KEY: LATEST_MODERN_VERSION, + "io.modelcontextprotocol/clientCapabilities": {}, + } + }, + } + headers = { + "accept": "application/json", + "content-type": "application/json", + MCP_METHOD_HEADER: "tools/list", + } + if version_header is not None: + headers[MCP_PROTOCOL_VERSION_HEADER] = version_header + + async with manager.run(): + async with httpx2.AsyncClient( + transport=StreamingASGITransport(manager.handle_request), + base_url=BASE_URL, + ) as client: + response = await client.post("/mcp", json=body, headers=headers) + + assert response.status_code == 400 + payload = response.json() + assert payload["error"]["code"] == HEADER_MISMATCH