Interface CancellationToken

All Known Implementing Classes:
DefaultCancellationToken

public interface CancellationToken
Token for cooperative cancellation of tool execution. Tools should periodically check isCancelled() and stop gracefully.

This interface follows the cooperative cancellation pattern, where the tool is responsible for checking the cancellation status and responding appropriately. This allows tools to clean up resources and complete partial work before stopping.

Example usage:


 public CompletableFuture<String> callAsync(String args, ToolContext ctx, CancellationToken token) {
     return CompletableFuture.supplyAsync(() -> {
         for (int i = 0; i < 100; i++) {
             token.throwIfCancelled(); // Check for cancellation
             // Do work...
         }
         return "result";
     });
 }
 
Since:
1.0.0
Author:
disaster
See Also:
  • Field Summary

    Fields
    Modifier and Type
    Field
    Description
    static final CancellationToken
    A no-op cancellation token that is never cancelled.
  • Method Summary

    Modifier and Type
    Method
    Description
    boolean
    Checks if cancellation has been requested.
    void
    onCancel(Runnable callback)
    Registers a callback to be invoked when cancellation is requested.
    default void
    Throws ToolCancelledException if cancelled.
  • Field Details

    • NONE

      static final CancellationToken NONE
      A no-op cancellation token that is never cancelled.

      This instance is used as a default when cancellation support is not needed. Since this token can never be cancelled, onCancel(Runnable) is a no-op and callbacks registered with it will never be invoked.

      Use DefaultCancellationToken if you need actual cancellation support.

  • Method Details

    • isCancelled

      boolean isCancelled()
      Checks if cancellation has been requested.
      Returns:
      true if cancelled
    • throwIfCancelled

      default void throwIfCancelled() throws ToolCancelledException
      Throws ToolCancelledException if cancelled.
      Throws:
      ToolCancelledException - if cancellation was requested
    • onCancel

      void onCancel(Runnable callback)
      Registers a callback to be invoked when cancellation is requested.

      If cancellation has already been requested, the callback may be invoked immediately (implementation-dependent).

      Parameters:
      callback - the callback to run on cancellation