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
74 changes: 52 additions & 22 deletions src/mcp/server/_streamable_http_modern.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
import logging
from collections.abc import Awaitable, Mapping
from dataclasses import dataclass, field
from types import MappingProxyType
from typing import TYPE_CHECKING, Any, Final, cast

import anyio
Expand All @@ -34,8 +35,11 @@
CLIENT_INFO_META_KEY,
HEADER_MISMATCH,
INVALID_REQUEST,
METHOD_NOT_FOUND,
MISSING_REQUIRED_CLIENT_CAPABILITY,
PARSE_ERROR,
PROTOCOL_VERSION_META_KEY,
UNSUPPORTED_PROTOCOL_VERSION,
ErrorData,
JSONRPCError,
JSONRPCNotification,
Expand All @@ -55,7 +59,7 @@
from mcp.server.streamable_http import check_accept_headers
from mcp.server.transport_security import TransportSecurityMiddleware, TransportSecuritySettings
from mcp.shared.dispatcher import CallOptions
from mcp.shared.exceptions import NoBackChannelError
from mcp.shared.exceptions import MCPError, NoBackChannelError
from mcp.shared.inbound import (
ERROR_CODE_HTTP_STATUS,
MCP_PARAM_HEADER_PREFIX,
Expand Down Expand Up @@ -123,21 +127,25 @@ async def progress(self, progress: float, total: float | None = None, message: s
await self.notify("notifications/progress", params)


async def _to_jsonrpc_response(
async def _execute_jsonrpc(
request_id: RequestId, coro: Awaitable[dict[str, Any]]
) -> JSONRPCResponse | JSONRPCError:
"""Await ``coro`` and wrap its outcome as the JSON-RPC reply for ``request_id``.

The exception-to-wire boundary for the modern HTTP entry, composed around
`serve_one`: `modern_error_data` maps the shared ladder and surfaces
anything else as a generic `INTERNAL_ERROR` so handler internals never
reach the wire.
) -> tuple[JSONRPCResponse | JSONRPCError, bool]:
"""Await ``coro`` and return ``(reply, from_handler)``.

``MCPError`` originates from dispatch/handlers (including ``MCPError``
conversions inside ``ServerRunner``) so HTTP status selection uses
``_HANDLER_ERROR_HTTP_STATUS``. Request/envelope ``ValidationError``
(e.g. a mis-shaped ``_meta`` envelope) keeps ``from_handler=False`` so it
maps through ``ERROR_CODE_HTTP_STATUS`` (400), and unmapped exceptions map
to ``INTERNAL_ERROR`` (HTTP 200).
"""
try:
result = await coro
except MCPError as exc:
return JSONRPCError(jsonrpc="2.0", id=request_id, error=modern_error_data(exc)), True
except Exception as exc:
return JSONRPCError(jsonrpc="2.0", id=request_id, error=modern_error_data(exc))
return JSONRPCResponse(jsonrpc="2.0", id=request_id, result=result)
return JSONRPCError(jsonrpc="2.0", id=request_id, error=modern_error_data(exc)), False
return JSONRPCResponse(jsonrpc="2.0", id=request_id, result=result), False


_SSE_PING_INTERVAL: float = 15.0
Expand Down Expand Up @@ -171,14 +179,35 @@ async def _write_rejection(
await _write(rej, scope, receive, send)


_HANDLER_ERROR_HTTP_STATUS: Final[Mapping[int, int]] = MappingProxyType(
{
HEADER_MISMATCH: 400,
MISSING_REQUIRED_CLIENT_CAPABILITY: 400,
UNSUPPORTED_PROTOCOL_VERSION: 400,
METHOD_NOT_FOUND: 404,
}
)
"""HTTP status overrides for handler/dispatch-origin JSON-RPC errors.

Only error codes with a transport HTTP status in the 2026-07-28 spec map
above `200`. `-32602 INVALID_PARAMS` is intentionally omitted here because
handler-origin `-32602` (such as a missing resource URI) is an in-band JSON-RPC
error on HTTP 200, whereas malformed request envelopes fail on the inbound
ladder via :func:`_write_rejection` (`400`).
"""


async def _write(
msg: JSONRPCResponse | JSONRPCError,
scope: Scope,
receive: Receive,
send: Send,
*,
from_handler: bool = False,
) -> None:
"""Serialise a JSON-RPC reply with the table-mapped HTTP status."""
status = ERROR_CODE_HTTP_STATUS.get(msg.error.code, 200) if isinstance(msg, JSONRPCError) else 200
"""Serialise a JSON-RPC reply with the origin-appropriate HTTP status."""
status_map = _HANDLER_ERROR_HTTP_STATUS if from_handler else ERROR_CODE_HTTP_STATUS
status = status_map.get(msg.error.code, 200) if isinstance(msg, JSONRPCError) else 200
body = msg.model_dump(mode="json", by_alias=True, exclude_none=True)
if isinstance(msg, JSONRPCError) and msg.id is None:
# JSON-RPC requires `id: null` to appear on the wire when the request
Expand Down Expand Up @@ -456,20 +485,20 @@ async def handle_modern_request(
# A listen response IS a notification stream, so it always takes the
# SSE path below regardless of the JSON-response preference (the
# TypeScript and Go SDKs route it the same way).
msg = await _to_jsonrpc_response(
msg, is_handler_error = await _execute_jsonrpc(
req.id, serve_one(app, dctx, req.method, req.params, connection=connection, lifespan_state=lifespan_state)
)
await _write(msg, scope, receive, send)
await _write(msg, scope, receive, send, from_handler=is_handler_error)
return

send_ch, recv_ch = anyio.create_memory_object_stream[bytes](0)
dctx.sink = send_ch
result: list[JSONRPCResponse | JSONRPCError] = []
result: list[tuple[JSONRPCResponse | JSONRPCError, bool]] = []

async def run_handler() -> None:
async with send_ch:
result.append(
await _to_jsonrpc_response(
await _execute_jsonrpc(
req.id,
serve_one(app, dctx, req.method, req.params, connection=connection, lifespan_state=lifespan_state),
)
Expand All @@ -494,10 +523,11 @@ async def watch_disconnect(cancel_scope: anyio.CancelScope) -> None:

if done:
# Handler completed within the deferral window without emitting:
# `application/json` with the table-mapped status. Kernel-dispatch
# errors (METHOD_NOT_FOUND, missing-capability, INVALID_PARAMS)
# resolve here in practice.
await _write(result[0], scope, receive, send)
# `application/json` with the handler-mapped status. Spec-assigned
# dispatch errors (`METHOD_NOT_FOUND`, missing-capability) still map
# to 404/400, while handler `INVALID_PARAMS` stays in-band on 200.
msg, is_handler_error = result[0]
await _write(msg, scope, receive, send, from_handler=is_handler_error)
else:
# First notification arrived, or the deferral window elapsed: commit
# `text/event-stream` and start pinging so a proxy idle-read timeout
Expand All @@ -522,6 +552,6 @@ async def watch_disconnect(cancel_scope: anyio.CancelScope) -> None:
event = await recv_ch.receive()
except anyio.EndOfStream:
done = True
await send({"type": "http.response.body", "body": _sse_event(result[0]), "more_body": False})
await send({"type": "http.response.body", "body": _sse_event(result[0][0]), "more_body": False})

tg.cancel_scope.cancel()
10 changes: 6 additions & 4 deletions src/mcp/shared/inbound.py
Original file line number Diff line number Diff line change
Expand Up @@ -316,11 +316,13 @@ def _value_at_path(arguments: Mapping[str, Any], path: tuple[str, ...]) -> Any:
METHOD_NOT_FOUND: 404,
}
)
"""HTTP status to send for a JSON-RPC `error.code`.
"""HTTP status to send for a transport/ladder-origin JSON-RPC `error.code`.

Consulted for classifier-origin *and* handler-origin errors, so one table
decides the wire status regardless of where the error was produced. Unmapped
codes fall back to the caller's default (typically 200).
Consulted for parse errors, malformed envelopes, and classifier ladder
rejections (where `-32602` for missing `_meta` envelope fields maps to HTTP
400). Handler-origin errors are mapped separately by `_streamable_http_modern`
so in-band `-32602` handler errors stay on HTTP 200. Unmapped codes fall back
to the caller's default (typically 200).
"""


Expand Down
77 changes: 67 additions & 10 deletions tests/server/test_streamable_http_modern.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,8 +46,8 @@

from mcp.server import Server, ServerRequestContext, _streamable_http_modern, runner
from mcp.server._streamable_http_modern import (
_execute_jsonrpc,
_SingleExchangeDispatchContext,
_to_jsonrpc_response,
handle_modern_request,
)
from mcp.server.context import CallNext, HandlerResult
Expand Down Expand Up @@ -356,36 +356,38 @@ async def list_tools(ctx: ServerRequestContext, params: PaginatedRequestParams |
assert "abandoning remaining callbacks" in caplog.text # pragma: lax no cover


# --- _to_jsonrpc_response ------------------------------------------------------
# --- _execute_jsonrpc ----------------------------------------------------------


async def test_to_jsonrpc_response_wraps_success_as_jsonrpc_response() -> None:
async def test_execute_jsonrpc_wraps_success_as_jsonrpc_response() -> None:
"""SDK-defined: a handler coroutine resolving to a result dict is wrapped as a
`JSONRPCResponse` carrying the supplied id and the dict verbatim as `result`."""

async def ok() -> dict[str, Any]:
return {"k": "v"}

reply = await _to_jsonrpc_response(7, ok())
reply, from_handler = await _execute_jsonrpc(7, ok())
assert from_handler is False
assert isinstance(reply, JSONRPCResponse)
assert reply.id == 7
assert reply.result == {"k": "v"}


async def test_to_jsonrpc_response_maps_mcp_error_to_jsonrpc_error() -> None:
async def test_execute_jsonrpc_maps_mcp_error_to_jsonrpc_error() -> None:
"""SDK-defined: an `MCPError` raised by the handler coroutine is wrapped as a
`JSONRPCError` whose `error` carries the same code, message, and data."""

async def fail() -> dict[str, Any]:
raise MCPError(code=METHOD_NOT_FOUND, message="nope", data="x")

reply = await _to_jsonrpc_response("rid", fail())
reply, from_handler = await _execute_jsonrpc("rid", fail())
assert from_handler is True
assert isinstance(reply, JSONRPCError)
assert reply.id == "rid"
assert reply.error == ErrorData(code=METHOD_NOT_FOUND, message="nope", data="x")


async def test_to_jsonrpc_response_maps_validation_error_to_invalid_params() -> None:
async def test_execute_jsonrpc_maps_validation_error_to_invalid_params() -> None:
"""SDK-defined: a pydantic `ValidationError` escaping the handler coroutine is
mapped to `INVALID_PARAMS` with a generic message (validator detail does not
reach the wire)."""
Expand All @@ -394,12 +396,13 @@ async def fail() -> dict[str, Any]:
Tool.model_validate({"name": 123}) # raises ValidationError
raise NotImplementedError

reply = await _to_jsonrpc_response(1, fail())
reply, from_handler = await _execute_jsonrpc(1, fail())
assert from_handler is False
assert isinstance(reply, JSONRPCError)
assert reply.error == ErrorData(code=INVALID_PARAMS, message="Invalid request parameters", data="")


async def test_to_jsonrpc_response_maps_unmapped_exception_to_internal_error_and_logs(
async def test_execute_jsonrpc_maps_unmapped_exception_to_internal_error_and_logs(
caplog: pytest.LogCaptureFixture,
) -> None:
"""SDK-defined: an unmapped exception is logged server-side and surfaced as
Expand All @@ -409,7 +412,8 @@ async def test_to_jsonrpc_response_maps_unmapped_exception_to_internal_error_and
async def fail() -> dict[str, Any]:
raise RuntimeError("boom")

reply = await _to_jsonrpc_response(1, fail())
reply, from_handler = await _execute_jsonrpc(1, fail())
assert from_handler is False
assert isinstance(reply, JSONRPCError)
assert reply.error.code == INTERNAL_ERROR
# Handler internals never reach the wire.
Expand Down Expand Up @@ -1353,3 +1357,56 @@ async def post() -> None:
"io.modelcontextprotocol/subscriptionId": 9,
SERVER_INFO_META_KEY: {"name": "test", "version": "1.2.3"},
}


async def test_handler_invalid_params_answers_http_200_while_envelope_invalid_params_stays_400() -> None:
"""Spec-mandated: handler-origin `-32602 INVALID_PARAMS` travels in-band on HTTP 200 in both JSON
and pre-commit SSE modes, whereas ladder `-32602` (malformed `_meta` envelope) remains HTTP 400."""

async def read_resource(ctx: ServerRequestContext, params: Any) -> Any:
raise MCPError(code=INVALID_PARAMS, message="Resource not found: 'demo://does-not-exist'")

meta = _list_tools_body()["params"]["_meta"]
read_body = {
"jsonrpc": "2.0",
"id": 7800,
"method": "resources/read",
"params": {"uri": "demo://does-not-exist", "_meta": meta},
}
read_headers = {MCP_METHOD_HEADER: "resources/read", MCP_NAME_HEADER: "demo://does-not-exist"}

for json_response in (True, False):
async with _asgi_client(Server("test", on_read_resource=read_resource), json_response=json_response) as http:
res = await http.post("/mcp", json=read_body, headers=read_headers)
assert res.status_code == 200
assert res.json() == {
"jsonrpc": "2.0",
"id": 7800,
"error": {"code": INVALID_PARAMS, "message": "Resource not found: 'demo://does-not-exist'"},
}

mcp = MCPServer("repro")

@mcp.resource("demo://widget")
def widget() -> str:
return "<html></html>"

async with _asgi_client(mcp._lowlevel_server, json_response=True) as http: # pyright: ignore[reportPrivateUsage]
mcp_res = await http.post("/mcp", json=read_body, headers=read_headers)
assert mcp_res.status_code == 200
assert mcp_res.json()["error"]["code"] == INVALID_PARAMS

bad_envelope_meta = {k: v for k, v in meta.items() if k != CLIENT_CAPABILITIES_META_KEY}
async with _asgi_client(Server("test", on_read_resource=read_resource), json_response=True) as http:
ladder_res = await http.post(
"/mcp",
json={
"jsonrpc": "2.0",
"id": 7802,
"method": "resources/read",
"params": {"uri": "demo://does-not-exist", "_meta": bad_envelope_meta},
},
headers=read_headers,
)
assert ladder_res.status_code == 400
assert ladder_res.json()["error"]["code"] == INVALID_PARAMS
Loading