René's URL Explorer Experiment


Title: Bug Report: FastMCP `RuntimeError: Received request before initialization was complete` Leading to Empty SSE Responses When Embedded in FastAPI · Issue #737 · modelcontextprotocol/python-sdk · GitHub

Open Graph Title: Bug Report: FastMCP `RuntimeError: Received request before initialization was complete` Leading to Empty SSE Responses When Embedded in FastAPI · Issue #737 · modelcontextprotocol/python-sdk

X Title: Bug Report: FastMCP `RuntimeError: Received request before initialization was complete` Leading to Empty SSE Responses When Embedded in FastAPI · Issue #737 · modelcontextprotocol/python-sdk

Description: Bug Report: FastMCP RuntimeError: Received request before initialization was complete Leading to Empty SSE Responses When Embedded in FastAPI **Library Version:** `mcp[cli]==1.8.0` (Python SDK) **Python Version:** 3.11.x **Web Framework:...

Open Graph Description: Bug Report: FastMCP RuntimeError: Received request before initialization was complete Leading to Empty SSE Responses When Embedded in FastAPI **Library Version:** `mcp[cli]==1.8.0` (Python SDK) **P...

X Description: Bug Report: FastMCP RuntimeError: Received request before initialization was complete Leading to Empty SSE Responses When Embedded in FastAPI **Library Version:** `mcp[cli]==1.8.0` (Python SDK) **P...

Opengraph URL: https://github.com/modelcontextprotocol/python-sdk/issues/737

X: @github

direct link

Domain: github.com


Hey, it has json ld scripts:
{"@context":"https://schema.org","@type":"DiscussionForumPosting","headline":"Bug Report: FastMCP `RuntimeError: Received request before initialization was complete` Leading to Empty SSE Responses When Embedded in FastAPI","articleBody":"  ## Bug Report: FastMCP `RuntimeError: Received request before initialization was complete` Leading to Empty SSE Responses When Embedded in FastAPI\n\n        **Library Version:** `mcp[cli]==1.8.0` (Python SDK)\n        **Python Version:** 3.11.x\n        **Web Framework:** FastAPI (e.g., 0.100+)\n        **ASGI Server:** Uvicorn\n\n        **Problem Description:**\n\n        When embedding `FastMCP.streamable_http_app()` as a sub-application within a FastAPI application and managing its lifecycle via FastAPI's `lifespan` context manager (using `asyncio.TaskGroup` to run `FastMCP` components), we encounter a persistent `RuntimeError: Received request before initialization was complete`.\n\n        This error occurs specifically when an MCP tool is called by a client and is expected to return data via Server-Sent Events (SSE).\n        The sequence of events observed is:\n        1. Client establishes a session successfully (receives `mcp-session-id` header, often with an initial 400 \"Missing session ID\" response which is then handled).\n        2. Client makes a `tools/call` request with the valid `mcp-session-id`.\n        3. The MCP server (FastAPI with FastMCP mounted) sends HTTP 200 OK headers with `Content-Type: text/event-stream`.\n        4. **Immediately after sending the 200 OK headers, before any `event: message` or `data:` lines are sent in the SSE stream, the `mcp.server.streamable_http_manager.StreamableHTTPSessionManager` logs that it is \"shutting down.\"**\n        5. The server then logs a `RuntimeError: Received request before initialization was complete` (traceback points to `mcp/server/session.py`).\n        6. The client receives the 200 OK but with an empty response body, as the SSE stream was closed before any data events were sent.\n\n        This issue occurs even if the tool is designed to return a very simple JSON payload (e.g., `{\"result_id\": \"some_id\"}`). The tool's Python code that prepares the `List[ContentPart]` often appears not to be fully executed, or at least its return value is not successfully processed for SSE streaming due to this premature shutdown.\n\n        **Steps to Reproduce (Conceptual - based on our integration pattern):**\n\n        1.  **`app.py` (FastAPI main application):**\n            *   A global `FastMCP` instance (`mcp_server`) is created. To avoid Uvicorn port conflicts when FastMCP's internal server mechanisms are invoked, we've tried initializing `FastMCP` with `host=\"127.0.0.1\", port=0`.\n            *   Tool modules (e.g., `core_tools.py` with a simple `log_decision` tool returning `[ContentPart(text=\"...\")]`) are imported *after* the global `mcp_server` is created, so decorators use this instance.\n            *   The FastAPI `lifespan` context manager is used:\n                *   It obtains `mcp_server.streamable_http_app()` and mounts it at a sub-path (e.g., `/mcp`).\n                *   It attempts to manage the lifecycle of FastMCP's services. Our current best approach (which starts the session manager but still leads to the runtime error) involves:\n                    ```python\n                    # (Inside lifespan)\n                    # Ensure session manager is created by accessing streamable_http_app first\n                    starlette_app = mcp_server.streamable_http_app()\n                    if mcp_server._session_manager is None:\n                        raise RuntimeError(\"Session manager not initialized by streamable_http_app\")\n\n                    async with mcp_server._session_manager.run(): # Manages StreamableHTTPSessionManager\n                        # We previously also tried running mcp_server.run_streamable_http_async()\n                        # in an asyncio.TaskGroup here, but that method unconditionally\n                        # tries to start its own Uvicorn server, causing port conflicts\n                        # unless host/port in FastMCP settings are None/0.\n                        # However, even then, the \"initialization not complete\" error persists\n                        # for actual data return.\n                        logger.info(\"FastAPI Lifespan: FastMCP components (attempted) started.\")\n                        yield\n                    ```\n        2.  **Client Script:**\n            *   Establishes a session with the `/mcp/mcp/` endpoint (receives `mcp-session-id` header).\n            *   Makes a `tools/call` POST request to `/mcp/mcp/` with the `mcp-session-id` header, targeting a simple tool that should return `List[ContentPart]`.\n            *   Client expects an SSE stream.\n\n        **Expected Behavior:**\n\n        The tool executes, and its `List[ContentPart]` result is serialized and streamed back to the client as SSE `data:` payloads after the initial 200 OK and SSE headers. The `StreamableHTTPSessionManager` should remain active throughout this process for the given session.\n\n        **Actual Behavior:**\n\n        *   HTTP 200 OK is received by the client.\n        *   `Content-Type: text/event-stream` header is present.\n        *   The response body is empty.\n        *   Server logs show `StreamableHTTPSessionManager` shutting down.\n        *   Server logs show `RuntimeError: Received request before initialization was complete` originating from `mcp/server/session.py`.\n        *   The actual tool code that generates the `List[ContentPart]` might not be reached or its result is not processed.\n\n        **Analysis \u0026 Hypothesis:**\n\n        It appears there's a race condition or an incomplete initialization of a required component (possibly the `RequestProcessor` or its internal `anyio.TaskGroup`) when FastMCP is embedded and its lifecycle is managed externally by FastAPI's lifespan. The `StreamableHTTPSessionManager` (started via `async with _session_manager.run()`) might be ready to accept HTTP connections and send initial headers, but the underlying machinery to fully process the tool call and stream results is not yet (or no longer) in a ready state when the request is internally dispatched after the initial HTTP handshake.\n\n        The method `FastMCP.run_streamable_http_async()` is documented to \"initialize all necessary components, including the RequestProcessor and its task group.\" However, this method also unconditionally starts its own Uvicorn server. We have not found parameters for `run_streamable_http_async()` or the `FastMCP` constructor that would allow it to perform *only* the service/task-group initializations without starting a new HTTP server instance, which is necessary for embedding within an existing FastAPI application managed by its own Uvicorn process.\n\n        The example `mcp/server/streamable_http_stateless_demo/server.py` in the SDK shows direct use of `StreamableHTTPSessionManager` with `mcp.server.lowlevel.Server`, and its lifespan correctly manages `session_manager.run()`. It seems the `FastMCP` wrapper around these components might have an issue when its `run_streamable_http_async` is not the primary server entry point.\n\n        **Question to SDK Authors:**\n\n        1.  What is the recommended pattern to fully initialize all FastMCP services (including `RequestProcessor` and its task group) when `FastMCP.streamable_http_app()` is mounted as a sub-application in a parent ASGI framework like FastAPI, ensuring that FastMCP does not attempt to start its own HTTP server?\n        2.  Is the `RuntimeError: Received request before initialization was complete` indicative of a specific component's lifecycle not being correctly managed in such an embedded scenario?\n        3.  Are there specific parameters for `FastMCP.__init__` or an alternative to `run_streamable_http_async` for performing a \"service-only\" initialization suitable for embedding?\n\n        Any guidance or clarification on the intended lifecycle management for embedded `FastMCP` instances would be greatly appreciated. We believe resolving this will significantly improve its usability with frameworks like FastAPI.\n\n        Thank you for your work on this SDK.\n","author":{"url":"https://github.com/jasny6969","@type":"Person","name":"jasny6969"},"datePublished":"2025-05-16T17:12:07.000Z","interactionStatistic":{"@type":"InteractionCounter","interactionType":"https://schema.org/CommentAction","userInteractionCount":5},"url":"https://github.com/737/python-sdk/issues/737"}

route-pattern/_view_fragments/issues/show/:user_id/:repository/:id/issue_layout(.:format)
route-controllervoltron_issues_fragments
route-actionissue_layout
fetch-noncev2:50a95553-6ca9-aedf-b731-ddcc0ce5562d
current-catalog-service-hash81bb79d38c15960b92d99bca9288a9108c7a47b18f2423d0f6438c5b7bcd2114
request-id9DE0:2AB1FC:325B5F9:48A2098:6A60F5EE
html-safe-nonce9b0523f01d0dabfa201e32b69fc7ecb5c2b5cc77302cddc622dc8411454ee525
visitor-payloadeyJyZWZlcnJlciI6IiIsInJlcXVlc3RfaWQiOiI5REUwOjJBQjFGQzozMjVCNUY5OjQ4QTIwOTg6NkE2MEY1RUUiLCJ2aXNpdG9yX2lkIjoiNjM5MjY1NDE0NTc2NzE0Mjg5NCIsInJlZ2lvbl9lZGdlIjoiaWFkIiwicmVnaW9uX3JlbmRlciI6ImlhZCJ9
visitor-hmac797a3b88a8db89efbdb9fd84a16b11bfbe614caba4d279e5afdc58c8cfc36ffd
hovercard-subject-tagissue:3069517293
github-keyboard-shortcutsrepository,issues,copilot
google-site-verificationApib7-x98H0j5cPqHWwSMm6dNU4GmODRoqxLiDzdx9I
octolytics-urlhttps://collector.github.com/github/collect
analytics-location///voltron/issues_fragments/issue_layout
fb:app_id1401488693436528
apple-itunes-appapp-id=1477376905, app-argument=https://github.com/_view_fragments/issues/show/modelcontextprotocol/python-sdk/737/issue_layout
twitter:imagehttps://opengraph.githubassets.com/616fbc16a6bdf82607e6c5ba49eebfe7ae59f841f514efe9fd0f8511d2b02883/modelcontextprotocol/python-sdk/issues/737
twitter:cardsummary_large_image
og:imagehttps://opengraph.githubassets.com/616fbc16a6bdf82607e6c5ba49eebfe7ae59f841f514efe9fd0f8511d2b02883/modelcontextprotocol/python-sdk/issues/737
og:image:altBug Report: FastMCP RuntimeError: Received request before initialization was complete Leading to Empty SSE Responses When Embedded in FastAPI **Library Version:** `mcp[cli]==1.8.0` (Python SDK) **P...
og:image:width1200
og:image:height600
og:site_nameGitHub
og:typeobject
og:author:usernamejasny6969
hostnamegithub.com
expected-hostnamegithub.com
None01a0f3379195d313175de239776b09dd4a079d5b2ea29dd9c37e85cd4cd5e990
turbo-cache-controlno-preview
go-importgithub.com/modelcontextprotocol/python-sdk git https://github.com/modelcontextprotocol/python-sdk.git
octolytics-dimension-user_id182288589
octolytics-dimension-user_loginmodelcontextprotocol
octolytics-dimension-repository_id862584018
octolytics-dimension-repository_nwomodelcontextprotocol/python-sdk
octolytics-dimension-repository_publictrue
octolytics-dimension-repository_is_forkfalse
octolytics-dimension-repository_network_root_id862584018
octolytics-dimension-repository_network_root_nwomodelcontextprotocol/python-sdk
turbo-body-classeslogged-out env-production page-responsive
disable-turbofalse
browser-stats-urlhttps://api.github.com/_private/browser/stats
browser-errors-urlhttps://api.github.com/_private/browser/errors
release00ca1a9089c8f2453e5d118d0554c8a26883d159
ui-targetfull
theme-color#1e2327
color-schemelight dark

Links:

Skip to contenthttps://github.com/modelcontextprotocol/python-sdk/issues/737#start-of-content
https://github.com/
Sign in https://github.com/login?return_to=https%3A%2F%2Fgithub.com%2Fmodelcontextprotocol%2Fpython-sdk%2Fissues%2F737
GitHub CopilotWrite better code with AIhttps://github.com/features/copilot
GitHub Copilot appDirect agents from issue to mergehttps://github.com/features/ai/github-app
MCP RegistryNewIntegrate external toolshttps://github.com/mcp
ActionsAutomate any workflowhttps://github.com/features/actions
CodespacesInstant dev environmentshttps://github.com/features/codespaces
IssuesPlan and track workhttps://github.com/features/issues
Code ReviewManage code changeshttps://github.com/features/code-review
Code QualityEnforce quality at mergehttps://github.com/features/code-quality
GitHub Advanced SecurityFind and fix vulnerabilitieshttps://github.com/security/advanced-security
Code securitySecure your code as you buildhttps://github.com/security/advanced-security/code-security
Secret protectionStop leaks before they starthttps://github.com/security/advanced-security/secret-protection
Why GitHubhttps://github.com/why-github
Documentationhttps://docs.github.com
Bloghttps://github.blog
Changeloghttps://github.blog/changelog
Marketplacehttps://github.com/marketplace
View all featureshttps://github.com/features
Enterpriseshttps://github.com/enterprise
Small and medium teamshttps://github.com/team
Startupshttps://github.com/enterprise/startups
Nonprofitshttps://github.com/solutions/industry/nonprofits
App Modernizationhttps://github.com/solutions/use-case/app-modernization
DevSecOpshttps://github.com/solutions/use-case/devsecops
DevOpshttps://github.com/solutions/use-case/devops
CI/CDhttps://github.com/solutions/use-case/ci-cd
View all use caseshttps://github.com/solutions/use-case
Healthcarehttps://github.com/solutions/industry/healthcare
Financial serviceshttps://github.com/solutions/industry/financial-services
Manufacturinghttps://github.com/solutions/industry/manufacturing
Governmenthttps://github.com/solutions/industry/government
View all industrieshttps://github.com/solutions/industry
View all solutionshttps://github.com/solutions
AIhttps://github.com/resources/articles?topic=ai
Software Developmenthttps://github.com/resources/articles?topic=software-development
DevOpshttps://github.com/resources/articles?topic=devops
Securityhttps://github.com/resources/articles?topic=security
View all topicshttps://github.com/resources/articles
Customer storieshttps://github.com/customer-stories
Events & webinarshttps://github.com/resources/events
Ebooks & reportshttps://github.com/resources/whitepapers
Business insightshttps://github.com/solutions/executive-insights
GitHub Skillshttps://skills.github.com
Documentationhttps://docs.github.com
Customer supporthttps://support.github.com
Community forumhttps://github.com/orgs/community/discussions
Trust centerhttps://github.com/trust-center
Partnershttps://github.com/partners
View all resourceshttps://github.com/resources
GitHub SponsorsFund open source developershttps://github.com/open-source/sponsors
Security Labhttps://securitylab.github.com
Maintainer Communityhttps://maintainers.github.com
Acceleratorhttps://github.com/open-source/accelerator
GitHub Starshttps://stars.github.com
Archive Programhttps://archiveprogram.github.com
Topicshttps://github.com/topics
Trendinghttps://github.com/trending
Collectionshttps://github.com/collections
Enterprise platformAI-powered developer platformhttps://github.com/enterprise
GitHub Advanced SecurityEnterprise-grade security featureshttps://github.com/security/advanced-security
Copilot for BusinessEnterprise-grade AI featureshttps://github.com/features/copilot/copilot-business
Premium SupportEnterprise-grade 24/7 supporthttps://github.com/enterprise/premium-support
Pricinghttps://github.com/pricing
Search syntax tipshttps://docs.github.com/search-github/github-code-search/understanding-github-code-search-syntax
documentationhttps://docs.github.com/search-github/github-code-search/understanding-github-code-search-syntax
Sign in https://github.com/login?return_to=https%3A%2F%2Fgithub.com%2Fmodelcontextprotocol%2Fpython-sdk%2Fissues%2F737
Sign up https://github.com/signup?ref_cta=Sign+up&ref_loc=header+logged+out&ref_page=%2F%3Cuser-name%3E%2F%3Crepo-name%3E%2Fvoltron%2Fissues_fragments%2Fissue_layout&source=header-repo&source_repo=modelcontextprotocol%2Fpython-sdk
Reloadhttps://github.com/modelcontextprotocol/python-sdk/issues/737
Reloadhttps://github.com/modelcontextprotocol/python-sdk/issues/737
Reloadhttps://github.com/modelcontextprotocol/python-sdk/issues/737
Please reload this pagehttps://github.com/modelcontextprotocol/python-sdk/issues/737
modelcontextprotocol https://github.com/modelcontextprotocol
python-sdkhttps://github.com/modelcontextprotocol/python-sdk
Notifications https://github.com/login?return_to=%2Fmodelcontextprotocol%2Fpython-sdk
Fork 3.7k https://github.com/login?return_to=%2Fmodelcontextprotocol%2Fpython-sdk
Star 23.7k https://github.com/login?return_to=%2Fmodelcontextprotocol%2Fpython-sdk
Code https://github.com/modelcontextprotocol/python-sdk
Issues 267 https://github.com/modelcontextprotocol/python-sdk/issues
Pull requests 312 https://github.com/modelcontextprotocol/python-sdk/pulls
Actions https://github.com/modelcontextprotocol/python-sdk/actions
Projects https://github.com/modelcontextprotocol/python-sdk/projects
Models https://github.com/modelcontextprotocol/python-sdk/models
Security and quality 6 https://github.com/modelcontextprotocol/python-sdk/security
Insights https://github.com/modelcontextprotocol/python-sdk/pulse
Code https://github.com/modelcontextprotocol/python-sdk
Issues https://github.com/modelcontextprotocol/python-sdk/issues
Pull requests https://github.com/modelcontextprotocol/python-sdk/pulls
Actions https://github.com/modelcontextprotocol/python-sdk/actions
Projects https://github.com/modelcontextprotocol/python-sdk/projects
Models https://github.com/modelcontextprotocol/python-sdk/models
Security and quality https://github.com/modelcontextprotocol/python-sdk/security
Insights https://github.com/modelcontextprotocol/python-sdk/pulse
Bug Report: FastMCP RuntimeError: Received request before initialization was complete Leading to Empty SSE Responses When Embedded in FastAPIhttps://github.com/modelcontextprotocol/python-sdk/issues/737#top
P1Significant bug affecting many users, highly requested featurehttps://github.com/modelcontextprotocol/python-sdk/issues?q=state%3Aopen%20label%3A%22P1%22
bugSomething isn't workinghttps://github.com/modelcontextprotocol/python-sdk/issues?q=state%3Aopen%20label%3A%22bug%22
ready for workEnough information for someone to start working onhttps://github.com/modelcontextprotocol/python-sdk/issues?q=state%3Aopen%20label%3A%22ready%20for%20work%22
FastMCP issueshttps://github.com/modelcontextprotocol/python-sdk/milestone/22
https://github.com/jasny6969
jasny6969https://github.com/jasny6969
on May 16, 2025https://github.com/modelcontextprotocol/python-sdk/issues/737#issue-3069517293
P1Significant bug affecting many users, highly requested featurehttps://github.com/modelcontextprotocol/python-sdk/issues?q=state%3Aopen%20label%3A%22P1%22
bugSomething isn't workinghttps://github.com/modelcontextprotocol/python-sdk/issues?q=state%3Aopen%20label%3A%22bug%22
ready for workEnough information for someone to start working onhttps://github.com/modelcontextprotocol/python-sdk/issues?q=state%3Aopen%20label%3A%22ready%20for%20work%22
FastMCP issuesNo due datehttps://github.com/modelcontextprotocol/python-sdk/milestone/22
https://github.com
Termshttps://docs.github.com/site-policy/github-terms/github-terms-of-service
Privacyhttps://docs.github.com/site-policy/privacy-policies/github-privacy-statement
Securityhttps://github.com/security
Statushttps://www.githubstatus.com/
Communityhttps://github.community/
Docshttps://docs.github.com/
Contacthttps://support.github.com?tags=dotcom-footer

Viewport: width=device-width


URLs of crawlers that visited me.