11import os
22import sys
33from contextlib import asynccontextmanager
4+ from typing import Literal
45
56import anyio
67import anyio .lowlevel
@@ -65,6 +66,21 @@ class StdioServerParameters(BaseModel):
6566 If not specified, the result of get_default_environment() will be used.
6667 """
6768
69+ encoding : str = "utf-8"
70+ """
71+ The text encoding used when sending/receiving messages to the server
72+
73+ defaults to utf-8
74+ """
75+
76+ encoding_error_handler : Literal ["strict" , "ignore" , "replace" ] = "strict"
77+ """
78+ The text encoding error handler.
79+
80+ See https://docs.python.org/3/library/codecs.html#codec-base-classes for
81+ explanations of possible values
82+ """
83+
6884
6985@asynccontextmanager
7086async def stdio_client (server : StdioServerParameters ):
@@ -93,7 +109,11 @@ async def stdout_reader():
93109 try :
94110 async with read_stream_writer :
95111 buffer = ""
96- async for chunk in TextReceiveStream (process .stdout ):
112+ async for chunk in TextReceiveStream (
113+ process .stdout ,
114+ encoding = server .encoding ,
115+ errors = server .encoding_error_handler ,
116+ ):
97117 lines = (buffer + chunk ).split ("\n " )
98118 buffer = lines .pop ()
99119
@@ -115,7 +135,12 @@ async def stdin_writer():
115135 async with write_stream_reader :
116136 async for message in write_stream_reader :
117137 json = message .model_dump_json (by_alias = True , exclude_none = True )
118- await process .stdin .send ((json + "\n " ).encode ())
138+ await process .stdin .send (
139+ (json + "\n " ).encode (
140+ encoding = server .encoding ,
141+ errors = server .encoding_error_handler ,
142+ )
143+ )
119144 except anyio .ClosedResourceError :
120145 await anyio .lowlevel .checkpoint ()
121146
0 commit comments