fix: handle non-UTF-8 bytes in stdio server stdin
TextIOWrapper(sys.stdin.buffer, encoding="utf-8") defaults to errors="strict", which raises UnicodeDecodeError when stdin contains bytes that are not valid UTF-8. The exception occurs during async for line in stdin: iteration — outside the JSON-parsing try/except — so it propagates through the task group and terminates the server process.
With errors="replace", invalid bytes become U+FFFD. The resulting line then fails JSON validation, which is already caught and sent into the read stream as an exception for the session layer to handle — the same path as any other malformed input.
Motivation and Context
The MCP spec requires clients to send valid UTF-8 JSON-RPC, and in stdio transport the client spawns the server as its own subprocess — so in practice this only triggers when a client sends protocol-violating input to its own child. But the server process dying on a single bad byte is worse than surfacing a parse error, and the other MCP SDKs (TypeScript, C#, Go, Rust) all handle this gracefully.
How Has This Been Tested?
Regression test test_stdio_server_invalid_utf8 monkeypatches sys.stdin with a binary buffer containing \xff\xfe\n followed by a valid JSON-RPC message. It verifies the invalid line surfaces as an in-stream exception and the valid message still comes through afterward. Fails on main with ExceptionGroup(UnicodeDecodeError), passes with this fix.
Breaking Changes
None.
Types of changes
- Bug fix (non-breaking change which fixes an issue)
- New feature (non-breaking change which adds functionality)
- Breaking change (fix or feature that would cause existing functionality to change)
- Documentation update
Checklist
- I have read the MCP Documentation
- My code follows the repository's style guidelines
- New and existing tests pass locally
- I have added appropriate error handling
- I have added or updated documentation as needed
Additional context
Reported by @manthanghasadiya.
src/mcp/client/stdio.py has a related issue — StdioServerParameters.encoding_error_handler defaults to "strict", so a buggy server can crash the client the same way. It's configurable so lower priority; worth a follow-up to change the default.