Skip to content

stdio server sends no reply to a request line that fails JSON validation (e.g. a lone surrogate escape "\ud83d"), so the call hangs #3894

Open

Description

@IngTian

Initial Checks

Release line

2.x (current stable)

Description

A stdio server does not reply to a JSON-RPC request line that fails to validate. The line is dropped, with nothing on stderr, so the client's call hangs until the client's own timeout. The server stays alive and answers later requests normally.

An easy way to hit it: a lone UTF-16 surrogate escape.

  • Python's json.dumps (with the default ensure_ascii=True) writes \ud83d for a string holding half of a surrogate pair, for example text cut in the middle of an emoji.
  • pydantic-core rejects that escape: Invalid JSON: unexpected end of hex escape.
  • The line is pure ASCII, so the non-UTF-8 handling from fix: handle non-UTF-8 bytes in stdio server stdin #2302 does not apply.

The request line in the example is exactly:

{"jsonrpc":"2.0","id":3,"method":"tools/call","params":{"name":"echo","arguments":{"text":"bad \ud83d bad"}}}

Expected: a reply for id 3. Either a JSON-RPC error, such as -32700 Parse error (with "id": null if the id cannot be recovered, as JSON-RPC 2.0 allows), or the call processed with U+FFFD in place of the lone surrogate.

Actual: no reply at all. This is the output of the example below on mcp 2.3.0:

id=1 initialize: {"jsonrpc":"2.0","id":1,"result":{"capabilities":{"tools":{"listChanged":false}},"protocolVersion":"2025-06-18","serverInfo":{"name":"repro","version":""}}}
id=2 normal: {"jsonrpc":"2.0","id":2,"result":{"content":[{"text":"hello","type":"text"}],"isError":false}}
id=3 lone surrogate: NOTHING within 5s
id=4 normal after bad line: {"jsonrpc":"2.0","id":4,"result":{"content":[{"text":"world","type":"text"}],"isError":false}}
server alive after: True returncode: None
stderr:

Where the line is dropped, at main (77001c9):

  • The stdin reader: src/mcp/server/stdio.py L188-L192. validate_json raises, the except Exception sends the exception into the read stream, and it continues. No error response is built, because the request id has not been parsed.
  • The dispatcher: src/mcp/shared/jsonrpc_dispatcher.py L555-L558. For an exception item, when on_stream_exception is None it only calls logger.debug(...) and returns.
  • Why only servers lose it: as far as I can see, only the client session sets on_stream_exception, and a server never does. So on a server every such exception is dropped at debug level.

This means any request line that fails validation is dropped without a reply, not only this one. The lone surrogate is simply an easy way for a real client to produce one.

Possible fixes, for discussion:

  • On a validation failure in the stdin reader, recover the id from the line where possible, and reply -32700 ("id": null otherwise).
  • Give the server side a default on_stream_exception that logs at warning level and writes a JSON-RPC error.
  • Replace lone surrogates with U+FFFD before validation.

Related:

Steps: run python -m venv venv && venv/bin/pip install "mcp==2.3.0", save the two files below side by side, then run venv/bin/python client.py.

Example Code

# ---- server.py ----
import anyio
import mcp_types as types
from mcp.server.lowlevel import Server
from mcp.server.stdio import stdio_server


async def list_tools(ctx, params):
    return types.ListToolsResult(tools=[types.Tool(
        name="echo", description="echo text",
        input_schema={"type": "object", "properties": {"text": {"type": "string"}}, "required": ["text"]})])


async def call_tool(ctx, params):
    return types.CallToolResult(content=[types.TextContent(type="text", text=params.arguments["text"])])


server = Server("repro", on_list_tools=list_tools, on_call_tool=call_tool)


async def main():
    async with stdio_server() as (r, w):
        await server.run(r, w, server.create_initialization_options())


anyio.run(main)


# ---- client.py ----
import os
import queue
import subprocess
import sys
import threading
import time

HERE = os.path.dirname(os.path.abspath(__file__))
p = subprocess.Popen([sys.executable, os.path.join(HERE, "server.py")], stdin=subprocess.PIPE,
                     stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out = queue.Queue()
threading.Thread(target=lambda: [out.put(l) for l in p.stdout], daemon=True).start()
err = []
threading.Thread(target=lambda: [err.append(l) for l in p.stderr], daemon=True).start()


def send(raw: str):
    p.stdin.write(raw.encode("ascii") + b"\n")  # pure ASCII bytes on the wire
    p.stdin.flush()


def recv(label, timeout=5):
    try:
        print(f"{label}: {out.get(timeout=timeout).decode().strip()}")
    except queue.Empty:
        print(f"{label}: NOTHING within {timeout}s")


def call(i, text_json):
    send('{"jsonrpc":"2.0","id":%d,"method":"tools/call","params":{"name":"echo","arguments":{"text":%s}}}' % (i, text_json))


send('{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18","capabilities":{},"clientInfo":{"name":"c","version":"0"}}}')
recv("id=1 initialize")
send('{"jsonrpc":"2.0","method":"notifications/initialized"}')
call(2, '"hello"')
recv("id=2 normal")
call(3, '"bad \\ud83d bad"')
recv("id=3 lone surrogate")
call(4, '"world"')
recv("id=4 normal after bad line")
print("server alive after:", p.poll() is None, "returncode:", p.poll())
p.stdin.close()
time.sleep(1)
print("stderr:", b"".join(err).decode()[-1500:])
p.kill()

Python & MCP Python SDK

Python 3.14.10
mcp 2.3.0 (mcp-types 2.3.0)
macOS (Darwin 27), stdio transport, low-level Server

Activity

  1. added a commit that references this issue on Nov 22, 2026
    84629e5
  2. added
    bug
    v1
    v2
    on Nov 22, 2026
  3. A7mdMe commented on Nov 23, 2026

    @A7mdMe

    This is a very thorough diagnosis of a critical client-side failure mode in stdio servers.

    Protocol Specification & Impact

    Emitting silence on an unparseable or malformed request line violates JSON-RPC 2.0 Specification §5:

    "When an rpc call encounters an error because the JSON is not well formed, the Response object MUST be an Error object with error code -32700 (Parse error). If the id could not be determined (e.g. parse error), it MUST be Null."

    In client-server architectures, client sessions maintain a pending request map (pending_requests[id] = Future). When the server drops the line without replying:

    1. The future remains unresolved in the client until its client-side deadline (e.g. 30s, 60s).
    2. The entire AI agent's turn freezes during that timeout window.
    3. Subsequent tool calls in the pipeline may be delayed or cancelled.

    Optimal Architectural Solution: The Two-Tiered Approach

    A combination of pre-validation surrogate sanitization and fail-safe ID extraction provides the most resilient solution:

    1. Tier 1: Pre-Sanitize Lone Surrogates to U+FFFD

    In real-world LLM pipelines, text streams frequently get sliced mid-emoji or encoded with ensure_ascii=True, producing lone surrogates like \ud83d.

    Rather than failing the request, replacing isolated surrogates with \uFFFD (Unicode Replacement Character) allows valid JSON syntax to be parsed cleanly. The application tool handler receives the string with \uFFFD and executes normally without throwing an error:

    import re
    
    # Matches high surrogates (D800-DBFF) and low surrogates (DC00-DFFF)
    _LONE_SURROGATE_RE = re.compile(
        r'\\u[dD][89a-bA-B][0-9a-fA-F]{2}(?!\\u[dD][c-fC-F][0-9a-fA-F]{2})|(?<!\\u[dD][89a-bA-B][0-9a-fA-F]{2})\\u[dD][c-fC-F][0-9a-fA-F]{2}'
    )
    
    def sanitize_surrogate_escapes(raw_line: str) -> str:
        """Replaces isolated UTF-16 surrogate escapes with \\uFFFD while preserving valid pairs."""
        return _LONE_SURROGATE_RE.sub(r'\\uFFFD', raw_line)

    2. Tier 2: Fail-Safe Request ID Recovery for Syntax Parse Errors

    If the line is genuinely corrupt JSON (e.g. truncated buffers, syntax errors, mismatched brackets), the stdin reader should fast-scan the line for an id field before discarding it:

    import json
    import re
    
    _ID_SCAN_RE = re.compile(r'"id"\s*:\s*(-?\d+|"[^"\\]*(?:\\.[^"\\]*)*"|null)')
    
    def extract_request_id(raw_line: str):
        """Recovers the request id from unparseable JSON lines to unblock client pending futures."""
        m = _ID_SCAN_RE.search(raw_line)
        if not m:
            return None
        val = m.group(1).strip()
        if val == "null":
            return None
        try:
            return json.loads(val)
        except Exception:
            return val
    
    def make_parse_error(req_id, details: str = "Parse error"):
        return {
            "jsonrpc": "2.0",
            "id": req_id,
            "error": {
                "code": -32700,
                "message": "Parse error",
                "data": details
            }
        }

    Integration in src/mcp/server/stdio.py

    In stdio_server(), when validate_json raises an exception:

    try:
        # 1. Attempt pre-sanitization of lone surrogates
        sanitized_line = sanitize_surrogate_escapes(line)
        message = validate_json(sanitized_line)
        await read_stream.send(message)
    except Exception as exc:
        # 2. Extract request ID if possible
        recovered_id = extract_request_id(line)
        
        # 3. Emit standard JSON-RPC -32700 Parse error to stdout
        error_reply = make_parse_error(recovered_id, str(exc))
        await write_stream.send(error_reply)

    Benefits

    • Zero Client Hangs: The client receives an immediate -32700 response and rejects the specific pending promise in 0ms, allowing the client to recover gracefully instead of freezing for 30-60s.
    • Emoji / Sliced String Fault-Tolerance: Sliced UTF-16 strings with lone surrogates parse and run cleanly with \uFFFD rather than failing outright.
    • Strict Spec Compliance: Adheres directly to JSON-RPC 2.0 §5.

    Disclosure: I maintain the open-source mcp-production-kit and the Production MCP Server Hardening Checklist, where we document and test stdio framing edge cases, surrogate handling, and parse error dispatching across MCP servers.

  4. MilindChatrabhuji commented on Nov 24, 2026

    @MilindChatrabhuji

    I have reproduced this issue locally where an unparseable or malformed request line (e.g. carrying an unescaped/lone surrogate \ud83d) causes validate_json to raise, but stdin_reader in src/mcp/server/stdio.py only forwards the exception to read_stream_writer without emitting any response to write_stream. Because server dispatchers do not register on_stream_exception, the line is dropped at debug level and the client's call hangs indefinitely until timeout, violating JSON-RPC 2.0 §5.

    I have implemented a focused fix in src/mcp/server/stdio.py that extracts the id from the raw line if present and emits a standard types.JSONRPCError with code=types.PARSE_ERROR (-32700) to write_stream, unblocking the client future immediately in 0ms.

    Verification:

    Could a maintainer please assign this issue to me so the PR (#3906) can be reviewed?

  5. MrSpy00 commented on Nov 24, 2026

    @MrSpy00

    I have a tested fix ready for this (replying with a JSONRPCError when a stdio request line fails JSON validation instead of dropping it silently). Could you assign this issue to me so I can reopen the PR?

  6. NUAAwqy commented on Nov 25, 2026

    @NUAAwqy

    Reproduced on main (77001c96) against the three drop points in the report, and confirmed a detail that changes what a correct fix has to do.

    The id is recoverable for this class of line, and that matters. json.loads accepts \ud83d — it is pydantic-core that refuses it (Invalid JSON: unexpected end of hex escape). So for the reported repro the id is not merely "probably readable": the envelope decodes cleanly under the stdlib parser, including id: 3.

    That distinction is load-bearing, because a -32700 carrying "id": null does not actually unblock the client. JSONRPCDispatcher._resolve_pending skips a null id outright:

    pending = self._pending.get(coerce_request_id(request_id)) if request_id is not None else None

    so the reply is written, the client logs "dropping response for unknown/late request id None", and the caller still waits for its own timeout. A fix that answers every validation failure with null therefore leaves the reported hang in place for the reported input — it only helps for inputs whose id cannot be determined at all.

    What I think the shape of the fix should be, based on probing each failure mode:

    1. Classification must not be guessed from the exception type. jsonrpc_message_adapter is a union of the four message models, so a batch, a bare scalar, {}, a bad jsonrpc version and a missing method all raise ValidationError at the envelope rung. Those are -32600, not -32700. Only a json_invalid failure is a parse error. Re-running just the decode stage (pydantic_core.from_json) separates the two reliably.
    2. Recover the id from the lenient decode, accept only a value that is a valid RequestId, and read it from the envelope's top-level id — never from params, where a tool argument may also be named id and would let a bad line resolve an unrelated request.
    3. Guard the echo. An id that is itself a string containing the lone surrogate decodes under json but cannot be re-serialized; writing it back raises UnicodeEncodeError in the writer and kills the transport, which is worse than the current behaviour. That id is genuinely undeterminable to this server, and null is the correct answer there.
    4. Keep forwarding the exception item so on_stream_exception observers keep their view, and swallow ClosedResourceError/BrokenResourceError from the reply send so a torn-down session cannot take the reader's task group with it.

    On the surrogate-sanitization suggestion above (\uFFFD substitution): it is a reasonable separate change, but I would not bundle it here. It silently mutates tool arguments — a model receiving "bad \uFFFD bad" instead of being told its input was corrupt is a worse failure mode for an LLM pipeline than a clear -32700 — and it needs its own discussion about whether the SDK should rewrite client payloads at the transport layer.

    I have a working implementation of the above with regression tests, on the reported repro end to end through MCPServer.run("stdio") (initialize, call, bad line, call → the error arrives addressed to id 3 and the trailing call is still served), plus a -32600/-32700 parametrization table and a test for the unserializable-id case. Before the change the stdio tests fail 18/19; after, all pass, with tests/ at 6251 passed. Posted as #3930 for whenever it is useful — happy to adjust the error data shape or drop the lenient decode in favour of a stricter scan if you would rather not depend on the two parsers disagreeing.

    Also worth noting for the record: the silence covers any line that fails validation on stdio, not only surrogates — a truncated write, a malformed envelope, an oversized integer literal — so this is a fairly broad class. (Stray output from a child process is not one of them: _claim_fd diverts fd 1 to stderr while serving precisely so children cannot pollute the wire.)

  7. buildwithpnj commented on Nov 28, 2026

    @buildwithpnj

    Verified locally (AI-assisted analysis & testing): invalid JSON or lone-surrogate stdin frames fail inside stdio_server's reader task without emitting a JSON-RPC -32700 Parse error response, leaving the client waiting.

    I have a tested fix adding MalformedJSONRPCError + _extract_request_id (src/mcp/server/stdio.py) and wiring _make_stream_exception_handler into JSONRPCDispatcher (src/mcp/server/runner.py) with regression tests in tests/server/test_stdio.py. Happy to submit a PR if assigned or labeled help wanted.

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

    bugv1v2

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions