Hooks Module
The hooks module provides a powerful hook system for intercepting and modifying agent behavior at various lifecycle points. Unlike callbacks (which are for UI events), hooks can intercept, modify, or block tool execution.Installation
Features
- Event-based hook system - BeforeTool, AfterTool, BeforeAgent, etc.
- Shell command hooks - External integrations via shell commands
- Python function hooks - In-process customization
- Matcher patterns - Selective hook execution
- Decision outcomes - allow, deny, block, ask
Quick Start (Simplified API)
The simplest way to use hooks:Return Values
| Return | Meaning |
|---|---|
None / no return | Allow |
True | Allow |
False | Deny |
"reason" | Deny with message |
HookResult(...) | Full control (advanced) |
Classes
HookEvent
Enumeration of available hook events.HookDecision
Possible decisions a hook can return.| Decision | Description |
|---|---|
allow | Allow the operation to proceed |
deny | Deny the operation with a reason |
block | Block the operation silently |
ask | Prompt for user confirmation |
HookResult
Result returned by a hook function.Attributes
| Attribute | Type | Description |
|---|---|---|
decision | str | The decision (allow/deny/block/ask) |
reason | str | Reason for the decision |
modified_input | dict | Modified input to pass to the operation |
metadata | dict | Additional metadata |
HookRegistry
Registry for managing hooks.Methods
| Method | Description |
|---|---|
on(event) | Decorator to register a function hook |
register_command_hook(event, command, matcher) | Register a shell command hook |
register_function_hook(event, func, matcher) | Register a function hook |
get_hooks(event) | Get all hooks for an event |
clear() | Clear all registered hooks |
HookRunner
Executes hooks for events.Event Input Types
BeforeToolInput
AfterToolInput
BeforeAgentInput / AfterAgentInput
Usage Examples
Basic Hook Registration
Logging Hook
Input Sanitization Hook
Shell Command Hook
Matcher Patterns
Best Practices
- Keep hooks lightweight - Hooks run synchronously, avoid heavy operations
- Use matchers - Only run hooks for relevant tools
- Return early - Return
allowquickly for non-matching cases - Log decisions - Log why hooks deny operations for debugging
- Handle errors - Wrap hook logic in try/except to avoid breaking agents
Related
- Agent - Using hooks with agents
- Tools - Tool system
- Guardrails - Output validation

