Skip to main content

Hooks

You wrote “always run the formatter” in CLAUDE.md. The agent did it nine times out of ten. The tenth time, it didn’t, and you found out in code review.

A sentence in an instruction file is a request. A hook is code. It runs every time, whether the model remembers or not. Hooks exist in Claude Code, and Codex’s hooks were modeled on them: same basic contract, with differences in trust, caps, and some events.

What hooks are

A hook runs deterministic code at a lifecycle event: a set point in an agent’s work, like “a session just started” or “a tool is about to run.” It can return feedback at that event. It cannot enforce paths that never pass through it.

Hooks are best for “whenever this event happens, do this specific thing.” They’re usually the wrong choice for “figure out what work needs doing and manage it.”

Good fits:

  • Blocking writes to protected branches.
  • Validating tool inputs.
  • Formatting an edited file.
  • Recording a bounded handoff: a short, size-capped note, like a progress file, for the next session to pick up from.
  • Requiring fresh evidence before completion.

A few of the events you’ll see throughout this course:

  • SessionStart: A session (one conversation, from launch until you exit) begins.
  • PreToolUse: A tool call, like reading a file or running a shell command, is about to run. The hook can block it.
  • PostToolUse: A tool just ran. Too late to block, but good for feedback and cleanup.
  • UserPromptSubmit: You just submitted a prompt. A hook can add context alongside it, but can’t replace it.
  • PermissionRequest: The agent is waiting for you to approve something.
  • Stop: The agent is about to finish a turn (one round of responding, possibly running several tools) and wait for you.
  • SubagentStop: A subagent (a helper agent with fresh context that returns only a final report) is about to finish.

There are more, including TaskCreated, TaskCompleted, and TeammateIdle for agent teams, and PreCompact and PostCompact around compaction. The hooks reference lists them all.

A caveat from someone who’s used them

Almost every time I’ve decided to use hooks, I’ve eventually ripped them out because they were more annoying than helpful.

The data disagrees with me a little. When I had agents audit my own sessions, the problems I fixed with a hook or a script stayed fixed, and the ones I fixed with a sentence in CLAUDE.md didn’t.

So here’s where I’ve landed: keep enforcement hooks for the handful of rules that have to hold every single time, and use The Enforcement Ladder to decide which rules those are. Lightweight hooks, like a formatter, a notification, or a context loader, are fine too, because nothing depends on them holding.

How hooks work

The contract is refreshingly boring. The harness sends event JSON to your script on stdin, and your exit code does the talking:

  • Exit 0: “No objection.” That’s not the same as approval. Permission rules still get the final say.
  • Exit 2: Block, where the event supports blocking. Whatever you wrote to stderr goes to Claude, so tell it why.
  • Anything else: A non-blocking error, by default. The action proceeds, so a hook that crashes with exit 1 doesn’t stop anything unless you set "onFailure": "block" on the hook. The Enforcement Ladder has a story about how that one goes.

The other way to block on purpose is to print a JSON decision to stdout and exit 0. Exit 2 is simpler for a quick block with a message. Use JSON when you want more control, like asking you instead of denying, or having a PreToolUse hook rewrite the tool’s input with an updatedInput field.

There’s also a safety net for the accidental case. Set "onFailure": "block" on a command, http, or mcp_tool hook (Claude Code v2.1.295 or later, v2.1.328 for mcp_tool) and a hook that can’t start, times out, or exits with anything other than 0 or 2 blocks the action instead of waving it through. It has no effect on Stop, SubagentStop, TaskCompleted, or TeammateIdle hooks.

Some details that will save you an afternoon:

  • Decision fields differ per event: PreToolUse takes {"hookSpecificOutput": {"hookEventName": "PreToolUse", "permissionDecision": "deny", "permissionDecisionReason": "..."}}. Stop and SubagentStop take {"decision": "block", "reason": "..."}. PermissionRequest uses hookSpecificOutput.decision.behavior. JSON shaped for the wrong event does nothing, silently.
  • Not every event can block: PostToolUse can’t, because the tool already ran. SessionStart can’t either. Exiting 2 there doesn’t stop the session.
  • Matchers only see what they match: A matcher is the pattern that decides which tool calls trigger a hook. An Edit|Write matcher misses writes made through Bash. And PreToolUse doesn’t fire at all for the shell commands a skill injects while it loads. Those get their own event, PreSkillShellCommand (Claude Code v2.1.332 or later). The general filesystem backstop is a repository scan on Stop: it detects after the fact and can refuse to let the agent finish until the problem is fixed.
  • FileChanged reports, it doesn’t guard: It only fires for explicitly watched files and can’t block changes. Its matcher registers literal filenames in the working directory, separated by |, so * registers a file literally named *, not every file. For dynamic paths, return absolute watchPaths from a SessionStart, CwdChanged, or FileChanged hook and omit the FileChanged matcher to handle every watched file. The FileChanged reference describes how to seed and update that watch list.
  • Use command handlers for invariants: A handler is what runs when the hook fires. A command handler runs a program you wrote. prompt (asks a model), agent (runs an agent), http (calls a URL), and mcp_tool (calls a tool on an MCP server) handlers are fine for advice or a central policy, but they aren’t deterministic gates. (An MCP server is a program that adds tools to the harness over the Model Context Protocol.)
  • Injected output is capped: Each string a hook injects into the model’s context tops out at 10,000 characters. Go over, and Claude gets a file path and a preview of the first 2,000 characters instead. Nothing tells it to read the file.

Configuring hooks

Each event holds matcher groups, and each group holds handlers. A command handler has a type, a command, and a timeout in seconds. Most command hooks default to 600 seconds, but UserPromptSubmit, PreModelSwitch, and PostModelSwitch default to 30, MessageDisplay defaults to 10, and SessionEnd defaults to 1.5 with a shared execution budget. A timeout can cancel the hook before it returns its decision, so check the event in the hooks reference and set an explicit timeout that fits the work.

Here’s a minimal one, under the hooks key of .claude/settings.json, that runs a script before every Bash call:

{
  "hooks": {
    "PreToolUse": [
      {
        "matcher": "Bash",
        "hooks": [
          {
            "type": "command",
            "command": "${CLAUDE_PROJECT_DIR}/.claude/hooks/allow-lint.sh",
            "args": [],
            "timeout": 10,
            "onFailure": "block"
          }
        ]
      }
    ]
  }
}

The absolute ${CLAUDE_PROJECT_DIR} path keeps the hook anchored to the launch project when Claude changes directories or enters a worktree. The JSON input’s cwd still says where the tool call will run. The empty args runs the script directly, with no shell in between to mangle the path. And onFailure covers what the script can’t: if it’s missing or it times out, the call is blocked.

Here’s a deliberately narrow script: it accepts only the exact command bun run lint. Everything else, including malformed event JSON or a missing jq, blocks with exit 2.

#!/bin/bash
if ! jq -e -s '
  length == 1 and
  (.[0] | type == "object" and
    .tool_name == "Bash" and
    .tool_input.command == "bun run lint")
' >/dev/null; then
  echo "Blocked: expected one Bash event for exactly bun run lint" >&2
  exit 2
fi
exit 0

This compares the whole command instead of parsing shell syntax, so bun run lint && rm -rf x, leading whitespace, and wrappers all fail. The lint script and the hook still have to be trusted: an exact command runs whatever that script contains. Before installing it, feed the hook valid and malformed events and verify both exits.

For ordinary command restrictions, use Claude Code’s documented compound-command matching instead of a homemade prefix test. A deny rule for Bash(rm *) catches cd /tmp && rm -rf x, but alternate invocations such as /bin/rm still need their own rules. Use sandbox filesystem controls when the boundary is what can be deleted, regardless of command spelling.

Hooks can live in a bunch of places:

  • Settings files: ~/.claude/settings.json for you across projects, .claude/settings.json for the project (committed, so your team gets it), and .claude/settings.local.json for you in this project only.
  • Managed policy (settings an organization pushes to every machine), where allowManagedHooksOnly blocks user, project, local, and plugin hooks. The one exception is hooks from plugins the managed settings force-enable.
  • Skill and agent frontmatter, the YAML block at the top of those files. (See Configuring Skills and Configuring Subagents.)
  • A plugin’s hooks/hooks.json. (A plugin is a bundle of skills, hooks, and agents you install together.)

Hooks from all of these are merged, and every matching hook runs in parallel, with no guaranteed order. Define the same handler in more than one settings file and it runs once. Most other settings pick one winner instead: when the same key conflicts across levels, policy wins, then a command-line flag, then local, then project, then user.

A few fields worth knowing:

  • args: Runs the command in exec form, with no shell in between, which is safer when inputs contain odd characters. Leave it out when you need pipes or &&.
  • if: Filters using permission-rule syntax. It’s best-effort, so don’t rely on it for a hard allow or deny.
  • Know when your matcher is a regular expression. A matcher made only of letters, digits, _, -, spaces, commas, and | is an exact match. Add any other character and it becomes an unanchored regular expression: Edit.* also matches NotebookEdit. Anchor those with ^ and $, like ^my-plugin:reviewer$. MCP tool names are plain, so mcp__x__y matches only that tool, a bare mcp__x matches nothing, and mcp__x__.* matches every tool on the server.

Hooks and permissions

Each side gets the last word on something different. A hook has the last word over blocking: exit 2 (or a JSON deny) stops the call even if permission rules would allow it. Permission rules (settings that allow, ask about, or deny specific tool calls) have the last word on allowing.

So a hook can’t grant what a permission rule denies. Permission rules resolve deny first, then ask, then allow, and the first match wins. A deny at any settings level beats every other level, and a PreToolUse hook that returns allow doesn’t bypass a matching deny or ask rule. That makes “allow Bash, then block specific commands with a hook” a documented pattern. See the permissions documentation for the full rules.

Mods are the exception

On a machine with no managed settings, no managed-mcp.json, and no Team or Enterprise login, an installed mod that handles tool.check can approve a call a hook blocked, and some calls a deny rule refuses.

Use a permission rule when a plain yes or no on a pattern is enough. Use a hook when the decision depends on what’s inside the call.

Last modified on .