Disable response compression for SSE responses (#208)

This commit is contained in:
Stephen Halter 2025-04-03 17:53:58 -07:00 • committed by GitHub
commit d1a3c201a4
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
2 changed files with 21 additions and 1 deletions

View file

@ -1,4 +1,5 @@
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Features;
using Microsoft.AspNetCore.Routing;
using Microsoft.AspNetCore.WebUtilities;
using Microsoft.Extensions.DependencyInjection;
@ -39,7 +40,7 @@ public static class McpEndpointRouteBuilderExtensions
var requestAborted = context.RequestAborted;
response.Headers.ContentType = "text/event-stream";
response.Headers.CacheControl = "no-store";
response.Headers.CacheControl = "no-cache,no-store";
var sessionId = MakeNewSessionId();
await using var transport = new SseResponseStreamTransport(response.Body, $"/message?sessionId={sessionId}");
@ -50,6 +51,10 @@ public static class McpEndpointRouteBuilderExtensions
try
{
// Make sure we disable all response buffering for SSE
context.Response.Headers.ContentEncoding = "identity";
context.Features.GetRequiredFeature<IHttpResponseBodyFeature>().DisableBuffering();
var transportTask = transport.RunAsync(cancellationToken: requestAborted);
await using var server = McpServerFactory.Create(transport, mcpServerOptions.Value, loggerFactory, endpoints.ServiceProvider);

View file

@ -280,6 +280,21 @@ public class SseServerIntegrationTests : LoggedTest, IClassFixture<SseServerInte
}
}
[Fact]
public async Task EventSourceResponse_Includes_ExpectedHeaders()
{
using var httpClient = GetHttpClient();
using var sseResponse = await httpClient.GetAsync("", HttpCompletionOption.ResponseHeadersRead, TestContext.Current.CancellationToken);
sseResponse.EnsureSuccessStatusCode();
Assert.Equal("text/event-stream", sseResponse.Content.Headers.ContentType?.MediaType);
Assert.Equal("identity", sseResponse.Content.Headers.ContentEncoding.ToString());
Assert.NotNull(sseResponse.Headers.CacheControl);
Assert.True(sseResponse.Headers.CacheControl.NoStore);
Assert.True(sseResponse.Headers.CacheControl.NoCache);
}
[Fact]
public async Task EventSourceStream_Includes_MessageEventType()
{