Coffee
← Blog Mac Productivity

Claude Code Hooks: Events, Exit Codes and 8 Recipes

By FavTray ·

Written by the team behind FavTray, a Mac developer dashboard for the menu bar. We check every app we cover against its own site, docs or a hands-on test, and each post says which.

Short answer: Claude Code hooks are commands that Claude Code runs automatically at set points in a session. You add them under a "hooks" key in ~/.claude/settings.json (or .claude/settings.json per project), pick an event such as PreToolUse, PostToolUse, Stop or PermissionRequest, optionally filter by tool with a matcher, and control the outcome with exit code 2 or JSON on stdout.

TL;DR

  • 33 events as of November 2026, from SessionStart to SessionEnd; the five most people use are PreToolUse, PostToolUse, Notification, Stop and PermissionRequest.
  • Structure: event → matcher group → hooks array → handler (command, http, mcp_tool, prompt or agent).
  • Exit 0 means carry on, exit 2 blocks (on events that can block), any other code is a non-blocking error.
  • JSON output gives finer control: allow, deny or ask on PreToolUse, allow or deny on PermissionRequest, keep working on Stop.
  • Hooks run with your full user permissions, so read any hook before you add it.

Checked 14 November 2026 against Anthropic’s hooks reference and hooks guide. We make FavTray, so weigh our take accordingly; it appears once below as an example of a PermissionRequest hook.

What are Claude Code hooks?

Claude Code hooks are user-defined commands that run automatically when something specific happens in a Claude Code session, like a tool call, a file edit or the end of a turn. Anthropic’s guide describes them as “deterministic control”: the action always happens, instead of relying on the model to remember to do it.

That’s the difference from writing “always run Prettier” in CLAUDE.md. An instruction is a request the model may follow. A hook is code that runs every time its event fires, whatever the model decides.

MechanismWhat it isRuns every time?Best for
HooksCommands or prompts tied to lifecycle eventsYes, when the event and matcher fitFormatting, notifications, logging, guardrails
CLAUDE.mdInstructions loaded into contextNo, the model choosesConventions, project background
Permission rules (/permissions)Allow, ask and deny lists for toolsYesHard allow and deny decisions
SkillsInstructions and scripts Claude loads on demandNo, Claude or you invoke themRepeatable multi-step tasks

Anthropic’s reference is blunt about one boundary: the if filter on hooks is best-effort, so for a hard allow or deny you should use the permission system, with hooks as an extra layer.

Which hook events does Claude Code support?

As of November 2026 the hooks reference lists 33 events. They cover the session (SessionStart, SessionEnd), your prompt (UserPromptSubmit), every tool call (PreToolUse, PermissionRequest, PostToolUse), the end of a turn (Stop), subagents, tasks, compaction, config changes and MCP elicitations. These are the ones worth knowing first:

EventWhen it firesMatcher filters onCan it block?
SessionStartA session starts or resumesstartup, resume, clear, compact, forkNo
UserPromptSubmitYou submit a prompt, before Claude sees it(no matcher)Yes, rejects the prompt
PreToolUseBefore a tool call runsTool name (Bash, Edit, Write, mcp__…)Yes, cancels the call
PermissionRequestClaude Code is about to ask you for permissionTool nameThrough JSON decision, not exit 2
PostToolUseAfter a tool call succeedsTool nameNo, the tool already ran
PostToolUseFailureAfter a tool call failsTool nameNo
NotificationClaude Code sends a notificationType (permission_prompt, idle_prompt, …)No
StopClaude finishes responding (not on Ctrl+C)(no matcher)Yes, Claude keeps working
SubagentStart / SubagentStopA subagent starts or finishesAgent typeSubagentStop only
PreCompact / PostCompactBefore and after context compactionmanual, autoPreCompact only
ConfigChangeA settings or skills file changes mid-sessionConfig sourceYes (except policy settings)
FileChangedA watched file changes on diskLiteral filenamesNo
SessionEndThe session endsclear, logout, prompt_input_exit, …No

The rest (Setup, UserPromptExpansion, PermissionDenied, PostToolBatch, MessageDisplay, TaskCreated, TaskCompleted, StopFailure, TeammateIdle, InstructionsLoaded, CwdChanged, DirectoryAdded, WorktreeCreate, WorktreeRemove, PreModelSwitch, PostModelSwitch, Elicitation, ElicitationResult) are covered in the full reference. New events arrive often, so check there before relying on one.

How do you configure hooks in settings.json?

You add a "hooks" object to a Claude Code settings file, keyed by event name. Each event holds a list of matcher groups, and each group holds a hooks array of handlers:

{
  "hooks": {
    "PreToolUse": [
      {
        "matcher": "Bash",
        "hooks": [
          {
            "type": "command",
            "command": "\"$CLAUDE_PROJECT_DIR\"/.claude/hooks/check-bash.sh",
            "timeout": 30
          }
        ]
      }
    ]
  }
}

Where do Claude Code hook settings live?

FileApplies toShared with your team?
~/.claude/settings.jsonEvery project on your MacNo
.claude/settings.jsonOne projectYes, commit it
.claude/settings.local.jsonOne projectNo, it’s gitignored
Managed policy settingsThe whole organisationSet by admins
Plugin hooks/hooks.json, skill or subagent frontmatterWhile that plugin, skill or subagent is activeYes

Hooks from all levels merge rather than replace each other. Type /hooks inside Claude Code to see a read-only list of what loaded and where each hook came from. To switch every hook off without deleting anything, set "disableAllHooks": true.

What handler types are there?

typeWhat it doesDefault timeout
commandRuns a shell command, event JSON on stdin600 s
httpPOSTs the event JSON to a URL600 s
mcp_toolCalls a tool on a configured MCP server600 s
promptAsks a Claude model for a yes or no decision30 s
agentRuns a subagent that can use tools (experimental)60 s

Override any of them with "timeout" in seconds. UserPromptSubmit command hooks default to 30 seconds, and all SessionEnd hooks share a 1.5-second budget.

How do matchers work in Claude Code hooks?

A matcher decides which tool calls, or which subtypes of an event, a hook group runs for. "*", "" or no matcher at all means everything. A matcher made only of letters, digits, _, -, spaces, commas and | is an exact name or list, like Edit|Write. Anything else is treated as an unanchored JavaScript regex.

  • Bash matches only the Bash tool. Matchers are case-sensitive.
  • Edit|Write matches either tool.
  • Edit.* also matches NotebookEdit; use ^Edit$ for an exact regex match.
  • MCP tools are named mcp__<server>__<tool>, so mcp__github__.* matches every tool from the github server.

For finer filtering on tool events, add an if field using permission-rule syntax, such as "if": "Bash(git *)" or "if": "Edit(*.ts)".

What do Claude Code hook exit codes mean?

Exit code 0 means success, exit code 2 means “block this”, and any other code is a non-blocking error that shows a hook error notice while Claude carries on. On exit 2, Claude Code ignores stdout and uses your stderr text as the reason.

Exit codeResultWhere your output goes
0Continuestdout parsed as JSON if it’s one JSON object; plain text becomes context on SessionStart and UserPromptSubmit
2Block (on events that can block)stderr goes to Claude, or to you, as the reason
1 or otherNon-blocking error, action continuesstderr shown as a hook error notice

Two traps catch most people. Exit 1 does not block anything. And exit 2 can’t block on PermissionRequest (deny through JSON there), PostToolUse (the tool already ran, so Claude only sees your stderr) or Notification (exit code and stderr are ignored).

How do you return JSON from a hook?

Print one JSON object to stdout and exit 0. Every event accepts continue (set false to stop Claude), stopReason and systemMessage; event-specific decisions go in hookSpecificOutput with hookEventName set. To deny a tool call from PreToolUse with a reason:

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

permissionDecision takes allow, deny, ask or defer. When several hooks answer, the most restrictive wins, in the order deny, defer, ask, allow. A deny from PreToolUse holds even with --dangerously-skip-permissions.

On Stop, {"decision": "block", "reason": "Run the tests first"} keeps Claude working, and the reason becomes its next instruction. Check the stop_hook_active field in the input so you don’t loop forever; Claude Code also overrides a Stop hook after eight blocks in a row.

Build the JSON with jq rather than by gluing strings together, so quotes inside values are escaped. Every hook receives JSON on stdin with session_id, transcript_path, cwd and hook_event_name, plus tool_name and tool_input on tool events. The recipes below read it with jq (brew install jq).

What are the most useful Claude Code hook examples?

These eight recipes cover what people search for most: notifications, guardrails, formatting and approvals. Merge each one into your existing "hooks" object rather than replacing it.

1. How do I get a Mac notification when Claude Code needs input?

Use a Notification hook that runs osascript. This is Anthropic’s own macOS example:

{
  "hooks": {
    "Notification": [
      {
        "matcher": "",
        "hooks": [
          {
            "type": "command",
            "command": "osascript -e 'display notification \"Claude Code needs your attention\" with title \"Claude Code\"'"
          }
        ]
      }
    ]
  }
}

If no banner shows, allow Script Editor under System Settings › Notifications. Terminal-specific setup for Ghostty, iTerm2 and tmux is in our guide to Claude Code notifications on Mac.

2. How do I play a sound when Claude Code finishes?

A Stop hook fires the moment each turn ends:

{
  "hooks": {
    "Stop": [
      {
        "hooks": [
          { "type": "command", "command": "afplay /System/Library/Sounds/Glass.aiff" }
        ]
      }
    ]
  }
}

It fires after every turn, not only at the end of a whole task, and not when you interrupt with Ctrl+C.

3. How do I stop Claude Code running rm -rf?

Save this as .claude/hooks/block-rm-rf.sh and run chmod +x on it:

#!/bin/bash
cmd=$(jq -r '.tool_input.command // empty')
if echo "$cmd" | grep -Eq 'rm[[:space:]]+-[a-zA-Z]*([rR][a-zA-Z]*f|f[a-zA-Z]*[rR])'; then
  echo "Blocked: recursive force delete. Ask the user to run it themselves." >&2
  exit 2
fi
exit 0

Register it on PreToolUse with the matcher Bash and the command "\"$CLAUDE_PROJECT_DIR\"/.claude/hooks/block-rm-rf.sh". A regex won’t catch every spelling (rm -r -f, a script that deletes for you), so pair it with a deny rule such as "Bash(rm -rf *)" under permissions.deny.

4. How do I stop Claude Code editing .env files?

Anthropic’s guide has a protect-files.sh script on PreToolUse with the matcher Edit|Write. It reads .tool_input.file_path, loops over patterns such as .env, package-lock.json and .git/, and exits 2 with a “Blocked:” message on a match. Claude sees the message and changes approach. Claude can still change those files through shell commands, so Anthropic recommends Edit deny rules or sandboxing as well.

5. How do I auto-format files after Claude Code edits them?

Run Prettier from PostToolUse on Edit|Write, in your project’s .claude/settings.json:

{
  "hooks": {
    "PostToolUse": [
      {
        "matcher": "Edit|Write",
        "hooks": [
          {
            "type": "command",
            "command": "f=$(jq -r '.tool_input.file_path') && npx prettier --write --ignore-unknown \"$f\""
          }
        ]
      }
    ]
  }
}

Swap in ruff format, gofmt -w or swift-format for other languages. A successful run prints nothing; the file just comes back formatted.

6. How do I log every command Claude Code runs?

Add a second handler to your PreToolUse Bash group:

{ "type": "command", "command": "jq -r .tool_input.command >> ~/.claude/bash.log" }

Hooks in the same group run in parallel, so the log line is written even when the rm guard in recipe 3 blocks the command.

7. How do I remind Claude of project rules after compaction?

Compaction summarises the conversation and can drop details. A SessionStart hook with the matcher compact puts them back, because plain stdout from SessionStart is added to Claude’s context:

{
  "hooks": {
    "SessionStart": [
      {
        "matcher": "compact",
        "hooks": [
          { "type": "command", "command": "echo 'Use pnpm, not npm. Current task: auth refactor.' && git log --oneline -5" }
        ]
      }
    ]
  }
}

Fewer re-explanations after compaction also helps with Claude Code token usage.

8. How do I auto-approve one kind of permission prompt?

Use a PermissionRequest hook with the narrowest matcher you can. Anthropic’s example approves ExitPlanMode, so a finished plan doesn’t stop for a prompt:

{
  "hooks": {
    "PermissionRequest": [
      {
        "matcher": "ExitPlanMode",
        "hooks": [
          {
            "type": "command",
            "command": "jq -c '{hookSpecificOutput: {hookEventName: \"PermissionRequest\", decision: {behavior: \"allow\", updatedInput: .tool_input}}}'"
          }
        ]
      }
    ]
  }
}

An empty or .* matcher here would approve every prompt, including shell commands and file writes. Never do that. A hook’s allow also doesn’t override deny rules in your settings.

How do apps use the PermissionRequest hook?

Apps that let you approve Claude Code away from the terminal are built on the same event. The hook passes each permission request to the app, waits, and prints a hookSpecificOutput.decision with "behavior": "allow" or "deny" back to Claude Code once you choose.

FavTray is a macOS menu bar app with 15+ developer and productivity tools, free with daily limits, $4.99 once for Lifetime. Its notch island, FavShelf, adds PermissionRequest, Stop and Notification hooks (plus a PreToolUse hook for Claude’s questions) to ~/.claude/settings.json next to yours, and talks to them over a local socket. Requests appear under the notch with Approve and Deny. If you don’t answer within 55 seconds, Claude Code asks in the terminal as usual; FavTray never approves or denies on its own. Turning it off removes only FavTray’s hooks. Approvals are a Pro feature, with a 7-day free trial on every install.

Other apps do the same with different prices and agent support; we compare them in approve Claude Code from the notch. Whatever you install, open /hooks afterwards and read what it added.

How do you debug a Claude Code hook that isn’t working?

Start with /hooks: if the hook isn’t listed under the event you expect, Claude Code never loaded it. Then work through these:

  1. Validate the JSON. Trailing commas and comments aren’t allowed in settings.json.

  2. Check the matcher’s case. bash won’t match the Bash tool.

  3. Make scripts executable with chmod +x, and use absolute paths or $CLAUDE_PROJECT_DIR.

  4. Test the script by hand with sample input:

    echo '{"tool_name":"Bash","tool_input":{"command":"rm -rf build"}}' | .claude/hooks/block-rm-rf.sh
    echo $?
  5. Read the debug log. Start claude --debug, trigger the hook, then open ~/.claude/debug/<session-id>.txt. Press Ctrl+O in a session for the transcript view.

  6. Silence your shell profile. An echo in ~/.zshrc that runs before your JSON makes Claude Code treat the output as plain text. Wrap it in if [[ $- == *i* ]]; then … fi.

  7. Put fields at the right level. permissionDecision belongs inside hookSpecificOutput; at the top level it’s silently ignored.

Are Claude Code hooks safe?

They’re as safe as the commands in them. Anthropic’s warning is direct: command hooks “execute shell commands with your full user permissions” and can modify, delete or read any file your account can.

  • Workspace trust: in an interactive session, Claude Code holds back hooks until you accept the trust dialog for the folder. In claude -p and SDK runs there’s no dialog, so a cloned repo’s .claude/settings.json hooks run straight away. Review them first, or run with --settings '{"disableAllHooks": true}'.
  • Quote variables ("$VAR"), reject .. in file paths, and skip .env, .git/ and keys.
  • Read third-party hooks. Plugins and notch apps add hooks too; /hooks shows where each came from.

Hooks pair well with the rest of your setup: watch your limits with our Claude Code usage limits guide, and if you run more than one login, see tools for multiple Claude Code accounts. FavTray’s plans and pricing cover the notch approvals described above.

Sources (checked 14 November 2026): Anthropic’s Claude Code hooks reference, hooks guide, permissions and settings docs; jq; Prettier; FavShelf behaviour from the FavShelf page.

Try FavTray Free

One free Mac menu bar app: notch island, ports, keep-awake, clipboard, eye rest, and Claude and Codex limits.

Download Free

Frequently Asked Questions

What are Claude Code hooks?

Claude Code hooks are shell commands, HTTP calls, MCP tools or model prompts that Claude Code runs automatically at fixed points in a session, such as before a tool runs, after a file edit or when Claude finishes responding. You define them under a hooks key in settings.json. Unlike instructions in CLAUDE.md, they always run, so they suit formatting, notifications and guardrails.

Where do I put Claude Code hooks?

Put them in a settings file under a hooks key. Use ~/.claude/settings.json for hooks that apply to every project, .claude/settings.json in a repository for hooks your team shares through git, or .claude/settings.local.json for project hooks only you use. Plugins, skills and subagents can also carry hooks. Hooks from every level are merged, and the /hooks command shows what loaded.

How do I block a command with a Claude Code hook?

Add a PreToolUse hook with the matcher Bash that reads the command from tool_input.command on stdin and exits with code 2 when it matches something you forbid. Claude Code cancels the tool call and passes your stderr text to Claude as the reason. Exit code 1 does not block. For a hard rule, also add a deny rule under permissions in settings.json.

Why is my Claude Code hook not running?

Type /hooks and check the hook is listed under the right event. Matchers are case-sensitive, so bash will not match the Bash tool. Check the JSON has no trailing commas, the script is executable with chmod +x, and jq is installed if the command uses it. Interactive sessions also hold back hooks until you accept the folder's workspace trust dialog. claude --debug writes a log with every hook run.

Can a Claude Code hook approve permission requests automatically?

Yes. A PermissionRequest hook can print JSON with hookSpecificOutput.decision.behavior set to allow or deny, and Claude Code answers the prompt for you. Keep the matcher narrow, because an empty matcher would approve every prompt. A hook's allow never overrides a deny rule in your settings. Notch apps such as FavTray use the same event to show the prompt on screen and send back your choice.

Do Claude Code hooks work on Mac, Linux and Windows?

Yes. Command hooks run in a shell on macOS and Linux, and on Windows they use Git Bash or, with shell set to powershell, PowerShell. Recipes in this guide use macOS tools such as osascript and afplay for alerts, and jq for reading the JSON input, which you can install on a Mac with brew install jq.