René's URL Explorer Experiment


Title: Streamable HTTP hangs forever when the server attempts any callback · Issue #680 · modelcontextprotocol/python-sdk · GitHub

Open Graph Title: Streamable HTTP hangs forever when the server attempts any callback · Issue #680 · modelcontextprotocol/python-sdk

X Title: Streamable HTTP hangs forever when the server attempts any callback · Issue #680 · modelcontextprotocol/python-sdk

Description: I'm debugging the issue described in PrefectHQ/fastmcp#393. Essentially, attempting to use a callback for sampling in conjunction with a Streamable HTTP connection results in an indefinite hang. I've successfully traced the issue to a sp...

Open Graph Description: I'm debugging the issue described in PrefectHQ/fastmcp#393. Essentially, attempting to use a callback for sampling in conjunction with a Streamable HTTP connection results in an indefinite hang. I'...

X Description: I'm debugging the issue described in PrefectHQ/fastmcp#393. Essentially, attempting to use a callback for sampling in conjunction with a Streamable HTTP connection results in an indefinite hang...

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

X: @github

direct link

Domain: github.com


Hey, it has json ld scripts:
{"@context":"https://schema.org","@type":"DiscussionForumPosting","headline":"Streamable HTTP hangs forever when the server attempts any callback","articleBody":"I'm debugging the issue described in https://github.com/jlowin/fastmcp/issues/393. \n\nEssentially, attempting to use a callback for sampling in conjunction with a Streamable HTTP connection results in an indefinite hang. \n\nI've successfully traced the issue to a specific moment in the low-level interaction. The server correctly sends the sampling request to the client, and the client successfully processes it via its sampling callback and sends a response to the server. However, the server never receives that response, with the result that it blocks forever waiting. \n\n(Note that this also happens if the client doesn't even support sampling and the default sampling callback responds with an appropriate error -- the ultimate effect being that anytime the server requests a sample it immediately locks itself up)\n\nUnfortunately I'm not knowledgeable enough on how the server streams work to suggest a solution, but I have created a complete unit test that I think demonstrates the issue. It is based on similar low-level code in https://github.com/modelcontextprotocol/python-sdk/blob/main/tests/shared/test_streamable_http.py and contains a single unit test that can be run with `pytest`. If you add debug prints to the session classes you can see the server and client writing messages, with the last one being the client's attempt to respond to the server.\n\nApologies for the length of the test but wanted to be sure everything was covered and self-contained.\n\n```python\n\"\"\"\nTests for the StreamableHTTP server and client transport.\n\nContains tests for both server and client sides of the StreamableHTTP transport.\n\"\"\"\n\nimport multiprocessing\nimport socket\nimport time\nfrom collections.abc import Generator\n\nimport httpx\nimport pytest\nimport uvicorn\nfrom starlette.applications import Starlette\nfrom starlette.routing import Mount\n\nimport mcp.types as types\nfrom mcp.client.session import ClientSession\nfrom mcp.client.streamable_http import streamablehttp_client\nfrom mcp.server import Server\nfrom mcp.server.streamable_http import (\n    EventStore,\n)\nfrom mcp.server.streamable_http_manager import StreamableHTTPSessionManager\nfrom mcp.types import (\n    TextContent,\n    Tool,\n)\n\n# Test constants\nSERVER_NAME = \"test_streamable_http_server\"\nTEST_SESSION_ID = \"test-session-id-12345\"\nINIT_REQUEST = {\n    \"jsonrpc\": \"2.0\",\n    \"method\": \"initialize\",\n    \"params\": {\n        \"clientInfo\": {\"name\": \"test-client\", \"version\": \"1.0\"},\n        \"protocolVersion\": \"2025-03-26\",\n        \"capabilities\": {},\n    },\n    \"id\": \"init-1\",\n}\n\n\nclass ServerTest(Server):\n    def __init__(self):\n        super().__init__(SERVER_NAME)\n\n        @self.list_tools()\n        async def handle_list_tools() -> list[Tool]:\n            return [\n                Tool(\n                    name=\"sample_tool\",\n                    description=\"A tool that uses sampling\",\n                    inputSchema={\"type\": \"object\", \"properties\": {}},\n                ),\n            ]\n\n        @self.call_tool()\n        async def handle_call_tool(name: str, args: dict) -> list[TextContent]:\n            ctx = self.request_context\n\n            response = await ctx.session.create_message(\n                messages=[\n                    types.SamplingMessage(\n                        role=\"user\",\n                        content=types.TextContent(type=\"text\", text=\"Hello, world!\"),\n                    ),\n                ],\n                max_tokens=100,\n            )\n            return [TextContent(type=\"text\", text=f\"{response}\")]\n\n\ndef create_app(\n    is_json_response_enabled=False, event_store: EventStore | None = None\n) -> Starlette:\n    \"\"\"Create a Starlette application for testing using the session manager.\n\n    Args:\n        is_json_response_enabled: If True, use JSON responses instead of SSE streams.\n        event_store: Optional event store for testing resumability.\n    \"\"\"\n    # Create server instance\n    server = ServerTest()\n\n    # Create the session manager\n    session_manager = StreamableHTTPSessionManager(\n        app=server,\n        event_store=event_store,\n        json_response=is_json_response_enabled,\n    )\n\n    # Create an ASGI application that uses the session manager\n    app = Starlette(\n        debug=True,\n        routes=[\n            Mount(\"/mcp\", app=session_manager.handle_request),\n        ],\n        lifespan=lambda app: session_manager.run(),\n    )\n\n    return app\n\n\ndef run_server(\n    port: int, is_json_response_enabled=False, event_store: EventStore | None = None\n) -> None:\n    \"\"\"Run the test server.\n\n    Args:\n        port: Port to listen on.\n        is_json_response_enabled: If True, use JSON responses instead of SSE streams.\n        event_store: Optional event store for testing resumability.\n    \"\"\"\n\n    app = create_app()\n    # Configure server\n    config = uvicorn.Config(\n        app=app,\n        host=\"127.0.0.1\",\n        port=port,\n        log_level=\"info\",\n        limit_concurrency=10,\n        timeout_keep_alive=5,\n        access_log=False,\n    )\n\n    # Start the server\n    server = uvicorn.Server(config=config)\n\n    # This is important to catch exceptions and prevent test hangs\n    try:\n        server.run()\n    except Exception:\n        import traceback\n\n        traceback.print_exc()\n\n\n# Test fixtures - using same approach as SSE tests\n@pytest.fixture\ndef basic_server_port() -> int:\n    \"\"\"Find an available port for the basic server.\"\"\"\n    with socket.socket() as s:\n        s.bind((\"127.0.0.1\", 0))\n        return s.getsockname()[1]\n\n\n@pytest.fixture\ndef basic_server(basic_server_port: int) -> Generator[None, None, None]:\n    \"\"\"Start a basic server.\"\"\"\n    proc = multiprocessing.Process(\n        target=run_server, kwargs={\"port\": basic_server_port}, daemon=True\n    )\n    proc.start()\n\n    # Wait for server to be running\n    max_attempts = 20\n    attempt = 0\n    while attempt \u003c max_attempts:\n        try:\n            with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:\n                s.connect((\"127.0.0.1\", basic_server_port))\n                break\n        except ConnectionRefusedError:\n            time.sleep(0.1)\n            attempt += 1\n    else:\n        raise RuntimeError(f\"Server failed to start after {max_attempts} attempts\")\n\n    yield\n\n    # Clean up\n    proc.kill()\n    proc.join(timeout=2)\n\n\n@pytest.fixture\ndef basic_server_url(basic_server_port: int) -> str:\n    \"\"\"Get the URL for the basic test server.\"\"\"\n    return f\"http://127.0.0.1:{basic_server_port}\"\n\n\n# Client-specific fixtures\n@pytest.fixture\nasync def http_client(basic_server, basic_server_url):\n    \"\"\"Create test client matching the SSE test pattern.\"\"\"\n    async with httpx.AsyncClient(base_url=basic_server_url) as client:\n        yield client\n\nasync def sample_callback(*args, **kwargs):\n    print(\"IN SAMPLE CALLBACK\")\n\n    result = types.CreateMessageResult(\n        role=\"user\",\n        content=types.TextContent(type=\"text\", text=\"Hello, world!\"),\n        model=\"hi\",\n    )\n\n    return result\n\n@pytest.fixture\nasync def initialized_client_session(basic_server, basic_server_url):\n    \"\"\"Create initialized StreamableHTTP client session.\"\"\"\n    async with streamablehttp_client(f\"{basic_server_url}/mcp\") as (\n        read_stream,\n        write_stream,\n        _,\n    ):\n        async with ClientSession(\n            read_stream,\n            write_stream,\n            sampling_callback=sample_callback,\n        ) as session:\n            await session.initialize()\n            yield session\n\n\n@pytest.mark.anyio\nasync def test_callback(initialized_client_session):\n    \"\"\"Test client tool invocation.\"\"\"\n    # First list tools\n    tools = await initialized_client_session.list_tools()\n    assert len(tools.tools) == 1\n    assert tools.tools[0].name == \"sample_tool\"\n\n    # Call the tool\n    result = await initialized_client_session.call_tool(\"sample_tool\", {})\n    assert len(result.content) == 1\n    assert result.content[0].type == \"text\"\n    assert \"Hello, world!\" in result.content[0].text\n```","author":{"url":"https://github.com/jlowin","@type":"Person","name":"jlowin"},"datePublished":"2025-05-10T22:34:04Z","url":"https://github.com/modelcontextprotocol/python-sdk/issues/680"}

react-profiling0
react-import-mapreact,react-dom,react-dom/client,react-dom/profiling,react-is,react/compiler-runtime,react/jsx-dev-runtime,react/jsx-runtime,scheduler@b8488ee2c322
route-pattern/_view_fragments/issues/show/:user_id/:repository/:id/issue_layout(.:format)
route-controllervoltron_issues_fragments
route-actionissue_layout
fetch-noncev2:cd04687f-5366-094f-86e5-06e23a7fc2a4
current-catalog-service-hash81bb79d38c15960b92d99bca9288a9108c7a47b18f2423d0f6438c5b7bcd2114
request-idD8FA:237673:27E906:365E4A:6B00C32D
html-safe-nonce1c13903832b1d156c601e636a4815728386236bf0add6b5e3a3d9e1c049ade7d
visitor-payloadeyJyZWZlcnJlciI6IiIsInJlcXVlc3RfaWQiOiJEOEZBOjIzNzY3MzoyN0U5MDY6MzY1RTRBOjZCMDBDMzJEIiwidmlzaXRvcl9pZCI6IjI3NTM3NjgxMjY3MjEwODIxNTciLCJyZWdpb25fZWRnZSI6ImlhZCIsInJlZ2lvbl9yZW5kZXIiOiJpYWQifQ==
visitor-hmac8ce6c8451610459aa78797b7d25559d9a1bf80ca2fe2e7ef13a03680484fc3c4
hovercard-subject-tagissue:3054552075
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/680/issue_layout
twitter:imagehttps://opengraph.githubassets.com/278e95e9f4495ab91eafd733ffab14fe1eb2a09b204d1728ded59d8267f18188/modelcontextprotocol/python-sdk/issues/680
twitter:cardsummary_large_image
og:imagehttps://opengraph.githubassets.com/278e95e9f4495ab91eafd733ffab14fe1eb2a09b204d1728ded59d8267f18188/modelcontextprotocol/python-sdk/issues/680
og:image:altI'm debugging the issue described in PrefectHQ/fastmcp#393. Essentially, attempting to use a callback for sampling in conjunction with a Streamable HTTP connection results in an indefinite hang. I'...
og:image:width1200
og:image:height600
og:site_nameGitHub
og:typeobject
og:author:usernamejlowin
hostnamegithub.com
expected-hostnamegithub.com
None93edd3bebc4afb7ce711ee74cb5d2a95927850b082a4d43e212222389cb1c415
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
release1fee81a280ea86312b69448e261b418189bfd5b5
ui-targetfull
theme-color#1e2327
color-schemelight dark
react-app-nameissues

Links:

Skip to contenthttps://github.com/modelcontextprotocol/python-sdk/issues/680#start-of-content
https://github.com/
Sign inhttps://github.com/login?return_to=https%3A%2F%2Fgithub.com%2Fmodelcontextprotocol%2Fpython-sdk%2Fissues%2F680
GitHubRepository hosting, code review, and collaborationhttps://github.com/platform
CopilotAI coding agent for tasks, projects, and automated workhttps://github.com/features/copilot
ActionsCI/CD and automationhttps://github.com/features/actions
Code QualityQuality analysis, fixes, and enforcementhttps://github.com/features/code-quality
CodespacesCloud development environmentshttps://github.com/features/codespaces
Code SecurityVulnerability detection and remediationhttps://github.com/security/advanced-security/code-security
Secret ProtectionSecret scanning and leak preventionhttps://github.com/security/advanced-security/secret-protection
All Featureshttps://github.com/features
Documentationhttps://docs.github.com/en
Traininghttps://learn.github.com/skills
Certificationshttps://learn.github.com/credentials
Build with Copilothttps://github.com/features/ai
Customize Copilothttps://docs.github.com/en/copilot/how-tos/copilot-on-github/customize-copilot/customize-copilot-overview
Integrationshttps://github.com/marketplace
Trending reposhttps://github.com/trending
GitHub Sponsorshttps://github.com/open-source/sponsors
Developer articleshttps://github.com/resources/articles
ChangelogYour source for the latest features, improvements, and fixes across GitHub products, all in one place.https://github.blog/changelog/
Enterpriseshttps://github.com/enterprise
Teamhttps://github.com/team
Startupshttps://github.com/enterprise/startups
Nonprofitshttps://github.com/solutions/industry/nonprofits
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
See all industrieshttps://github.com/solutions/industry
Why GitHubhttps://github.com/why-github
Customer Storieshttps://github.com/customer-stories
Business insightshttps://github.com/solutions/executive-insights
Trust Centerhttps://github.com/trust-center
GitHub Advanced SecurityEnterprise-grade code securityhttps://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
Documentationhttps://docs.github.com/en
Resource centerhttps://github.com/resources
Bloghttps://github.blog/
Events & webinarshttps://github.com/resources/events
Community Forumhttps://github.com/orgs/community/discussions
Customer Storieshttps://github.com/customer-stories
Integrationshttps://github.com/marketplace
Customer supporthttps://help.github.com/
Traininghttps://learn.github.com/skills
GitHub Statushttps://www.githubstatus.com/
Abouthttps://github.com/about
Partnershttps://github.com/partners
Changeloghttps://github.blog/changelog/
GitHub UniverseThe event for developers, by developers — talks, workshops, and what’s next for GitHub.https://githubuniverse.com/
Pricinghttps://github.com/pricing
Sign inhttps://github.com/login?return_to=https%3A%2F%2Fgithub.com%2Fmodelcontextprotocol%2Fpython-sdk%2Fissues%2F680
Sign uphttps://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/680
Reloadhttps://github.com/modelcontextprotocol/python-sdk/issues/680
Reloadhttps://github.com/modelcontextprotocol/python-sdk/issues/680
modelcontextprotocolhttps://github.com/modelcontextprotocol
python-sdkhttps://github.com/modelcontextprotocol/python-sdk
Codehttps://github.com/modelcontextprotocol/python-sdk
Issues308 (308)https://github.com/modelcontextprotocol/python-sdk/issues
Pull requests112 (112)https://github.com/modelcontextprotocol/python-sdk/pulls
Actionshttps://github.com/modelcontextprotocol/python-sdk/actions
Projectshttps://github.com/modelcontextprotocol/python-sdk/projects
Security and quality12 (12)https://github.com/modelcontextprotocol/python-sdk/security
Insightshttps://github.com/modelcontextprotocol/python-sdk/insights
https://github.com/modelcontextprotocol/python-sdk
New issuehttps://github.com/login?return_to=https://github.com/modelcontextprotocol/python-sdk/issues/680
New issuehttps://github.com/login?return_to=https://github.com/modelcontextprotocol/python-sdk/issues/680
Streamable HTTP hangs forever when the server attempts any callbackhttps://github.com/modelcontextprotocol/python-sdk/issues/680#top
https://github.com/ihrpr
2025-03-26 spec releasehttps://github.com/modelcontextprotocol/python-sdk/milestone/6
https://github.com/jlowin
jlowinhttps://github.com/jlowin
on May 10, 2025https://github.com/modelcontextprotocol/python-sdk/issues/680#issue-3054552075
PrefectHQ/fastmcp#393https://github.com/PrefectHQ/fastmcp/issues/393
https://github.com/modelcontextprotocol/python-sdk/blob/main/tests/shared/test_streamable_http.pyhttps://github.com/modelcontextprotocol/python-sdk/blob/main/tests/shared/test_streamable_http.py
jlowinhttps://github.com/jlowin
on May 11, 2025https://github.com/modelcontextprotocol/python-sdk/issues/680#event-17605545566
ihrprhttps://github.com/ihrpr
on May 11, 2025https://github.com/modelcontextprotocol/python-sdk/issues/680#event-17606588954
ihrprhttps://github.com/ihrpr
r-05-25https://github.com/modelcontextprotocol/python-sdk/milestone/7
2025-03-26 spec releasehttps://github.com/modelcontextprotocol/python-sdk/milestone/6
on May 11, 2025https://github.com/modelcontextprotocol/python-sdk/issues/680#event-17606589516
https://github.com/ihrpr
ihrprhttps://github.com/ihrpr
on May 12, 2025https://github.com/modelcontextprotocol/python-sdk/issues/680#issuecomment-2873422709
ihrprhttps://github.com/ihrpr
completedhttps://github.com/modelcontextprotocol/python-sdk/issues?q=is%3Aissue%20state%3Aclosed%20archived%3Afalse%20reason%3Acompleted
on May 12, 2025https://github.com/modelcontextprotocol/python-sdk/issues/680#event-17621115563
Sign up for freehttps://github.com/signup?return_to=https://github.com/modelcontextprotocol/python-sdk/issues/680
Sign in to commenthttps://github.com/login?return_to=https://github.com/modelcontextprotocol/python-sdk/issues/680
ihrprhttps://github.com/ihrpr
2025-03-26 spec releasehttps://github.com/modelcontextprotocol/python-sdk/milestone/6
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.