0Pricing
MCP Academy · Lesson

Handle Cancellation Requests

Stop work cleanly when the client cancels.

Handle Cancellation Requests is a free MCP Academy lesson on CoddyKit — lesson 2 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the MCP Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

Why Cancellation Exists

A user may close a chat or change their mind while a long tool runs. MCP lets the client send a cancellation so wasted work stops.

The cancelled Notification

The client signals this with a notifications/cancelled message naming the requestId it wants to stop. It is fire-and-forget, with no reply.

{"method": "notifications/cancelled",
 "params": {"requestId": 7, "reason": "user aborted"}}

It Is Just a Request

Only an in-flight request can be cancelled, matched by its requestId. Notifications, which have no id, can never be cancelled.

Cancellation Is Best-Effort

A cancel is a polite request, not a hard kill. Your work may already be finishing, so treat it as a best-effort hint to wind down.

asyncio Does the Wiring

In the Python SDK, a cancel arrives as an asyncio.CancelledError raised inside your awaiting tool. You usually do not poll a flag yourself.

import asyncio
# CancelledError is raised at the next await point

Let It Propagate

The simplest correct behavior is to let CancelledError bubble up. The framework then stops the task and skips sending a normal result.

@mcp.tool()
async def crunch(ctx: Context) -> str:
    for item in items:
        await heavy(item)  # cancel lands here

Clean Up on Cancel

If your tool holds a file or lock, wrap it so a cancel still releases resources. A try/finally guarantees cleanup runs on the way out.

try:
    await do_work()
finally:
    handle.close()

Do Not Swallow It

Never catch CancelledError and quietly keep going. That defeats the whole point and leaves the client thinking the work was stopped.

# Anti-pattern:
# except asyncio.CancelledError:
#     pass  # do NOT do this

No Response After Cancel

Once a request is cancelled, do not send a result or error for it. The client has moved on and any late response is simply ignored.

Free the Budget

Honoring cancellation quickly frees CPU, network, and model tokens. A server that stops promptly is a good citizen in a busy agent.

Check at Natural Points

For tight CPU loops with no awaits, sprinkle a short await asyncio.sleep(0) so the cancellation has a chance to land between iterations.

for chunk in chunks:
    crunch(chunk)
    await asyncio.sleep(0)

Quick Check

Check how cancellation surfaces in a Python MCP tool.

Recap: Cancellation

You saw the cancelled notification, why cancels are best-effort, and how to let CancelledError propagate while cleaning up. Well done!

Frequently asked questions

Is the “Handle Cancellation Requests” lesson free?

Yes — the full text of “Handle Cancellation Requests” is free to read here on the web, and the MCP Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the MCP Academy course, upgrade to CoddyKit PRO.

What will I learn in “Handle Cancellation Requests”?

Stop work cleanly when the client cancels. You practise MCP Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start MCP Academy?

No prior experience is required. MCP Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 2 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “Handle Cancellation Requests” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this MCP Academy lesson?

Yes. Every MCP Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. Send Progress for Long Tasks
  2. Handle Cancellation Requests
  3. Structured Logging to the Client
  4. Set Log Levels at Runtime
← Back to MCP Academy