Skip to content

Commit dcdba10

Browse files
Copilotstephentoub
andcommitted
Fix race condition in StdioClientTransport on .NET Framework
Add thread synchronization around Console.InputEncoding modification to prevent race conditions when multiple transports are created concurrently on .NET Framework. Co-authored-by: stephentoub <2642209+stephentoub@users.noreply.github.com>
1 parent 8b9e999 commit dcdba10

1 file changed

Lines changed: 19 additions & 8 deletions

File tree

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

@@ -156,18 +162,23 @@ public async Task<ITransport> ConnectAsync(CancellationToken cancellationToken =
156162
// up the encoding from Console.InputEncoding. As such, when not targeting .NET Core,
157163
// we temporarily change Console.InputEncoding to no-BOM UTF-8 around the Process.Start
158164
// call, to ensure it picks up the correct encoding.
165+
// IMPORTANT: This must be synchronized to prevent race conditions when multiple
166+
// transports are created concurrently.
159167
#if NET
160168
processStarted = process.Start();
161169
#else
162-
Encoding originalInputEncoding = Console.InputEncoding;
163-
try
164-
{
165-
Console.InputEncoding = StreamClientSessionTransport.NoBomUtf8Encoding;
166-
processStarted = process.Start();
167-
}
168-
finally
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)