Refactor transports to help enable graceful shutdown (#142)

- This also paves the way for better multi-session support
- We should definitely rethink names for the transport API
- For now, I kept the names similar as possible, so we can
  focus on the API shape

Co-authored-by: Stephen Toub <stoub@microsoft.com>
This commit is contained in:
Stephen Halter 2025-03-30 17:10:14 -07:00 • committed by GitHub
commit 2ab9db0878
No known key found for this signature in database
GPG key ID: B5690EEEBB952194

View file

@ -44,8 +44,6 @@ public class Program
ServerInstructions = "This is a test server with only stub functionality"
};
IMcpServer? server = null;
Console.WriteLine("Registering handlers.");
#region Helped method
@ -186,7 +184,7 @@ public class Program
{
throw new McpServerException("Missing required arguments 'prompt' and 'maxTokens'");
}
var sampleResult = await server!.RequestSamplingAsync(CreateRequestSamplingParams(prompt?.ToString() ?? "", "sampleLLM", Convert.ToInt32(maxTokens?.ToString())),
var sampleResult = await request.Server.RequestSamplingAsync(CreateRequestSamplingParams(prompt?.ToString() ?? "", "sampleLLM", Convert.ToInt32(maxTokens?.ToString())),
cancellationToken);
return new CallToolResponse()
@ -384,22 +382,14 @@ public class Program
};
loggerFactory ??= CreateLoggerFactory();
server = McpServerFactory.Create(new HttpListenerSseServerTransport("TestServer", 3001, loggerFactory), options, loggerFactory);
await using var httpListenerSseTransport = new HttpListenerSseServerTransport("TestServer", 3001, loggerFactory);
Console.WriteLine("Server running...");
Console.WriteLine("Server initialized.");
await server.StartAsync(cancellationToken);
Console.WriteLine("Server started.");
try
// Each IMcpServer represents a new SSE session.
while (true)
{
// Run until process is stopped by the client (parent process) or test
await Task.Delay(Timeout.Infinite, cancellationToken);
}
finally
{
await server.DisposeAsync();
var server = await McpServerFactory.AcceptAsync(httpListenerSseTransport, options, loggerFactory, cancellationToken: cancellationToken);
_ = server.RunAsync(cancellationToken: cancellationToken);
}
}