-
Notifications
You must be signed in to change notification settings - Fork 545
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 7 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
81 changes: 81 additions & 0 deletions
81
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,81 @@ | ||
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; | ||
|
||
protected override async Task ExecuteAsync(CancellationToken stoppingToken) | ||
{ | ||
var timeProvider = options.Value.TimeProvider; | ||
var timer = new PeriodicTimer(TimeSpan.FromSeconds(5), timeProvider); | ||
|
||
try | ||
{ | ||
while (!stoppingToken.IsCancellationRequested && await timer.WaitForNextTickAsync(stoppingToken)) | ||
{ | ||
var idleActivityCutoff = timeProvider.GetUtcNow().Ticks - options.Value.IdleTimeout.Ticks; | ||
|
||
foreach (var (_, session) in handler.Sessions) | ||
{ | ||
if (session.IsActive || session.LastActivityTicks > idleActivityCutoff) | ||
{ | ||
continue; | ||
} | ||
|
||
if (handler.Sessions.TryRemove(session.Id, out var removedSession)) | ||
{ | ||
LogSessionIdle(removedSession.Id); | ||
await DisposeSessionAsync(removedSession); | ||
halter73 marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
} | ||
} | ||
} | ||
} | ||
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.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
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,110 @@ | ||
using Microsoft.AspNetCore.Http; | ||
using Microsoft.Extensions.Hosting; | ||
using Microsoft.Extensions.Logging; | ||
using Microsoft.Extensions.Options; | ||
using ModelContextProtocol.Protocol.Messages; | ||
using ModelContextProtocol.Protocol.Transport; | ||
using ModelContextProtocol.Server; | ||
using ModelContextProtocol.Utils.Json; | ||
using System.Collections.Concurrent; | ||
using System.Diagnostics; | ||
|
||
namespace ModelContextProtocol.AspNetCore; | ||
|
||
internal sealed class SseHandler( | ||
IOptions<McpServerOptions> mcpServerOptionsSnapshot, | ||
IOptionsFactory<McpServerOptions> mcpServerOptionsFactory, | ||
IOptions<HttpServerTransportOptions> httpMcpServerOptions, | ||
IHostApplicationLifetime hostApplicationLifetime, | ||
ILoggerFactory loggerFactory) | ||
{ | ||
private readonly ConcurrentDictionary<string, HttpMcpSession<SseResponseStreamTransport>> _sessions = new(StringComparer.Ordinal); | ||
|
||
public async Task HandleSseRequestAsync(HttpContext context) | ||
{ | ||
var sessionId = StreamableHttpHandler.MakeNewSessionId(); | ||
|
||
// If the server is shutting down, we need to cancel all SSE connections immediately without waiting for HostOptions.ShutdownTimeout | ||
// which defaults to 30 seconds. | ||
using var sseCts = CancellationTokenSource.CreateLinkedTokenSource(context.RequestAborted, hostApplicationLifetime.ApplicationStopping); | ||
var cancellationToken = sseCts.Token; | ||
|
||
StreamableHttpHandler.InitializeSseResponse(context); | ||
|
||
await using var transport = new SseResponseStreamTransport(context.Response.Body, $"message?sessionId={sessionId}"); | ||
await using var httpMcpSession = new HttpMcpSession<SseResponseStreamTransport>(sessionId, transport, context.User, httpMcpServerOptions.Value.TimeProvider); | ||
if (!_sessions.TryAdd(sessionId, httpMcpSession)) | ||
{ | ||
throw new UnreachableException($"Unreachable given good entropy! Session with ID '{sessionId}' has already been created."); | ||
} | ||
|
||
try | ||
{ | ||
var mcpServerOptions = mcpServerOptionsSnapshot.Value; | ||
if (httpMcpServerOptions.Value.ConfigureSessionOptions is { } configureSessionOptions) | ||
{ | ||
mcpServerOptions = mcpServerOptionsFactory.Create(Options.DefaultName); | ||
await configureSessionOptions(context, mcpServerOptions, cancellationToken); | ||
} | ||
|
||
var transportTask = transport.RunAsync(cancellationToken); | ||
|
||
try | ||
{ | ||
await using var mcpServer = McpServerFactory.Create(transport, mcpServerOptions, loggerFactory, context.RequestServices); | ||
httpMcpSession.Server = mcpServer; | ||
context.Features.Set(mcpServer); | ||
|
||
var runSessionAsync = httpMcpServerOptions.Value.RunSessionHandler ?? StreamableHttpHandler.RunSessionAsync; | ||
httpMcpSession.ServerRunTask = runSessionAsync(context, mcpServer, cancellationToken); | ||
await httpMcpSession.ServerRunTask; | ||
} | ||
finally | ||
{ | ||
await transport.DisposeAsync(); | ||
await transportTask; | ||
} | ||
} | ||
catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) | ||
{ | ||
// RequestAborted always triggers when the client disconnects before a complete response body is written, | ||
// but this is how SSE connections are typically closed. | ||
} | ||
finally | ||
{ | ||
_sessions.TryRemove(sessionId, out _); | ||
} | ||
} | ||
|
||
public async Task HandleMessageRequestAsync(HttpContext context) | ||
{ | ||
if (!context.Request.Query.TryGetValue("sessionId", out var sessionId)) | ||
{ | ||
await Results.BadRequest("Missing sessionId query parameter.").ExecuteAsync(context); | ||
return; | ||
} | ||
|
||
if (!_sessions.TryGetValue(sessionId.ToString(), out var httpMcpSession)) | ||
{ | ||
await Results.BadRequest($"Session ID not found.").ExecuteAsync(context); | ||
return; | ||
} | ||
|
||
if (!httpMcpSession.HasSameUserId(context.User)) | ||
{ | ||
await Results.Forbid().ExecuteAsync(context); | ||
return; | ||
} | ||
|
||
var message = (JsonRpcMessage?)await context.Request.ReadFromJsonAsync(McpJsonUtilities.DefaultOptions.GetTypeInfo(typeof(JsonRpcMessage)), context.RequestAborted); | ||
if (message is null) | ||
{ | ||
await Results.BadRequest("No message in request body.").ExecuteAsync(context); | ||
return; | ||
} | ||
|
||
await httpMcpSession.Transport.OnMessageReceivedAsync(message, context.RequestAborted); | ||
context.Response.StatusCode = StatusCodes.Status202Accepted; | ||
await context.Response.WriteAsync("Accepted"); | ||
} | ||
} |
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.