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
FieldsModifier and TypeFieldDescriptionstatic final CancellationTokenA no-op cancellation token that is never cancelled. -
Method Summary
Modifier and TypeMethodDescriptionbooleanChecks if cancellation has been requested.voidRegisters a callback to be invoked when cancellation is requested.default voidThrows ToolCancelledException if cancelled.
-
Field Details
-
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
DefaultCancellationTokenif you need actual cancellation support.
-
-
Method Details
-
isCancelled
boolean isCancelled()Checks if cancellation has been requested.- Returns:
- true if cancelled
-
throwIfCancelled
Throws ToolCancelledException if cancelled.- Throws:
ToolCancelledException- if cancellation was requested
-
onCancel
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
-