File tree Expand file tree Collapse file tree 2 files changed +30
-4
lines changed
src/ModelContextProtocol/Hosting
tests/ModelContextProtocol.Tests/Configuration Expand file tree Collapse file tree 2 files changed +30
-4
lines changed Original file line number Diff line number Diff line change @@ -6,7 +6,11 @@ namespace ModelContextProtocol.Hosting;
6
6
/// <summary>
7
7
/// Hosted service for a single-session (e.g. stdio) MCP server.
8
8
/// </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
10
14
{
11
15
/// <inheritdoc />
12
16
protected override async Task ExecuteAsync ( CancellationToken stoppingToken )
@@ -17,7 +21,7 @@ protected override async Task ExecuteAsync(CancellationToken stoppingToken)
17
21
}
18
22
finally
19
23
{
20
- lifetime . StopApplication ( ) ;
24
+ lifetime ? . StopApplication ( ) ;
21
25
}
22
26
}
23
27
}
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 ;
3
4
using Moq ;
5
+ using System . IO . Pipelines ;
4
6
5
7
namespace ModelContextProtocol . Tests . Configuration ;
6
8
@@ -19,4 +21,24 @@ public void WithStdioServerTransport_Sets_Transport()
19
21
Assert . NotNull ( transportType ) ;
20
22
Assert . Equal ( typeof ( StdioServerTransport ) , transportType . ImplementationType ) ;
21
23
}
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
+ }
22
44
}
You can’t perform that action at this time.
0 commit comments