Skip to main content

Tool Hooks

Tool hooks let you observe and modify tool execution at every stage - from initial detection through final results.

Overview

Tool hooks provide 6 execution points:

Hook Registration

Decorator Syntax

Subscribe API

Tool Hook Context

Every tool hook receives a ToolExecContext with:

Execution Flow

Pre-Execution Hook

Fires before tool loop starts - useful for setup:

Post-Execution Hook

Fires after tool loop completes - useful for cleanup:

Pre-Call Hook

Fires before each individual tool call:

Post-Call Hook

Fires after each individual tool call:

Error Hook

Fires when tool execution fails:

Intercept Hook

Dual-phase hook for validation and output modification:

Usage Patterns

Pattern 1: Tool Usage Tracking

Track which tools are used and how often:

Pattern 2: Rate Limiting

Prevent too many tool calls in a time window:

Pattern 3: Parameter Injection

Automatically add context to tool calls:

Pattern 4: Result Caching

Cache tool results to avoid redundant calls:

Pattern 5: Audit Logging

Complete audit trail of tool usage:

Pattern 6: Sensitive Data Redaction

Automatically redact sensitive information from tool results:

Hook Execution Order

Multiple hooks execute in registration order:
Lifecycle sequence:
  1. pre_exec hook fires (once per execution)
  2. For each tool call:
    • pre_call hooks fire
    • Tool executes
    • post_call hooks fire (or on_error if failed)
  3. post_exec hook fires (once per execution)

Async Hook Support

All tool hooks support both sync and async functions:

Error Propagation

Errors in hooks propagate to error hooks:

Best Practices

Performance Considerations

  • Hook overhead: Less than 5ms per hook on average
  • Async hooks: Run concurrently when possible
  • Error hooks: Fire even if other hooks fail
  • Context creation: Reuses agent reference (no copying)

Integration with Scaffolds

Tool hooks work seamlessly with scaffold operations:

What’s Next?

Context Hooks

Context tree operation hooks

Streaming Hooks

Real-time content processing

Subscribe API

Dynamic hook registration

Modifying Tool Outputs

Comprehensive guide to output modification