Blog
Claude Code hooks: every event, with examples to copy
What hooks are, all 33 events, where to configure them, how exit codes and JSON output steer Claude, and four example hooks to adapt.
Alex Mercer
Claude Code hooks are commands, HTTP calls, MCP tool calls, prompts or subagents that Claude Code runs automatically at set points in a session: before a tool call, after it, when Claude finishes responding, and 30 more events. You define them in a settings file, they fire every time their event happens, and their exit code or JSON output can block the action, send Claude feedback, or add context.
That makes hooks the place for rules that must hold every time. A line in CLAUDE.md is context that Claude reads and interprets. A hook is code that Claude Code runs on its own, so the action happens whether or not the model thinks of it. Anthropic's hooks guide calls this deterministic control.
Hook events and settings here follow Anthropic's docs as of Oct 12, 2026. If you're setting up Claude Code for a team, start with our practical guide to using Claude Code.
How a Claude Code hook works
Every hook has three layers:
Event: the moment it fires, such as
PreToolUseorStop.Matcher: a filter on when it fires, such as "only the Bash tool".
Handlers: what runs when the event and matcher line up.
Handlers come in five types:
commandruns a shell command. It receives the event as JSON on stdin and answers through its exit code, stdout and stderr.httpsends the same JSON as a POST request and reads the response body.mcp_toolcalls a tool on an MCP server you've configured.promptsends the input to a Claude model, which returns a decision as JSON. Use it for checks that need judgment.agentstarts a subagent that can read files before it decides. Anthropic marks agent hooks as experimental.
Per Anthropic's features overview, a hook adds nothing to Claude's context unless it returns output, so a formatter that runs after every edit costs no context. For instructions that never change, a line in CLAUDE.md is simpler than a script; our guide to CLAUDE.md and AGENTS.md covers how those files load.
Every Claude Code hook event
Anthropic's hooks reference lists 33 events as of Oct 12, 2026. A few run once per session (SessionStart, SessionEnd), a few once per turn (UserPromptSubmit, Stop, StopFailure), and PreToolUse and PostToolUse run on every tool call. "Can block" means exit code 2, or a blocking JSON decision, stops the action.
Event | When it fires | Can block? |
|---|---|---|
| A session starts or resumes | No |
| Claude Code starts with | No |
| A CLAUDE.md or | No |
| You submit a prompt, before Claude processes it | Yes, rejects the prompt |
| A command you typed expands into a prompt | Yes, blocks the expansion |
| Before a tool call runs | Yes, blocks the call |
| A tool call needs a permission decision | Through JSON only (allow or deny) |
| Auto mode denies a tool call | No (JSON can allow a retry) |
| After a tool call succeeds | No, but stderr reaches Claude |
| After a tool call fails | No, but stderr reaches Claude |
| After a batch of parallel tool calls resolves, before the next model call | Yes, stops the loop |
| Claude Code sends a notification | No |
| While Claude's message text is displayed | No (can change the displayed text) |
| A subagent is spawned | No |
| A subagent finishes | Yes, keeps it working |
| A task is created with | Yes, cancels the task |
| A task is being marked complete | Yes, keeps it open |
| An agent team teammate is about to go idle | Yes, keeps it working |
| Claude finishes responding | Yes, keeps Claude working |
| A turn ends because of an API error | No |
| Before context compaction | Yes |
| After compaction completes | No |
| Before a model switch you or a client requested | Yes |
| After the session's model changes | No |
| A configuration file changes during the session | Yes, except policy settings |
| The working directory changes | No |
| A directory is added with | No |
| A file you told it to watch changes on disk | No |
| A worktree is created; the hook replaces the default git behavior | Yes, any non-zero exit fails it |
| A worktree is removed | Yes, a non-zero exit fails the removal |
| An MCP server asks for user input during a tool call | Yes, denies the request |
| After you answer an MCP elicitation, before the answer goes back | Yes |
| The session ends | No |
Matchers filter on a different field for each event. Tool events match the tool name, such as Bash, Edit|Write or mcp__github__.*. SessionStart matches how the session began (startup, resume, clear, compact or fork). SubagentStart and SubagentStop match the subagent's name, and Notification matches the notification type, such as permission_prompt or idle_prompt. UserPromptSubmit, Stop, PostToolBatch, TeammateIdle, TaskCreated, TaskCompleted, WorktreeCreate, WorktreeRemove, MessageDisplay and CwdChanged don't take a matcher and fire every time.
Where hooks are configured
Hooks live in JSON settings files and a few other places, including plugins and skills. Where you put one sets its scope:
Location | Scope | Shared with the team? |
|---|---|---|
| All your projects | No, local to your machine |
| One project | Yes, commit it to the repo |
| One project | No, Claude Code gitignores it when it saves a setting there |
Managed policy settings | Whole organization | Yes, set by admins |
A plugin's | While the plugin is enabled | Yes, ships with the plugin |
Skill frontmatter | Rest of the session once the skill is invoked | Yes, in the skill file |
Subagent frontmatter | While that subagent runs | Yes, in the subagent file |
A few rules about how these combine:
Hooks from every level merge. A project hook doesn't replace a user hook, and a handler defined in two settings files runs once.
Claude Code normally picks up edits to settings files on its own, and
/hookslists every hook and where it came from.To pause all hooks, set
"disableAllHooks": true. There is no switch for one hook, and only managed settings can turn off managed hooks.Cloud sessions don't read your local
~/.claude/settings.json.Settings, managed and plugin hooks also run inside subagents, with
agent_idandagent_typein the input. A subagent's own frontmatter hooks run only while it's active; our subagents guide uses one to keep a reviewer read-only.
The shape of a hook entry
Each event name is a key inside one hooks object. Under it sits a list of matcher groups, and each group holds a list of handlers. This one, from Anthropic's reference, runs a lint script after Claude writes or edits a file:
If your settings file already has a hooks key, add new events as siblings inside it rather than a second hooks object.
Matchers and the if field
"*",""or no matcher at all matches everything.A matcher made only of letters, digits,
_,-, spaces, commas and|is an exact match or a list of them, soEdit|Writematches either tool.Anything else is a JavaScript regular expression, and it isn't anchored:
Edit.*also matchesNotebookEdit. Write^Edit$when you need a whole-name match.Matchers are case-sensitive. MCP tools are named
mcp__<server>__<tool>, somcp__memory__.*matches every tool from thememoryserver.
On tool events you can narrow further with the if field. It takes one permission rule, such as "Bash(git *)" or "Edit(*.ts)", and the handler only spawns when the tool call matches. For Bash, each subcommand is checked, so Bash(git *) fires on npm test && git push. Anthropic calls if best-effort and recommends permission rules, not hooks, for a hard allow or deny.
Pointing at scripts
Use ${CLAUDE_PROJECT_DIR} for the project root, or ${CLAUDE_PLUGIN_ROOT} inside a plugin. Anthropic recommends setting args (an argument list, even an empty one) whenever a command uses one of these placeholders: Claude Code then runs the executable directly with no shell, each argument is passed as is, and paths with spaces need no quoting. The examples below also use timeout, in seconds (600 by default for command hooks on most events), and statusMessage, the spinner text while the hook runs.
What a hook receives
A command hook gets one JSON object on stdin. The common fields are:
session_idandprompt_idtranscript_path, the path to the conversation filecwd, the directory Claude is working inpermission_mode, such asdefault,plan,acceptEditsorauto(most events)hook_event_nameagent_idandagent_type, when the hook fires inside a subagent
Each event adds its own fields. A PreToolUse hook for a Bash call receives something like this:
For scripts that read this input:
For
Write,EditandRead,tool_input.file_pathis always absolute. Claude Code expands~and relative paths first, so a path check can't be dodged with a different spelling.Stophooks getstop_hook_active, which istruewhen Claude is already continuing because a Stop hook blocked it, andlast_assistant_message, the text of Claude's final reply. Read that rather than the transcript file, which is written asynchronously and can lag.
How exit codes and output control Claude
The exit code is the simplest signal:
Exit code | Meaning | What Claude Code does |
|---|---|---|
0 | Success | Proceeds and reads any JSON on stdout. Plain stdout goes to the debug log, except on |
2 | Block | On events that can block, stops the action. The message is your stderr, or your JSON's reason; for a blocked tool call or |
Anything else | Non-blocking error (most events) | Proceeds and shows a |
On most events, exit code 1, the usual Unix failure code, doesn't block, so a policy hook should exit 2. And a hook that can't start, because the path is wrong or the script isn't executable, also lands in the non-blocking bucket. A typo in settings.json quietly turns your gate off, so watch for a hook error notice the first time a new hook runs. On Claude Code v2.1.295 or later, setting "onFailure": "block" on a command or HTTP hook makes a hook that can't start, times out or exits with an unexpected code block the action instead; it has no effect on Stop hooks.
JSON output for finer control
When block-or-allow isn't enough, exit 0 and print a JSON object on stdout. Pick one approach per hook: exit codes alone, or exit 0 plus JSON. On events that can block, exit 2 wins even if your JSON says allow.
Universal fields work on most events.
"continue": falsestops Claude entirely and shows the userstopReason, andsystemMessageshows the user a warning.decisionandreasonlet events such asUserPromptSubmit,PostToolUse,StopandSubagentStopblock or send feedback. The only value fordecisionis"block".hookSpecificOutputcarries richer control and needs ahookEventName. OnPreToolUseit holdspermissionDecision(allow,deny,askordefer) with apermissionDecisionReason, andupdatedInputcan rewrite the tool's arguments. On several events it can holdadditionalContext, text Claude reads as a system reminder.
This denies a tool call and tells Claude why:
Write additionalContext as plain facts ("This repo uses bun test"), not as commands. Anthropic notes that text framed as system instructions can trip Claude's prompt-injection defenses. Each additionalContext, systemMessage and plain stdout value is capped at 10,000 characters.
Hooks also sit above permission modes. A PreToolUse hook that returns deny blocks the tool even in bypassPermissions mode, but one that returns allow can't override a deny rule in your settings.
Four example Claude Code hooks
These are examples to adapt. The first two follow Anthropic's guide; the test gate and review hook are our own, so try each one in a scratch repo before you rely on it. Each goes in .claude/settings.json, so the whole team gets it. The scripts parse JSON with jq, so install it first. Save scripts under .claude/hooks/ and run chmod +x on them, or they fail without blocking anything.
1. Format every file Claude edits
A PostToolUse hook with an Edit|Write matcher runs after each file edit. This one, from Anthropic's guide, passes the edited path to Prettier:
When it works, you see nothing in the conversation; the file is just formatted. Swap in the formatter your project uses. PostToolUse can't undo the edit, and the matcher only sees the Edit and Write tools. To catch a specific file however it changes, including a Bash rewrite, use a FileChanged hook.
2. Block edits to sensitive files
A PreToolUse hook runs before the edit, so it can stop it. This script, adapted from Anthropic's guide, exits 2 when the target path matches a protected pattern, and Claude gets the message as feedback. Unlike the original, it fails closed: without jq, it blocks the edit.
The check is a substring match, so .env also covers .env.local and .env.example. Adjust the list for your repo. Like the formatter, it only sees Edit and Write. To keep Claude's file tools from reading a file, add a Read deny rule such as Read(./.env) to permissions.deny in your settings.
3. Run tests before Claude stops
Stop fires when Claude finishes responding. Exit 2 from a Stop hook keeps Claude working and hands it your stderr as the reason. That gives you a test gate: if tests fail, Claude fixes them before handing the turn back to you.
Replace npm test with your test command. How it behaves:
Stopfires after every response, not only at the end of a task, so the script skips the run when the working tree is clean.The first failure blocks and sends Claude the last 40 lines of output. If tests still fail at the next stop,
stop_hook_activeistrue, so the script lets Claude stop and warns you throughsystemMessageinstead of looping. Claude Code also ends the turn itself after Stop hooks block eight times in a row with no tool call in between.It fails safe: without
jqor outside a git repo it lets Claude stop, and if the suite runs past the hook'stimeout, Claude Code cancels the hook and the turn ends as if nothing blocked.
4. Review the diff before every commit
Claude Code wrote 78.1% of the AI-written code that cubic reviewed in the latest full week, according to Bug Bench. That share covers code reviewed by cubic, not the whole market. A PreToolUse hook on git commit puts a review in front of each commit Claude makes, while Claude still has the context to fix what it finds.
This example calls cubic's CLI as its docs describe it. On macOS or Linux, install it with curl -fsSL https://cubic.dev/install | bash, then run cubic once in your repo to sign in. cubic review --json reviews uncommitted changes and returns one JSON object with an issues array.
The wrapper exists because the CLI exits with code 1 when it reports findings, and Claude Code treats exit code 1 from a hook as a non-blocking error, so every commit would go through. The script exits 2 instead, which blocks the commit and hands Claude the findings. How it handles trouble:
It fails open. If
jqor the CLI is missing, or the review errors out, the commit goes ahead. Add anexit 2for an empty report if you'd rather fail closed.Command hooks time out after 600 seconds by default, and a timed-out
PreToolUsehook doesn't block. Raisetimeoutif your reviews take longer.The message tells Claude to stop and ask you when it disagrees with a finding, so a disputed finding doesn't turn into a loop.
With another review tool, keep the wrapper and swap the command: exit 2 with the findings on stderr when the commit should wait.
A local review is a first pass. cubic's docs recommend its GitHub pull request review as the final one, since that review uses a different model and pipeline and may find issues the CLI misses. Our guide to AI code review covers where each step fits, and a pre-review safety gate for AI-generated code covers gating agent output. For the whole loop in Claude Code, from a local review to fixing pull request comments, see our Claude Code review guide.
Security: hooks run with your permissions
Command hooks run with your full user permissions. They can read, change or delete anything your account can, so review every hook before you add it, especially one from a repo you didn't write.
Workspace trust adds a guard in interactive sessions: Claude Code holds back hooks from settings files until you accept the trust dialog for the folder. A claude -p or Agent SDK session treats the folder as trusted, so hooks committed in a repo's .claude/settings.json run without asking. Before you script claude -p over someone else's repository, read its .claude/ settings, or turn hooks off for that run with --settings '{"disableAllHooks": true}'.
Anthropic's checklist for hook scripts: validate input, quote shell variables ("$VAR"), reject paths that contain .., use absolute paths, and skip sensitive files such as .env and keys.
Debugging a hook that doesn't fire
Run
/hooksand check that the hook is listed under the right event.Check the matcher. Matchers are case-sensitive.
Run the script by hand with sample input:
echo '{"tool_name":"Bash","tool_input":{"command":"ls"}}' | ./my-hook.sh; echo $?If your JSON output has no effect, look for a shell profile that prints text on startup. Anything printed before the
{makes Claude Code treat the whole output as plain text.Start Claude Code with
claude --debug-file /tmp/claude.logto log which hooks matched, their exit codes and their output, or run/debugto turn logging on mid-session.
FAQ
Which exit code blocks an action in a Claude Code hook?
Exit code 2. On events that can block, such as PreToolUse, UserPromptSubmit and Stop, it stops the action, and for a tool call or Stop, Claude gets your stderr as the reason. On most events, exit code 1 and other non-zero codes are non-blocking errors, so the action goes ahead. You can also block by exiting 0 with a JSON decision, such as "permissionDecision": "deny" on PreToolUse.
What is the difference between hooks and mods in Claude Code?
The hooks in this guide are configured in settings. A mod is a plugin that registers hooks as JavaScript functions, which Claude Code calls in its own process, and it can also draw in the interface. Both work side by side, but a mod that handles tool.check can approve a call your PreToolUse hook blocked, unless that hook lives in managed settings.
How do I get a notification when Claude Code needs input?
Add a Notification hook to ~/.claude/settings.json. On macOS, Anthropic's guide uses the command osascript -e 'display notification "Claude Code needs your attention" with title "Claude Code"'. Use a matcher such as permission_prompt or idle_prompt to limit which notifications trigger it. For a terminal notification that also works in tmux, return the escape sequence in the terminalSequence JSON field instead of writing to /dev/tty.
