René's URL Explorer Experiment


Title: Bug: AssertionError: Request already responded to — cancellation race in v1.27.0 · Issue #2416 · modelcontextprotocol/python-sdk · GitHub

Open Graph Title: Bug: AssertionError: Request already responded to — cancellation race in v1.27.0 · Issue #2416 · modelcontextprotocol/python-sdk

X Title: Bug: AssertionError: Request already responded to — cancellation race in v1.27.0 · Issue #2416 · modelcontextprotocol/python-sdk

Description: Initial Checks I confirm that I'm using the latest version of MCP Python SDK I confirm that I searched for my issue in https://github.com/modelcontextprotocol/python-sdk/issues before opening this issue Description Bug: AssertionError: R...

Open Graph Description: Initial Checks I confirm that I'm using the latest version of MCP Python SDK I confirm that I searched for my issue in https://github.com/modelcontextprotocol/python-sdk/issues before opening this ...

X Description: Initial Checks I confirm that I'm using the latest version of MCP Python SDK I confirm that I searched for my issue in https://github.com/modelcontextprotocol/python-sdk/issues before opening t...

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

X: @github

direct link

Domain: github.com


Hey, it has json ld scripts:
{"@context":"https://schema.org","@type":"DiscussionForumPosting","headline":"Bug: AssertionError: Request already responded to — cancellation race in v1.27.0","articleBody":"### Initial Checks\n\n- [x] I confirm that I'm using the latest version of MCP Python SDK\n- [x] I confirm that I searched for my issue in https://github.com/modelcontextprotocol/python-sdk/issues before opening this issue\n\n### Description\n\n# Bug: `AssertionError: Request already responded to` — cancellation race in v1.27.0\n\n`AssertionError: Request already responded to` when CancelledNotification arrives after handler completes but before `respond()`\n\n## Description\n\nWhen a client sends a `notifications/cancelled` for a request whose handler has already finished executing but hasn't yet called `message.respond()`, the server crashes with `AssertionError: Request already responded to`.\n\nPR #2334 (v1.27.0) fixed the `ClosedResourceError` crash path by catching `CancelledError` in `_handle_request` and guarding `respond()` against `BrokenResourceError`/`ClosedResourceError`. However, it left a race window between handler completion and `respond()` where a cancellation notification can set `_completed = True` first, causing the assert on line 129 of `session.py` to fire.\n\n## Reproduction scenario\n\n1. Client sends a `tools/call` request with a long-running handler (e.g. polling with 600s timeout)\n2. Handler completes and returns a result\n3. Between the handler's `return` and the `await message.respond(response)` call in `_handle_request`, the client sends `notifications/cancelled` for that same request ID\n4. The cancellation notification handler (`session.py:403-406`) calls `responder.cancel()`, which:\n   - Calls `_cancel_scope.cancel()` \n   - Sets `_completed = True`\n   - Sends an error response `\"Request cancelled\"`\n5. Back in `_handle_request`, execution reaches `await message.respond(response)` at `server.py:800`\n6. `respond()` hits `assert not self._completed` at `session.py:129` → **crash**\n\nThe `cancel_scope.cancel()` only raises `CancelledError` if the task is currently in an `await`. Since the handler already returned, the code path between the handler return and `respond()` is synchronous — no checkpoint where `CancelledError` can be delivered. The `except anyio.get_cancelled_exc_class()` guard at `server.py:773` never fires.\n\n## Stack trace\n\n```\nExceptionGroup: unhandled errors in a TaskGroup (1 sub-exception)\n  +-+---------------- 1 ----------------\n    | ExceptionGroup: unhandled errors in a TaskGroup (1 sub-exception)\n    +-+---------------- 1 ----------------\n      | ExceptionGroup: unhandled errors in a TaskGroup (1 sub-exception)\n      +-+---------------- 1 ----------------\n        | Traceback (most recent call last):\n        |   File \"mcp/server/lowlevel/server.py\", line 703, in _handle_message\n        |     await self._handle_request(message, req, session, lifespan_context, raise_exceptions)\n        |   File \"mcp/server/lowlevel/server.py\", line 800, in _handle_request\n        |     await message.respond(response)\n        |   File \"mcp/shared/session.py\", line 129, in respond\n        |     assert not self._completed, \"Request already responded to\"\n        | AssertionError: Request already responded to\n        +------------------------------------\n```\n\n## Impact\n\nThis crashes the entire MCP server process, killing all in-flight requests. In our case, the server manages multiple long-running background agents, so a crash loses all active work. The crash is triggered by normal client behavior (user cancels an operation), making it a reliability issue rather than an edge case.\n\n## Related\n\n- #2328 — original ClosedResourceError report\n- #2334 — v1.x fix (covers ClosedResourceError but not this assert race)\n- #2306 — main branch transport-close cancellation\n\n\n### Example Code\n\n```Python\nThe race window in `_handle_request` (`server.py:719`):\n\n\n# Line 770: handler completes, returns response\nresponse = await handler(req)\n\n# ... exception handling ...\n\n# Line 799-800: GAP — between handler return and respond(),\n# a CancelledNotification can arrive on another task and call\n# responder.cancel(), setting _completed = True and sending\n# an error response. No await in this gap means no CancelledError\n# can be delivered.\ntry:\n    await message.respond(response)  # \u003c-- assert fires here\nexcept (anyio.BrokenResourceError, anyio.ClosedResourceError):\n    ...\n\n\nThe `except anyio.get_cancelled_exc_class()` at line 773 correctly handles the case where the cancellation arrives *during* handler execution. But it cannot handle cancellation that arrives *after* the handler returns, because there's no async checkpoint between the handler return and `respond()`.\n\n## Suggested fix\n\nIn `session.py`, change `respond()` to handle the already-completed case gracefully instead of asserting:\n\n\nasync def respond(self, response: SendResultT | ErrorData) -\u003e None:\n    if not self._entered:\n        raise RuntimeError(\"RequestResponder must be used as a context manager\")\n    \n    # If already completed (e.g. by a concurrent cancellation), skip silently.\n    if self._completed:\n        return\n\n    if not self.cancelled:\n        self._completed = True\n        await self._session._send_response(\n            request_id=self.request_id, response=response\n        )\n\n\nAlternatively, the guard could be added in `_handle_request` before calling `respond()`:\n\n\nif not message._completed:\n    try:\n        await message.respond(response)\n    except (anyio.BrokenResourceError, anyio.ClosedResourceError):\n        logger.debug(\"Response for %s dropped - transport closed\", message.request_id)\n\n\nThe first approach (in `respond()` itself) is more robust since it closes the race for all callers.\n```\n\n### Python \u0026 MCP Python SDK\n\n```Text\n- `mcp` 1.27.0\n- Python 3.14\n- anyio (asyncio backend)\n- FastMCP stdio transport\n- Client: Claude Code 2.1.92\n```","author":{"url":"https://github.com/bbarwik","@type":"Person","name":"bbarwik"},"datePublished":"2026-04-09T20:25:05.000Z","interactionStatistic":{"@type":"InteractionCounter","interactionType":"https://schema.org/CommentAction","userInteractionCount":4},"url":"https://github.com/2416/python-sdk/issues/2416"}

route-pattern/_view_fragments/issues/show/:user_id/:repository/:id/issue_layout(.:format)
route-controllervoltron_issues_fragments
route-actionissue_layout
fetch-noncev2:11161776-f5fe-0443-6a87-67f91e006b8e
current-catalog-service-hash81bb79d38c15960b92d99bca9288a9108c7a47b18f2423d0f6438c5b7bcd2114
request-idDADE:19C3B6:5A04A8:80429A:6A59E54C
html-safe-nonce06745d062907936e1e5685a6b0e634c8258b6bc04529fcfdbf69c6c61823854a
visitor-payloadeyJyZWZlcnJlciI6IiIsInJlcXVlc3RfaWQiOiJEQURFOjE5QzNCNjo1QTA0QTg6ODA0MjlBOjZBNTlFNTRDIiwidmlzaXRvcl9pZCI6IjU0NTQ1ODM3MjQzOTc2ODQwNDQiLCJyZWdpb25fZWRnZSI6ImlhZCIsInJlZ2lvbl9yZW5kZXIiOiJpYWQifQ==
visitor-hmac20a76e7404f8359eb5fb21e88e5b2451c54af5649987a77a87fac6eb143cfa5c
hovercard-subject-tagissue:4234724647
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/2416/issue_layout
twitter:imagehttps://opengraph.githubassets.com/8a0d14b3774ef6eefa3baff2f2615b9cd903240bf8783c0e02beba14dd24bb16/modelcontextprotocol/python-sdk/issues/2416
twitter:cardsummary_large_image
og:imagehttps://opengraph.githubassets.com/8a0d14b3774ef6eefa3baff2f2615b9cd903240bf8783c0e02beba14dd24bb16/modelcontextprotocol/python-sdk/issues/2416
og:image:altInitial Checks I confirm that I'm using the latest version of MCP Python SDK I confirm that I searched for my issue in https://github.com/modelcontextprotocol/python-sdk/issues before opening this ...
og:image:width1200
og:image:height600
og:site_nameGitHub
og:typeobject
og:author:usernamebbarwik
hostnamegithub.com
expected-hostnamegithub.com
Noneba3976babb66479b1c943a8edc0777d96157da48fadc0161f9ddb219deee8353
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
release26f17126414f953984d8ae42f57c0db48e7dbde3
ui-targetfull
theme-color#1e2327
color-schemelight dark

Links:

Skip to contenthttps://github.com/modelcontextprotocol/python-sdk/issues/2416#start-of-content
https://github.com/
Sign in https://github.com/login?return_to=https%3A%2F%2Fgithub.com%2Fmodelcontextprotocol%2Fpython-sdk%2Fissues%2F2416
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
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%2F2416
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/2416
Reloadhttps://github.com/modelcontextprotocol/python-sdk/issues/2416
Reloadhttps://github.com/modelcontextprotocol/python-sdk/issues/2416
Please reload this pagehttps://github.com/modelcontextprotocol/python-sdk/issues/2416
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.6k https://github.com/login?return_to=%2Fmodelcontextprotocol%2Fpython-sdk
Code https://github.com/modelcontextprotocol/python-sdk
Issues 255 https://github.com/modelcontextprotocol/python-sdk/issues
Pull requests 303 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: AssertionError: Request already responded to — cancellation race in v1.27.0https://github.com/modelcontextprotocol/python-sdk/issues/2416#top
P2Moderate issues affecting some users, edge cases, potentially valuable featurehttps://github.com/modelcontextprotocol/python-sdk/issues?q=state%3Aopen%20label%3A%22P2%22
bugSomething isn't workinghttps://github.com/modelcontextprotocol/python-sdk/issues?q=state%3Aopen%20label%3A%22bug%22
fix proposedBot has a verified fix diff in the commenthttps://github.com/modelcontextprotocol/python-sdk/issues?q=state%3Aopen%20label%3A%22fix%20proposed%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
https://github.com/bbarwik
bbarwikhttps://github.com/bbarwik
on Apr 9, 2026https://github.com/modelcontextprotocol/python-sdk/issues/2416#issue-4234724647
https://github.com/modelcontextprotocol/python-sdk/issueshttps://github.com/modelcontextprotocol/python-sdk/issues
#2334https://github.com/modelcontextprotocol/python-sdk/pull/2334
[Bug] Server crashes with anyio.ClosedResourceError when receiving raw invalid UTF-8 bytes #2328https://github.com/modelcontextprotocol/python-sdk/issues/2328
[v1.x] fix: handle ClosedResourceError when transport closes mid-request #2334https://github.com/modelcontextprotocol/python-sdk/pull/2334
fix: cancel in-flight handlers when transport closes in server.run() #2306https://github.com/modelcontextprotocol/python-sdk/pull/2306
P2Moderate issues affecting some users, edge cases, potentially valuable featurehttps://github.com/modelcontextprotocol/python-sdk/issues?q=state%3Aopen%20label%3A%22P2%22
bugSomething isn't workinghttps://github.com/modelcontextprotocol/python-sdk/issues?q=state%3Aopen%20label%3A%22bug%22
fix proposedBot has a verified fix diff in the commenthttps://github.com/modelcontextprotocol/python-sdk/issues?q=state%3Aopen%20label%3A%22fix%20proposed%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
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.