Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 4 additions & 13 deletions src/mcp/server/runner.py
Original file line number Diff line number Diff line change
Expand Up @@ -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]:
Expand Down
54 changes: 52 additions & 2 deletions src/mcp/server/streamable_http_manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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

Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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))
Expand Down
16 changes: 16 additions & 0 deletions src/mcp/shared/inbound.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
44 changes: 44 additions & 0 deletions tests/server/test_streamable_http_manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Loading