Overview
Tool hooks provide a powerful mechanism to intercept and react to tool invocations throughout their lifecycle. This allows you to implement cross-cutting concerns like logging, monitoring, validation, and error handling without modifying tool implementations.Available Hooks
The xpander.ai SDK provides three decorators for tool lifecycle hooks:@on_tool_before: Execute before tool invocation@on_tool_after: Execute after successful tool invocation@on_tool_error: Execute when tool invocation fails
Quick Start
Hook Parameters
All hooks receive the following parameters:| Parameter | Type | Description |
|---|---|---|
tool | Tool | The Tool object being invoked |
payload | Any | The payload sent to the tool |
payload_extension | Optional[Dict[str, Any]] | Additional payload data |
tool_call_id | Optional[str] | Unique ID of the tool call |
agent_version | Optional[str] | Version of the agent making the call |
- After hooks also receive:
result- The result returned by the tool - Error hooks also receive:
error- The exception that occurred
Async Support
Both sync and async hooks are supported:Common Use Cases
Request Validation
Performance Monitoring
Error Alerting
Audit Logging
Hook Execution Flow
Multiple Hooks
You can register multiple hooks of the same type - they execute in registration order:Best Practices
Keep hooks lightweight
Keep hooks lightweight
Hooks should be fast to avoid delaying tool execution. Move expensive operations to background tasks or use async hooks for I/O operations.
Use async for I/O operations
Use async for I/O operations
If your hook does I/O (database, API calls), make it async to avoid blocking tool execution.
Don't modify tool behavior
Don't modify tool behavior
Hooks should observe, not alter tool execution. They’re for cross-cutting concerns like logging and monitoring.
Handle errors gracefully
Handle errors gracefully
Hook failures shouldn’t break tool invocations. Exceptions in hooks are logged but don’t prevent tool execution.
Be careful with sensitive data
Be careful with sensitive data
When logging payloads, ensure you’re not exposing sensitive information like API keys or personal data.
Use structured logging
Use structured logging
Include
tool_call_id in your logs for traceability across your system.Integration with @on_task
Tool hooks work seamlessly with@on_task handlers:
Troubleshooting
Hooks not executing
Hooks not executing
Ensure hooks are registered before any tool invocations. Register hooks at module level, not inside functions.
Performance issues
Performance issues
If hooks slow down execution, consider:
- Making hooks async if they do I/O
- Moving expensive operations to background tasks
- Using sampling for high-frequency tools
Debugging hook execution
Debugging hook execution
Enable debug logging to see hook execution:

