Claude Code Hooks Reference

Everything needed to write Claude Code hooks: where they live, every event and whether it can block, matchers and the if filter, the five handler types, input JSON, exit codes, JSON decision fields, how hooks interact with permissions, ready-to-use recipes, security and debugging.

On this page

Simple definition#

A hook is your own handler — a shell command, an HTTP endpoint, an MCP tool, or a model prompt — that Claude Code runs at a fixed point in its loop, such as before a tool call or when Claude tries to finish. Unlike CLAUDE.md, a command or HTTP hook is deterministic: the harness runs it every time, whatever the model decided. Hooks are how you make a rule hold with zero exceptions.

Anatomy of a hook#

Configuration has three levels: event → matcher group → handlers.

{
  "hooks": {
    "PreToolUse": [                                    // 1. event
      {
        "matcher": "Bash",                             // 2. matcher group: which tool
        "hooks": [                                     // 3. one or more handlers
          {
            "type": "command",
            "if": "Bash(rm *)",                        //    optional: one permission-rule filter
            "command": "${CLAUDE_PROJECT_DIR}/.claude/hooks/block-rm.sh",
            "args": [],
            "timeout": 30,
            "onFailure": "block"
          }
        ]
      }
    ]
  }
}

Your handler receives the event as JSON on stdin (or as the POST body for HTTP hooks) and answers with an exit code and optionally JSON on stdout. All matching handlers for an event run in parallel; an identical handler defined in several settings files runs once.

Where hooks live#

Location Scope Shared
~/.claude/settings.json All your projects No
.claude/settings.json This project Yes, committed
.claude/settings.local.json This project No (gitignored)
Managed settings Organisation Admin-controlled
Plugin hooks/hooks.json While the plugin is enabled With the plugin
Skill frontmatter (hooks:) Rest of the session once the skill runs With the skill
Sub-agent frontmatter While that sub-agent runs With the agent
  • Hooks merge across levels — your hooks add to managed ones, never remove them.
  • Hooks from settings and plugins also fire inside sub-agents (input carries agent_id, agent_type).
  • /hooks shows what’s configured; disableAllHooks: true turns off non-managed hooks.
  • Admins can allow only managed hooks (allowManagedHooksOnly) and restrict HTTP hook URLs (allowedHttpHookUrls).
  • Cloud sessions don’t read your ~/.claude/settings.json — commit project hooks you need there.

Events#

Cadence: per session (SessionStart, SessionEnd), per turn (UserPromptSubmit, Stop, StopFailure), and per tool call (PreToolUse, PostToolUse …).

Event Fires Exit 2 does Matcher filters
SessionStart Session begins or resumes — (stdout becomes context) startup, resume, clear, compact, fork
Setup --init-only, or -p with --init/--maintenance — init, maintenance
InstructionsLoaded A CLAUDE.md or rule file loads — Load reason: session_start, path_glob_match, compact …
UserPromptSubmit Before Claude sees your prompt Blocks the prompt —
UserPromptExpansion A typed command expands to a prompt Blocks the expansion Command name
PreToolUse Before a tool runs Blocks the call Tool name
PermissionRequest A permission decision is needed Not honoured — use JSON decision Tool name
PermissionDenied Auto mode denied a call — (JSON retry: true allows retry) Tool name
PostToolUse Tool succeeded Stderr shown to Claude Tool name
PostToolUseFailure Tool failed Stderr shown to Claude Tool name
PostToolBatch A batch of parallel calls resolved Stops the loop before the next model call —
SubagentStart / SubagentStop Sub-agent spawned / finishing — / Keeps it working Agent type
TaskCreated / TaskCompleted Task created / marked done Rolls back / prevents completion —
TeammateIdle Agent-team teammate about to go idle Keeps it working —
Stop Claude finishes responding Keeps Claude working —
StopFailure Turn ended by an API error Ignored Error type: rate_limit, overloaded, …
Notification Claude Code sends a notification Ignored permission_prompt, idle_prompt, …
MessageDisplay Assistant text displayed — (can change on-screen text only) —
PreCompact / PostCompact Around compaction Blocks compaction / — manual, auto
PreModelSwitch / PostModelSwitch Model change Blocks the switch / — Target model
ConfigChange A config file changes mid-session Blocks the change (except policy) user_settings, project_settings, skills …
CwdChanged, DirectoryAdded, FileChanged Directory or watched file changes — FileChanged: filenames, e.g. .envrc|.env
WorktreeCreate / WorktreeRemove Worktree created / removed Any non-zero exit fails it —
Elicitation / ElicitationResult MCP server asks for user input Declines / blocks the response MCP server name
SessionEnd Session terminates (1.5 s budget) — clear, logout, …

In the Exit 2 column, “—” means the hook can’t block; stderr is shown to the user or logged. In the Matcher column, “—” means the event has no matcher and always fires.

Matchers and the if filter#

Matcher Evaluated as Example
"*", "" or omitted Everything —
Letters, digits, _, -, spaces, ,, | only Exact names, | or , separated Edit|Write, Bash
Any other character Unanchored JavaScript regex mcp__github__.*, ^Notebook

Edit.* also matches NotebookEdit — anchor with ^Edit$ for a whole-name match.

The handler-level if holds exactly one permission rule ("Bash(git *)", "Edit(*.ts)") and only applies to tool events. For Bash it checks each subcommand, including those inside $() and backticks, and runs the hook anyway when it can’t tell. It is best-effort — use permission rules for hard allow and deny.

Handler types#

Type Runs Deterministic? Default timeout
command Shell command or executable (args = exec form, no shell) Yes 600 s (30 s on UserPromptSubmit and model-switch events)
http POST of the event JSON to a URL Yes 600 s
mcp_tool A tool on a configured MCP server Yes 600 s
prompt Single-turn model evaluation returning JSON No 30 s
agent Sub-agent that can Read/Grep/Glob before deciding (experimental) No 60 s

Useful fields: timeout, statusMessage, async (run in background), asyncRewake (background, wake Claude on exit 2), shell (bash or powershell), once (skill hooks only), onFailure: "continue" | "block".

Input#

Every event receives common fields plus event-specific ones:

{
  "session_id": "abc123",
  "prompt_id": "550e8400-…",
  "transcript_path": "/home/user/.claude/projects/…/transcript.jsonl",
  "cwd": "/home/user/my-project",
  "permission_mode": "default",
  "hook_event_name": "PreToolUse",
  "tool_name": "Bash",
  "tool_input": { "command": "npm test", "description": "Run test suite" },
  "tool_use_id": "toolu_01ABC…"
}

Also available: agent_id/agent_type inside sub-agents, effort.level on tool and stop events, last_assistant_message on Stop. Environment: $CLAUDE_PROJECT_DIR, ${CLAUDE_PLUGIN_ROOT} in plugins, $CLAUDE_ENV_FILE in SessionStart (append export lines to set env vars for later commands), $CLAUDE_CODE_REMOTE in cloud sessions. There is no $CLAUDE_MODEL; use PostModelSwitch to track the model.

Output: exit codes#

Exit Meaning Effect
0 Success JSON on stdout is applied; plain stdout is logged (and added as context on SessionStart, UserPromptSubmit, UserPromptExpansion, PostModelSwitch)
2 Blocking error Blocks on events that can block; stderr is the reason Claude sees. JSON can’t override the block
other Non-blocking error Action proceeds (unless onFailure: "block"); first stderr line shown as a notice

Choose one style per hook: exit codes alone, or exit 0 with JSON. Print only the JSON object to stdout — a shell profile that echoes text breaks parsing. additionalContext, systemMessage and plain stdout are capped at 10,000 characters each.

Output: JSON fields#

Field Where Does
continue: false + stopReason Any event Stop Claude entirely
systemMessage Any event Warning shown to the user
terminalSequence Any event Desktop notification, title or bell (allowlisted OSC sequences)
decision: "block" + reason UserPromptSubmit, PostToolUse, PostToolBatch, Stop, SubagentStop, ConfigChange, PreCompact … Block with feedback
hookSpecificOutput.permissionDecision PreToolUse allow, deny, ask, defer (+ permissionDecisionReason)
hookSpecificOutput.updatedInput PreToolUse Replace the tool’s whole input before it runs
hookSpecificOutput.updatedToolOutput PostToolUse Replace the tool’s result (redaction)
hookSpecificOutput.decision.behavior PermissionRequest allow or deny the prompt
hookSpecificOutput.additionalContext SessionStart, PreToolUse, Stop, … Text injected as a system reminder

When several PreToolUse hooks disagree: deny > defer > ask > allow.

Hooks and permissions#

How a tool call is decided: hooks, rules, mode · drawn with Archify · zoom, guided views, search and SVG/PNG export. © 2026 Samir Kumar Sahoo, all rights reserved. Open full screen ↗
  • PreToolUse hooks run before the permission prompt, for every tool.
  • A hook that exits 2 blocks even if an allow rule matches.
  • A hook returning "allow" does not bypass deny or ask rules — they are always evaluated. Hooks can tighten, never loosen.
  • A hook’s "deny" holds in every permission mode.

Recipes#

Format every edited file

{ "hooks": { "PostToolUse": [{ "matcher": "Edit|Write", "hooks": [{
  "type": "command",
  "command": "npx prettier --write --ignore-unknown \"$(jq -r '.tool_input.file_path')\"" }] }] } }

Don’t finish until the typecheck passes

{ "hooks": { "Stop": [{ "hooks": [{ "type": "command",
  "command": "pnpm tsc --noEmit 1>&2 || exit 2" }] }] } }

Claude Code overrides a Stop hook after 8 consecutive blocks with no tool call between (CLAUDE_CODE_STOP_HOOK_BLOCK_CAP).

Protect paths

#!/bin/bash
# .claude/hooks/protect.sh — PreToolUse on Edit|Write
path=$(jq -r '.tool_input.file_path // empty')
case "$path" in
  *migrations/*|*src/gen/*|*.env*) echo "Protected path: $path" >&2; exit 2 ;;
esac
exit 0

Re-inject key context after compaction

{ "hooks": { "SessionStart": [{ "matcher": "compact", "hooks": [{ "type": "command",
  "command": "echo 'Reminder: use Bun, not npm. Run bun test before committing.'; git log --oneline -5" }] }] } }

Desktop notification when Claude needs you

#!/bin/bash
# Notification hook
body=$(jq -r '.message // "Needs your attention"')
seq=$(printf '\033]777;notify;%s;%s\007' "Claude Code" "$body")
jq -nc --arg seq "$seq" '{terminalSequence: $seq}'

Rewrite a command before it runs (PreToolUse, exit 0):

{ "hookSpecificOutput": { "hookEventName": "PreToolUse", "permissionDecision": "allow",
  "updatedInput": { "command": "npm test -- --runInBand", "description": "Run tests serially" } } }

Audit configuration changes — a ConfigChange hook that appends the event JSON to a log, or exits 2 to block unapproved edits. Reload the environment on directory change — a CwdChanged hook running direnv export bash >> "$CLAUDE_ENV_FILE".

Security#

  • Command hooks run with your full user permissions. Review every hook before adding it.
  • Interactive sessions hold back settings-file hooks until you accept workspace trust for the folder. -p and SDK runs treat the folder as trusted — before scripting over a repository you didn’t write, review its .claude/, use --bare, or pass --settings '{"disableAllHooks": true}'.
  • Quote variables ("$VAR"), reject .. in paths, use absolute paths (${CLAUDE_PROJECT_DIR}), skip .env, .git/ and keys.
  • Prefer exec form (args) when passing paths — no shell quoting problems.
  • CLAUDE_CODE_SUBPROCESS_ENV_SCRUB=1 strips credentials from the environment of hooks, Bash and stdio MCP servers.

Debugging#

  • claude --debug (log at ~/.claude/debug/<session-id>.txt) or --debug-file <path>; search for your event name and Hooks: timing lines.
  • Ctrl+O transcript view shows hook notices.
  • Hook not firing: check the matcher (case-sensitive tool names), workspace trust, and /hooks.
  • JSON ignored: something else printed to stdout, or a field is at the wrong level (permissionDecision belongs inside hookSpecificOutput).
  • Stop loop: your check never passes — fix it, or the block cap ends the turn.

Common mistakes#

Review questions#

A PreToolUse hook returns "allow" for git push, but a project rule says ask: ["Bash(git push *)"]. What happens? The user is still prompted. Hooks can’t bypass deny or ask rules; they can only tighten.

Your secret-scanning hook crashes. Does the commit go through? Yes, by default — a crash is a non-blocking error. Set "onFailure": "block" so a failed hook blocks the action.

How does a Stop hook keep Claude working? It exits 2 (or returns decision: "block"); Claude Code feeds stderr or the reason back to Claude, which continues until the hook passes or the block cap is reached.

References#