diff --git a/src/mcp/server/stdio.py b/src/mcp/server/stdio.py index d74d6bc..0e0e491 100644 --- a/src/mcp/server/stdio.py +++ b/src/mcp/server/stdio.py @@ -20,6 +20,7 @@ Example usage: import sys from contextlib import asynccontextmanager +from io import TextIOWrapper import anyio import anyio.lowlevel @@ -38,11 +39,13 @@ async def stdio_server( from the current process' stdin and writing to stdout. """ # Purposely not using context managers for these, as we don't want to close - # standard process handles. + # standard process handles. Encoding of stdin/stdout as text streams on + # python is platform-dependent (Windows is particularly problematic), so we + # re-wrap the underlying binary stream to ensure UTF-8. if not stdin: - stdin = anyio.wrap_file(sys.stdin) + stdin = anyio.wrap_file(TextIOWrapper(sys.stdin.buffer, encoding="utf-8")) if not stdout: - stdout = anyio.wrap_file(sys.stdout) + stdout = anyio.wrap_file(TextIOWrapper(sys.stdout.buffer, encoding="utf-8")) read_stream: MemoryObjectReceiveStream[types.JSONRPCMessage | Exception] read_stream_writer: MemoryObjectSendStream[types.JSONRPCMessage | Exception]