Skip to content

Commit a7df2fe

Browse files
Copilothalter73
andcommitted
Update test expectations for session cancellation with flushed responses
Co-authored-by: halter73 <54385+halter73@users.noreply.github.com>
1 parent eebc773 commit a7df2fe

2 files changed

Lines changed: 14 additions & 6 deletions

File tree

src/ModelContextProtocol.Core/Server/StreamableHttpPostTransport.cs

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -79,7 +79,15 @@ public async ValueTask<bool> HandlePostAsync(JsonRpcMessage message, Cancellatio
7979
// If there's no priming write, flush the stream to ensure HTTP response headers are
8080
// sent to the client now that the server is ready to process the request.
8181
// This prevents HttpClient timeout for long-running requests.
82-
await responseStream.FlushAsync(cancellationToken).ConfigureAwait(false);
82+
try
83+
{
84+
await responseStream.FlushAsync(cancellationToken).ConfigureAwait(false);
85+
}
86+
catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
87+
{
88+
// The session was canceled before we could flush. This is expected during session disposal.
89+
// Don't propagate the exception - let the request handling continue and fail naturally.
90+
}
8391
}
8492

8593
// Ensure that we've sent the priming event before processing the incoming request.

tests/ModelContextProtocol.AspNetCore.Tests/StreamableHttpServerConformanceTests.cs

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -371,14 +371,14 @@ Task<HttpResponseMessage> CallLongRunningToolAsync() =>
371371
var sseResponseBody = await getResponse.Content.ReadAsStringAsync(TestContext.Current.CancellationToken);
372372
Assert.Empty(sseResponseBody);
373373

374-
// Currently, the OCE thrown by the canceled session is unhandled and turned into a 500 error by Kestrel.
374+
// Currently, responses are flushed immediately to prevent HttpClient timeouts for long-running requests.
375+
// This means the response starts with a 200 status code. When the session is canceled, the connection
376+
// is closed abruptly, causing HttpClient errors.
375377
// The spec suggests sending CancelledNotifications. That would be good, but we can do that later.
376-
// For now, the important thing is that request completes without indicating success.
377-
await Task.WhenAll(longRunningToolTasks);
378+
// For now, the important thing is that requests fail to complete successfully.
378379
foreach (var task in longRunningToolTasks)
379380
{
380-
var response = await task;
381-
Assert.False(response.IsSuccessStatusCode);
381+
await Assert.ThrowsAnyAsync<HttpRequestException>(async () => await task);
382382
}
383383
}
384384

0 commit comments

Comments
 (0)