⚠ This page is served via a proxy. Original site: https://github.com
This service does not collect credentials or authentication data.
Skip to content

Conversation

@mkmeral
Copy link
Contributor

@mkmeral mkmeral commented Jan 28, 2026

Description

This PR adds a @hook decorator that transforms Python functions into HookProvider implementations with automatic event type detection from type hints.

Motivation

Defining hooks currently requires implementing the HookProvider protocol with a class, which is verbose for simple use cases:

# Current approach - verbose
class LoggingHooks(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=[LoggingHooks()])

The @hook decorator provides a simpler function-based approach that reduces boilerplate while maintaining full compatibility with the existing hooks system.

Resolves: #1483

Public API Changes

New @hook decorator exported from strands and strands.hooks:

# After - concise
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])

The decorator supports multiple usage patterns:

# Type hint detection
@hook
def my_hook(event: BeforeToolCallEvent) -> None: ...

# Explicit event type
@hook(event=BeforeToolCallEvent)
def my_hook(event) -> None: ...

# Multiple events via parameter
@hook(events=[BeforeToolCallEvent, AfterToolCallEvent])
def my_hook(event) -> None: ...

# Multiple events via Union type
@hook
def my_hook(event: BeforeToolCallEvent | AfterToolCallEvent) -> None: ...

# Async hooks
@hook
async def my_hook(event: BeforeToolCallEvent) -> None: ...

# Class methods
class MyHooks:
    @hook
    def my_hook(self, event: BeforeToolCallEvent) -> None: ...

Agent injection is available for hooks handling HookEvent subclasses:

@hook
def my_hook(event: BeforeToolCallEvent, agent: Agent) -> None:
    print(f"Agent {agent.name} calling tool")

Related Issues

Fixes #1483

Documentation PR

No documentation changes required.

Type of Change

New feature

Testing

  • Added comprehensive unit tests (53 test cases)
  • Tests cover: basic usage, explicit events, multi-events, union types, async, class methods, agent injection, error handling
  • I ran hatch run prepare

Checklist

  • I have read the CONTRIBUTING document
  • I have added any necessary tests that prove my fix is effective or my feature works
  • I have updated the documentation accordingly
  • I have added an appropriate example to the documentation to outline the feature, or no new docs are needed
  • My changes generate no new warnings
  • Any dependent changes have been merged and published

By submitting this pull request, I confirm that you can use, modify, copy, and redistribute this contribution, under the terms of your choice.

strands-agent and others added 7 commits January 28, 2026 19:46
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
- 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.
- Fix mypy type errors by importing HookEvent and properly casting events
- Add __get__ descriptor method to support class methods like @tool
- Fix agent injection to validate event types at decoration time
- Reject agent injection for multiagent events (BaseHookEvent without .agent)
- Skip 'self' and 'cls' params when detecting event type for class methods
- Remove version check for types.UnionType (SDK requires Python 3.10+)
- Add comprehensive tests for new functionality

Issues fixed:
1. Mypy type errors accessing event.agent on BaseHookEvent
2. Missing descriptor protocol for class method support
3. Agent injection failing at runtime for multiagent events
4. Merge conflicts with main branch (ModelRetryStrategy, multiagent events)
@codecov
Copy link

codecov bot commented Jan 28, 2026

Codecov Report

❌ Patch coverage is 96.69421% with 4 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
src/strands/hooks/decorator.py 96.63% 2 Missing and 2 partials ⚠️

📢 Thoughts on this report? Let us know!

Agent injection was unnecessary complexity - users can simply access
event.agent directly when needed, which is consistent with how
class-based HookProviders work.

Changes:
- Remove agent parameter detection and injection logic
- Remove has_agent_param from HookMetadata
- Simplify DecoratedFunctionHook (532 -> 327 lines)
- Update tests to remove agent injection tests (53 -> 35 tests)
- Add PR_DESCRIPTION.md
@github-actions github-actions bot added size/xl and removed size/xl labels Jan 28, 2026
@github-actions github-actions bot added size/xl and removed size/xl labels Jan 28, 2026
@github-actions github-actions bot added size/l and removed size/xl labels Jan 28, 2026
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

2 participants