Skip to content

Conversation

@johns10
Copy link

@johns10 johns10 commented Mar 25, 2025

Background Server Host Implementation

Problem

Currently, the MCP server is designed to be the primary entry point of an application, blocking the main thread. This makes it difficult to integrate into larger applications where the MCP server should be a component rather than the main process.

Solution

I've introduced a new MCPServerHost class that provides a background thread execution model for the MCP server. This allows the server to run asynchronously while the main application continues executing. Key features include:

  • Non-blocking server startup and shutdown
  • Proper lifecycle management with timeouts to prevent deadlocks
  • Clean resource disposal through IAsyncDisposable
  • Thread-safe operation using JoinableTaskFactory
  • Graceful shutdown handling with timeout protection

Implementation Details

  • Added MCPServerHost class in Core/MCPServerHost.cs
  • Modified MCPServer to expose its instance and make Dispose public
  • Added a new example project MCPSharp.Example.BackgroundServer demonstrating usage
  • Updated solution file to include the new project

Example Usage

await using var server = await MCPServerHost.StartAsync("MyServer", "1.0.0");
// Server is now running in background
// When the using block exits, server will be properly disposed

Testing

The changes include a new example project that demonstrates the background server functionality. The example shows how to:

  1. Start the server in a background thread
  2. Add tool handlers
  3. Keep the main thread running while the server operates

Additional Context

This implementation allows the MCP server to be used as a component in larger applications while maintaining its core functionality. The background execution model ensures that the server doesn't block the main application thread, making it suitable for integration into existing codebases.

Additional Note

I wrote this before you added net8.0/net9.0 targeting, so I didn't use the newer IHostedService/DI/BackgroundService stuff. This worked on netstandard2.0 and still does. That said, I can rewrite with the newer patterns if you prefer.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant