The short version
  • A hook is a script Claude Code runs at a fixed moment in a session. The model does not decide whether it runs. That is the whole point.
  • Configuration is three levels deep: an event, a matcher that filters it, and one or more handlers. It lives in a settings file, most often ~/.claude/settings.json or .claude/settings.json.
  • The handler gets JSON on stdin and answers with an exit code. Exit 0 lets the action continue. Exit 2 blocks it, on events that can block, and sends your stderr to Claude as the reason.
  • Rules in CLAUDE.md are requests. Hooks are enforcement. We moved one git rule from the first to the second after it failed twice.
  • Hooks fail in two directions: they block too much, or they match text that was never a command. Test them by piping sample JSON before you trust them.
  • A command hook runs with your full user permissions. Read any hook before you install it, including ones that arrive in a repository.

We had a rule written down: in a checkout shared by several Claude Code sessions, never stage everything, and name your files when you commit. It was in memory, it was in the instructions, and on 10 November a commit still swept in five files another session had staged seconds earlier. That day the rule became a Claude Code hook. A commit like that is now refused before it runs.

This guide teaches hooks from the ground up: the lifecycle, the configuration format, what a hook receives and how it replies, then the real guard we run, simplified, with the ways it can go wrong. Facts about Claude Code come from the documentation as fetched in November 2026. The guard and its history are ours. For where hooks sit among the other building blocks, see AI agents explained.

What Claude Code hooks are

A hook is a handler that Claude Code runs when a session reaches a particular event. The hooks reference lists five handler types as of November 2026:

  • command runs a shell command. This is the one most people mean.
  • http sends the event as a POST request to a URL.
  • mcp_tool calls a tool on a configured MCP server.
  • prompt sends a prompt to a Claude model for a single-turn decision.
  • agent starts a subagent that can read files before deciding. The reference marks this type as experimental.

The property that matters is who is in charge. Instructions in CLAUDE.md and skills are read by the model, which then decides what to do. A hook is executed by the harness around the model. Anthropic's own feature overview puts it plainly: an instruction like "never edit .env" in CLAUDE.md or a skill "is a request, not a guarantee. A PreToolUse hook that blocks the edit is enforcement."

Hooks also cost no context unless they return output.

The hooks lifecycle

Events fire at three cadences. Some fire once per session, some once per turn, and some on every tool call inside the loop where Claude is working.

SessionStartUserPromptSubmitcan blockPreToolUsecan blocktool runsBash, Edit, an MCPtool…PostToolUsethe tool already ranStopkeeps Claude workingcan blockSessionEnd
The main hook events in order. PreToolUse and PostToolUse fire on every tool call. From the hooks reference.
Event When it fires Can it block?
SessionStart A session begins or resumes No
UserPromptSubmit You submit a prompt, before Claude sees it Yes
PreToolUse Before a tool call executes Yes
PermissionRequest A tool call needs a permission decision Through JSON, not exit code
PostToolUse After a tool call succeeds No; the tool already ran
Notification Claude Code sends a notification, such as waiting for input No
SubagentStart / SubagentStop A subagent is spawned or finishes Stop only
Stop Claude finishes responding Yes; it keeps Claude working
PreCompact Before context compaction Yes
SessionEnd The session terminates No

That table is the working set. The full list in the reference has 33 events as of November 2026, including Setup, InstructionsLoaded, UserPromptExpansion, PostToolUseFailure, PostToolBatch, PermissionDenied, TaskCreated, TaskCompleted, StopFailure, TeammateIdle, ConfigChange, CwdChanged, DirectoryAdded, FileChanged, WorktreeCreate, WorktreeRemove, PostCompact, PreModelSwitch, PostModelSwitch, MessageDisplay, Elicitation and ElicitationResult.

Two details from the reference save real debugging time:

  • PreToolUse only fires when Claude calls a tool. A file you reference with @ in your prompt is inserted while the prompt is built, with no tool call, so a hook matching Read never sees it. A Read deny rule in permissions covers that case.
  • Stop fires whenever Claude finishes responding, not only when a task is complete. A Stop hook that always blocks will loop. Claude Code overrides one after eight consecutive blocks, and the input includes a stop_hook_active field so your script can step aside.

Hooks from settings files also run inside subagents. When a subagent calls a tool, the same PreToolUse hooks fire, and the input carries agent_id and agent_type so the script can tell who is asking. If you delegate work to subagents, your guard goes with them.

Where hooks are configured

Hooks are defined in JSON settings files. The location sets the scope:

Location Scope
~/.claude/settings.json All your projects, this machine only
.claude/settings.json One project; can be committed and shared
.claude/settings.local.json One project, not shared
Managed policy settings Organisation-wide
A plugin's hooks/hooks.json Wherever the plugin is enabled
Skill or subagent frontmatter While that skill or subagent is active

Entries merge across those levels. A project hook does not replace your user hook; both run.

The structure has three levels: the event, a matcher group, and the handlers.

{
  "hooks": {
    "PreToolUse": [
      {
        "matcher": "Bash",
        "hooks": [
          {
            "type": "command",
            "command": "python3 ~/.claude/hooks/git-guard.py",
            "timeout": 10
          }
        ]
      }
    ]
  }
}

That is the block in our own user settings, with the script renamed. A second event is added as a sibling key inside the same hooks object.

Matcher syntax. What the matcher filters depends on the event. For tool events it is the tool name; for SessionStart it is how the session started (startup, resume, clear, compact); for Notification it is the notification type. The value is read one of three ways:

  • "*", an empty string, or no matcher: match everything.
  • Only letters, digits, underscores, hyphens, spaces, commas and pipes: an exact name or a list of exact names. Bash matches the Bash tool. Edit|Write matches either.
  • Anything else: an unanchored JavaScript regular expression. mcp__memory__.* matches every tool from one MCP server. Because it is unanchored, Edit.* also matches NotebookEdit; write ^Edit$ when you mean the whole name.

Matchers are case-sensitive. There is a second, finer filter: a handler's if field takes one permission rule, such as "Bash(git *)", and the handler only runs when the tool call matches it.

A minimal hook

Start with one that cannot hurt anything. This is the first example in Anthropic's hooks guide: a desktop notification on macOS when Claude is waiting for you.

  1. Open ~/.claude/settings.json (create it if it does not exist) and add:
{
  "hooks": {
    "Notification": [
      {
        "matcher": "",
        "hooks": [
          {
            "type": "command",
            "command": "osascript -e 'display notification \"Claude Code needs your attention\" with title \"Claude Code\"'"
          }
        ]
      }
    ]
  }
}
  1. In Claude Code, type /hooks. It opens a read-only browser of configured hooks, labelled by where each comes from. Your hook should be listed under Notification.
  2. Ask Claude for something that needs permission, switch windows, and wait for the alert.

Edits to settings files are normally picked up by a file watcher without a restart. If /hooks shows nothing, the usual causes are invalid JSON (trailing commas and comments are not allowed) or the wrong file.

What a hook receives, and how it answers

A command hook gets one JSON object on stdin. For a PreToolUse event on a Bash command, the reference shows this:

{
  "session_id": "abc123",
  "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",
    "timeout": 120000,
    "run_in_background": false
  },
  "tool_use_id": "toolu_01ABC123..."
}

session_id, transcript_path, cwd and hook_event_name are common to every event. tool_name and tool_input are specific to tool events. The reference lists a few more fields.

The answer is the exit code:

  • Exit 0 is success. The action goes ahead. If the hook printed a JSON object to stdout, Claude Code applies its fields.
  • Exit 2 is a blocking error. On events that can block, the action stops. For PreToolUse, the tool call is blocked and whatever you wrote to stderr is shown to Claude as the reason.
  • Any other exit code is a non-blocking error. The action goes ahead and you see a hook error notice in the transcript.

Read that third line twice. A guard that crashes with exit 1 does not guard anything. The reference documents an onFailure option for hooks whose failure should block, and it is worth reading before you rely on a guard that could crash.

For finer control, a PreToolUse hook can exit 0 and print JSON instead:

{
  "hookSpecificOutput": {
    "hookEventName": "PreToolUse",
    "permissionDecision": "deny",
    "permissionDecisionReason": "Destructive command blocked by hook"
  }
}

permissionDecision takes allow, deny, ask or defer. When several hooks disagree, the order of precedence is deny, then defer, then ask, then allow. Two limits are worth knowing. A hook's allow does not override deny rules in your settings. And a hook's deny holds in every permission mode, including bypass mode, because PreToolUse fires before any permission-mode check.

A worked guard: one checkout, several sessions

Here is the situation the guard exists for. We often run more than one Claude Code session against the same working tree. Two sessions in one checkout share the branch, the working files and the git index. Habits that are safe alone become destructive.

It went wrong twice. In August, on our own site's repository, a git add -A in one session swept another session's uncommitted template and build-script changes into a commit, which then merged and deployed unreviewed. In November, in a client application's repository, a plain git commit took five files another session had staged between the first session's add and its commit. That one was caught and undone with a soft reset.

The rule that prevents both is simple: never stage everything, and commit with git commit --only -- <paths>, which commits just the named paths and leaves the rest of the index alone. The rule existed in writing before the second incident. So we stopped relying on it being read.

The hook is the PreToolUse block shown earlier, pointing at a Python script. This is a simplified version of that script, with the client's path replaced. We ran this exact version against sample input before publishing it.

#!/usr/bin/env python3
"""PreToolUse guard for Bash. In one shared checkout, a commit must name
its own files and nothing may stage everything."""
import json
import os
import re
import shlex
import sys

SCOPE = os.path.expanduser("~/work/shared-app")

def strip_heredocs(command):
    # A heredoc body (a commit message, a script) is data, not commands.
    out, lines, i = [], command.split("\n"), 0
    while i < len(lines):
        out.append(lines[i])
        for _, tag in re.findall(r"<<-?\s*(['\"]?)(\w+)\1", lines[i]):
            i += 1
            while i < len(lines) and lines[i].strip() != tag:
                i += 1
        i += 1
    return "\n".join(out)

def problem(tokens):
    if len(tokens) < 2 or os.path.basename(tokens[0]) != "git":
        return None
    sub, args = tokens[1], tokens[2:]
    if sub == "add" and any(a in ("-A", "--all", "-u", "--update", ".") for a in args):
        return "git add -A/-u/. stages other sessions' work: add each path by name"
    if sub == "commit":
        paths = args[args.index("--") + 1:] if "--" in args else []
        if "--only" not in args or not paths:
            return "a commit here names its files: git commit --only -- <paths>"
    return None

def main():
    try:
        data = json.load(sys.stdin)
    except ValueError:
        return 0  # unreadable input: stay out of the way
    command = (data.get("tool_input") or {}).get("command") or ""
    if "git" not in command or not (data.get("cwd") or "").startswith(SCOPE):
        return 0
    for part in re.split(r"&&|\|\||;|\||\n", strip_heredocs(command)):
        try:
            tokens = shlex.split(part, comments=True)
        except ValueError:
            tokens = part.split()
        reason = problem(tokens)
        if reason:
            print(f"Blocked by git-guard.py: {reason}.", file=sys.stderr)
            return 2
    return 0

if __name__ == "__main__":
    sys.exit(main())

How it works, in order:

  1. Read the event. One JSON object from stdin. If it cannot be parsed, exit 0 and let the call through.
  2. Get out of the way fast. If the command does not mention git, or the session's working directory is not inside the shared checkout, exit 0. This script runs before every Bash call in every project, so the cheap exit comes first.
  3. Drop heredoc bodies. More on this below.
  4. Split the command line on &&, ||, ;, pipes and newlines, and tokenise each piece the way a shell would.
  5. Judge each git call. Staging everything is refused. A commit without --only and without paths after -- is refused.
  6. Exit 2 with a reason. The stderr line goes to Claude, which reads it and retries with the correct command. The message says what to do, not just what was wrong.

The production script does more: it skips environment assignments and git's own options such as -C <dir> before finding the subcommand, catches git commit -a inside combined short flags, and also applies when a command names the project from another directory.

Test a hook the way the hooks guide suggests, by piping JSON into it:

echo '{"cwd":"'$HOME'/work/shared-app","tool_input":{"command":"git add -A"}}' \
  | python3 ~/.claude/hooks/git-guard.py; echo "exit=$?"

That prints the block message and exit=2. The same command with a cwd elsewhere prints exit=0.

the guard above, fed the JSON a PreToolUse hook receives# cwd ~/work/shared-app$ git add -ABlocked by git-guard.py: git add -A/-u/. stages other sessions' work: add each path by name.exit=2# cwd ~/work/shared-app$ git commit -m "wip"Blocked by git-guard.py: a commit here names its files: git commit --only -- <paths>.exit=2# cwd ~/work/shared-app$ git commit --only -m "Fix footer" -- src/footer.cssexit=0# cwd ~/work/other-repo$ git add -Aexit=0
Real run of the script above, 18 November 2026. Exit 2 blocks the call and the message goes to Claude.

Failure modes

A guard on every shell command is a sharp tool. These are the ways it goes wrong.

Heredoc bodies tripping the pattern. A commit message is often passed as a heredoc, and a commit message can say anything. Suppose the message reads "never run git add -A here; git commit -a". Without the strip_heredocs step, the script splits on the newline and the semicolon, finds a line fragment that starts with git commit -a, and blocks a perfectly good commit because of its own description. A heredoc body is data. Strip it before you look for commands.

Blocking too much. The quick version of this guard is if "git add" in command: exit 2. It blocks git add src/page.html, it blocks echo "use git add carefully", and it blocks every other repository on the machine. Three habits keep a guard narrow: scope it to a directory, parse tokens instead of matching substrings, and give the reason and the fix in the message so the model is not left guessing. Our production script has one deliberate over-reach we accept: it also triggers when a command merely mentions the project's name, so a command run from another directory is still covered. The price is the occasional false match.

Failing open without noticing. Exit 1 is not a block. An uncaught exception in Python exits 1, the tool call proceeds, and the only sign is an error notice in the transcript. Decide on purpose what your guard does with input it cannot read.

Slow hooks. A PreToolUse hook on Bash runs before every shell command. The default timeout for a command hook is 600 seconds as of November 2026. We set ours to 10, and the script exits in its first few lines for anything that is not git.

Someone else's hooks. Command hooks run with your full user permissions. In an interactive session, Claude Code holds back settings-file hooks until you accept the workspace trust dialog. In claude -p and SDK runs there is no dialog, and the reference says hooks committed in a repository's .claude/settings.json run in a folder you have never trusted. Before scripting Claude over a repository you did not write, read its .claude/ folder, or pass --settings '{"disableAllHooks": true}' for that run.

Hooks you cannot see firing. Run claude --debug and read the log at ~/.claude/debug/<session-id>.txt. It records each hook's output and how the run ended.

Hooks vs skills, and what belongs where

A quick sort, because the features overlap in what they seem to promise:

  • It must happen every time, and it is mechanical → a hook. Formatting, logging, refusing a command, a notification.
  • It needs judgement about the task → a skill. A review checklist, a deploy procedure, a house style.
  • It is a standing fact about the project → CLAUDE.md. Where things live, which command runs the tests.
  • It is a flat ban on a tool or a path → a permission deny rule. No script needed.
  • It is a check Claude should pass before stopping → a Stop hook that exits 2 until the typecheck or test suite is clean. Anthropic's best practices page has an example.

Our own count is modest: one hook, on one event, for one rule that had already failed twice as prose. That is the right order. Write the rule down first. When it is broken at a cost, and a script can check it, promote it to a hook. We compare the three mechanisms side by side in Claude Code skills vs subagents vs hooks, and the same thinking shapes the scheduled agents we describe in building a daily SEO audit agent.

The takeaway for Claude Code hooks: anything you have told an agent twice is a candidate, and anything that cost you a deploy is overdue. If you are putting agents to work in a business and want the guardrails built in from the start, that is part of our AI integration work. Tell us what the agent must never do.

Common questions

What are some Claude Code hooks examples?

The common ones: a Notification hook that sends a desktop alert when Claude is waiting for you; a PostToolUse hook on Edit and Write that runs a formatter on the changed file; a PreToolUse hook on Bash that refuses dangerous commands; a Stop hook that sends Claude back to work until the typecheck passes; and a SessionStart hook that injects context. Ours is a PreToolUse guard that refuses git add -A and any commit that does not name its files, in one checkout that several sessions share.

Where is the Claude Code hooks documentation?

Anthropic keeps two pages. The hooks guide at code.claude.com/docs/en/hooks-guide is the walkthrough, with a first hook and common recipes. The hooks reference at code.claude.com/docs/en/hooks is the full specification: every event, its input schema, matcher rules, exit-code behaviour and JSON output. Read the guide first, then keep the reference open while you write. Inside Claude Code, typing /hooks opens a read-only browser of the hooks you have configured and where each one comes from.

What are the main Claude Code hooks use cases?

Three kinds. Enforcement: rules that must hold every time, such as blocking edits to protected files or refusing a class of shell command. Automation: things that should happen after an action without anyone asking, such as formatting, logging or running tests. Awareness: notifications when Claude needs input or finishes. The shared test is that the action is mechanical. If it needs judgement about the task, it belongs in a skill or in CLAUDE.md, not a hook.

How does the Claude Code hooks lifecycle work?

Events fire at three cadences. SessionStart and SessionEnd fire once per session. UserPromptSubmit, Stop and StopFailure fire once per turn. PreToolUse and PostToolUse fire on every tool call inside the agentic loop. When an event fires, Claude Code checks each configured matcher, and for every match it runs the handler and passes it JSON describing the event. The handler answers with an exit code and optional JSON, and on events that can block, that answer decides whether the action goes ahead.

Is there a Claude Code hooks list of every event?

As of November 2026 the reference lists 33 events: SessionStart, Setup, InstructionsLoaded, UserPromptSubmit, UserPromptExpansion, MessageDisplay, PreToolUse, PermissionRequest, PermissionDenied, PostToolUse, PostToolUseFailure, PostToolBatch, Notification, SubagentStart, SubagentStop, TaskCreated, TaskCompleted, Stop, StopFailure, TeammateIdle, ConfigChange, CwdChanged, DirectoryAdded, FileChanged, WorktreeCreate, WorktreeRemove, PreCompact, PostCompact, PreModelSwitch, PostModelSwitch, Elicitation, ElicitationResult and SessionEnd. The list grows, so check the reference.

Claude Code hooks vs skills: when do I use each?

A hook is run by Claude Code itself at a lifecycle event. A skill is a set of instructions loaded into context for Claude to apply. Use a hook when the action must happen the same way every time and needs no thinking: format on save, refuse a command, send a notification. Use a skill when Claude needs to follow a procedure with judgement. An instruction in a skill or CLAUDE.md is a request. A PreToolUse hook that blocks the call is enforcement.

Can you give me Claude Code hooks explained simply?

A hook is a script you attach to a moment in a Claude Code session. You pick the moment (before a tool runs, after a file is edited, when Claude stops), optionally filter it (only the Bash tool), and name a command. Claude Code runs that command at that moment and hands it a JSON description of what is happening. The command can just do something, such as format a file, or it can exit with code 2 to stop the action and tell Claude why.