Skip to content

Commit 1066199

Browse files
rnortmandsp-ant
authored andcommitted
Force stdin/stdout encoding to UTF-8
The character encoding of the stdin/stdout streams in Python is platform- dependent. On Windows it will be something weird, like CP437 or CP1252, depending on the locale. This change ensures that no matter the platform, UTF-8 is used.
1 parent 5480f67 commit 1066199

File tree

1 file changed

+6
-3
lines changed

1 file changed

+6
-3
lines changed

src/mcp/server/stdio.py

+6-3
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@ async def run_server():
2020

2121
import sys
2222
from contextlib import asynccontextmanager
23+
from io import TextIOWrapper
2324

2425
import anyio
2526
import anyio.lowlevel
@@ -38,11 +39,13 @@ async def stdio_server(
3839
from the current process' stdin and writing to stdout.
3940
"""
4041
# Purposely not using context managers for these, as we don't want to close
41-
# standard process handles.
42+
# standard process handles. Encoding of stdin/stdout as text streams on
43+
# python is platform-dependent (Windows is particularly problematic), so we
44+
# re-wrap the underlying binary stream to ensure UTF-8.
4245
if not stdin:
43-
stdin = anyio.wrap_file(sys.stdin)
46+
stdin = anyio.wrap_file(TextIOWrapper(sys.stdin.buffer, encoding="utf-8"))
4447
if not stdout:
45-
stdout = anyio.wrap_file(sys.stdout)
48+
stdout = anyio.wrap_file(TextIOWrapper(sys.stdout.buffer, encoding="utf-8"))
4649

4750
read_stream: MemoryObjectReceiveStream[types.JSONRPCMessage | Exception]
4851
read_stream_writer: MemoryObjectSendStream[types.JSONRPCMessage | Exception]

0 commit comments

Comments
 (0)