File tree Expand file tree Collapse file tree 1 file changed +19
-8
lines changed
src/ModelContextProtocol.Core/Client Expand file tree Collapse file tree 1 file changed +19
-8
lines changed Original file line number Diff line number Diff line change @@ -25,6 +25,12 @@ namespace ModelContextProtocol.Client;
2525/// </remarks>
2626public sealed partial class StdioClientTransport : IClientTransport
2727{
28+ #if ! NET
29+ // On .NET Framework, we need to synchronize access to Console.InputEncoding
30+ // to prevent race conditions when multiple transports are created concurrently.
31+ private static readonly object s_consoleEncodingLock = new ( ) ;
32+ #endif
33+
2834 private readonly StdioClientTransportOptions _options ;
2935 private readonly ILoggerFactory ? _loggerFactory ;
3036
@@ -159,15 +165,20 @@ public async Task<ITransport> ConnectAsync(CancellationToken cancellationToken =
159165#if NET
160166 processStarted = process . Start ( ) ;
161167#else
162- Encoding originalInputEncoding = Console . InputEncoding ;
163- try
164- {
165- Console . InputEncoding = StreamClientSessionTransport . NoBomUtf8Encoding ;
166- processStarted = process . Start ( ) ;
167- }
168- finally
168+ // IMPORTANT: This must be synchronized to prevent race conditions when multiple
169+ // transports are created concurrently.
170+ lock ( s_consoleEncodingLock )
169171 {
170- Console . InputEncoding = originalInputEncoding ;
172+ Encoding originalInputEncoding = Console . InputEncoding ;
173+ try
174+ {
175+ Console . InputEncoding = StreamClientSessionTransport . NoBomUtf8Encoding ;
176+ processStarted = process . Start ( ) ;
177+ }
178+ finally
179+ {
180+ Console . InputEncoding = originalInputEncoding ;
181+ }
171182 }
172183#endif
173184
You can’t perform that action at this time.
0 commit comments