Claude Code hooks: run a script on every tool call

Claude Code hooks run your own script before or after a tool call. Learn the config format, exit codes and three working examples you can paste today.

· 6 min read

A Claude Code hook is a command you register in settings.json that Claude Code itself runs at a fixed point: before a tool call, after an edit, when Claude stops, when it needs your attention. Unlike a line in CLAUDE.md, a hook is not a suggestion. The harness executes it every time, whatever the model decided. Use hooks for the rules that cannot have exceptions.

#When should you use a hook instead of CLAUDE.md?

A prompt or a CLAUDE.md line is read by the model, and the model usually follows it, but not always. A hook is code that Claude Code runs, so it always happens. Anthropic's own best-practices page puts it this way: if you keep adding emphasis to a CLAUDE.md line and Claude still misses it, the line belongs in a hook.

Good candidates:

  • Never edit a generated folder or a .env file.
  • Always run the formatter after an edit.
  • Don't let Claude finish while the type check fails.
  • Get a desktop notification when Claude is waiting for you.

Bad candidates are plain preferences ("prefer small functions"). Leave those in your CLAUDE.md and let Claude judge.

#What does a hook configuration look like?

Hooks live in the hooks key of a settings file, in three nested levels: the event, a matcher group, and the handlers to run.

{
  "hooks": {
    "PreToolUse": [
      {
        "matcher": "Edit|Write",
        "hooks": [
          {
            "type": "command",
            "command": "${CLAUDE_PROJECT_DIR}/.claude/hooks/protect-files.sh"
          }
        ]
      }
    ]
  }
}

Where you put it decides who gets it:

FileScope
~/.claude/settings.jsonAll your projects
.claude/settings.jsonThis project, committed to git
.claude/settings.local.jsonThis project, just you, not committed

Entries from the different levels are merged. CLAUDE_PROJECT_DIR is the project root; use it in paths so the hook works from any working directory. A plugin or a skill can also ship hooks, and a subagent can carry its own that apply only while it runs.

#Which events can you hook into?

There are more than thirty. The ones you will use first:

EventFiresCan block?
PreToolUseBefore a tool runsYes
PostToolUseAfter a tool succeededNo, the tool already ran
UserPromptSubmitWhen you send a promptYes
StopWhen Claude is about to finishYes, it keeps going
NotificationWhen Claude needs your attentionNo
SessionStartAt the start or resume of a sessionNo
SubagentStopWhen a subagent finishesYes
PreCompactBefore the context is compactedYes

The full list, including events for worktrees, permission requests and model switches, is on the hooks reference.

#How does the matcher work?

For tool events the matcher is matched against the tool name. "Bash" matches Bash. A list separated by | such as "Edit|Write" matches either one. Leave it out, or use "*", to match everything. A matcher that contains any other character is treated as a regular expression, so mcp__memory__.* matches every tool of an MCP server called memory. Some events, like UserPromptSubmit and Stop, have no matcher: it is ignored.

To narrow a handler further, add an if field with a permission rule, for example "if": "Bash(git push *)". It applies to tool events and holds a single rule.

#How does a hook talk to Claude Code?

Your script receives a JSON object on stdin. For a tool event it includes hook_event_name, session_id, cwd, permission_mode, tool_name and tool_input. For an Edit or Write call, tool_input.file_path is the file.

It answers with its exit code:

  • 0: success. Stdout is parsed if it is a single JSON object.
  • 2: a blocking error. On PreToolUse the call is cancelled, and whatever you wrote to stderr is shown to Claude as the reason, so it can adapt.
  • Anything else, including 1: a non-blocking error. The action goes ahead and a notice appears. This trips people up: exit 1 does not enforce anything.

For finer control, print JSON instead. This denies a call with a reason:

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

permissionDecision also accepts allow, ask and defer.

#Three hooks worth copying

1. Protect files from edits. Save as .claude/hooks/protect-files.sh and chmod +x it:

#!/bin/bash
file=$(jq -r '.tool_input.file_path // empty')
case "$file" in
  *.env|*/src/gen/*|*package-lock.json)
    echo "Blocked: $file is protected. Edit the source instead." >&2
    exit 2 ;;
esac
exit 0

Register it on PreToolUse with the matcher Edit|Write, as in the configuration above. When Claude tries to touch .env, the edit is refused and Claude reads your message and takes another route.

2. Format after every edit. On PostToolUse, matcher Edit|Write:

{
  "type": "command",
  "command": "jq -r '.tool_input.file_path' | xargs npx prettier --write"
}

The tool has already run, so this cannot block. It just keeps the diff tidy without spending a turn on it.

3. Notify me when Claude waits. On Notification, on a Mac:

{
  "type": "command",
  "command": "osascript -e 'display notification \"Claude needs you\" with title \"Claude Code\"'"
}

#What about the other hook types?

command is the default and the most common. There are four others: http posts the event JSON to a URL, mcp_tool calls a tool of a connected MCP server, prompt asks a Claude model a single yes-or-no style question about the event, and agent spawns a subagent that can use tools to check a condition (marked experimental). Prompt and agent hooks are useful when the rule is fuzzy ("does this change touch the public API?"), at the price of tokens and latency. Command hooks cost nothing but a process.

#How do you debug a hook?

  • Type /hooks in a session. It is a read-only browser of every configured hook, with its source file, so you can see why a hook is or isn't there.
  • Run the script by hand with a sample payload: echo '{"tool_input":{"file_path":"a/.env"}}' | .claude/hooks/protect-files.sh; echo $?.
  • Remember that hooks for the same event run in parallel, and that the default timeout for a command hook is 600 seconds. Set timeout lower for anything that should be quick.
  • A Stop hook that exits 2 sends Claude back to work instead of letting it finish, which is how you enforce "the type check must pass" (pnpm tsc --noEmit 1>&2 || exit 2). Claude Code ends the turn anyway if the hook blocks eight stops in a row with no tool call between them.

Two cautions. Hooks run with your user's permissions, so treat a hook in a repository you cloned like any other script from that repository. And in non-interactive runs the project's hooks run too, unless you pass --bare; see headless mode for what that implies in CI. If a hook blocks something you meant to allow, the permission modes article explains how rules and hooks combine.

#In Relais

Relais runs your real Claude Code sessions, so hooks you set in ~/.claude/settings.json or in a project's .claude/settings.json are Claude Code's to run, as in a terminal. Relais adds its own layer around the session (the queue of what needs you, undo, commit and push), described on the features page.

Claude Code,
better organized.

$14.99 a month, everything included. Mac and Linux, on your Claude Pro or Max plan. Cancel any time.