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 aToolExecContext 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:pre_exechook fires (once per execution)- For each tool call:
pre_callhooks fire- Tool executes
post_callhooks fire (oron_errorif failed)
post_exechook 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
Use pre_call for validation, post_call for processing
Use pre_call for validation, post_call for processing
Keep hooks fast and focused
Keep hooks fast and focused
Use on_error for graceful degradation
Use on_error for graceful degradation
Use intercept for dual-phase operations
Use intercept for dual-phase operations
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

