Obsługa żądań anulowania
Zatrzymuj pracę w uporządkowany sposób po anulowaniu przez klienta.
Obsługa żądań anulowania to bezpłatna lekcja MCP Academy na CoddyKit. To lekcja 2 z 4. Możesz przeczytać całą lekcję poniżej za darmo — a potem ćwiczyć ją interaktywnie w przeglądarce z wbudowanym edytorem kodu i tutorem AI dostępnym 24/7. To część ścieżki edukacyjnej MCP Academy, a Twój postęp synchronizuje się między webem a aplikacją CoddyKit. Kurs MCP Academy zawiera 4 lekcji w sumie.
Części tej lekcji nie zostały jeszcze przetłumaczone i są wyświetlane po angielsku.
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!
Często zadawane pytania
Czy lekcja „Obsługa żądań anulowania” jest bezpłatna?
Tak — pełny tekst „Obsługa żądań anulowania” jest dostępny za darmo tutaj w sieci. Aby ćwiczyć ją interaktywnie (wbudowany edytor kodu i tutor AI dostępny 24/7) i odblokować resztę kursu MCP Academy, przejdź na CoddyKit PRO. Kurs MCP Academy zawiera 4 lekcji w sumie.
Co nauczysz się w „Obsługa żądań anulowania”?
Zatrzymuj pracę w uporządkowany sposób po anulowaniu przez klienta. Ćwiczysz MCP Academy z praktycznym kodem, który uruchamiasz bezpośrednio w przeglądarce, a tutor AI dostępny 24/7 odpowiada na Twoje pytania podczas pracy nad lekcją.
Czy potrzebuję doświadczenia, aby zacząć MCP Academy?
Nie wymagamy żadnego doświadczenia. MCP Academy w CoddyKit jest strukturyzowany dla początkujących i zaawansowanych użytkowników, więc możesz zacząć tutaj lub od początku i uczyć się w swoim tempie. To lekcja 2 z 4.
Ile czasu zajmuje lekcja „Obsługa żądań anulowania”?
Większość lekcji CoddyKit trwa około 5–10 minut. Każda lekcja to mały, interaktywny krok, dzięki czemu robisz systematyczne postępy i zawsze wracasz dokładnie do tego samego miejsca — na webie i w aplikacji.
Czy mogę pisać i uruchamiać kod w tej lekcji MCP Academy?
Tak. Każda lekcja MCP Academy zawiera wbudowany edytor kodu, więc piszesz i uruchamiasz prawdziwy kod bezpośrednio w przeglądarce i od razu otrzymujesz sprzężenie zwrotne od AI — bez konfiguracji na komputerze.
Wszystkie lekcje w tym kursie
- Wysyłanie postępu długich zadań
- Obsługa żądań anulowania
- Ustrukturyzowane logowanie do klienta
- Ustawianie poziomów logowania w czasie działania