0Pricing
MCP Academy · 课时

处理取消请求

客户端取消时干净地停止工作。

处理取消请求 是 CoddyKit 上的免费 MCP Academy 课时。 这是第 2 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 MCP Academy 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 MCP Academy 课程共包含 4 节课。

本课时的部分内容尚未翻译,以英文显示。

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!

常见问题解答

「处理取消请求」课时是免费的吗?

是的 — 「处理取消请求」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 MCP Academy 课程的其余内容,请升级到 CoddyKit PRO。 MCP Academy 课程共包含 4 节课。

「处理取消请求」这节课中我会学到什么?

客户端取消时干净地停止工作。 你通过在浏览器中直接运行的动手代码来练习 MCP Academy,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 MCP Academy 需要有经验吗?

无需任何先前经验。CoddyKit 上的 MCP Academy 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 2 节课,共 4 节。

「处理取消请求」课时需要多长时间?

大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。

我能在这节 MCP Academy 课中编写并运行代码吗?

能。每节 MCP Academy 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

此课程中的所有课时

  1. 为长任务发送进度
  2. 处理取消请求
  3. 向客户端发送结构化日志
  4. 在运行时设置日志级别
← 返回 MCP Academy