Back to catalog / MCP reliability
Make long-running MCP tool calls respond to cancellation
Propagate cancellation from the client to a long-running task, clean up resources, and stop unnecessary work.
Goal
When a user cancels a pending tool operation, have the server stop promptly or finish safely.
Steps
- Identify long I/O or compute stages and define a safe post-cancellation state. [mcp-cancel]
- In an async
@mcp.tool()handler, put cleanup infinally; wrap awaited cleanup inanyio.move_on_after(5, shield=True). [mcp-cancel] - For a plain
deftool running in a thread, callanyio.from_thread.check_cancelled()between work units; clients cancel the awaiting task or let its read timeout expire. [mcp-cancel] - Do not enable
json_response=Trueon modern Streamable HTTP orstateless_http=Trueon legacy connections; both suppress handler cancellation. [mcp-cancel] - Cancel a slow test task and verify the handler stops, resources are released, and the result is marked cancelled. [mcp-cancel]
How to verify
After cancellation, async cleanup runs in `finally` within the five-second shielded bound, sync tools exit at a poll, and HTTP settings allow cancellation.
Troubleshooting
If cancellation is ignored, check whether the handler propagates the cancellation token to downstream I/O.
Permissions
Prerequisites
- Python 3.10+ and the MCP Python SDK compatible with the pinned revision
Permissions
- Use a local or isolated test environment; use least privilege and approval for external data or side effects
Limitations
SDK behavior varies by version. Check the pinned revision against your agent or client, then review data retention, authorization, and side effects before production use.
Pinned upstream source
- Repository
- modelcontextprotocol/python-sdk
- File path
- docs/handlers/cancellation.md
- Pinned commit
754254c08fe1c3eda18b69da3d336106fe8d72d6- Source checked
- 2026-10-14 · Reviewed against the pinned upstream source
Repository metrics
These values describe the upstream repository, not popularity or likes for an individual skill or playbook.
- Stars
- Not collected
- Forks
- Not collected
- Observed at
- Not collected
No metrics snapshot is available yet.
License: MIT