File tree Expand file tree Collapse file tree 2 files changed +40
-4
lines changed
src/ModelContextProtocol/Hosting
tests/ModelContextProtocol.Tests/Configuration Expand file tree Collapse file tree 2 files changed +40
-4
lines changed Original file line number Diff line number Diff line change @@ -6,8 +6,22 @@ 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 ) : 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 />
12- protected override Task ExecuteAsync ( CancellationToken stoppingToken ) => session . RunAsync ( stoppingToken ) ;
16+ protected override async Task ExecuteAsync ( CancellationToken stoppingToken )
17+ {
18+ try
19+ {
20+ await session . RunAsync ( stoppingToken ) ;
21+ }
22+ finally
23+ {
24+ lifetime ? . StopApplication ( ) ;
25+ }
26+ }
1327}
Original file line number Diff line number Diff line change 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 ;
34using Moq ;
5+ using System . IO . Pipelines ;
46
57namespace 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}
You can’t perform that action at this time.
0 commit comments