Skip to main content

Overview

Hooks allow you to intercept tool calls before and after execution. This example demonstrates using a BeforeToolUse hook to block dangerous bash commands - a practical security pattern for agentic applications. Key concepts:
  • CallableHook: Wraps a closure as a hook
  • HookContext: Provides access to tool call and agent state
  • HookTriggers: Defines when the hook fires (e.g., beforeToolUse())
  • UseHook: Registers a hook capability with explicit trigger/priority
  • AgentEventConsoleObserver: Provides visibility into agent execution stages

Example

How It Works

  1. Hook Registration: UseHook registers a CallableHook with HookTriggers::beforeToolUse()
  2. Context Access: HookContext provides toolCall() and state() accessors
  3. Priority: Higher priority (100) ensures this security check runs before other hooks
  4. Blocking: $ctx->withToolExecutionBlocked($reason) blocks the tool call with a reason
  5. Allowing: Returning $ctx unchanged allows execution to proceed

Other Hook Types