Skip to content

Conversation

@strands-agent
Copy link
Contributor

Description

This PR adds a @hook decorator that transforms Python functions into HookProvider implementations with automatic event type detection from type hints - mirroring the ergonomics of the existing @tool decorator.

Features

  • Simple decorator syntax: @hook extracts event type from type hints
  • Explicit event type: @hook(event=EventType) for functions without type hints
  • Multi-event support: @hook(events=[...]) or Union types (A | B)
  • Async support: Works with both sync and async hook functions
  • Metadata preservation: Function name, docstring preserved via functools.wraps
  • Direct invocation: Decorated hooks can be called directly for testing

Before (Class-based):

from strands.hooks import HookProvider, HookRegistry, BeforeToolCallEvent

class MyHooks(HookProvider):
    def register_hooks(self, registry: HookRegistry) -> None:
        registry.add_callback(BeforeToolCallEvent, self.on_tool_call)
    
    def on_tool_call(self, event: BeforeToolCallEvent) -> None:
        print(f"Tool: {event.tool_use}")

agent = Agent(hooks=[MyHooks()])

After (Decorator-based):

from strands import Agent, hook
from strands.hooks import BeforeToolCallEvent

@hook
def log_tool_calls(event: BeforeToolCallEvent) -> None:
    """Log all tool calls before execution."""
    print(f"Tool: {event.tool_use}")

agent = Agent(hooks=[log_tool_calls])

New Exports

# From strands
from strands import hook

# From strands.hooks
from strands.hooks import hook, DecoratedFunctionHook, FunctionHookMetadata, HookMetadata

Related Issues

Fixes #1483

Documentation PR

No documentation changes required - follows existing patterns established by @tool.

Type of Change

New feature (non-breaking addition)

Testing

  • Added comprehensive unit tests (20 test cases)
  • Tests cover: basic usage, explicit events, multi-events, union types, async, errors, mixed usage with class-based hooks
  • I ran hatch run prepare

Checklist

  • I have read the CONTRIBUTING document
  • I have added tests that prove my fix is effective or my feature works
  • I have updated the documentation accordingly (exports in __init__.py)
  • My changes generate no new warnings
  • Any dependent changes have been merged and published

This adds a @hook decorator that transforms Python functions into
HookProvider implementations with automatic event type detection
from type hints - mirroring the ergonomics of the existing @tool
decorator.

Features:
- Simple decorator syntax: @hook
- Automatic event type extraction from type hints
- Explicit event type specification: @hook(event=EventType)
- Multi-event support: @hook(events=[...]) or Union types
- Support for both sync and async hook functions
- Preserves function metadata (name, docstring)
- Direct invocation for testing

New exports:
- from strands import hook
- from strands.hooks import hook, DecoratedFunctionHook,
  FunctionHookMetadata, HookMetadata

Example:
    from strands import Agent, hook
    from strands.hooks import BeforeToolCallEvent

    @hook
    def log_tool_calls(event: BeforeToolCallEvent) -> None:
        print(f'Tool: {event.tool_use}')

    agent = Agent(hooks=[log_tool_calls])

Fixes strands-agents#1483
@codecov
Copy link

codecov bot commented Jan 14, 2026

Codecov Report

❌ Patch coverage is 87.75510% with 18 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
src/strands/hooks/decorator.py 87.58% 11 Missing and 7 partials ⚠️

📢 Thoughts on this report? Let us know!

- Add cast() for HookCallback type in register_hooks method
- Add HookCallback import from registry
- Use keyword-only arguments in overload signature 2 to satisfy mypy
This enhancement addresses feedback from @cagataycali - the agent instance
is now automatically injected to @hook decorated functions when they have
an 'agent' parameter in their signature.

Usage:
  @hook
  def my_hook(event: BeforeToolCallEvent, agent: Agent) -> None:
      # agent is automatically injected from event.agent
      print(f'Agent {agent.name} calling tool')

Features:
- Detect 'agent' parameter in function signature
- Automatically extract agent from event.agent when callback is invoked
- Works with both sync and async hooks
- Backward compatible - hooks without agent param work unchanged
- Direct invocation supports explicit agent override for testing

Tests added:
- test_agent_param_detection
- test_agent_injection_in_repr
- test_hook_without_agent_param_not_injected
- test_hook_with_agent_param_receives_agent
- test_direct_call_with_explicit_agent
- test_agent_injection_with_registry
- test_async_hook_with_agent_injection
- test_hook_metadata_includes_agent_param
- test_mixed_hooks_with_and_without_agent
Add 13 new test cases to improve code coverage from 89% to 98%:

- TestCoverageGaps: Optional type hint, async/sync agent injection via registry,
  direct call without agent param, hook() empty parentheses, Union types
- TestAdditionalErrorCases: Invalid annotation types, invalid explicit event list
- TestEdgeCases: get_type_hints exception fallback, empty type hints fallback

Coverage improvements:
- Lines 139-141: get_type_hints exception handling
- Line 157: Annotation fallback when type hints unavailable
- Lines 203-205: NoneType skipping in Optional[X]
- Line 216: Invalid annotation error path
- Lines 313-320: Async/sync callback with agent injection

Addresses codecov patch coverage failure in PR strands-agents#1484.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Feature] @hook decorator for simplified hook definitions

1 participant