Fix StdioServerTransport.DisposeAsync hang (#235)
- It's not just Unix, it's all platforms that can hang - Windows doesn't hang on Ctrl-C because that triggers the end of the Stream, but that doesn't help in IHostApplicationLifetime.StopAsync() scenarios4e9627e311/src/libraries/System.Console/src/System/ConsolePal.Unix.ConsoleStream.cs (L13)4e9627e311/src/libraries/System.Console/src/System/ConsolePal.Windows.cs (L1149)
This commit is contained in:
parent
3e21f3594a
commit
bab74d5895
5 changed files with 114 additions and 8 deletions
|
|
@ -2,7 +2,7 @@
|
||||||
|
|
||||||
<PropertyGroup>
|
<PropertyGroup>
|
||||||
<OutputType>Exe</OutputType>
|
<OutputType>Exe</OutputType>
|
||||||
<TargetFramework>net9.0</TargetFramework>
|
<TargetFrameworks>net9.0;net8.0</TargetFrameworks>
|
||||||
<ImplicitUsings>enable</ImplicitUsings>
|
<ImplicitUsings>enable</ImplicitUsings>
|
||||||
<Nullable>enable</Nullable>
|
<Nullable>enable</Nullable>
|
||||||
<!--
|
<!--
|
||||||
|
|
|
||||||
|
|
@ -60,7 +60,7 @@ public sealed class StdioServerTransport : StreamServerTransport
|
||||||
/// </para>
|
/// </para>
|
||||||
/// </remarks>
|
/// </remarks>
|
||||||
public StdioServerTransport(string serverName, ILoggerFactory? loggerFactory = null)
|
public StdioServerTransport(string serverName, ILoggerFactory? loggerFactory = null)
|
||||||
: base(Console.OpenStandardInput(),
|
: base(new CancellableStdinStream(Console.OpenStandardInput()),
|
||||||
new BufferedStream(Console.OpenStandardOutput()),
|
new BufferedStream(Console.OpenStandardOutput()),
|
||||||
serverName ?? throw new ArgumentNullException(nameof(serverName)),
|
serverName ?? throw new ArgumentNullException(nameof(serverName)),
|
||||||
loggerFactory)
|
loggerFactory)
|
||||||
|
|
@ -73,4 +73,37 @@ public sealed class StdioServerTransport : StreamServerTransport
|
||||||
|
|
||||||
return serverOptions.ServerInfo?.Name ?? McpServer.DefaultImplementation.Name;
|
return serverOptions.ServerInfo?.Name ?? McpServer.DefaultImplementation.Name;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Neither WindowsConsoleStream nor UnixConsoleStream respect CancellationTokens or cancel any I/O on Dispose.
|
||||||
|
// WindowsConsoleStream will return an EOS on Ctrl-C, but that is not the only reason the shutdownToken may fire.
|
||||||
|
private sealed class CancellableStdinStream(Stream stdinStream) : Stream
|
||||||
|
{
|
||||||
|
public override bool CanRead => true;
|
||||||
|
public override bool CanSeek => false;
|
||||||
|
public override bool CanWrite => false;
|
||||||
|
|
||||||
|
public override Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
|
||||||
|
=> stdinStream.ReadAsync(buffer, offset, count, cancellationToken).WaitAsync(cancellationToken);
|
||||||
|
|
||||||
|
#if NET
|
||||||
|
public override ValueTask<int> ReadAsync(Memory<byte> buffer, CancellationToken cancellationToken = default)
|
||||||
|
{
|
||||||
|
ValueTask<int> vt = stdinStream.ReadAsync(buffer, cancellationToken);
|
||||||
|
return vt.IsCompletedSuccessfully ? vt : new(vt.AsTask().WaitAsync(cancellationToken));
|
||||||
|
}
|
||||||
|
#endif
|
||||||
|
|
||||||
|
// The McpServer shouldn't call flush on the stdin Stream, but it doesn't need to throw just in case.
|
||||||
|
public override void Flush() { }
|
||||||
|
|
||||||
|
public override long Length => throw new NotSupportedException();
|
||||||
|
|
||||||
|
public override long Position { get => throw new NotSupportedException(); set => throw new NotSupportedException(); }
|
||||||
|
|
||||||
|
public override int Read(byte[] buffer, int offset, int count) => throw new NotSupportedException();
|
||||||
|
public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException();
|
||||||
|
|
||||||
|
public override void SetLength(long value) => throw new NotSupportedException();
|
||||||
|
public override void Write(byte[] buffer, int offset, int count) => throw new NotSupportedException();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -47,6 +47,7 @@
|
||||||
<ProjectReference Include="..\..\src\ModelContextProtocol\ModelContextProtocol.csproj" />
|
<ProjectReference Include="..\..\src\ModelContextProtocol\ModelContextProtocol.csproj" />
|
||||||
<ProjectReference Include="..\ModelContextProtocol.TestServer\ModelContextProtocol.TestServer.csproj" />
|
<ProjectReference Include="..\ModelContextProtocol.TestServer\ModelContextProtocol.TestServer.csproj" />
|
||||||
<ProjectReference Include="..\ModelContextProtocol.TestSseServer\ModelContextProtocol.TestSseServer.csproj" />
|
<ProjectReference Include="..\ModelContextProtocol.TestSseServer\ModelContextProtocol.TestSseServer.csproj" />
|
||||||
|
<ProjectReference Include="..\..\samples\TestServerWithHosting\TestServerWithHosting.csproj" />
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
|
|
@ -56,6 +57,12 @@
|
||||||
<Content Condition="$([MSBuild]::IsOSPlatform('Linux'))" Include="$([System.IO.Path]::GetFullPath('$(ArtifactsBinDir)ModelContextProtocol.TestServer\$(Configuration)'))\$(TargetFramework)\TestServer.dll">
|
<Content Condition="$([MSBuild]::IsOSPlatform('Linux'))" Include="$([System.IO.Path]::GetFullPath('$(ArtifactsBinDir)ModelContextProtocol.TestServer\$(Configuration)'))\$(TargetFramework)\TestServer.dll">
|
||||||
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
|
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
|
||||||
</Content>
|
</Content>
|
||||||
|
<Content Condition="$([MSBuild]::IsOSPlatform('Windows'))" Include="$([System.IO.Path]::GetFullPath('$(ArtifactsBinDir)TestServerWithHosting\$(Configuration)'))\$(TargetFramework)\TestServerWithHosting.exe">
|
||||||
|
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
|
||||||
|
</Content>
|
||||||
|
<Content Condition="$([MSBuild]::IsOSPlatform('Linux'))" Include="$([System.IO.Path]::GetFullPath('$(ArtifactsBinDir)TestServerWithHosting\$(Configuration)'))\$(TargetFramework)\TestServerWithHosting.dll">
|
||||||
|
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
|
||||||
|
</Content>
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|
||||||
</Project>
|
</Project>
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,66 @@
|
||||||
|
using ModelContextProtocol.Client;
|
||||||
|
using ModelContextProtocol.Protocol.Transport;
|
||||||
|
using ModelContextProtocol.Tests.Utils;
|
||||||
|
using System.Diagnostics;
|
||||||
|
using System.Runtime.InteropServices;
|
||||||
|
|
||||||
|
namespace ModelContextProtocol.Tests;
|
||||||
|
|
||||||
|
public class StdioServerIntegrationTests(ITestOutputHelper testOutputHelper) : LoggedTest(testOutputHelper)
|
||||||
|
{
|
||||||
|
public static bool CanSendSigInt { get; } = RuntimeInformation.IsOSPlatform(OSPlatform.Linux) || RuntimeInformation.IsOSPlatform(OSPlatform.OSX);
|
||||||
|
private const int SIGINT = 2;
|
||||||
|
|
||||||
|
[Fact(Skip = "Platform not supported by this test.", SkipUnless = nameof(CanSendSigInt))]
|
||||||
|
public async Task SigInt_DisposesTestServerWithHosting_Gracefully()
|
||||||
|
{
|
||||||
|
using var process = new Process
|
||||||
|
{
|
||||||
|
StartInfo = new ProcessStartInfo
|
||||||
|
{
|
||||||
|
FileName = "dotnet",
|
||||||
|
Arguments = "TestServerWithHosting.dll",
|
||||||
|
RedirectStandardInput = true,
|
||||||
|
RedirectStandardOutput = true,
|
||||||
|
UseShellExecute = false,
|
||||||
|
CreateNoWindow = true,
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
process.Start();
|
||||||
|
|
||||||
|
await using var streamServerTransport = new StreamServerTransport(
|
||||||
|
process.StandardOutput.BaseStream,
|
||||||
|
process.StandardInput.BaseStream,
|
||||||
|
serverName: "TestServerWithHosting");
|
||||||
|
|
||||||
|
await using var client = await McpClientFactory.CreateAsync(
|
||||||
|
new TestClientTransport(streamServerTransport),
|
||||||
|
loggerFactory: LoggerFactory,
|
||||||
|
cancellationToken: TestContext.Current.CancellationToken);
|
||||||
|
|
||||||
|
// I considered writing a similar test for Windows using Ctrl-C, then saw that dotnet watch doesn't even send a Ctrl-C
|
||||||
|
// signal because it's such a pain without support for CREATE_NEW_PROCESS_GROUP in System.Diagnostics.Process.
|
||||||
|
// https://github.com/dotnet/sdk/blob/43b1c12e3362098a23ca1018503eb56516840b6a/src/BuiltInTools/dotnet-watch/Internal/ProcessRunner.cs#L277-L303
|
||||||
|
// https://github.com/dotnet/runtime/issues/109432, https://github.com/dotnet/runtime/issues/44944
|
||||||
|
Assert.Equal(0, kill(process.Id, SIGINT));
|
||||||
|
|
||||||
|
using var shutdownCts = CancellationTokenSource.CreateLinkedTokenSource(TestContext.Current.CancellationToken);
|
||||||
|
shutdownCts.CancelAfter(TimeSpan.FromSeconds(10));
|
||||||
|
await process.WaitForExitAsync(shutdownCts.Token);
|
||||||
|
|
||||||
|
Assert.True(process.HasExited);
|
||||||
|
Assert.Equal(0, process.ExitCode);
|
||||||
|
}
|
||||||
|
|
||||||
|
[DllImport("libc", SetLastError = true)]
|
||||||
|
private static extern int kill(int pid, int sig);
|
||||||
|
|
||||||
|
private sealed class TestClientTransport(ITransport sessionTransport) : IClientTransport
|
||||||
|
{
|
||||||
|
public string Name => nameof(TestClientTransport);
|
||||||
|
|
||||||
|
public Task<ITransport> ConnectAsync(CancellationToken cancellationToken = default)
|
||||||
|
=> Task.FromResult(sessionTransport);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -8,8 +8,8 @@ public sealed class KestrelInMemoryConnection : ConnectionContext
|
||||||
{
|
{
|
||||||
private readonly Pipe _clientToServerPipe = new();
|
private readonly Pipe _clientToServerPipe = new();
|
||||||
private readonly Pipe _serverToClientPipe = new();
|
private readonly Pipe _serverToClientPipe = new();
|
||||||
private readonly CancellationTokenSource _connectionClosedCts = new CancellationTokenSource();
|
private readonly CancellationTokenSource _connectionClosedCts = new();
|
||||||
private readonly IFeatureCollection _features = new FeatureCollection();
|
private readonly FeatureCollection _features = new();
|
||||||
|
|
||||||
public KestrelInMemoryConnection()
|
public KestrelInMemoryConnection()
|
||||||
{
|
{
|
||||||
|
|
@ -37,17 +37,17 @@ public sealed class KestrelInMemoryConnection : ConnectionContext
|
||||||
|
|
||||||
public override IDictionary<object, object?> Items { get; set; } = new Dictionary<object, object?>();
|
public override IDictionary<object, object?> Items { get; set; } = new Dictionary<object, object?>();
|
||||||
|
|
||||||
public override ValueTask DisposeAsync()
|
public override async ValueTask DisposeAsync()
|
||||||
{
|
{
|
||||||
// This is called by Kestrel. The client should dispose the DuplexStream which
|
// This is called by Kestrel. The client should dispose the DuplexStream which
|
||||||
// completes the other half of these pipes.
|
// completes the other half of these pipes.
|
||||||
_serverToClientPipe.Writer.Complete();
|
await _serverToClientPipe.Writer.CompleteAsync();
|
||||||
_serverToClientPipe.Reader.Complete();
|
await _serverToClientPipe.Reader.CompleteAsync();
|
||||||
|
|
||||||
// Don't bother disposing the _connectionClosedCts, since this is just for testing,
|
// Don't bother disposing the _connectionClosedCts, since this is just for testing,
|
||||||
// and it's annoying to synchronize with DuplexStream.
|
// and it's annoying to synchronize with DuplexStream.
|
||||||
|
|
||||||
return base.DisposeAsync();
|
await base.DisposeAsync();
|
||||||
}
|
}
|
||||||
|
|
||||||
private class DuplexPipe : IDuplexPipe
|
private class DuplexPipe : IDuplexPipe
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue