Bug: AssertionError: Request already responded to — cancellation race in v1.27.0
Initial Checks
- [x] I confirm that I'm using the latest version of MCP Python SDK
- [x] I confirm that I searched for my issue in https://github.com/modelcontextprotocol/python-sdk/issues before opening this issue
Description
Bug: AssertionError: Request already responded to — cancellation race in v1.27.0
AssertionError: Request already responded to when CancelledNotification arrives after handler completes but before respond()
Description
When 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.
PR #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.
Reproduction scenario
- Client sends a
tools/callrequest with a long-running handler (e.g. polling with 600s timeout) - Handler completes and returns a result
- Between the handler's
returnand theawait message.respond(response)call in_handle_request, the client sendsnotifications/cancelledfor that same request ID - The cancellation notification handler (
session.py:403-406) callsresponder.cancel(), which:- Calls
_cancel_scope.cancel() - Sets
_completed = True - Sends an error response
"Request cancelled"
- Calls
- Back in
_handle_request, execution reachesawait message.respond(response)atserver.py:800 respond()hitsassert not self._completedatsession.py:129→ crash
The 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.
Stack trace
ExceptionGroup: unhandled errors in a TaskGroup (1 sub-exception)
+-+---------------- 1 ----------------
| ExceptionGroup: unhandled errors in a TaskGroup (1 sub-exception)
+-+---------------- 1 ----------------
| ExceptionGroup: unhandled errors in a TaskGroup (1 sub-exception)
+-+---------------- 1 ----------------
| Traceback (most recent call last):
| File "mcp/server/lowlevel/server.py", line 703, in _handle_message
| await self._handle_request(message, req, session, lifespan_context, raise_exceptions)
| File "mcp/server/lowlevel/server.py", line 800, in _handle_request
| await message.respond(response)
| File "mcp/shared/session.py", line 129, in respond
| assert not self._completed, "Request already responded to"
| AssertionError: Request already responded to
+------------------------------------
Impact
This 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.
Related
- #2328 — original ClosedResourceError report
- #2334 — v1.x fix (covers ClosedResourceError but not this assert race)
- #2306 — main branch transport-close cancellation
Example Code
The race window in `_handle_request` (`server.py:719`):
# Line 770: handler completes, returns response
response = await handler(req)
# ... exception handling ...
# Line 799-800: GAP — between handler return and respond(),
# a CancelledNotification can arrive on another task and call
# responder.cancel(), setting _completed = True and sending
# an error response. No await in this gap means no CancelledError
# can be delivered.
try:
await message.respond(response) # <-- assert fires here
except (anyio.BrokenResourceError, anyio.ClosedResourceError):
...
The `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()`.
## Suggested fix
In `session.py`, change `respond()` to handle the already-completed case gracefully instead of asserting:
async def respond(self, response: SendResultT | ErrorData) -> None:
if not self._entered:
raise RuntimeError("RequestResponder must be used as a context manager")
# If already completed (e.g. by a concurrent cancellation), skip silently.
if self._completed:
return
if not self.cancelled:
self._completed = True
await self._session._send_response(
request_id=self.request_id, response=response
)
Alternatively, the guard could be added in `_handle_request` before calling `respond()`:
if not message._completed:
try:
await message.respond(response)
except (anyio.BrokenResourceError, anyio.ClosedResourceError):
logger.debug("Response for %s dropped - transport closed", message.request_id)
The first approach (in `respond()` itself) is more robust since it closes the race for all callers.
Python & MCP Python SDK
- `mcp` 1.27.0
- Python 3.14
- anyio (asyncio backend)
- FastMCP stdio transport
- Client: Claude Code 2.1.92
bug confirmed on both main (3d7b311) and origin/v1.x (73d458b).
respond() asserts not self._completed at session.py:133. when a notifications/cancelled arrives after the handler returns but before await message.respond(...) is called (server.py:523), a concurrent task calls responder.cancel(), which sets _completed = True and sends the error response. _handle_request's except CancelledError guard (server.py:503) never fires because there's no await checkpoint between handler return and respond(), so the cancel scope can't deliver CancelledError there. the assert crashes the server.
repro script + output
# repro.py — run with: uv run python repro.py
import anyio
from unittest.mock import AsyncMock, MagicMock
from mcp.shared.session import RequestResponder
from mcp.types import ErrorData, JSONRPCRequest
def make_responder():
mock_session = MagicMock()
mock_session._send_response = AsyncMock()
request = JSONRPCRequest(jsonrpc="2.0", id=1, method="tools/call")
responder = RequestResponder(
request_id=1, request_meta=None, request=request,
session=mock_session, on_complete=lambda r: None,
)
return responder, mock_session
async def test_race_direct():
responder, _ = make_responder()
with responder:
await responder.cancel() # simulates CancelledNotification after handler returned
try:
await responder.respond(ErrorData(code=0, message="ok")) # server.py:523
print("PASS")
except AssertionError as e:
print(f"REPRODUCED: {e} _completed={responder._completed}")
async def main():
print("=== Test: direct sequence ===")
await test_race_direct()
anyio.run(main)
=== Test: direct sequence ===
REPRODUCED: Request already responded to _completed=True
code path:
_handle_request(server.py:500):response = await handler(ctx, req.params)— handler returns normally- concurrent task:
cancel()(session.py:142-155) sets_cancel_scope.cancel()+_completed = True+ sends error response _handle_request(server.py:523):await message.respond(response)— no await checkpoint between steps 1 and 3respond()(session.py:133):assert not self._completed— fires because_completedwas set in step 2
suggested fix
# src/mcp/shared/session.py
- assert not self._completed, "Request already responded to"
+ if self._completed:
+ return
cancel() already sent the error response; silently dropping the duplicate in respond() is correct behavior.
test to verify: call cancel() then respond() on the same RequestResponder within a context manager and assert no exception is raised (added as test_respond_after_cancel_does_not_raise in tests/shared/test_session.py).
Hit this same crash on Windows with Claude Code's stdio transport (MCP SDK 1.14.1, Python 3.12). The recent Claude Code update started sending notifications/cancelled on user interrupt, which reliably triggers the race.
The fix is two guards in RequestResponder (session.py):
respond() — replace the assert with an early return:
# before
assert not self._completed, "Request already responded to"
# after
if self._completed:
return
cancel() — skip the error response if the handler already responded:
self._cancel_scope.cancel()
if self._completed:
return
self._completed = True
await self._session._send_response(...)
Both directions are safe under cooperative multitasking since _completed is set synchronously before the first await in each method, so exactly one of them wins and sends a single JSON-RPC response. No double-response, no crash.
I've got a branch with the fix + two unit tests (respond-after-cancel and cancel-after-respond) passing against main, full suite green (1171 passed). Happy to open a PR if that'd be useful.
Confirming this reproduces downstream, and sharing the guard we're using.
hive is an MCP stdio server. A tool that offloads sync work (git) to a worker thread can call message.respond() after a notifications/cancelled for that request has already run responder.cancel() (setting _completed = True). respond() then hits assert not self._completed at mcp/shared/session.py:129, the AssertionError propagates into the receive loop's task group, and every subsequent call on the shared process returns Connection closed — a single rejected/cancelled call poisons the whole session.
This matches the report exactly (handler done → cancel arrives → respond() asserts). On mcp 1.26.0 the sibling __exit__ leak (#2610) is already masked by the except anyio.get_cancelled_exc_class(): return guard in Server._handle_request, but this respond() window is not, so it's still live.
As a stopgap we self-gate a patch on RequestResponder.respond that short-circuits only when _completed is already set (debug-log instead of assert), so it goes inert the moment upstream guards respond():
async def _patched_respond(self, response):
if not self._entered:
raise RuntimeError("RequestResponder must be used as a context manager")
if self._completed:
# handler finished after client cancellation — drop the late response
return
await original_respond(self, response)
We back it with a deterministic in-memory regression test that drives a real lowlevel Server and sends notifications/cancelled mid-handler. Happy to open a PR porting a guarded respond() plus that test if it'd help land #2416.
I'd like to work on this. The fix is straightforward: replace \ssert not self._completed\ with a silent early return in \RequestResponder.respond()\ so a cancellation notification that arrives after the handler returns doesn't crash the server. I'll also add a regression test. Opening a PR shortly.
Following up on my June comment — we still carry this guard in production in hive (an MCP stdio server). Ours patches respond() only, self-gated to the exact state (_completed already set) so it goes inert the moment upstream guards it.
#3088 was withdrawn by its author and #2418 has been dormant since April, so as far as I can tell nobody is currently on this.
If a fix would be accepted, I am happy to open a PR: early return in respond() when _completed is already set, the matching skip in cancel() so it does not send a second response, plus regression tests for both orderings (respond-after-cancel and cancel-after-respond).
One question before I do — which base would you want it against, main, v1.x, or both?
Confirming this on 1.29.0, with a variant that may be worth folding into the title: when the tool handler is synchronous, this is not a race — it is deterministic.
The report above describes a narrow window between the handler returning and respond() being reached. That window is real, but with a def handler (rather than async def) there is no window at all: the cancel scope has no checkpoint anywhere in the handler, so except anyio.get_cancelled_exc_class() at server.py:773 can never fire, and the normal-completion path at line 806 is always the one taken. Every cancellation of an in-flight sync handler ends in the assert.
That matters for severity because it removes the timing luck. Reproduces on the first attempt, every time, with one process, one session, three sequential calls, and no concurrency:
# repro.py — mcp 2.0.0 client, mcp 1.29.0 server (mcp-server-datahub 0.6.0, all handlers sync)
import os, anyio
from mcp import ClientSession
from mcp.client.stdio import StdioServerParameters, stdio_client
PARAMS = StdioServerParameters(command="mcp-server-datahub", env={...})
async def main() -> None:
async with stdio_client(PARAMS) as (read, write), ClientSession(read, write) as s:
await s.initialize()
r = await s.call_tool("get_entities", {"urns": [URN]})
print("1: isError =", r.isError) # 1: False
try:
with anyio.fail_after(0.02): # shorter than the ~2s handler
await s.call_tool("get_entities", {"urns": [URN]})
except TimeoutError:
print("2: timed out (expected)") # 2: timed out (expected)
await anyio.sleep(2)
r = await s.call_tool("get_entities", {"urns": [URN]})
print("3: isError =", r.isError) # 3: MCPError: Connection closed
anyio.run(main)
fail_after only has to be shorter than the handler. The traceback matches the one above and unwinds through mcp/server/stdio.py, fastmcp/server/mixins/transport.py run_stdio_async, and out of the server's main() — the process exits.
Two things this cost us downstream, in case they are useful as impact evidence. First, the failure names nothing true: the client sees an ordinary timeout on one call and a dead transport on every call after it, so we localised it only by running four concurrent workers and noticing the shape of the damage. Second, the damage is shaped by when rather than how much — four workers writing to the same backend lost 5 of 18 writes distributed 4/1/0 across three of them, which is simply the order in which each one first hit a timeout, because after that it could never write again.
cancel_on_abandon defaults to True in the 2.x client (mcp/shared/dispatcher.py:98) and sending notifications/cancelled for an abandoned request is what the spec asks for, so a client can only avoid this by never bounding a request at all — which is what we now do, at the cost of being unable to time-bound an in-flight call.
The respond()-side guard proposed above closes it for sync handlers too, and is the one we would prefer for that reason: the _handle_request variant still leaves any other caller of respond() exposed. Making respond() a no-op-with-warning rather than an assert also seems worth doing on its own — an assert in a request-dispatch path is compiled out entirely under python -O, and when it is not, it takes the process down.
This deterministic sync-handler case materially strengthens the report. It shows that the core invariant should live at the response boundary rather than depend on every request handler reaching cancellation checkpoints correctly.
I would define the invariant as:
one request ID → one terminal protocol response at most
Once a request becomes terminal—completed, cancelled or failed—later completion attempts should be rejected safely without terminating the transport or emitting a second response.
The regression matrix should ideally cover:
sync handler: cancel before completion; async handler: cancellation at a checkpoint; completion immediately before cancellation; cancellation immediately before completion; repeated cancellation; late handler completion after the client has abandoned the request; subsequent requests remaining usable on the same session.
A warning should also carry the request ID and attempted transition, for example cancelled → completed, without logging arguments or sensitive tool output. That would make the failure diagnosable while preserving the server process and session.
I agree that an assertion is the wrong production boundary here: its behaviour changes under python -O, and without optimisation it converts a recoverable duplicate terminal transition into a process-wide availability failure.
The “third call still succeeds” assertion may be the most important acceptance test because it verifies the operational outcome, not merely that the original exception disappeared.
Agreed on the invariant, and the phrasing is better than what I had. Putting it at the response boundary is what makes it hold for handlers the SDK does not control — a sync handler cannot be made to reach a checkpoint, and a server author has no way to know that the tool they wrote in def has quietly opted out of the guard.
On the acceptance test being the operational outcome rather than the absent exception: I can offer a measurement for that, since we shipped the client-side workaround and watched the number move. Four processes writing concurrently through separate stdio sessions, each write confirmed by a bounded read-after-write poll, so the deadline occasionally expires with a request in flight.
- Before, still cancelling: 5 of 18 writes lost, distributed 4 / 1 / 0 across three workers, and the backend held 4 records — all from the one worker that never happened to time out.
- After, bounding only the caller's wait and never cancelling on the wire: 1 of 18, and the backend held 9 across all three.
The distribution is the part worth noticing. It is not proportional to load; it is the order in which each worker first hit a timeout, because after that it could never write again. That is why "the third call still succeeds" is the test that matters — the first exception disappearing tells you nothing about whether the session survived, and a fix that only stops the traceback would leave that 4 / 1 / 0 shape untouched.
Two small additions to the matrix, from the same failure. Cancellation of a request whose handler is already blocked in I/O behaves like the sync case even when the handler is async, if the blocking call is not itself a checkpoint — worth a row because it makes the bug reachable from code that looks correctly written. And on the last row: a caller that gives up locally but leaves the request on the wire will have the next queued request wait behind the abandoned one. That is the right trade against a dead session, but it is a behaviour change worth pinning so nobody later "fixes" the queuing by reintroducing the cancel.
Happy to contribute the repro as a test case if that is useful.
That before/after distribution is excellent impact evidence because it distinguishes a single failed request from session-wide progressive failure.
Agreed on both additions:
an async handler blocked in non-cooperative I/O belongs in the matrix because its observable cancellation behaviour is equivalent to the synchronous case; caller-side abandonment without wire cancellation should have its queueing behaviour captured explicitly, so a later optimisation cannot silently restore the fatal transition.
A strong end-to-end regression would therefore assert the complete sequence:
the caller’s bounded wait expires; late completion of the abandoned request does not terminate the transport or emit a duplicate terminal response; the next request on the same session remains processable; any expected queueing behind the still-running handler is measured and documented.
Your reproducible production numbers and test case would materially improve the evidence for accepting the response-boundary guard.
Here is that test case, and running it turned up one thing worth folding into the invariant: guarding respond() alone is not sufficient. cancel() is the other terminal path and has the same duplicate-transition problem — a repeated notifications/cancelled, or a cancel arriving after the handler has already responded, still puts a second terminal response on the wire. The invariant as you stated it is right; it just has to be enforced at both doors.
Verified as a sequence, on a clean mcp==1.29.0:
| state | result |
|---|---|
| unpatched | 3 of 3 fail |
guard in respond() only |
2 pass, repeated-cancellation still fails |
guard in respond() and cancel() |
3 of 3 pass |
And the operational assertion you singled out, end to end against a real stdio server (mcp-server-datahub 0.6.0, all handlers sync) with the guard in place:
1: isError = False
2: timed out (expected)
3: isError = False <-- the session survived
Unpatched, that third line is MCPError: Connection closed.
The test
Written against the responder rather than a subprocess so it runs in CI without spawning a server, and driving RequestResponder directly because that is where the invariant lives.
class _RecordingSession:
"""Enough session for a responder: record what reaches the wire."""
def __init__(self) -> None:
self.sent: list[tuple[str, object]] = []
async def _send_response(self, request_id, response) -> None:
self.sent.append(("error" if isinstance(response, ErrorData) else "result", request_id))
def _responder(session, request_id):
return RequestResponder(
request_id=request_id, request_meta=None,
request=ClientRequest(PingRequest(method="ping")),
session=session, on_complete=lambda _r: None,
)
@pytest.mark.anyio
async def test_late_completion_after_cancellation_is_not_a_second_response():
"""A sync handler cannot observe cancellation, so it finishes anyway."""
session = _RecordingSession()
with _responder(session, "req-1") as responder:
await responder.cancel()
assert session.sent == [("error", "req-1")]
await responder.respond(ServerResult(root={})) # the handler completes
assert session.sent == [("error", "req-1")]
@pytest.mark.anyio
async def test_the_session_survives_and_the_next_request_still_works():
"""The operational outcome: not one lost request, but every one after it."""
session = _RecordingSession()
with _responder(session, "abandoned") as first:
await first.cancel()
await first.respond(ServerResult(root={}))
with _responder(session, "next") as second:
await second.respond(ServerResult(root={}))
assert session.sent == [("error", "abandoned"), ("result", "next")]
@pytest.mark.anyio
async def test_repeated_cancellation_is_idempotent():
"""The case that showed respond()-only guarding is incomplete."""
session = _RecordingSession()
with _responder(session, "twice") as responder:
await responder.cancel()
await responder.cancel()
assert session.sent == [("error", "twice")]
The guard the tests pass against
Same shape in both methods — refuse the second terminal transition, log which one it was, and return rather than raise:
if self._completed:
logger.warning(
"Request %s: ignoring duplicate terminal transition (%s -> completed)",
self.request_id, "cancelled" if self.cancelled else "completed",
)
return
and in cancel(), before self._cancel_scope.cancel():
if self._completed:
logger.warning(
"Request %s: ignoring duplicate terminal transition (completed -> cancelled)",
self.request_id,
)
return
The warning carries the request id and the attempted transition and nothing else, per your point about not logging arguments or tool output.
Three of the seven rows in your matrix are covered above. The remaining four — async cancellation at a checkpoint, completion immediately before cancellation, cancellation immediately before completion, and the measured queueing behind a still-running handler — want a subprocess or a timing harness rather than the in-memory pair, so I have left them out rather than write something that passes without exercising the ordering.
Happy to open this as a PR with the guard and these tests if that is wanted, or to leave it here for whoever picks the issue up.
This is excellent validation — and the cancel() result closes the remaining hole in the invariant.
I agree the rule now becomes simpler and stronger:
a request may enter one terminal state exactly once, regardless of which terminal path gets there first.
So respond() and cancel() should both be idempotent with respect to an already-completed request, and any attempted second transition should become diagnostic evidence rather than another wire action.
Your three-step result is particularly useful:
unpatched → 3/3 fail respond() guard only → incomplete respond() + cancel() guards → 3/3 pass
And the end-to-end result matters even more:
timeout → session survives → next request succeeds
That is the operational invariant worth protecting.
I also like the warning shape you used: request ID + attempted transition, with no arguments or tool output. That preserves reviewability without leaking sensitive payloads.
One additional distinction I would keep visible in the eventual fix/docs:
protocol terminal state tells us whether another response may be emitted; execution/outcome evidence tells us whether the underlying side effect actually occurred.
Those are related but not identical, especially for write-capable tools where the handler may finish after the caller has abandoned the request.
I think this is strong enough to justify the PR. The tests now demonstrate both the local state-machine invariant and the real operational consequence.
— Adam Al-Zayed Founder | EcoCitizenz Ltd ECZ-ID — MCP & Agent Trust https://mcp.ecocitizenz.com/ Resolver: https://resolver.ecocitizenz.org/passport/ECZ-GB-RBS1NW
This is excellent validation — and the cancel() result closes the remaining hole in the invariant.
I agree the rule now becomes simpler and stronger:
a request may enter one terminal state exactly once, regardless of which terminal path gets there first.
So respond() and cancel() should both be idempotent with respect to an already-completed request, and any attempted second transition should become diagnostic evidence rather than another wire action.
Your three-step result is particularly useful:
unpatched → 3/3 fail respond() guard only → incomplete respond() + cancel() guards → 3/3 pass
And the end-to-end result matters even more:
timeout → session survives → next request succeeds
That is the operational invariant worth protecting.
I also like the warning shape you used: request ID + attempted transition, with no arguments or tool output. That preserves reviewability without leaking sensitive payloads.
One additional distinction I would keep visible in the eventual fix/docs:
protocol terminal state tells us whether another response may be emitted; execution/outcome evidence tells us whether the underlying side effect actually occurred.
Those are related but not identical, especially for write-capable tools where the handler may finish after the caller has abandoned the request.
I think this is strong enough to justify the PR. The tests now demonstrate both the local state-machine invariant and the real operational consequence.
— Adam Al-Zayed Founder | EcoCitizenz Ltd ECZ-ID — MCP & Agent Trust https://mcp.ecocitizenz.com/ Resolver: https://resolver.ecocitizenz.org/passport/ECZ-GB-RBS1NW
Agreed on the invariant as you have now stated it — one terminal state, once, whichever path arrives first — and the distinction you want kept visible is the right one. It is exactly what bit us downstream: the transport died while the write it was confirming may already have landed, so protocol-terminal and side-effect-occurred had to be tracked separately or a lost session would have been reported as a lost write.
Before opening the PR I checked where it should land, and the answer is not main. main is now v2.0.0 (released 2026-07-28) and has been refactored past this code path entirely — there is no RequestResponder, no _completed, and no mcp/shared/session.py; the dispatch surface is shared/dispatcher.py, shared/jsonrpc_dispatcher.py, shared/inbound.py and shared/peer.py. The guard as written applies to the 1.x line, where the assertion still stands, and 1.29.0 shipped the same day as 2.0.0.
So there are two different pieces of work and I would rather ask than guess:
- 1.x: the patch above, as-is — the guard in
respond()andcancel(), plus the three tests. Ready to submit against whichever branch that line is maintained on; I could not see one from the public branch list, so I do not know the target. - 2.x: the same invariant re-expressed against the new dispatcher. That is a different change and I have not read enough of it to claim the equivalent hole exists — it may already be closed by the restructure, and someone who knows that code will settle it in a minute where I would take an afternoon.
Happy to do either. If 1.x is still receiving fixes, point me at the branch and I will open it with the tests. If the useful question is now whether 2.x has the same hole, I can test that instead and report before writing anything.
Either way the reproduction and the three-step result stand for 1.29.0, which is what mcp-server-datahub 0.6.0 and anything else pinned to the 1.x client are running today.
Still reproduces on 1.30.0 (released 2026-09-07), the latest v1.x — and it needs no DataHub or third-party server. Self-contained repro, 3 of 3 runs, every run on the first cancellation:
Server — mcp==1.30.0, one tool whose work cannot observe cancellation (a sync call on a worker thread, which is what a def tool amounts to):
# server.py
import time
import anyio
import mcp.types as types
from mcp.server.lowlevel import Server
from mcp.server.stdio import stdio_server
server = Server("repro")
@server.list_tools()
async def list_tools() -> list[types.Tool]:
return [types.Tool(name="slow", description="1s of sync work",
inputSchema={"type": "object", "properties": {}})]
@server.call_tool()
async def call_tool(name: str, arguments: dict) -> list[types.TextContent]:
await anyio.to_thread.run_sync(time.sleep, 1.0)
return [types.TextContent(type="text", text="done")]
async def main() -> None:
async with stdio_server() as (read, write):
await server.run(read, write, server.create_initialization_options())
anyio.run(main)
Client — mcp==2.2.0 in a separate environment, default cancel_on_abandon; run as python client.py /path/to/v1-env/bin/python server.py:
# client.py
import sys, anyio
from mcp import ClientSession
from mcp.client.stdio import StdioServerParameters, stdio_client
PARAMS = StdioServerParameters(command=sys.argv[1], args=[sys.argv[2]])
async def main() -> None:
async with stdio_client(PARAMS) as (read, write), ClientSession(read, write) as s:
await s.initialize()
r = await s.call_tool("slow", {})
print("1: is_error =", r.is_error)
try:
with anyio.fail_after(0.05):
await s.call_tool("slow", {})
except TimeoutError:
print("2: timed out (expected)")
await anyio.sleep(2)
try:
r = await s.call_tool("slow", {})
print("3: is_error =", r.is_error)
except Exception as e:
print(f"3: {type(e).__name__}: {e}")
anyio.run(main)
Output:
1: is_error = False
2: timed out (expected)
3: MCPError: Connection closed
and the server dies with mcp/server/lowlevel/server.py", line 806, in _handle_request → AssertionError: Request already responded to.
In 1.30.0 the normal-completion respond() at server.py:806 is still unguarded and the bare assert at shared/session.py:129 is unchanged. The two v1.x fix PRs that followed this issue (#2949, #3088) were closed unmerged, and #2418 targets main, where v2 no longer has this code path — so as far as I can tell there is currently no open fix aimed at v1.x.
If a v1.x fix is still wanted, I'm happy to open a PR against v1.x with the guard on both terminal paths (respond() and cancel(), per the test case earlier in this thread) and this repro as a regression test.
Re-tested on mcp 2.3.0. In the same scenario (start a slow tool call, cancel it while it runs, then send another request), the session stays usable in 6 out of 6 runs: 3 with a synchronous tool and 3 with an async tool that uses anyio.to_thread.run_sync. On 1.30.0, the latest v1 release, it still fails in 3 out of 3 runs.
One affected downstream project is mcp-server-datahub 0.8.0, which requires fastmcp>=3.2.0,<4 and so runs on mcp 1.x. I reported it there: acryldata/mcp-server-datahub#262.
A server-side workaround for 1.x servers that can't upgrade yet, with no SDK patch. Seen and tested on 1.28.1 (anyio 4.14.1), where our def tools run through anyio.to_thread.run_sync.
Raise the pending cancellation after the offloaded call, so it surfaces inside _handle_request's try and takes the if message.cancelled: return path, not respond():
async def run_off_loop(**kwargs):
async with one_call_at_a_time: # anyio.Lock()
try:
return await anyio.to_thread.run_sync(partial(fn, **kwargs))
finally:
await anyio.lowlevel.checkpoint_if_cancelled()
checkpoint_if_cancelled doesn't yield when nothing is pending, so it adds no new interleaving point. The finally also covers a tool that raises. A regression test that cancels a running read and a running write, then requires a ping and a further call to succeed, fails on the unguarded version with AssertionError: Request already responded to and passes with the guard.
What it doesn't cover: a cancel processed while respond() itself is waiting for the writer. That one escapes through RequestResponder.__exit__ and stops the server silently; details in #2610.
thanks for working on this! I'm looking forward to a release.. for me, i'm seeing the same on MCP Python SDK 1.x with FastMCP 2.14.x (mcp 1.30.0) and Streamable HTTP (POST /mcp), not stdio.
Symptom: Long-lived sessions drop with Session
AssertionError: Request already responded to File ".../mcp/shared/session.py", line 129, in respond assert not self._completed, "Request already responded to" Often preceded by notifications/cancelled on the same session while a long tools/call is still in flight (heavy background tools/call from other clients on separate sessions). Sometimes follow-on anyio.BrokenResourceError on POST.
Transport: Streamable HTTP; clients send Mcp-Session-Id after init. Overlap pattern: in-flight tools/call + concurrent tools/list / cancel, not necessarily OOM or full process exit.
Stack: fastmcp 2.14.7 → mcp 1.30.0 (still has the assert). Same class of race described in #2416 (cancel completes RequestResponder before late respond()).
Mitigation until fixed in a released wheel: startup monkey-patch aligning with #2949 — idempotent respond() / cancel() (no assert on second completion; don’t send second cancel if already responded). Happy path unchanged in our testing.
Would love a released mcp 1.x with #2949 (or equivalent) so we can drop the patch.