Обработка запросов на отмену
Корректно прекращайте работу при отмене со стороны клиента.
«Обработка запросов на отмену» — бесплатный урок MCP Academy на CoddyKit. Это урок 2 из 4. Ты можешь прочитать весь урок бесплатно ниже — а потом практиковать его прямо в браузере с встроенным редактором кода и ИИ-репетитором 24/7. Это часть пути обучения 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 pointLet 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 hereClean 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 thisNo 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!
Часто задаваемые вопросы
Урок «Обработка запросов на отмену» бесплатный?
Да — полный текст урока «Обработка запросов на отмену» бесплатно доступен здесь в веб-версии. Чтобы практиковать его интерактивно (встроенный редактор кода и ИИ-репетитор 24/7) и разблокировать остальной курс MCP Academy, подпишись на CoddyKit PRO. Курс MCP Academy содержит 4 уроков всего.
Чему я научусь в уроке «Обработка запросов на отмену»?
Корректно прекращайте работу при отмене со стороны клиента. Ты практикуешь MCP Academy с помощью реального кода, который запускаешь прямо в браузере, и ИИ-репетитор 24/7 отвечает на твои вопросы во время урока.
Нужен ли мне опыт, чтобы начать MCP Academy?
Предыдущий опыт не требуется. MCP Academy на CoddyKit структурирован для всех уровней — от новичков до продвинутых, поэтому ты можешь начать отсюда или с самого начала и учиться в своем темпе. Это урок 2 из 4.
Сколько времени занимает урок «Обработка запросов на отмену»?
Большинство уроков CoddyKit занимают около 5–10 минут. Каждый из них компактный и интерактивный, поэтому ты постоянно делаешь прогресс и продолжаешь с того же места в веб-версии и приложении.
Можно ли писать и запускать код в этом уроке MCP Academy?
Да. Каждый урок MCP Academy включает встроенный редактор кода, поэтому ты пишешь и запускаешь реальный код прямо в браузере и получаешь моментальную обратную связь от AI — локальная установка не требуется.
Все уроки этого курса
- Отправка сведений о ходе длительных задач
- Обработка запросов на отмену
- Структурированное журналирование для клиента
- Настройка уровней журналирования во время работы