Skip to content

Commit 4b1869b

Browse files
committed
Add test
1 parent 4c23b45 commit 4b1869b

File tree

2 files changed

+30
-4
lines changed

2 files changed

+30
-4
lines changed

src/ModelContextProtocol/Hosting/SingleSessionMcpServerHostedService.cs

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,11 @@ namespace ModelContextProtocol.Hosting;
66
/// <summary>
77
/// Hosted service for a single-session (e.g. stdio) MCP server.
88
/// </summary>
9-
internal sealed class SingleSessionMcpServerHostedService(IMcpServer session, IHostApplicationLifetime lifetime) : BackgroundService
9+
/// <param name="session">The server representing the session being hosted.</param>
10+
/// <param name="lifetime">
11+
/// The host's application lifetime. If available, it will have termination requested when the session's run completes.
12+
/// </param>
13+
internal sealed class SingleSessionMcpServerHostedService(IMcpServer session, IHostApplicationLifetime? lifetime = null) : BackgroundService
1014
{
1115
/// <inheritdoc />
1216
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
@@ -17,7 +21,7 @@ protected override async Task ExecuteAsync(CancellationToken stoppingToken)
1721
}
1822
finally
1923
{
20-
lifetime.StopApplication();
24+
lifetime?.StopApplication();
2125
}
2226
}
2327
}

tests/ModelContextProtocol.Tests/Configuration/McpServerBuilderExtensionsTransportsTests.cs

Lines changed: 24 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
1-
using ModelContextProtocol.Protocol.Transport;
2-
using Microsoft.Extensions.DependencyInjection;
1+
using Microsoft.Extensions.DependencyInjection;
2+
using Microsoft.Extensions.Hosting;
3+
using ModelContextProtocol.Protocol.Transport;
34
using Moq;
5+
using System.IO.Pipelines;
46

57
namespace ModelContextProtocol.Tests.Configuration;
68

@@ -19,4 +21,24 @@ public void WithStdioServerTransport_Sets_Transport()
1921
Assert.NotNull(transportType);
2022
Assert.Equal(typeof(StdioServerTransport), transportType.ImplementationType);
2123
}
24+
25+
[Fact]
26+
public async Task HostExecutionShutsDownWhenSingleSessionServerExits()
27+
{
28+
Pipe clientToServerPipe = new(), serverToClientPipe = new();
29+
30+
var builder = Host.CreateEmptyApplicationBuilder(null);
31+
builder.Services
32+
.AddMcpServer()
33+
.WithStreamServerTransport(clientToServerPipe.Reader.AsStream(), serverToClientPipe.Writer.AsStream());
34+
35+
IHost host = builder.Build();
36+
37+
Task t = host.RunAsync(TestContext.Current.CancellationToken);
38+
await Task.Delay(1, TestContext.Current.CancellationToken);
39+
Assert.False(t.IsCompleted);
40+
41+
clientToServerPipe.Writer.Complete();
42+
await t;
43+
}
2244
}

0 commit comments

Comments
 (0)