Skip to content

Stop the host when the single session server service finishes #226

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Apr 7, 2025
Merged
Show file tree
Hide file tree
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
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,22 @@ namespace ModelContextProtocol.Hosting;
/// <summary>
/// Hosted service for a single-session (e.g. stdio) MCP server.
/// </summary>
internal sealed class SingleSessionMcpServerHostedService(IMcpServer session) : BackgroundService
/// <param name="session">The server representing the session being hosted.</param>
/// <param name="lifetime">
/// The host's application lifetime. If available, it will have termination requested when the session's run completes.
/// </param>
internal sealed class SingleSessionMcpServerHostedService(IMcpServer session, IHostApplicationLifetime? lifetime = null) : BackgroundService
{
/// <inheritdoc />
protected override Task ExecuteAsync(CancellationToken stoppingToken) => session.RunAsync(stoppingToken);
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
try
{
await session.RunAsync(stoppingToken);
}
finally
{
lifetime?.StopApplication();
}
}
}
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
using ModelContextProtocol.Protocol.Transport;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using ModelContextProtocol.Protocol.Transport;
using Moq;
using System.IO.Pipelines;

namespace ModelContextProtocol.Tests.Configuration;

Expand All @@ -19,4 +21,24 @@ public void WithStdioServerTransport_Sets_Transport()
Assert.NotNull(transportType);
Assert.Equal(typeof(StdioServerTransport), transportType.ImplementationType);
}

[Fact]
public async Task HostExecutionShutsDownWhenSingleSessionServerExits()
{
Pipe clientToServerPipe = new(), serverToClientPipe = new();

var builder = Host.CreateEmptyApplicationBuilder(null);
builder.Services
.AddMcpServer()
.WithStreamServerTransport(clientToServerPipe.Reader.AsStream(), serverToClientPipe.Writer.AsStream());

IHost host = builder.Build();

Task t = host.RunAsync(TestContext.Current.CancellationToken);
await Task.Delay(1, TestContext.Current.CancellationToken);
Assert.False(t.IsCompleted);

clientToServerPipe.Writer.Complete();
await t;
}
}