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,21 @@ 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
81
+ explanations of possible values
82
+ """
83
+
68
84
69
85
@asynccontextmanager
70
86
async def stdio_client (server : StdioServerParameters ):
@@ -93,7 +109,11 @@ async def stdout_reader():
93
109
try :
94
110
async with read_stream_writer :
95
111
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
+ ):
97
117
lines = (buffer + chunk ).split ("\n " )
98
118
buffer = lines .pop ()
99
119
@@ -115,7 +135,12 @@ async def stdin_writer():
115
135
async with write_stream_reader :
116
136
async for message in write_stream_reader :
117
137
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
+ )
119
144
except anyio .ClosedResourceError :
120
145
await anyio .lowlevel .checkpoint ()
121
146
0 commit comments