Skip to content

Commit a95d986

Browse files
author
xiangb-a
committed
We should check in advance whether we are using a console program. If we are not using a console program, setting the input and output language of Console will have no effect and will throw an exception. For example, when using WPF, an exception will be thrown here, causing the connection to fail
1 parent 5e5b1af commit a95d986

File tree

1 file changed

+17
-10
lines changed

1 file changed

+17
-10
lines changed

src/ModelContextProtocol.Core/Client/StdioClientTransport.cs

Lines changed: 17 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -156,20 +156,21 @@ public async Task<ITransport> ConnectAsync(CancellationToken cancellationToken =
156156
// up the encoding from Console.InputEncoding. As such, when not targeting .NET Core,
157157
// we temporarily change Console.InputEncoding to no-BOM UTF-8 around the Process.Start
158158
// call, to ensure it picks up the correct encoding.
159-
#if NET
160-
processStarted = process.Start();
161-
#else
159+
#if !NET
162160
Encoding originalInputEncoding = Console.InputEncoding;
163-
try
164-
{
165-
Console.InputEncoding = StreamClientSessionTransport.NoBomUtf8Encoding;
166-
processStarted = process.Start();
167-
}
168-
finally
161+
if (HasConsole())
169162
{
170-
Console.InputEncoding = originalInputEncoding;
163+
try
164+
{
165+
Console.InputEncoding = StreamClientSessionTransport.NoBomUtf8Encoding;
166+
}
167+
finally
168+
{
169+
Console.InputEncoding = originalInputEncoding;
170+
}
171171
}
172172
#endif
173+
processStarted = process.Start();
173174

174175
if (!processStarted)
175176
{
@@ -199,7 +200,13 @@ public async Task<ITransport> ConnectAsync(CancellationToken cancellationToken =
199200
throw new IOException("Failed to connect transport.", ex);
200201
}
201202
}
203+
[DllImport("kernel32.dll")]
204+
private static extern IntPtr GetConsoleWindow();
202205

206+
private static bool HasConsole()
207+
{
208+
try { return GetConsoleWindow() != IntPtr.Zero; } catch { return false; }
209+
}
203210
internal static void DisposeProcess(
204211
Process? process, bool processRunning, TimeSpan shutdownTimeout, string endpointName)
205212
{

0 commit comments

Comments
 (0)