Overview
Tool hooks are executed at two critical points:- Before Tool Call: Modify inputs, validate parameters, or block execution
- After Tool Call: Transform results, sanitize outputs, or log execution details
Hook Types
Before Tool Call Hooks
Executed before every tool execution, these hooks can:- Inspect and modify tool inputs
- Block tool execution based on conditions
- Implement approval gates for dangerous operations
- Validate parameters
- Log tool invocations
After Tool Call Hooks
Executed after every tool execution, these hooks can:- Modify or sanitize tool results
- Add metadata or formatting
- Log execution results
- Implement result validation
- Transform output formats
Tool Hook Context
TheToolCallHookContext object provides comprehensive access to tool execution state:
Modifying Tool Inputs
Important: Always modify tool inputs in-place:Registration Methods
1. Global Hook Registration
Register hooks that apply to all tool calls across all crews:2. Decorator-Based Registration
Use decorators for cleaner syntax:3. Crew-Scoped Hooks
Register hooks for a specific crew instance:Common Use Cases
1. Safety Guardrails
2. Human Approval Gate
3. Input Validation and Sanitization
4. Result Sanitization
5. Tool Usage Analytics
6. Rate Limiting
7. Caching Tool Results
8. Debug Logging
Hook Management
Unregistering Hooks
Clearing Hooks
Listing Registered Hooks
Advanced Patterns
Conditional Hook Execution
Context-Aware Input Modification
Tool Chain Monitoring
Best Practices
- Keep Hooks Focused: Each hook should have a single responsibility
- Avoid Heavy Computation: Hooks execute on every tool call
- Handle Errors Gracefully: Use try-except to prevent hook failures
- Use Type Hints: Leverage
ToolCallHookContextfor better IDE support - Document Blocking Conditions: Make it clear when/why tools are blocked
- Test Hooks Independently: Unit test hooks before using in production
- Clear Hooks in Tests: Use
clear_all_tool_call_hooks()between test runs - Modify In-Place: Always modify
context.tool_inputin-place, never replace - Log Important Decisions: Especially when blocking tool execution
- Consider Performance: Cache expensive validations when possible
Error Handling
Type Safety
Integration with Existing Tools
Wrapping Existing Validation
Logging to External Systems
Troubleshooting
Hook Not Executing
- Verify hook is registered before crew execution
- Check if previous hook returned
False(blocks execution and subsequent hooks) - Ensure hook signature matches expected type
Input Modifications Not Working
- Use in-place modifications:
context.tool_input['key'] = value - Don’t replace the dict:
context.tool_input = {}
Result Modifications Not Working
- Return the modified string from after hooks
- Returning
Nonekeeps the original result - Ensure the tool actually returned a result
Tool Blocked Unexpectedly
- Check all before hooks for blocking conditions
- Verify hook execution order
- Add debug logging to identify which hook is blocking
