Intercept and control agent behavior with hooks - Claude Code Docs
Documentation Index Fetch the complete documentation index at: /docs/llms.txt Use this file to discover all available pages before exploring further. Skip to main content Assistant Responses are generated using AI and may contain mistakes. Hooks are callback functions that run your code in response to agent events, like a tool being called, a session starting, or execution stopping. With hooks, you can: Block dangerous operations before they execute, like destructive shell commands or unauthorized file access Log and audit tool calls for compliance, debugging, or analytics Transform inputs and outputs to sanitize data, inject credentials, or redirect file paths Require human approval for sensitive actions like database writes or API calls Track session lifecycle to manage state, clean up resources, or send notifications How hooks work 1 An event fires Something happens during agent execution and the SDK fires an event: a tool is about to be called ( PreToolUse ), a tool returned a result ( PostToolUse ), a subagent started or stopped, the agent is idle, or execution finished.
See the full list of events . 2 The SDK collects registered hooks The SDK checks for hooks registered for that event type. This includes callback hooks you pass in options.hooks and shell command hooks from settings files when the corresponding settingSources or setting_sources entry is enabled, which it is for default query() options. 3 Matchers filter which hooks run If a hook has a matcher pattern (like "Write|Edit" ), the SDK tests it against the event’s target (for example, the tool name).
Hooks without a matcher run for every event of that type. 4 Callback functions execute Each matching hook’s callback function receives input about what’s happening: the tool name, its arguments, the session ID, and other event-specific details. 5 Your callback returns a decision After performing any operations (logging, API calls, validation), your callback returns an output object that tells the agent what to do: allow the operation, block it, modify the input, or inject context into the conversation.
This example registers a PreToolUse hook (step 1) with a "Write|Edit" matcher (step 3) so the callback fires for the Write and Edit tools. When triggered, the callback receives the tool’s input (step 4), checks if the file path targets a .env file, and returns permissionDecision: "deny" to block the operation (step 5): import asyncio from claude_agent_sdk import ( AssistantMessage, ClaudeSDKClient, ClaudeAgentOptions, HookMatcher, ResultMessage, ) # Define a hook callback that receives tool call details async def protect_env_files ( input_data , tool_use_id , context ): # Extract the file path from the tool's input arguments file_path = input_data[ "tool_input" ].get( "file_path" , "" ) file_name = file_path.split( "/" )[ - 1 ] # Block the operation if targeting a .env file if file_name.lower() == ".env" : return { "hookSpecificOutput" : { "hookEventName" : input_data[ "hook_event_name" ], "permissionDecision" : "deny" , "permissionDecisionReason" : "Cannot modify .env files" , } } # Empty object: no decision, normal permissions apply return {} async def main (): options = ClaudeAgentOptions( hooks = { # Register the hook for PreToolUse events # The matcher filters to only Write and Edit tool calls "PreToolUse" : [HookMatcher( matcher = "Write|Edit" , hooks = [protect_env_files])] } ) async with ClaudeSDKClient( options = options) as client: await client.query( "Create a .env file with the standard local development database configuration" ) async for message in client.receive_response(): # Filter for assistant and result messages if isinstance (message, (AssistantMessage, ResultMessage)): print (message) asyncio.run(main()) import { query , HookCallback , PreToolUseHookInput } from "@anthropic-ai/claude-agent-sdk" ; // Define a hook callback with the HookCallback type const protectEnvFiles : HookCallback = async ( input , toolUseID , { signal }) => { // Cast input to the specific hook type for type safety const preInput = input as PreToolUseHookInput ; // Cast tool_input to access its properties (typed as unknown in the SDK) const toolInput = preInput . tool_input as Record < string , unknown >; const filePath = toolInput ?. file_path as string ; const fileName = filePath ?. split ( "/" ). pop (); // Block the operation if targeting a .env file if ( fileName ?. toLowerCase () === ".env" ) { return { hookSpecificOutput: { hookEventName: preInput . hook_event_name , permissionDecision: "deny" , permissionDecisionReason: "Cannot modify .env files" } }; } // Empty object: no decision, normal permissions apply return {}; }; for await ( const message of query ({ prompt: "Create a .env file with the standard local development database configuration" , options: { hooks: { // Register the hook for PreToolUse events // The matcher filters to only Write and Edit tool calls PreToolUse: [{ matcher: "Write|Edit" , hooks: [ protectEnvFiles ] }] } } })) { // Filter for assistant and result messages if ( message . type === "assistant" || message . type === "result" ) { console . log ( message ); } } The hook denies a Write or Edit call whose file_path ends in /.env , in any letter case.
On Windows, file_path uses backslashes, such as C:\project\.env , and this hook doesn’t block a Write or Edit call to C:\project\.env . The Write|Edit matcher limits this hook to the Write and Edit tools. If Claude writes .env with a Bash command, the hook doesn’t run. To block Bash writes to a file where the sandbox runs , see the sandbox configuration for Python or TypeScript . Available hooks The SDK provides hooks for different stages of agent execution.
Some hooks are available in both SDKs, while others are TypeScript-only. Hook Event Python SDK TypeScript SDK What triggers it Example use case PreToolUse Yes Yes Tool call request (can block or modify) Block dangerous shell commands PostToolUse Yes Yes Tool execution result Log file changes to an audit trail PostToolUseFailure Yes Yes Tool execution failure Handle or log tool errors PostToolBatch No Yes A full batch of tool calls resolves, once per batch before the next model call Inject conventions once for the whole batch UserPromptSubmit Yes Yes A prompt is submitted, including a turn Claude Code starts on its own Inject additional context into prompts UserPromptExpansion No Yes A user-typed command, or an MCP prompt, expands into a prompt before it reaches Claude.
Doesn’t fire when Claude invokes a skill itself Block a command from direct invocation or add context when a skill is typed MessageDisplay No Yes An assistant message with text completes, once per message with the full message text Redact or reformat the displayed text without changing the transcript Stop Yes Yes Agent execution stop Save session state before exit StopFailure No Yes The turn ends with an API error instead of a normal stop Log failures or send alerts SubagentStart Yes Yes Subagent initialization Track parallel task spawning SubagentStop Yes Yes Subagent completion Aggregate results from parallel tasks PreCompact Yes Yes Conversation compaction request Archive full transcript before summarizing PostCompact No Yes Conversation compaction completes Log the generated summary PreModelSwitch No Yes A requested model switch, before it happens (can block) Block switching to a specific model PostModelSwitch No Yes The session’s model changes, including an automatic fallback Give Claude model-specific guidance for the new model PermissionRequest Yes Yes A tool call needs a permission decision Custom permission handling PermissionDenied No Yes Auto mode denies a tool call, including denials without a classifier verdict Log denials, or tell the model it may retry; Claude Code ignores retry: true for no-verdict denials.
See PermissionDenied SessionStart No Yes Session initialization Initialize logging and telemetry SessionEnd No Yes Session termination Clean up temporary resources Not
The rest of this page is on the live site.