Hooks in the SDK and in Claude Code
Hooks are code the harness runs at fixed points in the agent loop, so unlike CLAUDE.md or prompts they always run. Know the events and which ones can block, how matchers and exit codes work, where each JSON output field goes, and how SDK callbacks differ from settings-file command hooks.
Key points
- 1
Configuration nests three levels under
hooks: event name, then matcher groups, then handlers. In settings files a handler iscommand,http,mcp_tool,promptoragent. In the Agent SDK it is an in-process callback:hooks: { PreToolUse: [{ matcher: 'Bash', hooks: [fn], timeout }] }(HookMatcherin Python). The SDK also runs settings-file hooks from whicheversettingSourcesare loaded (all of them by default;[]loads none). - 2
Matchers:
*,""or no matcher matches everything. A matcher made only of letters, digits,_,-, spaces,,and|is an exact name or list of names (Edit|Write). Any other character makes it an unanchored JS regex (Edit.*also matchesNotebookEdit; use^Edit$). Matchers are case-sensitive and test the tool name, not arguments. MCP tools needmcp__server__.*.Stop,UserPromptSubmitandPostToolBatchhave no matcher support. - 3
The handler's
iffield filters by tool arguments with permission-rule syntax (Bash(git *),Edit(*.ts)), only on tool events. It is best-effort for Bash, so enforce hard allow and deny rules with the permission system. - 4
Exit codes: 0 means success (JSON on stdout applies), 2 means blocking error (stderr becomes the reason), and any other code is a non-blocking error, so the action goes ahead. Valid JSON with exit 1 still decides; exit 2 blocks even if the JSON says
allow. - 5
Events that can block on exit 2 include
PreToolUse,UserPromptSubmit,Stop,SubagentStop,PreCompactandPostToolBatch.PostToolUseonly shows stderr to Claude (the tool already ran),SessionStartshows it to the user only,Notificationignores it, andPermissionRequestignores exit 2 entirely (usedecision.behavior). - 6
PreToolUse returns
hookSpecificOutput.permissionDecision:allow,deny,askordefer(defer only in-pmode, with a single tool call in the turn). Precedence across hooks is deny > defer > ask > allow. A hook deny holds in every mode, including bypassPermissions; a hook allow never skips deny or ask rules. - 7
updatedInputreplaces the whole tool input, so spread the original fields. Permission rules are evaluated against the rewritten input. Pair it withallowto auto-approve oraskto show it to the user;deferignores it. If several hooks rewrite input, the last to finish wins. - 8
Output channels:
additionalContextgoes to Claude as a system reminder,systemMessagegoes to the user,permissionDecisionReasongoes to Claude on deny, andcontinue: falseplusstopReasonstops processing. Strings are capped at 10,000 characters; longer text is saved to a file and Claude gets a path plus a 2,000-character preview. - 9
PostToolUse can add
additionalContext,decision: "block"with a reason, orupdatedToolOutput(it must match the tool's output shape, for example Bash's{stdout, stderr, interrupted, isImage}). The tool has already run, so redaction only changes what Claude sees. UsePostToolBatch(TypeScript callbacks or settings files) to inject context once per batch of parallel calls. - 10
Stop hooks: exit 2 or
decision: "block"keeps Claude working. Checkstop_hook_activeto avoid loops. Claude Code overrides after 8 consecutive continuations, but the count resets whenever Claude calls a tool.SubagentStopuses the same format and keeps the subagent running; for parent-side context usePostToolUseon theAgenttool. - 11
SDK specifics: callbacks get
(input, toolUseID, { signal }), and returning{}changes nothing. Async output (async: true,async_in Python) cannot block or add context. Python usescontinue_andasync_, and itsHookEventlacks SessionStart, SessionEnd, PostToolBatch and other TypeScript-only events, so use settings-file hooks there.matchertimeouts are in seconds. - 12
Timeouts and failures: an SDK PreToolUse callback that times out blocks the call, while a command hook that times out fails open unless
onFailure: "block"is set (v2.1.295+). A hook that can't start is a non-blocking error by default.-pand SDK sessions run repository hooks without the workspace trust dialog.
Common traps
Using
exit 1for a policy hook: it is a non-blocking error, so the tool call still runs.Putting
permissionDecisionoradditionalContextat the top level instead of insidehookSpecificOutput: the JSON parses, but the fields are silently ignored. A shell profile that echoes before the JSON has the same effect.Returning
updatedInputwith only the changed field, which drops every other argument the tool needs.Writing a matcher like
mcp__github(exact match, matches nothing) or.env(matchers never see file paths).A Stop hook that blocks on a condition Claude cannot fix: it loops, and tool calls keep resetting the 8-continuation cap.
Expecting
systemMessageto reach the model, or stderr from an exit-0 hook to reach Claude: neither does.Relying on
canUseToolor a PermissionRequest hook for an invariant: calls that rules or modes approve never reach them, while PreToolUse runs for every call.
Read the source
Further reading
Suggest a resourceNo extra reading for Hooks in the SDK and in Claude Code yet. Found a guide, video or cheat sheet that made it click? Share it and help the next learner.
Test yourself on Hooks in the SDK and in Claude Code
Ten questions, with the answer and explanation after each one.