stdio server sends no reply to a request line that fails JSON validation (e.g. a lone surrogate escape "\ud83d"), so the call hangs
Mantenedores costumam responder em até 1 dia
Ninguém assumiu esta issue ainda.
- #3895 de @IngTian — fechado sem integrar
- #3902 de @MrSpy00 — fechado sem integrar
- #3905 de @chengwudi1 — fechado sem integrar
- #3906 de @MilindChatrabhuji — fechado sem integrar
- #3916 de @EnesKartal — fechado sem integrar
- #3930 de @NUAAwqy — fechado sem integrar
- #3942 de @Echolonius — fechado sem integrar
Avaliação
- Dificuldade
- 3/5
- Tempo estimado
- 1-2 dias
- Facilidade para iniciantes
- 62/100
Direção de pesquisa
Read the stdin reader at src/mcp/server/stdio.py around L188-L192, where validate_json raises and the loop continues, then the exception branch at src/mcp/shared/jsonrpc_dispatcher.py L555-L558 that drops the item when on_stream_exception is None. Run the reporter's server.py and client.py pair to watch id=3 time out while ids 1, 2 and 4 answer. Done means a -32700 reply (or an U+FFFD-substituted call) reaches the client for the bad line, with a regression test alongside the existing stdio transport tests; pick one of the three proposed fixes before coding.
Escrita pelo modelo de indexação a partir do texto da issue.
Descrição
Initial Checks
- I confirm that I'm using the newest release of my line (the latest 2.x, or the latest 1.x if I'm still on v1)
- I confirm that I searched for my issue in https://github.com/modelcontextprotocol/python-sdk/issues before opening this issue
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 defaultensure_ascii=True) writes\ud83dfor 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 #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.pyL188-L192.validate_jsonraises, theexcept Exceptionsends the exception into the read stream, and itcontinues. No error response is built, because the request id has not been parsed. - The dispatcher:
src/mcp/shared/jsonrpc_dispatcher.pyL555-L558. For an exception item, whenon_stream_exceptionis None it only callslogger.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
idfrom the line where possible, and reply-32700("id": nullotherwise). - Give the server side a default
on_stream_exceptionthat logs at warning level and writes a JSON-RPC error. - Replace lone surrogates with U+FFFD before validation.
Related:
- #3707 covers the outgoing direction: a lone surrogate in a message the server writes.
- #2302 covers non-UTF-8 bytes on stdin.
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
- Linguagem predominante
- Python
- Estrelas
- 25k
- Forks
- 4.2k
- Merge médio
- 10min
- PRs com merge (30d)
- 1
Preparar o ambiente
- Sem Dockerfile nem arquivo Docker Compose
- Tem um modelo de pull request
- Ler o guia de contribuição
Primeiros passos
- Leia a issue inteira e depois o guia de contribuição do projeto.
- Comente na issue dizendo que vai assumir — evita que duas pessoas façam o mesmo trabalho.
- Faça um fork do repositório e trabalhe em uma branch.
- Abra um pull request que referencie o número da issue.
Mais de modelcontextprotocol/python-sdk
-
v2
Dificuldade 1/5 Menos de uma hora Facilidade para iniciantes 86/100
modelcontextprotocol/python-sdk#3978 · 2 comentários ·
Mantenedores costumam responder em até 1 dia
-
Client serves cached tools after its context exits with an exceptionTalvez já em andamento @jonxsong assumiu há 1 dia. Aberta
Dificuldade 2/5 1-3 horas Facilidade para iniciantes 65/100
modelcontextprotocol/python-sdk#3968 · 1 comentário ·
Mantenedores costumam responder em até 1 dia
-
Dificuldade 2/5 1-3 horas Facilidade para iniciantes 85/100
modelcontextprotocol/python-sdk#3957 ·
Mantenedores costumam responder em até 1 dia
-
v2
Dificuldade 1/5 Menos de uma hora Facilidade para iniciantes 91/100
modelcontextprotocol/python-sdk#3934 · 2 comentários ·
Mantenedores costumam responder em até 1 dia
-
bug v1
Dificuldade 2/5 1-3 horas Facilidade para iniciantes 79/100
modelcontextprotocol/python-sdk#3929 · 2 comentários ·
Mantenedores costumam responder em até 1 dia
Todas as issues de modelcontextprotocol/python-sdk
Issues semelhantes
-
soup prune-prompt exits 1 after writing its output on a file over 100,000 rows, and reports a capped row count otherwiseTalvez já em andamento @abdulwaarith0 assumiu hoje. Abertaneeds-triage
Dificuldade 2/5 1-3 horas Facilidade para iniciantes 84/100
MakazhanAlpamys/Soup#3690 · 1 comentário ·
Mantenedores costumam responder em até 1 dia
-
Dificuldade 2/5 1-3 horas Facilidade para iniciantes 78/100
Mantenedores costumam responder em até 1 dia
-
Dificuldade 2/5 1-3 horas Facilidade para iniciantes 78/100
-
bug data-types native-format
Dificuldade 2/5 1-3 horas Facilidade para iniciantes 65/100
ClickHouse/clickhouse-connect#1320 ·
Mantenedores costumam responder em até 1 dia
-
Public benchmark import end-to-end test fails when the test stack's worker runs the parity jobAbertaaccepted
Dificuldade 2/5 1-3 horas Facilidade para iniciantes 68/100
future-agi/future-agi#6392 ·
Mantenedores costumam responder em até 1 dia