0Pricing
MCP Academy · Lección

Gestionar solicitudes de cancelación

Detenga el trabajo correctamente cuando el cliente lo cancele.

Gestionar solicitudes de cancelación es una lección gratuita de MCP Academy en CoddyKit. Esta es la lección 2 de 4. Puedes leer la lección completa abajo gratuitamente — luego la practicas en el navegador con un editor de código integrado y un tutor de IA 24/7. Forma parte de la ruta de aprendizaje de MCP Academy, y tu progreso se sincroniza en la web y la app de CoddyKit. El curso de MCP Academy incluye 4 lecciones en total.

Partes de esta lección aún no han sido traducidas y se muestran en inglés.

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!

Preguntas frecuentes

¿La lección «Gestionar solicitudes de cancelación» es gratis?

Sí — el texto completo de «Gestionar solicitudes de cancelación» es gratis para leer aquí en la web. Para practicarla de forma interactiva (editor de código integrado y tutor de IA 24/7) y desbloquear el resto del curso de MCP Academy, actualiza a CoddyKit PRO. El curso de MCP Academy incluye 4 lecciones en total.

¿Qué aprenderé en «Gestionar solicitudes de cancelación»?

Detenga el trabajo correctamente cuando el cliente lo cancele. Practicas MCP Academy con código real que ejecutas directamente en el navegador, y un tutor de IA 24/7 responde tus preguntas mientras trabajas en la lección.

¿Necesito experiencia previa para empezar MCP Academy?

No se requiere experiencia previa. MCP Academy en CoddyKit está estructurado para principiantes hasta estudiantes avanzados, así que puedes empezar aquí o desde el inicio y avanzar a tu ritmo. Esta es la lección 2 de 4.

¿Cuánto tiempo toma la lección «Gestionar solicitudes de cancelación»?

La mayoría de las lecciones de CoddyKit toman alrededor de 5–10 minutos. Cada una es compacta e interactiva, así que avanzas constantemente y retomas exactamente por donde dejaste en la web y la app.

¿Puedo escribir y ejecutar código en esta lección de MCP Academy?

Sí. Cada lección de MCP Academy incluye un editor de código integrado, así que escribes y ejecutas código real directamente en tu navegador y obtienes retroalimentación instantánea de IA — sin configuración local necesaria.

Todas las lecciones de este curso

  1. Enviar progreso para tareas largas
  2. Gestionar solicitudes de cancelación
  3. Registro estructurado para el cliente
  4. Establecer niveles de registro en tiempo de ejecución
← Volver a MCP Academy