Skip to main content

Message Hooks

Message hooks let you intercept, inspect, and modify messages as they flow through the agent - perfect for content filtering, PII redaction, validation, and audit logging.

Overview

Message hooks provide 3 execution points:

Hook Registration

Decorator Syntax

Subscribe API

Message Hook Context

Every message hook receives a MessageExecContext with:

Return Value Format

Message hooks that modify content must return a tuple:
Important:
  • Return (modified_content, True) if content was changed
  • Return (original_content, False) if no changes made
  • Returning only content without boolean will raise error
  • Returning None passes message through unchanged

Execution Flow

On User Message Hook

Fires when user message is received - before sending to provider:

On Provider Message Hook

Fires when provider response is received - before adding to context:

On Error Hook

Fires when message processing fails:

Usage Patterns

Pattern 1: PII Redaction

Remove sensitive information from user messages:

Pattern 2: Content Validation

Enforce content policies before processing:

Pattern 3: Response Formatting

Standardize provider response formatting:

Pattern 4: Audit Logging

Log all message traffic for compliance:

Pattern 5: Translation

Translate messages between languages:

Pattern 6: Rate Limiting

Implement message rate limiting:

Message Types

Message hooks handle different message types:

User Messages

Provider Messages

System Messages

Integration with ProviderThread

Message hooks fire before messages enter the ProviderThread:
Example with ProviderThread access:

Best Practices

Performance Considerations

  • Hook overhead: Less than 2ms per message hook
  • Modification impact: Only modified messages incur serialization cost
  • Async support: Message hooks can be async functions
  • Error handling: Errors in hooks propagate and cancel message processing

Error Handling

Errors in message hooks stop message processing:

What’s Next?

Scaffold Hooks

Scaffold state change hooks

Tool Hooks

Tool execution lifecycle hooks

Subscribe API

Dynamic hook registration

Context Hooks

Context tree operation hooks