Claude Hooks
Use Claude Code and Agent SDK hooks as deterministic guardrails: pick the right event and matcher, block correctly, place the configuration at the right scope, and know how hooks interact with permission rules.
Key points
- 1
Hooks run in the harness at fixed lifecycle points, so they fire every time. Use them for rules that must hold, such as blocking
rm -rf, force-pushes or edits to protected files, rather than relying on CLAUDE.md or prompt instructions. - 2
PreToolUseruns before a tool executes and is the event that can prevent it.PostToolUseruns after success, which suits linters, formatters and feedback, but the action has already happened. - 3
Blocking from PreToolUse: exit code
2(stderr becomes the reason shown to Claude), or exit0with JSONhookSpecificOutput.permissionDecision: "deny"pluspermissionDecisionReason. Exit code1is a non-blocking error and the call proceeds. - 4
Command hooks receive JSON on stdin, including
tool_nameandtool_input(for Bash, the full command; for Edit and Write,file_path), so the hook can inspect arguments. - 5
Matchers filter by tool name for tool events:
"Bash"or"Edit|Write"match exactly, a pattern with other characters is a regex (such asmcp__.*), and"*"or an empty matcher matches everything. - 6
UserPromptSubmitruns before Claude processes a prompt and can reject it, for example a prompt that contains a pasted secret. It sees user prompts, not commands Claude generates. - 7
Stopfires when Claude finishes responding. Returningdecision: "block"with areasonmakes Claude keep working, for example until tests pass. Check thestop_hook_activeinput so the hook does not keep blocking on a condition Claude cannot fix. - 8
Scope comes from where the hook is defined:
~/.claude/settings.json(you, all projects),.claude/settings.json(committed and shared with the team),.claude/settings.local.json(personal, gitignored), managed policy settings (organization-wide), plugins, and Skill or agent frontmatter. - 9
Hooks merge across levels, and
disableAllHooksset in user, project or local settings cannot disable managed hooks. Admins can useallowManagedHooksOnlyto block all non-managed hooks. - 10
Hooks and permission rules layer. A hook "allow" skips a prompt but does not override matching deny or ask rules, while a hook that exits 2 blocks even when an allow rule matches.
- 11
A hook matched to Edit and Write does not see Bash. If the shell can reach the same files, add sandbox filesystem restrictions or also cover Bash.
- 12
In the Agent SDK, hooks are callback functions passed in the options (for example on
PreToolUse) that can deny or allow calls. They run before permission rules and thecanUseToolcallback.
Read the source
Test yourself on Claude Hooks
Ten questions, with the answer and explanation after each one.