Skip to content

Legacy Streamable HTTP and stdio pass NaN/Infinity from request JSON into tool handlers #3965

Backlog

Description

@beartester34

Initial Checks

Release line

v2 (main)

Description

Follow-up to #3961, which covers the modern (2026-07-28) Streamable HTTP path. The other server transports have the same inbound gap: a tools/call whose arguments contain the non-standard JSON literals NaN, Infinity or -Infinity reaches the tool handler as non-finite Python floats instead of being rejected as a parse error (-32700).

  • Legacy Streamable HTTP parses with pydantic_core.from_json(body) (src/mcp/server/streamable_http.py:581); its default allow_inf_nan=True accepts the literals. Confirmed end to end: HTTP 200, handler gets nan/inf/-inf.
  • stdio parses each line with types.jsonrpc_message_adapter.validate_json(...) (src/mcp/server/stdio.py:189), which accepts them too. Confirmed end to end: handler gets nan/inf/-inf.
  • SSE uses the same adapter (src/mcp/server/sse.py:272). I checked the adapter directly but did not run an SSE session.

arguments is dict[str, Any], so a per-field allow_inf_nan=False would not catch this; it needs to happen at the JSON parse. The client transports share jsonrpc_message_adapter, so changing the adapter itself would also change client-side parsing, which may or may not be wanted.

Example Code

Run from a checkout of main (77001c9) with uv run python repro.py. In-process ASGI for HTTP, a child process for stdio, no network.

import json
import subprocess
import sys
import textwrap

import anyio
import httpx2

from mcp.server import Server
from mcp.server.transport_security import TransportSecuritySettings
from mcp.types import CallToolResult

LEGACY_VERSION = "2025-06-18"
VALUES = (float("nan"), float("inf"), float("-inf"))


def legacy_call(arguments: dict) -> bytes:
    # json.dumps writes NaN/Infinity literally (allow_nan=True)
    return json.dumps(
        {"jsonrpc": "2.0", "id": 1, "method": "tools/call", "params": {"name": "probe", "arguments": arguments}}
    ).encode()


async def legacy_http() -> None:
    seen = []

    async def tool(ctx, params):
        seen.append(params.arguments)
        return CallToolResult(content=[])

    app = Server("probe", on_call_tool=tool).streamable_http_app(
        json_response=True,
        stateless_http=True,
        transport_security=TransportSecuritySettings(allowed_hosts=["test"]),
    )
    headers = {
        "mcp-protocol-version": LEGACY_VERSION,
        "accept": "application/json, text/event-stream",
        "content-type": "application/json",
    }
    async with (
        app.router.lifespan_context(app),
        httpx2.AsyncClient(transport=httpx2.ASGITransport(app=app), base_url="http://test") as c,
    ):
        codes = [(await c.post("/mcp", content=legacy_call({"x": v}), headers=headers)).status_code for v in VALUES]
    print("legacy streamable HTTP statuses:", codes)
    print("legacy streamable HTTP handler arguments:", seen)


STDIO_SERVER = textwrap.dedent(
    """
    import sys, anyio
    from mcp.server import Server
    from mcp.server.stdio import stdio_server
    from mcp.types import CallToolResult

    async def tool(ctx, params):
        print("handler arguments:", params.arguments, file=sys.stderr, flush=True)
        return CallToolResult(content=[])

    async def main():
        server = Server("probe", on_call_tool=tool)
        async with stdio_server() as (r, w):
            await server.run(r, w, server.create_initialization_options())

    anyio.run(main)
    """
)


def stdio() -> None:
    init = {
        "jsonrpc": "2.0",
        "id": 0,
        "method": "initialize",
        "params": {"protocolVersion": LEGACY_VERSION, "capabilities": {}, "clientInfo": {"name": "r", "version": "0"}},
    }
    lines = [json.dumps(init), json.dumps({"jsonrpc": "2.0", "method": "notifications/initialized"})]
    lines += [
        json.dumps({"jsonrpc": "2.0", "id": i + 1, "method": "tools/call", "params": {"name": "probe", "arguments": {"x": v}}})
        for i, v in enumerate(VALUES)
    ]
    proc = subprocess.run(
        [sys.executable, "-c", STDIO_SERVER], input="\n".join(lines) + "\n", capture_output=True, text=True, timeout=60
    )
    print("stdio", *[l for l in proc.stderr.splitlines() if l.startswith("handler arguments:")], sep="\n  ")


anyio.run(legacy_http)
stdio()

Output:

legacy streamable HTTP statuses: [<HTTPStatus.OK: 200>, <HTTPStatus.OK: 200>, <HTTPStatus.OK: 200>]
legacy streamable HTTP handler arguments: [{'x': nan}, {'x': inf}, {'x': -inf}]
stdio
  handler arguments: {'x': nan}
  handler arguments: {'x': inf}
  handler arguments: {'x': -inf}

Expected: reject before dispatch as -32700, as #3961 asks for the modern path.

Related: #3961 (modern Streamable HTTP, same bug); #3341 / #3897 cover non-finite floats in tool output (server → client).

Python & MCP Python SDK

Python 3.14.7
mcp 2.3.1.dev20+77001c9 (main)

AI disclosure: I used AI tools in my own detection-and-fix workflow; I ran the reproduction myself.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions