The ASP.NET Core package provides robust session management with support for idle timeout, session limits, and cross-instance migration.Documentation Index
Fetch the complete documentation index at: https://mintlify.com/modelcontextprotocol/csharp-sdk/llms.txt
Use this file to discover all available pages before exploring further.
Session Lifecycle
MCP sessions in ASP.NET Core are managed by theStatefulSessionManager (internal) and tracked through the StreamableHttpSession class.
Session States
Sessions progress through the following states:- Uninitialized - Session created but not yet registered with the session manager
- Started - Session registered and accepting requests
- Disposed - Session has been terminated and cleaned up
Session Tracking
The session manager tracks:- Active sessions - Sessions currently processing requests
- Idle sessions - Sessions with no active requests, subject to timeout
- Session references - Reference counting to prevent premature disposal
Idle Session Management
TheIdleTrackingBackgroundService runs every 5 seconds to prune idle sessions based on configured policies.
Configuration
Duration to wait between active requests before timing out a session.
Maximum number of idle sessions to keep in memory.When exceeded, the oldest idle sessions are terminated even if they haven’t reached
IdleTimeout.Keeping Sessions Alive
Clients can keep sessions alive by:- Maintaining an open GET request to the MCP endpoint
- Sending periodic requests before the
IdleTimeoutexpires
MaxIdleSessionCount.
Session Migration
TheISessionMigrationHandler interface enables session migration across server instances in horizontally scaled deployments.
ISessionMigrationHandler
Methods
Called after a session has been successfully initialized via the MCP initialization handshake.Parameters:
context- TheHttpContextfor the initialization requestsessionId- The unique identifier for the sessioninitializeParams- Initialization parameters from the client (capabilities, client info, protocol version)cancellationToken- Cancellation token
Called when a request arrives with an MCP-Session-Id that the current server doesn’t recognize.Parameters:
context- TheHttpContextfor the request with unrecognized session IDsessionId- The session ID from the requestcancellationToken- Cancellation token
- The original
InitializeRequestParamsto allow migration, ornullto reject (returns 404 to client)
Implementations should validate authorization (e.g., checking
HttpContext.User) to ensure the caller is permitted to migrate the session.Migration Behavior
When a request arrives with a session ID not found locally:- The server checks if an
ISessionMigrationHandleris registered - If registered, calls
AllowSessionMigrationAsyncto retrieve initialization parameters - If parameters are returned, recreates the session on the current instance
- If
nullis returned or no handler is registered, returns 404 to the client
Session migration does not solve session-affinity for in-flight server-to-client requests (sampling, elicitation). Responses to those requests must still be routed to the process that created the request. This interface only enables migration of idle sessions.
Implementation Example
Stateless Mode
For completely stateless operation without session tracking:McpSession.SessionIdisnull- No “MCP-Session-Id” header is used
RunSessionHandleris called once per request- The “/sse” endpoint is disabled
- Server-to-client messages and requests are unsupported
- Perfect for load-balanced environments without session affinity
Session Cleanup
Sessions are automatically cleaned up:- On idle timeout - After
IdleTimeoutwith no activity - On capacity limit - When
MaxIdleSessionCountis exceeded - On DELETE request - Client explicitly terminates session
- On graceful shutdown - All sessions disposed during app shutdown
Graceful Shutdown
TheIdleTrackingBackgroundService ensures all sessions are properly disposed during application shutdown:
Best Practices
- Set appropriate timeouts - Balance resource usage with client reconnection patterns
- Monitor idle session count - Watch for sessions approaching
MaxIdleSessionCount - Implement migration for HA - Use
ISessionMigrationHandlerfor high availability scenarios - Validate migration requests - Always check authorization in
AllowSessionMigrationAsync - Use stateless mode for simple APIs - If you don’t need server-initiated messages
- Keep sessions alive strategically - Maintain open GET requests only when needed