Repository navigation
fix(http): terminate active streamable-HTTP transports before lifespan shutdown - #4118
Merged
Merged
Conversation
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
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.
Description
StreamableHTTPSessionManager.run()(upstreammcp) cancels its task group insidefinallywithout first terminating active transports. During Uvicorn graceful shutdown the lifespan increate_streamable_http_appexits before the session manager, sotg.cancel_scope.cancel()aborts long-lived GET/mcp/SSE response tasks mid-flight. The streaming response never sends its finalhttp.response.bodyand Uvicorn logsERROR: ASGI callable returned without completing response.The fix wraps the lifespan's
yieldintry/finallyand, on exit, awaitsterminate()on every transport currently registered insession_manager._server_instances.StreamableHTTPServerTransport.terminate()is idempotent (_terminatedguard) and closes the per-request and read/write streams, so the SSE GET handler completes its ASGI response before the SDK's__aexit__cancels the task group. Termination errors are caught and logged at debug; shutdown must not raise.Stateless servers don't populate
_server_instances, so this is a no-op there. The issue's "Option 1"await anyio.sleep(0.5)isn't needed becauseterminate()already awaits stream close; the "Option 2"@on_shutdownhook is a larger API design and out of scope for a bug fix.A regression test in
tests/server/http/test_streamable_http_shutdown.pyregisters a fake transport on the live session manager during the lifespan and assertsterminate()is awaited before the lifespan completes. It fails onmainand passes with the fix.Closes #3025
Contribution type
Checklist
uv run prek run --all-filesand all checks pass