Claude Code & Context Engineering

Claude Code Hooks by Event: The Complete Map and 3 Recipes Worth Automating

29 September 2026 · Updated 28 November 2026 · 14 min read · by Yang Kai

Every Claude Code hook event explained — all 34 events with what fires when, which ones can block, and what each returns — plus a working settings.json config and three recipes to copy.

Config inside: Complete 34-event hook map table and a combined settings.json config

Contents
  1. The short version
  2. How hooks work, in one paragraph
  3. The complete event map
  4. Reading notes the table cannot show
  5. Recipe 1: format on every edit (PostToolUse)
  6. Recipe 2: block the commands you never want run (PreToolUse)
  7. Recipe 3: get pinged when a long task needs you (Notification + Stop)
  8. A combined settings.json
  9. Choosing the right event: three questions
  10. How we researched this
  11. Verdict

Most automation ideas in Claude Code stall at the same question: “which event would that even be?” Hooks fire at 34 different points in a session, and picking the wrong one means a guard that runs too late or a notification that never arrives.

This is the complete map. Every event in Anthropic’s current hooks reference, grouped by when it fires, with the one column that decides most designs: whether the hook can block what is about to happen, or only watch it.

The map is built from Anthropic’s official hooks reference, checked in November 2026. If you want the opinionated shortlist first — the five hooks that catch real mistakes — read 5 Claude Code Hooks That Save You. This piece is the reference underneath it.

The short version

If you only ever use five events, use these:

Job Event Why this one
Prevent a bad action PreToolUse The only event that runs before a tool executes
Verify “done” means done Stop Fires once, when the agent tries to finish
React to finished work PostToolUse Runs after every tool call, with the result attached
Get your attention back Notification Fires when Claude Code is waiting on you
Load context at the start SessionStart Runs before the first prompt of a session

Everything else on the map is a refinement of one of those five jobs.

How hooks work, in one paragraph

A hook is a handler Claude Code runs automatically when a lifecycle event fires. Handlers come in five types: a shell command, an HTTP endpoint, an MCP tool call, a prompt evaluated by a model, or an agent that verifies a condition with tools. Hooks are configured in settings.json — at user level in ~/.claude/settings.json, per project in .claude/settings.json, and in a few other locations covered below. Each hook can be narrowed with a matcher that filters which tools or situations it applies to. Some events let a hook block the action, by exit code or by a JSON decision; others are observational only. That distinction — can this event stop the agent, or only watch? — is the most important column in the tables that follow.

The complete event map

The 34 events fall into four cadences. Tables list what fires when, whether a hook on that event can block, and the job each event is typically hired for.

Session events

These fire around the edges of a session: starting, ending, configuration and environment changes.

Event Fires when Can block? Typical use
SessionStart A session begins or resumes No — context only Load project status, set env vars for the session
Setup Claude Code starts with --init, --init-only, or --maintenance No One-time preparation in CI or scripts
InstructionsLoaded A CLAUDE.md or .claude/rules/*.md file loads into context No Log which instruction files are active
ConfigChange A configuration file changes mid-session Yes Stop an unwanted settings change from applying
CwdChanged The working directory changes No Reload env vars, activate per-directory toolchains
DirectoryAdded A directory is added via /add-dir or the SDK No Register the new directory with your tooling
FileChanged A watched file changes on disk (matcher names the files) No React to .envrc or config edits outside the session
WorktreeCreate A git worktree is being created Yes — replaces default behaviour Create worktrees your own way; the hook prints the path
WorktreeRemove A worktree the hook created is being removed Partly — a non-zero exit fails the removal Clean up whatever creation set up
SessionEnd A session terminates No Cleanup, session summary, metrics

Turn and prompt events

These fire once per turn, around your prompt and the agent’s attempt to finish.

Event Fires when Can block? Typical use
UserPromptSubmit You submit a prompt, before Claude processes it Yes Validate prompts, inject context alongside the prompt
UserPromptExpansion A typed command expands into a prompt Yes Veto or annotate a slash-command expansion
Stop The main agent finishes responding Yes Verify done criteria before allowing the stop
StopFailure The turn ends because of an API error No — output is discarded Log failed turns
PreCompact Before context compaction runs Yes Save state, or steer the summary with instructions
PostCompact After compaction completes No Note what was compacted
PreModelSwitch Before a requested model switch applies Yes Refuse a switch to the wrong model
PostModelSwitch After the session’s model changes No — context only Tell Claude what changed
MessageDisplay While assistant message text is displayed No — display only Rewrite what you see on screen, not the transcript

Tool events

These fire inside the agentic loop, around individual tool calls. This is where guards live.

Event Fires when Can block? Typical use
PreSkillShellCommand Before a skill’s injected shell command runs Yes — block only Vet commands a skill is about to inject
PreToolUse Before a tool call executes Yes Guard dangerous commands, protect files, rewrite inputs
PermissionRequest A tool call needs a permission decision Yes — by returned JSON only Auto-approve safe, known commands
PermissionDenied Auto mode denies a tool call No — can offer a retry Log denials, tell the model it may retry
PostToolUse After a tool call succeeds Feedback only Format code, run linters, attach notes to the result
PostToolUseFailure After a tool call fails Feedback only Log failures, add recovery context
PostToolBatch After a full batch of parallel tool calls resolves Yes Inject context that depends on the whole batch

Agent, team, and MCP events

These fire around subagents, agent teams, and MCP servers asking for human input.

Event Fires when Can block? Typical use
SubagentStart A subagent is spawned No — context only Brief the subagent with extra context
SubagentStop A subagent finishes Yes Review subagent output before accepting it
TaskCreated A task is being created via TaskCreate Yes Enforce task naming or content rules
TaskCompleted A task is being marked as completed Yes Keep a task open until its criteria are met
TeammateIdle An agent-team teammate is about to go idle Yes Hand the teammate more work instead
Notification Claude Code sends a notification No Desktop or sound alert when a long task waits
Elicitation An MCP server requests user input mid-tool-call Yes Pre-answer or decline routine MCP prompts
ElicitationResult After you respond to an elicitation, before it reaches the server Yes Redact or adjust responses to MCP servers

Reading notes the table cannot show

Four rows deserve a warning, because older guides — and older versions of this article — describe them differently.

PostToolUse cannot undo anything. The tool has already run. What it can do is talk back: a decision: "block" output attaches your reason next to the tool result so Claude sees the complaint, and updatedToolOutput can replace the result Claude reads. That is feedback with teeth, not prevention.

PreCompact can block. Several older references list it as observational. In the current docs it accepts a blocking decision, and any plain text it prints on stdout becomes instructions for the compaction summary — two different ways to protect state you do not want summarised away.

PermissionRequest ignores exit code 2. On most events, exit 2 is the blocking signal. On PermissionRequest, Claude Code does not read exit codes as decisions at all: your hook must return the JSON decision object with a behavior of allow or deny. A PermissionRequest guard that only exits 2 silently does nothing, which is the worst kind of guard. The mechanics of each event’s decision format are covered in the hooks deep dive.

SubagentStart cannot block. It can only add context for the subagent. If you need a gate on subagent work, it belongs at SubagentStop, or on the tool events the subagent itself triggers — hooks from your settings files also run inside subagents.

Recipe 1: format on every edit (PostToolUse)

The starter hook almost everyone keeps. After any file edit or write, run your formatter on just the changed file, so style drift never accumulates into a noisy diff later.

The matcher Edit|Write scopes it to file-changing tools. The command receives the tool input as JSON on stdin, and the file path sits in the tool_input.file_path field — there is no environment variable for it. A one-line command with jq is enough:

jq -r '.tool_input.file_path // empty' | xargs -r prettier --write

Registered as a PostToolUse command hook, that formats exactly the file that changed. Even a simpler version — format the whole project, if it is small — beats no formatter hook at all. Keep it fast and make it fail quietly: a formatter that errors should exit 0 anyway, because a cosmetic hook must never break a session’s flow. Guard hooks follow the opposite rule, which is the subject of the next recipe. For the permission settings that pair with guards like these, see Claude Code permissions and sandboxing.

Recipe 2: block the commands you never want run (PreToolUse)

Guardrails belong here, not in CLAUDE.md prose. A PreToolUse hook on the Bash tool inspects the proposed command and blocks anything on your personal danger list — recursive deletes outside the project, force pushes to main, piping remote scripts into a shell. The clean way to block with a reason is a JSON deny:

// block-dangerous.mjs — reads the payload on stdin, decides, answers
const input = JSON.parse(await readStdin());
const cmd = input.tool_input?.command ?? "";
if (/rm\s+-rf\s+\//.test(cmd) || /push\s+--force.*\bmain\b/.test(cmd)) {
  console.log(JSON.stringify({
    hookSpecificOutput: {
      hookEventName: "PreToolUse",
      permissionDecision: "deny",
      permissionDecisionReason:
        "Blocked by project hook: destructive command. Use a safer alternative or ask the user."
    }
  }));
}
process.exit(0);

Exit code 2 with the reason on stderr also blocks, and is fine for simple scripts. The JSON form is better when the reason matters, because the reason travels with the decision. Keep the danger list short and unambiguous either way: a guard that fires on legitimate work gets disabled within a week.

Recipe 3: get pinged when a long task needs you (Notification + Stop)

Pair a Notification hook that plays a sound or sends a desktop alert with a Stop hook that runs your build. The Notification matcher filters by notification type — permission_prompt fires when Claude Code has waited about six seconds for an approval, and idle_prompt after roughly 60 seconds of you not typing — so you can alert on one and ignore the other.

Together the pair changes how long you are willing to let tasks run unattended. The Notification hook solves “the agent finished twenty minutes ago and I never noticed.” The Stop hook solves “the agent said done but the build is red.” One caution from the docs: a blocking Stop hook receives a stop_hook_active flag in its input when Claude is already continuing because of a stop hook. Check it, or your verification hook can loop — Claude Code caps the loop at eight consecutive continuations, but a hook that reads the flag ends the loop politely on the first pass.

A combined settings.json

This config wires all three recipes plus a SessionStart status line. Paths assume helper scripts in ~/.claude/hooks/ — write those scripts to match your own formatter and danger list.

{
  "hooks": {
    "SessionStart": [
      {
        "hooks": [
          { "type": "command",
            "command": "~/.claude/hooks/session-status.sh" }
        ]
      }
    ],
    "PreToolUse": [
      {
        "matcher": "Bash",
        "hooks": [
          { "type": "command",
            "command": "~/.claude/hooks/block-dangerous.sh" }
        ]
      }
    ],
    "PostToolUse": [
      {
        "matcher": "Edit|Write",
        "hooks": [
          { "type": "command",
            "command": "~/.claude/hooks/format-changed.sh" }
        ]
      }
    ],
    "Stop": [
      {
        "hooks": [
          { "type": "command",
            "command": "~/.claude/hooks/verify-build.sh" }
        ]
      }
    ],
    "Notification": [
      {
        "hooks": [
          { "type": "command",
            "command": "~/.claude/hooks/notify.sh" }
        ]
      }
    ]
  }
}

Each script receives a JSON payload on stdin describing the event and, for tool events, the tool name and input. Two operational rules apply to every script in the config. Keep them fast — a slow PostToolUse hook taxes every single edit. And decide each hook’s failure posture in advance: observational hooks fail quietly, while a PreToolUse guard that cannot run should fail closed on the patterns it exists to block — the onFailure: "block" handler option exists for exactly that case.

Hooks can also live in .claude/settings.local.json (personal, per project), in managed policy settings, inside plugins, and in skill and subagent frontmatter, where they apply only while that skill or subagent runs. Entries merge across levels rather than replacing each other.

Choosing the right event: three questions

When an automation idea strikes, ask three questions. Does it need to prevent something? Then it must live at PreToolUse, PermissionRequest, Stop, or another event whose row in the map says it can block — nowhere else can. Does it react to finished work? PostToolUse, PostToolUseFailure, or SubagentStop. Does it serve you, the human, rather than the agent? Notification, SessionStart, or SessionEnd.

Ideas that answer none of the three are usually CLAUDE.md lines or skills wearing a hook costume — and forcing them into hooks makes them brittle. Static instructions belong in your CLAUDE.md setup; repeatable procedures belong in a skill; hooks are for the rules that must happen mechanically, at a named moment, whether or not the agent remembers them. For the judgement calls on which mistakes deserve that enforcement, the hooks that save you is the companion read, and if your guard hooks protect tool calls into external systems, the MCP security checklist covers the adjacent ground.

How we researched this

meetBlogging is a desk-research site. This map was compiled from Anthropic’s official Claude Code hooks reference and cross-checked against the settings and permissions documentation in November 2026; it is not a claim that every event has been exercised in production on this site. Hook behaviour changes between Claude Code releases — several events above carry minimum-version notes in the docs — so treat the official reference as the final word for the version you run.

Verdict

Print the table. The next automation idea you have will take thirty seconds to place, and placement was always the hard part. Start with the five events in the short version, add the recipes in order, and go deeper only when a logged incident justifies a new hook. When you are ready for the mechanics underneath the map — matchers, exit codes, JSON decisions, and debugging silent hooks — the hooks deep dive is the next read.

FAQ

How many hook events does Claude Code have? 34, as of November 2026: 10 session events, 9 turn and prompt events, 7 tool events, and 8 agent, team, and MCP events. The count grows between releases — events like PostToolBatch, PermissionDenied, and PreModelSwitch are recent additions — so check the official reference for your version.

What is the difference between Stop and PostToolUse? PostToolUse fires after every individual tool call — right for formatters and quick checks. Stop fires once, when the agent believes it is finished — right for the verification steps that prove the work is actually done.

Can a hook add context instead of blocking? Yes. SessionStart, UserPromptSubmit, and the tool events can all inject text Claude sees, via the additionalContext output field. SessionStart hooks can also persist environment variables for the session by writing export lines to the file named in $CLAUDE_ENV_FILE.

Which events cannot block anything? The observational set: SessionStart, Setup, SessionEnd, Notification, SubagentStart, StopFailure, PostCompact, InstructionsLoaded, CwdChanged, DirectoryAdded, FileChanged, and MessageDisplay. Use them for logging, alerts, cleanup, and context — never for enforcement.

Why is my hook not firing? In order of likelihood: a JSON error in settings.json, a matcher that does not match the tool name’s capitalisation, or the hook sitting in the wrong settings file. Add a one-line logging hook and prove the event fires before debugging your script — the method is walked through in the hooks deep dive.

Category: Claude Code & Context Engineering · Tags: #claude-code #hooks #automation #ai-coding

Next step: this article is part of Claude Code guides, which covers the full topic from first setup to advanced use.

Related guides