Skip to content

Commit e6db415

Browse files
Copilotstephentoub
andauthored
Fix race condition in StdioClientTransport on .NET Framework (#996)
Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com> Co-authored-by: stephentoub <2642209+stephentoub@users.noreply.github.com>
1 parent a9427f9 commit e6db415

File tree

1 file changed

+19
-8
lines changed

1 file changed

+19
-8
lines changed

src/ModelContextProtocol.Core/Client/StdioClientTransport.cs

Lines changed: 19 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,12 @@ namespace ModelContextProtocol.Client;
2525
/// </remarks>
2626
public 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

0 commit comments

Comments
 (0)