Deterministic guardrails with Claude Code hooks
Added Updated Copyable prompt below
Published Last verified Released
Our verdict
Hooks turn 'please remember to run the formatter' into a guarantee. Use them for anything that must always happen, rather than hoping the model remembers. They take some care: a hook that exits 1 instead of 2 doesn't block anything, and an Edit|Write matcher won't see files changed through shell commands.
- Who it's for
- Claude Code users who want enforced rules
- Leverage
- Guaranteed checks around every agent action
- Effort
- Medium
- Date added
What Claude Code hooks do
Hooks are handlers that Claude Code runs automatically at set points in its lifecycle: shell commands, HTTP endpoints, MCP tool calls, single-turn LLM prompts or, experimentally, subagents. You define them in a JSON settings file in three levels: an event such as PreToolUse, PostToolUse, Notification, Stop or SessionStart; a matcher, which for tool events is the tool name (Edit|Write, Bash, mcp__memory__.*); and the handler. The handler gets the event as JSON on stdin, or as the POST body for HTTP hooks. Exit code 2 blocks the action on events that can be blocked, and JSON output gives finer control, such as a permissionDecision of deny. The same events fire in the terminal, IDE extensions, the Desktop app and cloud sessions.
How builders use Claude Code hooks
- Run Prettier on every file Claude edits: a PostToolUse hook with matcher Edit|Write and the command jq -r '.tool_input.file_path' | xargs npx prettier --write.
- Block edits to .env, package-lock.json and .git/ with a PreToolUse script that exits 2 and prints why to stderr, so Claude sees the reason and changes approach.
- Get a desktop notification when Claude is waiting for input: a Notification hook running osascript on macOS or notify-send on Linux.
- Re-inject key project context after compaction with a SessionStart hook matched on compact.
- Add a Stop prompt hook that asks a model whether every requested task is done; if not, Claude keeps working with the reason as its next instruction.
The events you'll use first
| Event | Typical use |
|---|---|
| PreToolUse | Block or rewrite a tool call before it runs. Can block. |
| PostToolUse | Format, lint or test after an edit. Can't undo the action. |
| Notification | Alert you when Claude needs input or permission. |
| Stop | Check the work before Claude ends its turn. Can send it back to work. |
| SessionStart | Load context such as the current branch or open issues, at startup or after compaction. |
| UserPromptSubmit | Add context to a prompt, or reject it, before Claude sees it. |
| ConfigChange | Audit or block changes to settings files during a session. |
Where hooks live
- ~/.claude/settings.json applies to all your projects; .claude/settings.json can be committed so the whole team gets the hook; .claude/settings.local.json stays on your machine.
- Hooks can also come from managed policy settings, a plugin's hooks/hooks.json, or the frontmatter of a skill or subagent.
- Type /hooks in Claude Code to browse every configured hook and see where it's defined.
- Set "disableAllHooks": true to switch hooks off without deleting them; it can't disable hooks set in managed settings.
- A PreToolUse deny holds in every permission mode, including bypassPermissions, while a hook's allow can't override deny rules in settings.
Claude Code hooks: limits and gotchas
- An Edit|Write matcher only fires for those tools. Claude can also change files through shell commands, so for full coverage add a Stop hook that scans the working tree, or match Bash too and check git status --porcelain.
- Exit code 1 is a non-blocking error: the action goes ahead. Policy hooks should exit 2, or set onFailure to block (Claude Code v2.1.295 or later) so a crashing or missing script blocks too.
- The if field is best-effort for Bash commands. Anthropic says to use permission rules, not hooks, for a hard allow or deny.
- Default timeouts are 10 minutes for command, HTTP and MCP tool hooks, 30 seconds for prompt hooks and 60 for agent hooks. A timed-out PreToolUse hook doesn't block unless onFailure is block.
- Stop hooks fire whenever Claude finishes responding, not only at task completion. Claude Code overrides a Stop hook after eight blocks in a row, so check stop_hook_active to avoid loops.
- Command hooks run with Claude Code's environment, so review hooks from a shared repo or plugin as you would any script.
Claude Code hooks compared with other tools here
- Claude Code subagents: specialised helpers with their own prompts and tools. Subagents delegate work; hooks enforce rules, and can be defined in a subagent's frontmatter.
- Claude Code skills: instructions and scripts Claude loads when relevant. A skill can carry hooks that apply once it's invoked.
- Cursor Rules and AGENTS.md: written guidance the model reads and weighs. Use rules to guide, hooks to guarantee.
- Claude Code GitHub Actions: runs Claude in CI on issues and pull requests; hooks act on every tool call in a session.
- Aider lint and test loop: a similar run-the-checks-after-every-edit idea, built into Aider.
When to pick Claude Code hooks
- Pick hooks for anything that must happen every time: formatting, blocking protected files, notifications, end-of-turn checks.
- Pick a PreToolUse hook that returns deny when a rule must hold even if someone switches permission mode.
- Use CLAUDE.md or rules instead for guidance the model should weigh rather than obey, such as style preferences.
Copy this: .claude/settings.json
{
"hooks": {
"PostToolUse": [
{
"matcher": "Edit|Write",
"hooks": [{ "type": "command", "command": "jq -r '.tool_input.file_path' | xargs npx prettier --write" }]
}
],
"PreToolUse": [
{
"matcher": "Edit|Write",
"hooks": [{ "type": "command", "command": "\"$CLAUDE_PROJECT_DIR\"/.claude/hooks/protect-files.sh" }]
}
]
}
}
# protect-files.sh reads the JSON on stdin, checks tool_input.file_path
# against .env, package-lock.json and .git/, and on a match:
# echo "Blocked: <path> is protected" >&2; exit 2
# Make it executable: chmod +x .claude/hooks/protect-files.shClaude Code hooks questions
Can a Claude Code hook block a tool call?
Yes. A PreToolUse hook blocks the call by exiting with code 2, or by printing JSON with permissionDecision set to deny. A deny holds even in bypassPermissions mode.
How do I share hooks with my team?
Put them in .claude/settings.json in the repository and commit it. Hooks in ~/.claude/settings.json and .claude/settings.local.json stay on your machine.
Why doesn't my MCP hook fire?
A matcher made only of letters, digits, underscores and hyphens is compared as an exact string, so mcp__memory matches no tool. Use mcp__memory__.* to match every tool from that server, and check /hooks to confirm the hook is loaded.
Do hooks run in cloud sessions?
The same events fire there, but cloud sessions don't read your local ~/.claude/settings.json, so put hooks you need there in the project's settings.
Related discoveries
See the newest picks →- ToolCoding & Shipping Agents
Sphinx: quiz yourself before shipping agent code
MIT Git hook that quizzes you on what your coding agent's change does before a protected push continues.
Effort: MediumPrompt#Plugin / extension#Open source
- ToolCoding & Shipping Agents
Shannon: open-source A.I. pentester for web apps and APIs
Keygraph's AGPL-3.0 A.I. pentester: it reads your web app's source, then attacks a running copy and only reports vulnerabilities it could actually exploit.
Effort: MediumPrompt#Open source#Self-hostable
Get the best new A.I. picks in your inbox
The best new agent workflows and tools we’ve vetted, with a clear verdict on each. Short, occasional, useful.