1
1
import os
2
2
import sys
3
3
from contextlib import asynccontextmanager
4
+ from typing import Literal
4
5
5
6
import anyio
6
7
import anyio .lowlevel
@@ -65,6 +66,20 @@ class StdioServerParameters(BaseModel):
65
66
If not specified, the result of get_default_environment() will be used.
66
67
"""
67
68
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 explanations of possible values
81
+ """
82
+
68
83
69
84
@asynccontextmanager
70
85
async def stdio_client (server : StdioServerParameters ):
@@ -93,7 +108,7 @@ async def stdout_reader():
93
108
try :
94
109
async with read_stream_writer :
95
110
buffer = ""
96
- async for chunk in TextReceiveStream (process .stdout ):
111
+ async for chunk in TextReceiveStream (process .stdout , encoding = server . encoding , errors = server . encoding_error_handler ):
97
112
lines = (buffer + chunk ).split ("\n " )
98
113
buffer = lines .pop ()
99
114
@@ -115,7 +130,7 @@ async def stdin_writer():
115
130
async with write_stream_reader :
116
131
async for message in write_stream_reader :
117
132
json = message .model_dump_json (by_alias = True , exclude_none = True )
118
- await process .stdin .send ((json + "\n " ).encode ())
133
+ await process .stdin .send ((json + "\n " ).encode (encoding = server . encoding , errors = server . encoding_error_handler ))
119
134
except anyio .ClosedResourceError :
120
135
await anyio .lowlevel .checkpoint ()
121
136
0 commit comments