From 69d83672f2d6935304f45417d11fe1e02752e9fb Mon Sep 17 00:00:00 2001 From: lzcdev <16014249+lzcdev@users.noreply.github.com> Date: Wed, 2 Dec 2026 22:42:01 +0800 Subject: [PATCH 1/2] Reject non-standard JSON constants in modern HTTP json.loads() accepts NaN, Infinity and -Infinity by default, which are outside RFC 8259. The modern Streamable HTTP entry passed those values straight to tool handlers. Parse with a parse_constant hook that raises ValueError so the existing PARSE_ERROR path rejects the request before dispatch. Fixes #3961 Signed-off-by: lzcdev <16014249+lzcdev@users.noreply.github.com> --- src/mcp/server/_streamable_http_modern.py | 9 +++++-- tests/server/test_streamable_http_modern.py | 26 +++++++++++++++++++++ 2 files changed, 33 insertions(+), 2 deletions(-) diff --git a/src/mcp/server/_streamable_http_modern.py b/src/mcp/server/_streamable_http_modern.py index ad4257319d..5d741af450 100644 --- a/src/mcp/server/_streamable_http_modern.py +++ b/src/mcp/server/_streamable_http_modern.py @@ -25,7 +25,7 @@ import logging from collections.abc import Awaitable, Mapping from dataclasses import dataclass, field -from typing import TYPE_CHECKING, Any, Final, cast +from typing import TYPE_CHECKING, Any, Final, NoReturn, cast import anyio from anyio.streams.memory import MemoryObjectSendStream @@ -362,6 +362,11 @@ async def _mcp_param_rejection( return validate_mcp_param_headers(input_schema, arguments, request.headers) +def _reject_nonstandard_json_constant(value: str) -> NoReturn: + """Reject NaN/Infinity, which are outside RFC 8259's number grammar.""" + raise ValueError(f"Non-standard JSON constant: {value}") + + async def handle_modern_request( app: Server[Any], security_settings: TransportSecuritySettings | None, @@ -399,7 +404,7 @@ async def handle_modern_request( body = await request.body() try: - decoded = json.loads(body) + decoded = json.loads(body, parse_constant=_reject_nonstandard_json_constant) except (ValueError, RecursionError): # Not just JSONDecodeError: oversized integer literals raise bare ValueError, deep nesting RecursionError. rej = JSONRPCError(jsonrpc="2.0", id=None, error=ErrorData(code=PARSE_ERROR, message="Parse error")) diff --git a/tests/server/test_streamable_http_modern.py b/tests/server/test_streamable_http_modern.py index a539720d58..792a0689c8 100644 --- a/tests/server/test_streamable_http_modern.py +++ b/tests/server/test_streamable_http_modern.py @@ -835,6 +835,32 @@ def _tool_call_body(arguments: dict[str, Any] | None = None, *, name: str | None _TOOL_CALL_HEADERS = {MCP_METHOD_HEADER: "tools/call", MCP_NAME_HEADER: "search"} +@pytest.mark.parametrize( + "constant", + [float("nan"), float("inf"), float("-inf")], + ids=["NaN", "Infinity", "-Infinity"], +) +async def test_handle_modern_request_rejects_nonstandard_json_constants(constant: float) -> None: + """NaN/Infinity are outside RFC 8259; they must not reach a tool handler as floats.""" + seen: list[Any] = [] + + async def record_call(ctx: ServerRequestContext, params: CallToolRequestParams) -> CallToolResult: + seen.append(params.arguments) + return CallToolResult(content=[]) + + server: Server[Any] = Server("test", on_call_tool=record_call) + body = json.dumps(_tool_call_body({"value": constant})) + async with _asgi_client(server) as http: + response = await http.post("/mcp", content=body.encode(), headers=_TOOL_CALL_HEADERS) + assert response.status_code == 400 + assert response.json() == { + "jsonrpc": "2.0", + "id": None, + "error": {"code": PARSE_ERROR, "message": "Parse error"}, + } + assert seen == [] + + async def _ok_call_tool(ctx: ServerRequestContext, params: CallToolRequestParams) -> CallToolResult: return CallToolResult(content=[]) From 8e8e5cff36573d7548266050caa456ec57c63dbd Mon Sep 17 00:00:00 2001 From: lzcdev <16014249+lzcdev@users.noreply.github.com> Date: Sat, 5 Dec 2026 19:22:00 +0800 Subject: [PATCH 2/2] Fix coverage in nonstandard JSON constants regression test The handler body in the regression test is never executed because the request must be rejected before dispatch, which drops repository coverage below the 100% gate. Use an AsyncMock and assert it was not awaited so the test still proves the handler was skipped without adding uncovered lines. Signed-off-by: lzcdev <16014249+lzcdev@users.noreply.github.com> --- tests/server/test_streamable_http_modern.py | 10 +++------- 1 file changed, 3 insertions(+), 7 deletions(-) diff --git a/tests/server/test_streamable_http_modern.py b/tests/server/test_streamable_http_modern.py index 792a0689c8..3b5b2a5e4f 100644 --- a/tests/server/test_streamable_http_modern.py +++ b/tests/server/test_streamable_http_modern.py @@ -10,6 +10,7 @@ import logging from collections.abc import Callable from typing import Annotated, Any +from unittest.mock import AsyncMock import anyio import httpx2 @@ -842,12 +843,7 @@ def _tool_call_body(arguments: dict[str, Any] | None = None, *, name: str | None ) async def test_handle_modern_request_rejects_nonstandard_json_constants(constant: float) -> None: """NaN/Infinity are outside RFC 8259; they must not reach a tool handler as floats.""" - seen: list[Any] = [] - - async def record_call(ctx: ServerRequestContext, params: CallToolRequestParams) -> CallToolResult: - seen.append(params.arguments) - return CallToolResult(content=[]) - + record_call = AsyncMock(return_value=CallToolResult(content=[])) server: Server[Any] = Server("test", on_call_tool=record_call) body = json.dumps(_tool_call_body({"value": constant})) async with _asgi_client(server) as http: @@ -858,7 +854,7 @@ async def record_call(ctx: ServerRequestContext, params: CallToolRequestParams) "id": None, "error": {"code": PARSE_ERROR, "message": "Parse error"}, } - assert seen == [] + record_call.assert_not_awaited() async def _ok_call_tool(ctx: ServerRequestContext, params: CallToolRequestParams) -> CallToolResult: