Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 19 additions & 8 deletions src/ModelContextProtocol.Core/Client/StdioClientTransport.cs
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,12 @@ namespace ModelContextProtocol.Client;
/// </remarks>
public sealed partial class StdioClientTransport : IClientTransport
{
#if !NET
// On .NET Framework, we need to synchronize access to Console.InputEncoding
// to prevent race conditions when multiple transports are created concurrently.
private static readonly object s_consoleEncodingLock = new();
#endif

private readonly StdioClientTransportOptions _options;
private readonly ILoggerFactory? _loggerFactory;

Expand Down Expand Up @@ -159,15 +165,20 @@ public async Task<ITransport> ConnectAsync(CancellationToken cancellationToken =
#if NET
processStarted = process.Start();
#else
Encoding originalInputEncoding = Console.InputEncoding;
try
{
Console.InputEncoding = StreamClientSessionTransport.NoBomUtf8Encoding;
processStarted = process.Start();
}
finally
// IMPORTANT: This must be synchronized to prevent race conditions when multiple
// transports are created concurrently.
lock (s_consoleEncodingLock)
{
Console.InputEncoding = originalInputEncoding;
Encoding originalInputEncoding = Console.InputEncoding;
try
{
Console.InputEncoding = StreamClientSessionTransport.NoBomUtf8Encoding;
processStarted = process.Start();
}
finally
{
Console.InputEncoding = originalInputEncoding;
}
}
#endif

Expand Down
Loading