diff --git a/src/mcp/server/sse.py b/src/mcp/server/sse.py index d71ef25004..67d5c0e945 100644 --- a/src/mcp/server/sse.py +++ b/src/mcp/server/sse.py @@ -44,6 +44,7 @@ async def handle_sse(request): import anyio import mcp_types as types +import pydantic_core from pydantic import ValidationError from sse_starlette import EventSourceResponse from starlette.requests import Request @@ -269,9 +270,13 @@ async def _handle_post_message(self, scope: Scope, receive: Receive, send: Send) logger.debug(f"Received JSON: {body}") try: - message = types.jsonrpc_message_adapter.validate_json(body, by_name=False) + # allow_inf_nan=False: NaN/Infinity/-Infinity are not valid JSON (RFC 8259); + # pydantic-core accepts them by default and they would reach tool handlers + # as non-finite floats. Reject them here like any other malformed body. + raw_message = pydantic_core.from_json(body, allow_inf_nan=False) + message = types.jsonrpc_message_adapter.validate_python(raw_message, by_name=False) logger.debug(f"Validated client message: {message}") - except ValidationError as err: + except (ValidationError, ValueError) as err: logger.exception("Failed to parse message") response = Response("Could not parse message", status_code=400) await response(scope, receive, send) diff --git a/src/mcp/server/stdio.py b/src/mcp/server/stdio.py index de8bbae5f1..fe79b95d09 100644 --- a/src/mcp/server/stdio.py +++ b/src/mcp/server/stdio.py @@ -23,6 +23,7 @@ async def run_server(): import anyio import anyio.lowlevel import mcp_types as types +import pydantic_core from mcp.os.win32.utilities import rebind_std_handle_to_fd from mcp.shared._context_streams import create_context_streams @@ -186,7 +187,12 @@ async def stdin_reader(): async with read_stream_writer: async for line in stdin: try: - message = types.jsonrpc_message_adapter.validate_json(line, by_name=False) + # allow_inf_nan=False: NaN/Infinity/-Infinity are not valid JSON + # (RFC 8259); pydantic-core accepts them by default and they would + # reach tool handlers as non-finite floats. Reject them here so the + # line surfaces as an in-stream exception instead of dispatching. + raw_message = pydantic_core.from_json(line, allow_inf_nan=False) + message = types.jsonrpc_message_adapter.validate_python(raw_message, by_name=False) except Exception as exc: await read_stream_writer.send(exc) continue diff --git a/src/mcp/server/streamable_http.py b/src/mcp/server/streamable_http.py index 416dd9e2b4..9eac8dcf12 100644 --- a/src/mcp/server/streamable_http.py +++ b/src/mcp/server/streamable_http.py @@ -578,7 +578,10 @@ async def _handle_post_request(self, scope: Scope, request: Request, receive: Re body = await request.body() try: - raw_message = pydantic_core.from_json(body) + # allow_inf_nan=False: NaN/Infinity/-Infinity are not valid JSON (RFC 8259); + # pydantic-core accepts them by default and they would reach tool handlers + # as non-finite floats. Reject them here so they take the PARSE_ERROR path. + raw_message = pydantic_core.from_json(body, allow_inf_nan=False) except ValueError as e: response = self._create_error_response(f"Parse error: {str(e)}", HTTPStatus.BAD_REQUEST, PARSE_ERROR) await response(scope, receive, send) diff --git a/tests/server/test_sse_security.py b/tests/server/test_sse_security.py index 7e84428600..5c8aae1760 100644 --- a/tests/server/test_sse_security.py +++ b/tests/server/test_sse_security.py @@ -494,6 +494,52 @@ async def test_sse_round_trip_delivers_posted_messages_and_streams_responses(): session.disconnect() +@pytest.mark.anyio +@pytest.mark.parametrize( + "literal", + [ + pytest.param("NaN", id="nan"), + pytest.param("Infinity", id="infinity"), + pytest.param("-Infinity", id="neg-infinity"), + ], +) +async def test_sse_rejects_non_finite_json_constants(literal: str) -> None: + """A POSTed message containing NaN/Infinity/-Infinity gets 400 and surfaces as an + in-stream exception, and the session stays alive for the next valid message. + + Follows #3965: the body is parsed with pydantic_core.from_json, whose default + allow_inf_nan=True accepted the non-standard literals as Python floats. + """ + transport = SseServerTransport("/messages/") + session = _SseSession(transport) + + with anyio.fail_after(5): + async with anyio.create_task_group() as tg: + tg.start_soon(session.hold) + await session.ready.wait() + + # The literal must appear raw in the body; json.dumps would quote it as a string. + body = ( + b'{"jsonrpc": "2.0", "id": 1, "method": "tools/call", ' + b'"params": {"name": "probe", "arguments": {"x": ' + literal.encode() + b"}}}" + ) + scope, receive, send, sent = _sse_scope( + "POST", "/messages/", None, query_string=f"session_id={session.session_id}".encode(), body=body + ) + await transport.handle_post_message(scope, receive, send) + assert _response_status(sent) == 400 + assert isinstance(await session.next_read_item(), Exception) + + # The session survives: a valid message still flows. + assert await _post_message(transport, session.session_id, None) == 202 + received = await session.next_read_item() + assert isinstance(received, SessionMessage) + assert isinstance(received.message, JSONRPCRequest) + assert received.message.method == "ping" + + session.disconnect() + + class _SseSession: """Drive an in-process SSE GET connection and surface what the server reads and the client receives. diff --git a/tests/server/test_stdio.py b/tests/server/test_stdio.py index eafd1fca59..c3c342a7ec 100644 --- a/tests/server/test_stdio.py +++ b/tests/server/test_stdio.py @@ -97,6 +97,44 @@ async def test_stdio_server_invalid_utf8(monkeypatch: pytest.MonkeyPatch) -> Non assert second.message == valid +@pytest.mark.anyio +@pytest.mark.parametrize( + "literal", + [ + pytest.param("NaN", id="nan"), + pytest.param("Infinity", id="infinity"), + pytest.param("-Infinity", id="neg-infinity"), + ], +) +async def test_stdio_server_rejects_non_finite_json_constants(literal: str) -> None: + """A stdin line containing NaN/Infinity/-Infinity surfaces as an in-stream exception + instead of dispatching, and the stream stays alive for the next valid message. + + Follows #3965: the line is parsed with pydantic_core.from_json, whose default + allow_inf_nan=True accepted the non-standard literals as Python floats. + """ + stdin = io.StringIO() + stdout = io.StringIO() + stdin.write('{"jsonrpc": "2.0", "id": 1, "method": "ping", "params": {"x": ' + literal + "}}\n") + valid = JSONRPCRequest(jsonrpc="2.0", id=2, method="ping") + stdin.write(valid.model_dump_json(by_alias=True, exclude_none=True) + "\n") + stdin.seek(0) + + with anyio.fail_after(5): + async with stdio_server(stdin=anyio.AsyncFile(stdin), stdout=anyio.AsyncFile(stdout)) as ( + read_stream, + write_stream, + ): + await write_stream.aclose() + async with read_stream: # pragma: no branch + first = await read_stream.receive() + assert isinstance(first, Exception) + + second = await read_stream.receive() + assert isinstance(second, SessionMessage) + assert second.message == valid + + @contextmanager def _pipe_planted_on_fd0(monkeypatch: pytest.MonkeyPatch) -> Iterator[tuple[int, int]]: """Plants a fresh pipe on fd 0 and rebinds sys.stdin over it; yields (read_fd, write_fd). diff --git a/tests/server/test_streamable_http_manager.py b/tests/server/test_streamable_http_manager.py index 1b8f9264f1..1d1899ceeb 100644 --- a/tests/server/test_streamable_http_manager.py +++ b/tests/server/test_streamable_http_manager.py @@ -14,6 +14,7 @@ from mcp_types import ( INTERNAL_ERROR, INVALID_REQUEST, + PARSE_ERROR, CallToolRequestParams, CallToolResult, ListToolsResult, @@ -37,6 +38,7 @@ DEFAULT_SESSION_IDLE_TIMEOUT, StreamableHTTPSessionManager, ) +from mcp.server.transport_security import TransportSecuritySettings from tests.interaction.transports import StreamingASGITransport # The in-process app is mounted at this origin purely so URLs are well-formed; nothing listens here. @@ -434,6 +436,54 @@ async def handle_list_tools(ctx: ServerRequestContext, params: PaginatedRequestP await client.list_tools() +@pytest.mark.anyio +@pytest.mark.parametrize( + "literal", + [ + pytest.param("NaN", id="nan"), + pytest.param("Infinity", id="infinity"), + pytest.param("-Infinity", id="neg-infinity"), + ], +) +async def test_legacy_streamable_http_rejects_non_finite_json_constants(literal: str) -> None: + """A legacy Streamable HTTP tools/call whose arguments contain NaN/Infinity/-Infinity + is rejected as a parse error (HTTP 400, -32700) and never reaches the tool handler. + + Follows #3965: the legacy path parses with pydantic_core.from_json, whose default + allow_inf_nan=True accepted the non-standard literals as Python floats. + """ + + async def handle_call_tool(ctx: ServerRequestContext, params: CallToolRequestParams | None) -> CallToolResult: + # Never invoked by design: the request is rejected as a parse error + # before dispatch. raise also keeps this body out of the 100% + # coverage gate (coverage excludes `raise NotImplementedError`). + raise NotImplementedError + + app = Server("test-server", on_call_tool=handle_call_tool) + mcp_app = app.streamable_http_app( + json_response=True, + stateless_http=True, + transport_security=TransportSecuritySettings(allowed_hosts=["test"]), + ) + # The literal must appear raw in the body; json.dumps would quote it as a string. + body = ( + b'{"jsonrpc": "2.0", "id": 1, "method": "tools/call", ' + b'"params": {"name": "probe", "arguments": {"x": ' + literal.encode() + b"}}}" + ) + headers = { + "mcp-protocol-version": "2025-06-18", + "accept": "application/json, text/event-stream", + "content-type": "application/json", + } + async with ( + mcp_app.router.lifespan_context(mcp_app), + httpx2.AsyncClient(transport=httpx2.ASGITransport(app=mcp_app), base_url="http://test") as client, + ): + response = await client.post("/mcp", content=body, headers=headers) + assert response.status_code == 400 + assert response.json()["error"]["code"] == PARSE_ERROR + + class _IdleTimeoutObserver(logging.Handler): """Resolves `reaped` when the manager logs that a session's idle timeout fired."""