feat(http): trigger lifespan events when using mount_http() (adopted from #311, closes #256) - #339
Open
K4bain wants to merge 1 commit into
Open
feat(http): trigger lifespan events when using mount_http() (adopted from #311, closes #256)#339K4bain wants to merge 1 commit into
K4bain wants to merge 1 commit into
Conversation
mount_http() left the StreamableHTTP session manager to start lazily on the first request, so user lifespan events ran detached from the MCP session manager and tools could not rely on lifespan-initialised resources, and shutdown never drained in-flight sessions. Wrap the host app's lifespan_context (works for both custom lifespans and Starlette's default) so the session manager starts after user startup and stops before user shutdown. Adopted from tadata-org#311 (original patch by @Emeralden), closes tadata-org#256.
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.
Adopted from #311 (original patch by @Emeralden) — rebased onto current main and verified. Closes #256.
Why this is needed
mount_http() starts the StreamableHTTP session manager lazily on the first request. Consequences:
The fix wraps the host app's lifespan_context with an asynccontextmanager that runs the user's lifespan first, then starts the session manager, and on teardown stops the session manager before user shutdown. Wrapping lifespan_context works for both plain apps (_DefaultLifespan still invokes on_startup/on_shutdown) and custom lifespans.
Also adds public startup()/shutdown() methods to FastApiHttpSessionManager and keeps the lazy start as a fallback for apps that never run a lifespan.
Verification
Credit to @Emeralden for the original report and patch in #311.