Agent Wealth HubFree public resources
中文 EN العربية

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

  1. Identify long I/O or compute stages and define a safe post-cancellation state. [mcp-cancel]
  2. In an async @mcp.tool() handler, put cleanup in finally; wrap awaited cleanup in anyio.move_on_after(5, shield=True). [mcp-cancel]
  3. For a plain def tool running in a thread, call anyio.from_thread.check_cancelled() between work units; clients cancel the awaiting task or let its read timeout expire. [mcp-cancel]
  4. Do not enable json_response=True on modern Streamable HTTP or stateless_http=True on legacy connections; both suppress handler cancellation. [mcp-cancel]
  5. 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

Permissions

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

https://github.com/modelcontextprotocol/python-sdk/blob/754254c08fe1c3eda18b69da3d336106fe8d72d6/docs/handlers/cancellation.md

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

Main topic

When to use a Skill or MCP

Related resources