- 
                Notifications
    You must be signed in to change notification settings 
- Fork 554
Add server-side Streamable HTTP transport support #330
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
          
     Merged
      
      
    
      
        
          +1,637
        
        
          −395
        
        
          
        
      
    
  
  
     Merged
                    Changes from all commits
      Commits
    
    
            Show all changes
          
          
            9 commits
          
        
        Select commit
          Hold shift + click to select a range
      
      cd33249
              
                Add server Streamable HTTP transport
              
              
                halter73 963cf3f
              
                Merge remote-tracking branch 'origin/main' into http-streaming
              
              
                halter73 d875bde
              
                fixup
              
              
                halter73 7dd167e
              
                Make IdleTrackingBackgroundService shutdown more graceful
              
              
                halter73 d2ed83b
              
                s/McpException/InvalidOperationException
              
              
                halter73 14ed925
              
                Remove unnecessary ConcurrentDictionary in StreamableHttpPostTransport
              
              
                halter73 5668986
              
                Use HttpMcpSession.DisposeAsync in SseHandler
              
              
                halter73 d72a377
              
                Add static IdleTrackingBackgroundService.MaxIdleCount
              
              
                halter73 9baf883
              
                Address PR feedback
              
              
                halter73 File filter
Filter by extension
Conversations
          Failed to load comments.   
        
        
          
      Loading
        
  Jump to
        
          Jump to file
        
      
      
          Failed to load files.   
        
        
          
      Loading
        
  Diff view
Diff view
There are no files selected for viewing
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              
        
          
          
            105 changes: 105 additions & 0 deletions
          
          105 
        
  src/ModelContextProtocol.AspNetCore/IdleTrackingBackgroundService.cs
  
  
      
      
   
        
      
      
    
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              | Original file line number | Diff line number | Diff line change | 
|---|---|---|
| @@ -0,0 +1,105 @@ | ||
| using Microsoft.Extensions.Hosting; | ||
| using Microsoft.Extensions.Logging; | ||
| using Microsoft.Extensions.Options; | ||
| using ModelContextProtocol.Protocol.Transport; | ||
|  | ||
| namespace ModelContextProtocol.AspNetCore; | ||
|  | ||
| internal sealed partial class IdleTrackingBackgroundService( | ||
|         
                  halter73 marked this conversation as resolved.
              Show resolved
            Hide resolved | ||
| StreamableHttpHandler handler, | ||
| IOptions<HttpServerTransportOptions> options, | ||
| ILogger<IdleTrackingBackgroundService> logger) : BackgroundService | ||
| { | ||
| // The compiler will complain about the parameter being unused otherwise despite the source generator. | ||
|         
                  halter73 marked this conversation as resolved.
              Show resolved
            Hide resolved | ||
| private ILogger _logger = logger; | ||
|  | ||
| // We can make this configurable once we properly harden the MCP server. In the meantime, anyone running | ||
| // this should be taking a cattle not pets approach to their servers and be able to launch more processes | ||
| // to handle more than 10,000 idle sessions at a time. | ||
| private const int MaxIdleSessionCount = 10_000; | ||
|  | ||
| protected override async Task ExecuteAsync(CancellationToken stoppingToken) | ||
| { | ||
| var timeProvider = options.Value.TimeProvider; | ||
| using var timer = new PeriodicTimer(TimeSpan.FromSeconds(5), timeProvider); | ||
|  | ||
| try | ||
| { | ||
| while (!stoppingToken.IsCancellationRequested && await timer.WaitForNextTickAsync(stoppingToken)) | ||
| { | ||
| var idleActivityCutoff = timeProvider.GetTimestamp() - options.Value.IdleTimeout.Ticks; | ||
|  | ||
| var idleCount = 0; | ||
| foreach (var (_, session) in handler.Sessions) | ||
| { | ||
| if (session.IsActive || session.SessionClosed.IsCancellationRequested) | ||
| { | ||
| // There's a request currently active or the session is already being closed. | ||
| continue; | ||
| } | ||
|  | ||
| idleCount++; | ||
| if (idleCount == MaxIdleSessionCount) | ||
| { | ||
| // Emit critical log at most once every 5 seconds the idle count it exceeded, | ||
| //since the IdleTimeout will no longer be respected. | ||
| LogMaxSessionIdleCountExceeded(); | ||
| } | ||
| else if (idleCount < MaxIdleSessionCount && session.LastActivityTicks > idleActivityCutoff) | ||
| { | ||
| continue; | ||
| } | ||
|  | ||
| if (handler.Sessions.TryRemove(session.Id, out var removedSession)) | ||
| { | ||
| LogSessionIdle(removedSession.Id); | ||
|  | ||
| // Don't slow down the idle tracking loop. DisposeSessionAsync logs. We only await during graceful shutdown. | ||
| _ = DisposeSessionAsync(removedSession); | ||
| } | ||
| } | ||
| } | ||
| } | ||
| catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested) | ||
| { | ||
| } | ||
| finally | ||
| { | ||
| if (stoppingToken.IsCancellationRequested) | ||
| { | ||
| List<Task> disposeSessionTasks = []; | ||
|  | ||
| foreach (var (sessionKey, _) in handler.Sessions) | ||
| { | ||
| if (handler.Sessions.TryRemove(sessionKey, out var session)) | ||
| { | ||
| disposeSessionTasks.Add(DisposeSessionAsync(session)); | ||
| } | ||
| } | ||
|  | ||
| await Task.WhenAll(disposeSessionTasks); | ||
| } | ||
| } | ||
| } | ||
|  | ||
| private async Task DisposeSessionAsync(HttpMcpSession<StreamableHttpServerTransport> session) | ||
| { | ||
| try | ||
| { | ||
| await session.DisposeAsync(); | ||
| } | ||
| catch (Exception ex) | ||
| { | ||
| LogSessionDisposeError(session.Id, ex); | ||
| } | ||
| } | ||
|  | ||
| [LoggerMessage(Level = LogLevel.Information, Message = "Closing idle session {sessionId}.")] | ||
| private partial void LogSessionIdle(string sessionId); | ||
|  | ||
| [LoggerMessage(Level = LogLevel.Critical, Message = "Exceeded static maximum of 10,000 idle connections. Now clearing all inactive connections regardless of timeout.")] | ||
| private partial void LogMaxSessionIdleCountExceeded(); | ||
|  | ||
| [LoggerMessage(Level = LogLevel.Error, Message = "Error disposing the IMcpServer for session {sessionId}.")] | ||
| private partial void LogSessionDisposeError(string sessionId, Exception ex); | ||
| } | ||
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              
      
      Oops, something went wrong.
        
    
  
  Add this suggestion to a batch that can be applied as a single commit.
  This suggestion is invalid because no changes were made to the code.
  Suggestions cannot be applied while the pull request is closed.
  Suggestions cannot be applied while viewing a subset of changes.
  Only one suggestion per line can be applied in a batch.
  Add this suggestion to a batch that can be applied as a single commit.
  Applying suggestions on deleted lines is not supported.
  You must change the existing code in this line in order to create a valid suggestion.
  Outdated suggestions cannot be applied.
  This suggestion has been applied or marked resolved.
  Suggestions cannot be applied from pending reviews.
  Suggestions cannot be applied on multi-line comments.
  Suggestions cannot be applied while the pull request is queued to merge.
  Suggestion cannot be applied right now. Please check back later.
  
    
  
    
Uh oh!
There was an error while loading. Please reload this page.