Skip to main content

hooks.middleware

Hooks middleware — dispatches hooks on tool lifecycle events.

HookRegistration Objects

@dataclass
class HookRegistration()

A registered hook binding.

matcher

Regex matched against tool name

timeout

seconds

background

Fire-and-forget (non-blocking)

name

Descriptive name for logging

HooksMiddleware Objects

class HooksMiddleware()

Dispatch lifecycle hooks on tool execution events.

Hooks are matched against tool names using regex patterns. Multiple hooks can register for the same event; they run sequentially (unless background=True).

Parameters

hooks : list[HookRegistration] Pre-configured hook registrations.

register

def register(hook: HookRegistration) -> None

Add a hook registration.

dispatch_pre_tool

async def dispatch_pre_tool(
tool_name: str,
tool_args: dict[str, Any],
agent_id: str | None = None,
user_id: str | None = None,
metadata: dict[str, Any] | None = None
) -> tuple[bool, dict[str, Any], str | None]

Dispatch PRE_TOOL_USE hooks.

Returns

tuple[bool, dict, str | None] (allowed, possibly_modified_args, denial_reason)

dispatch_post_tool

async def dispatch_post_tool(tool_name: str,
tool_args: dict[str, Any],
tool_result: str,
agent_id: str | None = None,
user_id: str | None = None,
metadata: dict[str, Any] | None = None) -> str

Dispatch POST_TOOL_USE hooks.

Returns

str Possibly modified tool result.

dispatch_post_tool_failure

async def dispatch_post_tool_failure(
tool_name: str,
tool_args: dict[str, Any],
error: Exception,
agent_id: str | None = None,
user_id: str | None = None,
metadata: dict[str, Any] | None = None) -> None

Dispatch POST_TOOL_USE_FAILURE hooks (all fire-and-forget).