Skip to content

Commit 34ac5f7

Browse files
committed
fix(http): return HTTP 200 for handler-origin INVALID_PARAMS in modern Streamable HTTP
1 parent 77001c9 commit 34ac5f7

3 files changed

Lines changed: 125 additions & 36 deletions

File tree

‎src/mcp/server/_streamable_http_modern.py‎

Lines changed: 52 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@
2525
import logging
2626
from collections.abc import Awaitable, Mapping
2727
from dataclasses import dataclass, field
28+
from types import MappingProxyType
2829
from typing import TYPE_CHECKING, Any, Final, cast
2930

3031
import anyio
@@ -34,8 +35,11 @@
3435
CLIENT_INFO_META_KEY,
3536
HEADER_MISMATCH,
3637
INVALID_REQUEST,
38+
METHOD_NOT_FOUND,
39+
MISSING_REQUIRED_CLIENT_CAPABILITY,
3740
PARSE_ERROR,
3841
PROTOCOL_VERSION_META_KEY,
42+
UNSUPPORTED_PROTOCOL_VERSION,
3943
ErrorData,
4044
JSONRPCError,
4145
JSONRPCNotification,
@@ -55,7 +59,7 @@
5559
from mcp.server.streamable_http import check_accept_headers
5660
from mcp.server.transport_security import TransportSecurityMiddleware, TransportSecuritySettings
5761
from mcp.shared.dispatcher import CallOptions
58-
from mcp.shared.exceptions import NoBackChannelError
62+
from mcp.shared.exceptions import MCPError, NoBackChannelError
5963
from mcp.shared.inbound import (
6064
ERROR_CODE_HTTP_STATUS,
6165
MCP_PARAM_HEADER_PREFIX,
@@ -123,21 +127,25 @@ async def progress(self, progress: float, total: float | None = None, message: s
123127
await self.notify("notifications/progress", params)
124128

125129

126-
async def _to_jsonrpc_response(
130+
async def _execute_jsonrpc(
127131
request_id: RequestId, coro: Awaitable[dict[str, Any]]
128-
) -> JSONRPCResponse | JSONRPCError:
129-
"""Await ``coro`` and wrap its outcome as the JSON-RPC reply for ``request_id``.
130-
131-
The exception-to-wire boundary for the modern HTTP entry, composed around
132-
`serve_one`: `modern_error_data` maps the shared ladder and surfaces
133-
anything else as a generic `INTERNAL_ERROR` so handler internals never
134-
reach the wire.
132+
) -> tuple[JSONRPCResponse | JSONRPCError, bool]:
133+
"""Await ``coro`` and return ``(reply, from_handler)``.
134+
135+
``MCPError`` originates from dispatch/handlers (including ``MCPError``
136+
conversions inside ``ServerRunner``) so HTTP status selection uses
137+
``_HANDLER_ERROR_HTTP_STATUS``. Request/envelope ``ValidationError``
138+
(e.g. a mis-shaped ``_meta`` envelope) keeps ``from_handler=False`` so it
139+
maps through ``ERROR_CODE_HTTP_STATUS`` (400), and unmapped exceptions map
140+
to ``INTERNAL_ERROR`` (HTTP 200).
135141
"""
136142
try:
137143
result = await coro
144+
except MCPError as exc:
145+
return JSONRPCError(jsonrpc="2.0", id=request_id, error=modern_error_data(exc)), True
138146
except Exception as exc:
139-
return JSONRPCError(jsonrpc="2.0", id=request_id, error=modern_error_data(exc))
140-
return JSONRPCResponse(jsonrpc="2.0", id=request_id, result=result)
147+
return JSONRPCError(jsonrpc="2.0", id=request_id, error=modern_error_data(exc)), False
148+
return JSONRPCResponse(jsonrpc="2.0", id=request_id, result=result), False
141149

142150

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

173181

182+
_HANDLER_ERROR_HTTP_STATUS: Final[Mapping[int, int]] = MappingProxyType(
183+
{
184+
HEADER_MISMATCH: 400,
185+
MISSING_REQUIRED_CLIENT_CAPABILITY: 400,
186+
UNSUPPORTED_PROTOCOL_VERSION: 400,
187+
METHOD_NOT_FOUND: 404,
188+
}
189+
)
190+
"""HTTP status overrides for handler/dispatch-origin JSON-RPC errors.
191+
192+
Only error codes with a transport HTTP status in the 2026-07-28 spec map
193+
above `200`. `-32602 INVALID_PARAMS` is intentionally omitted here because
194+
handler-origin `-32602` (such as a missing resource URI) is an in-band JSON-RPC
195+
error on HTTP 200, whereas malformed request envelopes fail on the inbound
196+
ladder via :func:`_write_rejection` (`400`).
197+
"""
198+
199+
174200
async def _write(
175201
msg: JSONRPCResponse | JSONRPCError,
176202
scope: Scope,
177203
receive: Receive,
178204
send: Send,
205+
*,
206+
from_handler: bool = False,
179207
) -> None:
180-
"""Serialise a JSON-RPC reply with the table-mapped HTTP status."""
181-
status = ERROR_CODE_HTTP_STATUS.get(msg.error.code, 200) if isinstance(msg, JSONRPCError) else 200
208+
"""Serialise a JSON-RPC reply with the origin-appropriate HTTP status."""
209+
status_map = _HANDLER_ERROR_HTTP_STATUS if from_handler else ERROR_CODE_HTTP_STATUS
210+
status = status_map.get(msg.error.code, 200) if isinstance(msg, JSONRPCError) else 200
182211
body = msg.model_dump(mode="json", by_alias=True, exclude_none=True)
183212
if isinstance(msg, JSONRPCError) and msg.id is None:
184213
# JSON-RPC requires `id: null` to appear on the wire when the request
@@ -456,20 +485,20 @@ async def handle_modern_request(
456485
# A listen response IS a notification stream, so it always takes the
457486
# SSE path below regardless of the JSON-response preference (the
458487
# TypeScript and Go SDKs route it the same way).
459-
msg = await _to_jsonrpc_response(
488+
msg, is_handler_error = await _execute_jsonrpc(
460489
req.id, serve_one(app, dctx, req.method, req.params, connection=connection, lifespan_state=lifespan_state)
461490
)
462-
await _write(msg, scope, receive, send)
491+
await _write(msg, scope, receive, send, from_handler=is_handler_error)
463492
return
464493

465494
send_ch, recv_ch = anyio.create_memory_object_stream[bytes](0)
466495
dctx.sink = send_ch
467-
result: list[JSONRPCResponse | JSONRPCError] = []
496+
result: list[tuple[JSONRPCResponse | JSONRPCError, bool]] = []
468497

469498
async def run_handler() -> None:
470499
async with send_ch:
471500
result.append(
472-
await _to_jsonrpc_response(
501+
await _execute_jsonrpc(
473502
req.id,
474503
serve_one(app, dctx, req.method, req.params, connection=connection, lifespan_state=lifespan_state),
475504
)
@@ -494,10 +523,11 @@ async def watch_disconnect(cancel_scope: anyio.CancelScope) -> None:
494523

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

527557
tg.cancel_scope.cancel()

‎src/mcp/shared/inbound.py‎

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -316,11 +316,13 @@ def _value_at_path(arguments: Mapping[str, Any], path: tuple[str, ...]) -> Any:
316316
METHOD_NOT_FOUND: 404,
317317
}
318318
)
319-
"""HTTP status to send for a JSON-RPC `error.code`.
319+
"""HTTP status to send for a transport/ladder-origin JSON-RPC `error.code`.
320320
321-
Consulted for classifier-origin *and* handler-origin errors, so one table
322-
decides the wire status regardless of where the error was produced. Unmapped
323-
codes fall back to the caller's default (typically 200).
321+
Consulted for parse errors, malformed envelopes, and classifier ladder
322+
rejections (where `-32602` for missing `_meta` envelope fields maps to HTTP
323+
400). Handler-origin errors are mapped separately by `_streamable_http_modern`
324+
so in-band `-32602` handler errors stay on HTTP 200. Unmapped codes fall back
325+
to the caller's default (typically 200).
324326
"""
325327

326328

‎tests/server/test_streamable_http_modern.py‎

Lines changed: 67 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -46,8 +46,8 @@
4646

4747
from mcp.server import Server, ServerRequestContext, _streamable_http_modern, runner
4848
from mcp.server._streamable_http_modern import (
49+
_execute_jsonrpc,
4950
_SingleExchangeDispatchContext,
50-
_to_jsonrpc_response,
5151
handle_modern_request,
5252
)
5353
from mcp.server.context import CallNext, HandlerResult
@@ -356,36 +356,38 @@ async def list_tools(ctx: ServerRequestContext, params: PaginatedRequestParams |
356356
assert "abandoning remaining callbacks" in caplog.text # pragma: lax no cover
357357

358358

359-
# --- _to_jsonrpc_response ------------------------------------------------------
359+
# --- _execute_jsonrpc ----------------------------------------------------------
360360

361361

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

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

369-
reply = await _to_jsonrpc_response(7, ok())
369+
reply, from_handler = await _execute_jsonrpc(7, ok())
370+
assert from_handler is False
370371
assert isinstance(reply, JSONRPCResponse)
371372
assert reply.id == 7
372373
assert reply.result == {"k": "v"}
373374

374375

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

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

382-
reply = await _to_jsonrpc_response("rid", fail())
383+
reply, from_handler = await _execute_jsonrpc("rid", fail())
384+
assert from_handler is True
383385
assert isinstance(reply, JSONRPCError)
384386
assert reply.id == "rid"
385387
assert reply.error == ErrorData(code=METHOD_NOT_FOUND, message="nope", data="x")
386388

387389

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

397-
reply = await _to_jsonrpc_response(1, fail())
399+
reply, from_handler = await _execute_jsonrpc(1, fail())
400+
assert from_handler is False
398401
assert isinstance(reply, JSONRPCError)
399402
assert reply.error == ErrorData(code=INVALID_PARAMS, message="Invalid request parameters", data="")
400403

401404

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

412-
reply = await _to_jsonrpc_response(1, fail())
415+
reply, from_handler = await _execute_jsonrpc(1, fail())
416+
assert from_handler is False
413417
assert isinstance(reply, JSONRPCError)
414418
assert reply.error.code == INTERNAL_ERROR
415419
# Handler internals never reach the wire.
@@ -1353,3 +1357,56 @@ async def post() -> None:
13531357
"io.modelcontextprotocol/subscriptionId": 9,
13541358
SERVER_INFO_META_KEY: {"name": "test", "version": "1.2.3"},
13551359
}
1360+
1361+
1362+
async def test_handler_invalid_params_answers_http_200_while_envelope_invalid_params_stays_400() -> None:
1363+
"""Spec-mandated: handler-origin `-32602 INVALID_PARAMS` travels in-band on HTTP 200 in both JSON
1364+
and pre-commit SSE modes, whereas ladder `-32602` (malformed `_meta` envelope) remains HTTP 400."""
1365+
1366+
async def read_resource(ctx: ServerRequestContext, params: Any) -> Any:
1367+
raise MCPError(code=INVALID_PARAMS, message="Resource not found: 'demo://does-not-exist'")
1368+
1369+
meta = _list_tools_body()["params"]["_meta"]
1370+
read_body = {
1371+
"jsonrpc": "2.0",
1372+
"id": 7800,
1373+
"method": "resources/read",
1374+
"params": {"uri": "demo://does-not-exist", "_meta": meta},
1375+
}
1376+
read_headers = {MCP_METHOD_HEADER: "resources/read", MCP_NAME_HEADER: "demo://does-not-exist"}
1377+
1378+
for json_response in (True, False):
1379+
async with _asgi_client(Server("test", on_read_resource=read_resource), json_response=json_response) as http:
1380+
res = await http.post("/mcp", json=read_body, headers=read_headers)
1381+
assert res.status_code == 200
1382+
assert res.json() == {
1383+
"jsonrpc": "2.0",
1384+
"id": 7800,
1385+
"error": {"code": INVALID_PARAMS, "message": "Resource not found: 'demo://does-not-exist'"},
1386+
}
1387+
1388+
mcp = MCPServer("repro")
1389+
1390+
@mcp.resource("demo://widget")
1391+
def widget() -> str:
1392+
return "<html></html>"
1393+
1394+
async with _asgi_client(mcp._lowlevel_server, json_response=True) as http: # pyright: ignore[reportPrivateUsage]
1395+
mcp_res = await http.post("/mcp", json=read_body, headers=read_headers)
1396+
assert mcp_res.status_code == 200
1397+
assert mcp_res.json()["error"]["code"] == INVALID_PARAMS
1398+
1399+
bad_envelope_meta = {k: v for k, v in meta.items() if k != CLIENT_CAPABILITIES_META_KEY}
1400+
async with _asgi_client(Server("test", on_read_resource=read_resource), json_response=True) as http:
1401+
ladder_res = await http.post(
1402+
"/mcp",
1403+
json={
1404+
"jsonrpc": "2.0",
1405+
"id": 7802,
1406+
"method": "resources/read",
1407+
"params": {"uri": "demo://does-not-exist", "_meta": bad_envelope_meta},
1408+
},
1409+
headers=read_headers,
1410+
)
1411+
assert ladder_res.status_code == 400
1412+
assert ladder_res.json()["error"]["code"] == INVALID_PARAMS

0 commit comments

Comments
 (0)