Claude Agent SDK hooks: block, log and rewrite a tool call
Hooks are how your application sees and steers the agent from the inside. They run in your process, which means your own policy code, your own logging, and your own rewrite of a tool's arguments.
This page owns SDK callback hooks. Agent SDK permissions owns allow and deny rules and the modes, the Claude Code hooks guide owns shell command hooks in a settings file, and the SDK overview owns the first agent.
Sources read November 26, 2026. By the Omniscio team. Updated .
How a hook runs
- An event fires. A tool is about to be called, a tool returned a result, a subagent started or stopped, the agent is idle, or execution finished.
- The SDK collects hooks. It checks for callbacks you passed in
options.hooksand shell command hooks from settings files whose setting source is enabled, which is on for defaultquery()options. - Matchers filter. A pattern such as
"Write|Edit"is tested against the event's target, usually the tool name. A hook without a matcher runs for every event of that type. - Callbacks run. Each matching callback receives the tool name, its arguments, the session ID and other event details.
- A decision comes back. Your return value tells the agent to allow, block, modify the input, or inject context.
Register a PreToolUse hook
This callback blocks writes to a .env file. The matcher limits it to the Write and Edit tools, and the deny reason is what the model sees.
import { query, HookCallback, PreToolUseHookInput } from "@anthropic-ai/claude-agent-sdk";
const protectEnvFiles: HookCallback = async (input, toolUseID, { signal }) => {
const preInput = input as PreToolUseHookInput;
const toolInput = preInput.tool_input as Record<string, unknown>;
const fileName = (toolInput?.file_path as string)?.split("/").pop();
if (fileName?.toLowerCase() === ".env") {
return {
hookSpecificOutput: {
hookEventName: preInput.hook_event_name,
permissionDecision: "deny",
permissionDecisionReason: "Cannot modify .env files"
}
};
}
return {};
};for await (const message of query({
prompt: "Create a .env file with the standard local development database configuration",
options: {
hooks: {
PreToolUse: [{ matcher: "Write|Edit", hooks: [protectEnvFiles] }]
}
}
})) { /* ... */ }The examples on this page are TypeScript. The Python form is the same shape: an async def callback receiving (input_data, tool_use_id, context), registered with HookMatcher(matcher="Write|Edit", hooks=[callback]), returning a dict with hookSpecificOutput.
Two limits to know before you rely on it. On Windows file_path uses backslashes, so a check written for / does not block C:\project\.env. And a Write|Edit matcher does not see a Bash command that writes the file, so the hook never runs for that route.
The events you are most likely to use
| Event | When it fires | Both SDKs? |
|---|---|---|
PreToolUse | A tool call is requested; it can block or modify it | Yes |
PostToolUse | A tool returned a result | Yes |
PostToolUseFailure | A tool call failed | Yes |
UserPromptSubmit | A prompt is submitted, including one Claude Code starts on its own | Yes |
Stop | Agent execution stops | Yes |
SubagentStart / SubagentStop | A subagent starts or finishes | Yes |
PreCompact | A compaction is requested | Yes |
PermissionRequest | A tool call needs a permission decision | Yes |
Notification | The agent posts a status message | Yes |
SessionStart / SessionEnd | A session initializes or terminates | TypeScript only |
PostToolBatch | A full batch of tool calls resolves | TypeScript only |
PostCompact | A compaction completes | TypeScript only |
The full list also carries UserPromptExpansion, MessageDisplay, StopFailure, PreModelSwitch, PostModelSwitch, PermissionDenied, Setup, TeammateIdle, TaskCreated, TaskCompleted, Elicitation, ElicitationResult, ConfigChange, InstructionsLoaded, WorktreeCreate, WorktreeRemove, CwdChanged, FileChanged and DirectoryAdded, with each one marked for Python and TypeScript in Anthropic’s event table.
Matchers, inputs and timeouts
A matcher is a pattern tested against the event's filter field: the tool name for tool hooks, the notification type for notifications. Built-in tool names include Bash, Read, Write, Edit, Glob, Grep, WebFetch and Agent; MCP tools use mcp__<server>__<action>. Target specific tools whenever you can, because an empty matcher matches everything.
Every callback receives three arguments: the typed input, which carries session_id, cwd and hook_event_name on every event plus agent_id and agent_type inside a subagent; the tool use ID, which correlates a PreToolUse with its PostToolUse; and in TypeScript a context holding an AbortSignal.
Each callback has a timeout. The default is 600 seconds for most events, 30 seconds for UserPromptSubmit, PreModelSwitch and PostModelSwitch, and 10 seconds for MessageDisplay. Set a different one in seconds on the HookMatcher.
What a callback returns
The return object has two kinds of field. Top-level fields are accepted on every event: systemMessage shows the user a message, and continue decides whether the agent keeps running, though some events discard them or deliver them elsewhere. hookSpecificOutput controls the current operation.
PreToolUse:permissionDecisionof"allow","deny","ask"or"defer", apermissionDecisionReason, andupdatedInputto replace what the tool receives."defer"ends the turn withstop_reason: "tool_deferred"so you can resume the call later.PostToolUse:additionalContextto append to the result, orupdatedToolOutputto replace it before Claude sees it.- No opinion: return
{}, so the normal permission flow applies.
When several PreToolUse hooks disagree, deny beats defer, which beats ask, which beats allow.
Logging is the case for an async output. A hook that only performs a side effect can start it and return at once, so the agent does not wait.
const logToolUse: HookCallback = async (input) => {
sendToLoggingService(input).catch(console.error);
return { async: true, asyncTimeout: 30000 };
};In Python, return {"async_": True, "asyncTimeout": 30000}. The agent continues immediately, so an async output cannot block, modify or inject context.
Rewriting the input
Return updatedInput inside hookSpecificOutput, and pair it with permissionDecision: "allow" to auto-approve the modified call or "ask" to show it to the user. Omit the decision and the modified input still applies through the normal permission flow. Always return a new object rather than mutating tool_input.
When a callback fails or times out
On most events, a callback that throws or returns invalid output lets the action go ahead, and your app receives an SDKInformationalMessage warning tagged hook_callback_failed. A PreToolUse guard that crashes therefore lets the tool call reach the normal permission flow, and a callback that returns nothing counts as failing.
To block instead, set onFailure: "block" in TypeScript or on_failure="block" in Python on the matcher. That needs TypeScript Agent SDK 0.3.317 or later, or Python Agent SDK 0.2.177 or later. With it set, the tool result says failed; blocking because onFailure is "block" and Claude does not see your error text. Some events ignore it: Stop, SubagentStop, TaskCompleted and TeammateIdle go ahead anyway.
A timeout is a different path. Claude Code cancels the callback and discards its output, and the event decides what follows: a PreToolUse timeout blocks the tool call, a PostToolUse timeout keeps the tool result, a UserPromptSubmit timeout blocks the prompt with a message naming the hook, and a Stop timeout counts as no decision.
Three things that look like bugs
- A tool is blocked unexpectedly. Check every
PreToolUsehook for adeny, log thepermissionDecisionReasoneach returns, and look for a matcher that is too broad: an empty matcher matches every tool. - Modified input is not applied.
updatedInputbelongs insidehookSpecificOutput, not at the top level, and it replaces the whole input, so include the fields you did not change. systemMessagedoes not appear. It is a message to the user, not to the model. From Claude Code v2.1.227 it can surface as anSDKInformationalMessage, depending on the event. To give the model context, returnadditionalContextinstead.
Sources
Every line on this page rests on this page of Anthropic's documentation, read on the date beside it.
- Intercept and control agent behavior with hooks, for the five steps, the event table, matchers, callback inputs and outputs, async output, failure and timeout behaviour, and the troubleshooting list. Read November 26, 2026.
No hook was run for this page. Every option name, default, message and version floor is transcribed from that page.
Common questions
What can a Claude Agent SDK hook do?
A hook runs your code at an event: it can block a dangerous tool call before it executes, log or audit tool calls, rewrite a tool's input or output, require your own approval for a sensitive action, and track the session lifecycle to clean up or notify.
How do I block a tool call in the Agent SDK?
Register a PreToolUse hook and return hookSpecificOutput with permissionDecision set to "deny" and a permissionDecisionReason. The reason reaches the model. A deny takes priority over defer, ask and allow when several hooks return different decisions.
What happens when several hooks return different decisions?
Deny wins. When several PreToolUse hooks return different decisions, deny takes priority over defer, which takes priority over ask, which takes priority over allow.
What happens when a hook callback throws?
On most events the action goes ahead and your app receives an SDKInformationalMessage warning tagged hook_callback_failed, so a guard that crashes lets the call reach the normal permission flow. Set onFailure: "block" on the matcher to block instead; that needs TypeScript Agent SDK 0.3.317 or later, or Python Agent SDK 0.2.177 or later.
How long may a hook callback take?
600 seconds by default for most events, 30 seconds for UserPromptSubmit, PreModelSwitch and PostModelSwitch, and 10 seconds for MessageDisplay. Set a different timeout in seconds on the HookMatcher. A callback that exceeds it is cancelled and its output discarded, and the event decides what happens next.
Every session, one window
Omniscio runs several agent sessions side by side in one window, each with its own context and its own diff view. Any model, any harness: Claude Code, Codex, OpenCode, Devin, Pi, and Hermes all supported.