Skip to content
harbor
How it worksAgentsReviewMeasureDocsPricing
Get started →
How it worksAgentsReviewMeasureDocsPricingGet started →
Home/Blog

Blog

  • Claude Code and AGENTS.md
  • Claude Code skills
  • Claude Code hooks
  • claude-mem
  • Claude Code best practices
  • Karpathy CLAUDE.md
  • AGENTS.md vs CLAUDE.md
  • Cursor rules
  • copilot-instructions.md
  • Why Claude ignores it
  • CLAUDE.md length
  • Committing CLAUDE.md
  • Agent memory compared
  • CLAUDE.md vs skills vs hooks
  • Same mistake again
  • Review comments to rules
  • Slack decisions
  • Company brain
  • Context engineering, Claude 5
  • Context rot, stale rules
  • AGENTS.md research
  • ADRs for agents
  • Memory poisoning
  • MCP memory servers
  • Claude Code, Cursor, Codex
  • Growing CLAUDE.md
  • Served vs cited

Blog

Claude Code hooks: a practical guide with examples

Published: September 23, 2026

Claude Code hooks are commands that run at fixed points in a session: before a tool runs, after a file is edited, when a prompt is submitted, when Claude stops. Unlike a line in CLAUDE.md, a hook is not advice. It always runs, and a PreToolUse hook can block the action outright by exiting with code 2.

Checked against the hooks guide and reference on 2026-09-23 (Claude Code 2.1.280). The event list has grown to more than thirty; the handful below are the ones most teams use.

What are Claude Code hooks?

Anthropic's best practices put it in one line: unlike CLAUDE.md instructions, which are advisory, hooks are deterministic and guarantee the action happens. A rule asks the model. A hook does not ask anyone. That is why the answer to “Claude keeps ignoring my rule” is so often “make it a hook”, and why the causes behind the ignoring, covered in why Claude ignores CLAUDE.md, do not apply to one.

Which hook events should you know?

EventFiresTypical use
PreToolUseBefore a tool call runs. Can block itRefuse dangerous commands, protect files
PostToolUseAfter a tool call succeedsFormat or lint the file that was just edited
UserPromptSubmitWhen you submit a prompt, before Claude sees itAdd context to the prompt, such as branch state
SessionStartWhen a session begins, resumes, clears or compactsLoad context the session should start with
StopWhen Claude finishes respondingRun the tests and refuse to stop until they pass
PreCompact / PostCompactAround context compactionRe-inject what must survive a summary
SessionEndWhen the session terminatesWrite logs, clean up
NotificationWhen Claude Code sends a notificationDesktop alert when Claude is waiting for you

How do you configure a hook?

Hooks live in a settings file under a hooks key. Each event takes matchers (a tool name or a regex such as Edit|Write) and the commands to run. This formats every file Claude edits:

// .claude/settings.json
{
  "hooks": {
    "PostToolUse": [
      {
        "matcher": "Edit|Write",
        "hooks": [
          {
            "type": "command",
            "command": "jq -r '.tool_input.file_path' | xargs npx prettier --write"
          }
        ]
      }
    ]
  }
}

Where the block goes decides who it applies to:

LocationScopeShared
~/.claude/settings.jsonAll your projectsNo
.claude/settings.jsonThis projectYes, commit it
.claude/settings.local.jsonThis projectNo, gitignored
Managed policy settingsThe whole organizationAdmin controlled
Plugin, skill or subagentWhile that is enabled or runningYes, ships with it

Run /hooks inside Claude Code to see everything configured, grouped by event.

How do you block a command with a PreToolUse hook?

The hook receives the tool call as JSON on stdin. Exit 0 lets it through. Exit 2 blocks it, and what you write to stderr goes back to Claude as the reason, so it can change course. This is the pattern from Anthropic's guide, protecting files:

#!/bin/bash
# .claude/hooks/protect-files.sh
INPUT=$(cat)
FILE_PATH=$(echo "$INPUT" | jq -r '.tool_input.file_path // empty')

for pattern in ".env" "package-lock.json" ".git/"; do
  if [[ "$FILE_PATH" == *"$pattern"* ]]; then
    echo "Blocked: $FILE_PATH matches protected pattern '$pattern'" >&2
    exit 2
  fi
done
exit 0

Register it on PreToolUse with the matcher Edit|Write, make it executable, and ask Claude to edit .env to test it. For structured control, exit 0 and print JSON with permissionDecision set to deny, ask or allow. When several hooks answer, the most restrictive wins.

Which commands are worth blocking?

The ones your agents actually run, not the ones that sound scariest. A guard written from imagination can sit for months without matching anything. The costly commands are often ordinary: rm -r on a source directory, git checkout -- <paths> or git reset --hard throwing away uncommitted work. Read your agents' command history before you decide which guard comes first.

Start a new guard in log-only mode for a week, count what it would have blocked, then switch it to blocking. A guard that fires on legitimate work gets disabled by the second person it annoys.

Can a hook add context for Claude?

Yes. On UserPromptSubmit, return JSON with hookSpecificOutput.additionalContext and the text is added to Claude's context for that prompt. The guide's example adds the branch and a deploy freeze. Put the field inside hookSpecificOutput; at the top level it is silently ignored. SessionStart with the compact matcher is the documented way to re-inject what must survive a compaction.

This is the part of hooks that is easiest to overdo. Every line a hook injects is in the prompt, with the same cost and the same context rot as a line in CLAUDE.md. Inject what applies to this prompt, not everything that might.

How do you debug a hook that is not running?

Press Ctrl+O for the transcript view. A successful hook shows nothing; a block shows its reason; a failing hook shows a hook error notice. For the full picture, start with claude --debug-file /tmp/claude.log and tail the log, or run /debug mid-session. The usual culprits: the script is not executable, jq is missing, the matcher does not match the tool name, or a project setting set disableAllHooks.

Where Harbor fits

Harbor is itself delivered through hooks. harbor init installs hooks in Claude Code, Codex and Cursor, and they serve each session the team's approved facts that apply to the repo and the task, so the agent starts with the decision from last month's review instead of rediscovering it. What a session learns is written back through review, not straight into the next prompt.

Harbor's guardrails follow the log-first advice above. Each one watches for a destructive command and records every match; nothing is refused until your team promotes a guard to block, after seeing what it would have caught. harbor off pauses the whole thing for one repo, and harbor doctor checks that the hooks are installed and reaching the agents you think they reach.

See what is installed where. Agents and MCP lists every hook event Harbor uses per agent, and the quickstart takes about ten minutes.

Questions

What are hooks in Claude Code?

Hooks are commands Claude Code runs at fixed points in a session, such as before a tool call, after a file edit, or when Claude stops. Unlike CLAUDE.md instructions, they always run.

How do I block a command in Claude Code?

Add a PreToolUse hook with a matcher such as Bash or Edit|Write. The script reads the tool call as JSON on stdin and exits with code 2 to block it; what it writes to stderr is passed back to Claude as the reason.

Where are Claude Code hooks configured?

In a settings file under a hooks key: ~/.claude/settings.json for all your projects, .claude/settings.json to share with the team, .claude/settings.local.json for yourself, or managed settings for the organization. Run /hooks to see them all.

Can a hook add context to Claude?

Yes. A UserPromptSubmit hook can return JSON with hookSpecificOutput.additionalContext, and that text is added to Claude’s context for the prompt. A SessionStart hook with the compact matcher can re-inject context after compaction.

Why is my Claude Code hook not running?

Common causes are a script that is not executable, a missing jq, a matcher that does not match the tool name, or disableAllHooks set in a settings file. Run Claude Code with --debug-file and read the log to see which hooks matched.

harbor

Decide once. Every agent knows. One company brain for all the agents your team runs, built from work you already do and kept only while it is still true.

Product

  • How it works
  • Review
  • Your agents
  • Guardrails
  • What it counts
  • Pricing

Developers

  • Docs
  • Blog
  • CLI
  • MCP server
  • Served and cited
  • Environments

Company

  • Get started
  • Contact
  • Privacy Policy
  • Terms of Service
  • Data Processing Agreement
  • Refund Policy
© 2026 harbor·Product names and logos are trademarks of their respective owners.