Claude Code Hooks: Events, Config and 5 Copy-Paste Examples

Raghav Chamadiya10 min read
On this page

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:

TypeWhat it does
commandRuns a shell command; the event JSON arrives on stdin
httpPOSTs the event JSON to a URL
mcp_toolCalls a tool on a configured MCP server
promptSends a single-turn prompt to a model to judge the event
agentSpawns 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.

EventFiresCan block?Typical use
SessionStartWhen a session starts or resumes (matchers startup, resume, clear, compact)NoLoad project context, check environment
UserPromptSubmitWhen you submit a prompt, before Claude sees itYesAdd context, reject prompts that leak secrets
PreToolUseBefore a tool call runsYesBlock dangerous commands, protect paths, rewrite input
PermissionRequestWhen a tool call needs a permission decisionYes, through a decision objectAuto-approve or deny known calls
PostToolUseAfter a tool call succeedsNo (can add feedback)Format, lint, add context to the result
PostToolUseFailureAfter a tool call failsNoExplain the failure, suggest a fix
NotificationWhen Claude Code sends a notificationNoDesktop alert when Claude needs input
SubagentStart / SubagentStopWhen a subagent is spawned / finishesSubagentStop: yesCheck a subagent's result
StopWhen Claude finishes respondingYesRun tests, keep Claude working until they pass
PreCompact / PostCompactAround context compactionPreCompact: yesSteer what the summary keeps
SessionEndWhen a session endsNoCleanup, 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.

json
{
  "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.

FileScopeShared with the team?
~/.claude/settings.jsonAll your projectsNo
.claude/settings.jsonThis projectYes, committed
.claude/settings.local.jsonThis projectNo, gitignored
Managed policy settingsOrganizationYes, set by admins
Plugin hooks/hooks.jsonWhile the plugin is enabledYes
Skill or subagent frontmatterWhile that skill or subagent is activeYes

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 codeEffect
0Success. JSON on stdout is applied; plain text becomes context on SessionStart and UserPromptSubmit
2Blocking error. On events that can block, the action stops and stderr is the reason Claude sees
OtherNon-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

json
"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

json
"PreToolUse": [
  {
    "matcher": "Edit|Write",
    "hooks": [
      { "type": "command", "command": "${CLAUDE_PROJECT_DIR}/.claude/hooks/protect-paths.sh" }
    ]
  }
]
bash
#!/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

json
"Stop": [
  {
    "hooks": [
      { "type": "command", "command": "${CLAUDE_PROJECT_DIR}/.claude/hooks/tests-pass.sh", "timeout": 300 }
    ]
  }
]
bash
#!/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

json
"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

json
"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 whenDeterministic?Best for
HooksAt a fixed event, every timeYesGuardrails, formatting, tests, injected facts
MCP serversWhen the model calls a toolNo, the model decidesQuestions about code, data or external systems
SkillsWhen the model loads one for a taskNoMulti-step procedures and their scripts
CLAUDE.mdLoaded at session startAlways loaded, followed as adviceBuild 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):

EventMatcherWhat the agent gets
SessionStartstartup|resume|clearA line when the index is behind HEAD, with the changed-file count; silent when current
PostToolUseGrep|Glob|Read|Edit|Write and repowise MCP callsSymbols, importers, dependencies and git signals for searched files; notices on stale reads; governing decisions and bug history on edit
PostToolUseFailureRead|Edit|Write|Grep|Glob|NotebookEditThe real path when a guessed path does not exist and exactly one indexed file has that name
PreToolUseBash|PowerShellNoisy 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:

text
[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 the stop_hook_active input field so the hook does not loop on a failure Claude cannot fix.
Can a hook block a tool call?
Yes. A PreToolUse hook blocks a call by exiting with code 2, with the reason on stderr, or by returning JSON with permissionDecision: "deny" inside hookSpecificOutput. It can also return ask to show the user a prompt, or allow to 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.json or the [hooks] table in config.toml, with events including SessionStart, PreToolUse, PostToolUse, UserPromptSubmit and Stop. Hooks are enabled by default, and project hooks live in .codex/hooks.json.