Skip to main content

Module 10: Cancellation

Cancel an in-progress prompt from the client side.

What You’ll Learn

  • Sending CancelNotification to interrupt a running prompt
  • Running prompts in background threads
  • How cancellation affects StopReason

The Code

How It Works

client.cancel() sends a one-way notification (not a request) to the agent. The agent’s cancelHandler receives it and sets a flag. The prompt handler checks this flag between steps and stops early when cancelled. On the agent side:
Cancellation is cooperative. The agent must check for it β€” the SDK does not forcefully interrupt handler execution.

Source Code

View on GitHub

Running the Example

Next Module

Module 11: Error Handling β€” handle protocol errors from agents.