On this page
- What are Claude Code hooks?
- Claude Code hook events
- Where hooks live and the JSON shape
- Exit codes and JSON output
- Five copy-paste Claude Code hook examples
- 1. Format every file Claude edits
- 2. Block edits to protected paths
- 3. Run the tests before Claude stops
- 4. Get a desktop notification when Claude needs you
- 5. Give Claude project context at session start
- Hooks vs MCP vs skills vs CLAUDE.md
- Codex hooks
- How repowise uses hooks: context before the agent asks
- FAQ
Claude Code hooks are user-defined handlers (shell commands, HTTP endpoints, MCP tools or model prompts) that Claude Code runs automatically at fixed points in a session: when it starts, before or after a tool call, when Claude stops, and more. Because they run every time, hooks turn rules you would otherwise ask for in a prompt into behavior the agent cannot skip.
Part of the AI Context & MCP guide. Event names and fields below are checked against the Claude Code hooks reference as of November 2026.
What are Claude Code hooks?
A hook is a handler attached to a lifecycle event, configured in a settings file, that Claude Code runs without the model deciding to. A PreToolUse hook on Bash sees every shell command before it runs and can allow, deny or ask. A PostToolUse hook on Edit runs after every file edit. A Stop hook runs when Claude finishes its reply and can send it back to work.
That is the main difference from instructions. A line in CLAUDE.md that says "run the formatter after editing" is advice the model may follow. A PostToolUse hook that runs the formatter is a guarantee. Hooks receive a JSON payload on stdin (session id, working directory, event name and event fields such as tool_name and tool_input) and answer with an exit code, plain text or JSON on stdout.
There are five handler types:
| Type | What it does |
|---|---|
command | Runs a shell command; the event JSON arrives on stdin |
http | POSTs the event JSON to a URL |
mcp_tool | Calls a tool on a configured MCP server |
prompt | Sends a single-turn prompt to a model to judge the event |
agent | Spawns a subagent that can use tools to check a condition (experimental) |
Scroll the table sideways to see every column.
Claude Code hook events
Claude Code has more than 30 hook events; seven cover most real use: SessionStart, UserPromptSubmit, PreToolUse, PostToolUse, Notification, Stop and SubagentStop.
| Event | Fires | Can block? | Typical use |
|---|---|---|---|
SessionStart | When a session starts or resumes (matchers startup, resume, clear, compact) | No | Load project context, check environment |
UserPromptSubmit | When you submit a prompt, before Claude sees it | Yes | Add context, reject prompts that leak secrets |
PreToolUse | Before a tool call runs | Yes | Block dangerous commands, protect paths, rewrite input |
PermissionRequest | When a tool call needs a permission decision | Yes, through a decision object | Auto-approve or deny known calls |
PostToolUse | After a tool call succeeds | No (can add feedback) | Format, lint, add context to the result |
PostToolUseFailure | After a tool call fails | No | Explain the failure, suggest a fix |
Notification | When Claude Code sends a notification | No | Desktop alert when Claude needs input |
SubagentStart / SubagentStop | When a subagent is spawned / finishes | SubagentStop: yes | Check a subagent's result |
Stop | When Claude finishes responding | Yes | Run tests, keep Claude working until they pass |
PreCompact / PostCompact | Around context compaction | PreCompact: yes | Steer what the summary keeps |
SessionEnd | When a session ends | No | Cleanup, logging |
Scroll the table sideways to see every column.
The rest cover narrower moments: Setup, UserPromptExpansion, PermissionDenied, PostToolBatch, MessageDisplay, TaskCreated, TaskCompleted, StopFailure, TeammateIdle, InstructionsLoaded, ConfigChange, CwdChanged, DirectoryAdded, FileChanged, WorktreeCreate, WorktreeRemove, PreModelSwitch, PostModelSwitch, Elicitation and ElicitationResult.
Where hooks live and the JSON shape
Hooks sit under a hooks key in a settings file, nested as event name, then a matcher group, then a hooks array of handlers.
{
"hooks": {
"PreToolUse": [
{
"matcher": "Bash",
"hooks": [
{
"type": "command",
"command": "${CLAUDE_PROJECT_DIR}/.claude/hooks/check-bash.sh",
"timeout": 30
}
]
}
]
}
}
The matcher is a tool name, a |-separated list such as Edit|Write, or a regular expression such as mcp__.*. Events without matchers ignore it. timeout is in seconds (600 by default for command). $CLAUDE_PROJECT_DIR is the project root, exported to every hook process.
| File | Scope | Shared with the team? |
|---|---|---|
~/.claude/settings.json | All your projects | No |
.claude/settings.json | This project | Yes, committed |
.claude/settings.local.json | This project | No, gitignored |
| Managed policy settings | Organization | Yes, set by admins |
Plugin hooks/hooks.json | While the plugin is enabled | Yes |
| Skill or subagent frontmatter | While that skill or subagent is active | Yes |
Scroll the table sideways to see every column.
Type /hooks in Claude Code to see every configured hook and where it came from. Edits to settings files are picked up by a file watcher, so you rarely need to restart.
Exit codes and JSON output
Exit 0 means success, exit 2 blocks the action, and any other code is a non-blocking error.
| Exit code | Effect |
|---|---|
0 | Success. JSON on stdout is applied; plain text becomes context on SessionStart and UserPromptSubmit |
2 | Blocking error. On events that can block, the action stops and stderr is the reason Claude sees |
| Other | Non-blocking error. The action continues and the transcript shows a hook error notice |
Scroll the table sideways to see every column.
For finer control, print JSON. A PreToolUse hook returns a hookSpecificOutput with hookEventName, permissionDecision (allow, deny, ask or defer) and permissionDecisionReason. A Stop hook returns {"decision": "block", "reason": "..."} to keep Claude working. Most events accept additionalContext inside hookSpecificOutput to add a note to Claude's context.
Five copy-paste Claude Code hook examples
These five hooks cover the most common requests: formatting, protected paths, tests before stopping, notifications and project context. Each is a fragment for the hooks object in .claude/settings.json. The scripts use jq to read the event JSON.
1. Format every file Claude edits
"PostToolUse": [
{
"matcher": "Edit|Write",
"hooks": [
{
"type": "command",
"command": "jq -r '.tool_input.file_path' | xargs npx prettier --write --ignore-unknown"
}
]
}
]
tool_input.file_path is always an absolute path for Edit, Write and Read. Swap in ruff format, gofmt -w or rustfmt for other languages.
2. Block edits to protected paths
"PreToolUse": [
{
"matcher": "Edit|Write",
"hooks": [
{ "type": "command", "command": "${CLAUDE_PROJECT_DIR}/.claude/hooks/protect-paths.sh" }
]
}
]
#!/usr/bin/env bash
# .claude/hooks/protect-paths.sh
path=$(jq -r '.tool_input.file_path // empty')
case "$path" in
*.env|*/.env.*|*/migrations/*|*/package-lock.json)
echo "Blocked: $path is protected. Ask the user before changing it." >&2
exit 2 ;;
esac
exit 0
Exit 2 stops the edit and hands Claude the stderr line as the reason, so it can explain or ask instead of retrying.
3. Run the tests before Claude stops
"Stop": [
{
"hooks": [
{ "type": "command", "command": "${CLAUDE_PROJECT_DIR}/.claude/hooks/tests-pass.sh", "timeout": 300 }
]
}
]
#!/usr/bin/env bash
# .claude/hooks/tests-pass.sh
input=$(cat)
# Already continuing because of this hook: let Claude stop.
[ "$(printf '%s' "$input" | jq -r '.stop_hook_active')" = "true" ] && exit 0
if ! out=$(npm test --silent 2>&1); then
tail=$(printf '%s\n' "$out" | tail -n 40)
jq -n --arg t "$tail" '{decision: "block", reason: ("Tests are failing. Fix them before you finish.\n" + $t)}'
fi
exit 0
stop_hook_active is true when Claude is already continuing because of a Stop hook. Checking it keeps the hook from looping on a failure Claude cannot fix.
The same block-and-continue pattern is how Anthropic's ralph-loop plugin runs a Ralph loop inside one session, the simplest form of loop engineering.
4. Get a desktop notification when Claude needs you
"Notification": [
{
"matcher": "permission_prompt|idle_prompt",
"hooks": [
{ "type": "command", "command": "notify-send 'Claude Code' 'Claude is waiting for you'" }
]
}
]
On macOS, run osascript -e 'display notification "Claude is waiting for you" with title "Claude Code"' from a script instead, which avoids escaping quotes inside the JSON. The permission_prompt and idle_prompt matchers fire when Claude needs approval or has been waiting for input.
5. Give Claude project context at session start
"SessionStart": [
{
"matcher": "startup|resume",
"hooks": [
{ "type": "command", "command": "git log --oneline -10 && git status --short" }
]
}
]
On SessionStart, plain text printed to stdout is added to Claude's context. Claude starts the session knowing the last ten commits and the uncommitted files, without spending a tool call to find out.
Hooks vs MCP vs skills vs CLAUDE.md
Use hooks for what must always happen, MCP for what the agent should be able to ask, skills for procedures it loads on demand, and CLAUDE.md for standing facts.
| Runs when | Deterministic? | Best for | |
|---|---|---|---|
| Hooks | At a fixed event, every time | Yes | Guardrails, formatting, tests, injected facts |
| MCP servers | When the model calls a tool | No, the model decides | Questions about code, data or external systems |
| Skills | When the model loads one for a task | No | Multi-step procedures and their scripts |
CLAUDE.md | Loaded at session start | Always loaded, followed as advice | Build commands, conventions, project facts |
Scroll the table sideways to see every column.
They combine well. A CLAUDE.md line tells Claude to call an MCP tool before grepping. A hook adds the same context after a grep when Claude skipped the tool. For what to put in the instruction file, see the CLAUDE.md and AGENTS.md guide. For why the tool call gets skipped, see your MCP server is probably not being called.
Codex hooks
Codex CLI supports hooks with the same three-level shape as Claude Code, and they are on by default. Per the Codex hooks docs, the events are SessionStart, SessionEnd, SubagentStart, SubagentStop, PreToolUse, PermissionRequest, PostToolUse, PreModelRequest, PostModelRequest, PreCompact, PostCompact, UserPromptSubmit, Stop and Interrupt.
Codex reads hooks from hooks.json in $CODEX_HOME (user), .codex/hooks.json (trusted project) or a system path, or inline under [hooks] in config.toml. Set hooks = false under [features] to turn them off. Codex has no Read, Grep or Glob tools, so most useful Codex hooks match its shell tool, which the hook matcher names Bash.
How repowise uses hooks: context before the agent asks
repowise installs Claude Code and Codex hooks that add codebase context at the moment the agent searches, reads or edits, so it gets the graph without having to ask for it. Every repowise hook reads only the local index and git, makes no LLM or network calls, and exits 0 on any failure, so it never blocks the agent.
repowise init writes these into ~/.claude/settings.json, keeping any hooks you already have (the PreToolUse rewrite is on by default: init asks with Yes preselected, --no-distill-hook skips it, and repowise hook rewrite install adds it later):
| Event | Matcher | What the agent gets |
|---|---|---|
SessionStart | startup|resume|clear | A line when the index is behind HEAD, with the changed-file count; silent when current |
PostToolUse | Grep|Glob|Read|Edit|Write and repowise MCP calls | Symbols, importers, dependencies and git signals for searched files; notices on stale reads; governing decisions and bug history on edit |
PostToolUseFailure | Read|Edit|Write|Grep|Glob|NotebookEdit | The real path when a guessed path does not exist and exactly one indexed file has that name |
PreToolUse | Bash|PowerShell | Noisy commands rewritten to repowise distill <cmd>, which trims output and keeps every error line |
Scroll the table sideways to see every column.
After a broad grep, the agent sees this next to the results:
[repowise] 2 related file(s) found:
src/billing/invoice_service.py
Symbols: class:InvoiceService, method:__init__, function:_now_iso
Imported by: api/routes.py, jobs/reconcile.py
Depends on: models.py, tax.py
Git: HOTSPOT, bus-factor=1, owner=alice
The distill rewrite cuts an npm ci log by 99.5%. For Codex, repowise init --codex writes .codex/hooks.json with a SessionStart note and PostToolUse checks that flag stale context after a commit, merge or pull. repowise hook stats reports how often each hook fired and whether the agent acted on it, from your own local transcripts.
The full list is in the hooks docs, and repowise for Claude Code shows the hooks working with the MCP tools. For the broader practice these hooks belong to, read what is context engineering.
FAQ
- What is the primary purpose of hooks in Claude Code?
- Hooks make behavior deterministic. They run your command, HTTP call or prompt at a fixed point in the session, such as before a tool call or when Claude stops, every time, so formatting, guardrails and checks happen whether or not the model remembers to do them.
- What is a Stop hook?
- A Stop hook runs when Claude finishes responding. It can return
{"decision": "block", "reason": "..."}or exit 2 to send Claude back to work, for example when tests fail. Check thestop_hook_activeinput field so the hook does not loop on a failure Claude cannot fix. - Can a hook block a tool call?
- Yes. A
PreToolUsehook blocks a call by exiting with code 2, with the reason on stderr, or by returning JSON withpermissionDecision: "deny"insidehookSpecificOutput. It can also returnaskto show the user a prompt, orallowto skip the prompt. - Are hooks the same as skills?
- No. A hook runs automatically at a lifecycle event and the model has no say in it. A skill is a set of instructions and files the model chooses to load when a task calls for it. Skills can declare their own hooks in frontmatter, which run only while the skill is active.
- Does Codex support hooks?
- Yes. Codex CLI runs hooks from
hooks.jsonor the[hooks]table inconfig.toml, with events includingSessionStart,PreToolUse,PostToolUse,UserPromptSubmitandStop. Hooks are enabled by default, and project hooks live in.codex/hooks.json.



