diff --git a/src/mcp/client/stdio.py b/src/mcp/client/stdio.py index 6a3ad12111..9a07b665ce 100644 --- a/src/mcp/client/stdio.py +++ b/src/mcp/client/stdio.py @@ -107,8 +107,12 @@ class StdioServerParameters(BaseModel): encoding: str = "utf-8" """Text encoding for messages to and from the server.""" - encoding_error_handler: Literal["strict", "ignore", "replace"] = "strict" - """Encoding error handler; see https://docs.python.org/3/library/codecs.html#error-handlers.""" + encoding_error_handler: Literal["strict", "ignore", "replace"] = "replace" + """Encoding error handler; see https://docs.python.org/3/library/codecs.html#error-handlers. + + Defaults to `"replace"` so that malformed output from the server becomes U+FFFD and the + line surfaces as a parse error on the read stream, leaving the session able to carry on. + """ @asynccontextmanager diff --git a/tests/client/test_stdio.py b/tests/client/test_stdio.py index b64eb01902..949e563167 100644 --- a/tests/client/test_stdio.py +++ b/tests/client/test_stdio.py @@ -323,6 +323,30 @@ async def test_invalid_json_from_the_server_surfaces_as_an_in_stream_exception( assert await _next_message(read_stream) == ping +@pytest.mark.anyio +async def test_invalid_utf8_from_the_server_surfaces_as_an_in_stream_exception( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """Undecodable bytes mid-session are replaced rather than ending the session. + + A server emitting a malformed line must not take the transport down with it; the line + arrives as an Exception and the messages after it still come through. + """ + ping = JSONRPCRequest(jsonrpc="2.0", id=1, method="ping") + process = FakeProcess(on_stdin_close=lambda: process.exit(0)) + + install_fake_process(monkeypatch, process) + + with anyio.fail_after(5): + async with stdio_client(FAKE_PARAMS) as (read_stream, _): + await process.feed(b"\xff\xfe\n" + _line(ping)) + + error = await read_stream.receive() + # The undecodable bytes become U+FFFD, which then fails JSON-RPC validation. + assert isinstance(error, ValueError) + assert await _next_message(read_stream) == ping + + @pytest.mark.anyio async def test_a_server_that_dies_before_responding_fails_initialize_with_connection_closed( monkeypatch: pytest.MonkeyPatch,