Claude Code & Context Engineering

Claude Code Hooks Deep Dive: Matchers, Exit Codes, JSON I/O and Debugging

16 October 2026 · Updated 28 November 2026 · 14 min read · by Yang Kai

Go beyond starter hooks: how matchers really evaluate, the if field, exit-code semantics, the JSON payloads hooks receive and return, the five handler types, and a calm method for debugging hooks that silently do nothing.

Config inside: Annotated advanced hooks configuration

Contents
  1. Matchers: the filter that decides everything
  2. The `if` field: filtering by arguments, not just tool name
  3. Five handler types, and their clocks
  4. Exit codes: the contract, and its exceptions
  5. JSON in: what your script receives
  6. JSON out: decisions, not just exit codes
  7. An annotated advanced configuration
  8. Debugging hooks that do nothing
  9. How we researched this
  10. Verdict

The dangerous hook failure is not the loud one. It is the guard hook that looks correct in settings.json, matches nothing at all, and never fires — while you believe a wall exists that does not. Hooks run without asking, and they fail without telling you.

This deep dive covers the mechanics underneath the starter hooks: how matchers are actually evaluated, the if field that filters by arguments, exit codes and what overrides them, the JSON payloads in both directions, the five handler types, and a debugging method built on evidence instead of hunches.

Everything here is drawn from Anthropic’s official hooks reference, checked in November 2026. If you do not yet have the map of which event does what, start with the complete event-by-event map.

Matchers: the filter that decides everything

A matcher filters when a hook fires, but it is not always a regular expression. How Claude Code evaluates it depends on the characters it contains:

Three traps follow from those rules. First, matching for tool events is against the tool name, not the file path or command text: a matcher of *.ts lands on the regex path, is tested against names like Edit, and never fires. Filtering by file type belongs in the if field or inside your script. Second, matching is case-sensitive and tool names are capitalised — bash is not Bash. Third, MCP tools carry prefixed names in the form mcp__<server>__<tool>, and a server-wide matcher needs the regex suffix: mcp__memory contains only exact-match characters, so it is compared as a literal string and matches no tool at all. mcp__memory__.* is the pattern that matches every tool from that server — worth knowing if you have worked through connecting Claude Code to MCP servers and want to guard one external action.

Each event also matches on a different field: tool events match the tool name, SessionStart matches how the session started (startup, resume, clear, compact, fork), Notification matches the notification type, and FileChanged takes literal filenames to watch. Some events — Stop, UserPromptSubmit, PostToolBatch, TaskCreated — have no matcher support at all; a matcher written on them is silently ignored.

The working rule: keep matchers broad and put the precise logic in the script or the if field, where it can be tested, logged, and read later. A matcher you cannot test is a matcher that will betray you quietly.

The if field: filtering by arguments, not just tool name

Matchers cannot see arguments. The if field on an individual handler can. It uses permission rule syntax against the tool name and its arguments together:

Three limits matter. The field holds exactly one rule — there is no && or list syntax, so define one handler per condition. It is only evaluated on the tool-flavoured events (PreToolUse, PostToolUse, PostToolUseFailure, PermissionRequest, PermissionDenied, PreSkillShellCommand); on any other event, a handler with if set does not run. And it is best-effort: when Claude Code cannot split a Bash input into subcommands, it runs your hook anyway. The docs are explicit that hard enforcement belongs in the permission system — treat if as a precision filter, not a wall.

Five handler types, and their clocks

A handler is not always a shell command. The current reference defines five types:

Type What runs Default timeout
command A shell command; JSON in on stdin, results via exit code and stdout 600s
http A POST of the JSON input to a URL; the response body uses the same JSON output format 600s
mcp_tool A tool call on a configured MCP server; its text output is treated like command stdout 600s
prompt A single-turn model evaluation that returns {"ok": true} or {"ok": false, "reason": "..."} 30s
agent A subagent with tools (Read, Grep, Glob) that verifies a condition before deciding; experimental 60s

Timeouts are defaults, not trivia: a few events lower them (30 seconds on UserPromptSubmit, 10 on MessageDisplay), and SessionEnd hooks share a budget of about 1.5 seconds, so cleanup there must be nearly instant. Prompt and agent hooks earn their keep on Stop, where “is the work actually done?” is a judgement call a script cannot always make.

Command hooks add two more fields worth knowing. async: true runs the hook in the background; its output is discarded, so it can never return a decision. asyncRewake: true also runs in the background but wakes Claude if the hook exits 2, surfacing its stderr as a system reminder.

Exit codes: the contract, and its exceptions

For command hooks, the exit code is the basic contract:

That stderr text on exit 2 matters more than most people realise: “blocked” teaches Claude nothing, while “blocked: this command rewrites the lockfile; run the package manager instead” lets it recover in one step instead of guessing.

The exceptions are where silent failures breed. A guard script that crashes with a generic error fails open — exit 1 does not block — so guards should validate their input and exit 2 when the payload is unparseable. Formatters and loggers should do the opposite: swallow errors and exit 0, because a cosmetic hook must never break a session’s flow. A timed-out hook renders no decision at all; on PreToolUse the tool call simply continues through the normal permission flow, so do not count on a stalled hook as a gate. And PermissionRequest is the special case: Claude Code does not read exit code 2 as a decision there at all. To grant or deny, return the JSON decision object described below.

Newer Claude Code versions add one more safety field: onFailure: "block" on a command, HTTP, or MCP tool handler makes the action block when the hook fails, times out, or cannot even start — the fix for a policy hook whose script path has a typo. Without it, a hook that never runs is indistinguishable from a hook that approved.

JSON in: what your script receives

Every hook receives a JSON payload on stdin (HTTP hooks receive it as the POST body). The common fields are session_id, transcript_path, cwd, permission_mode, and hook_event_name. Tool events add tool_name, tool_input, and tool_use_id — for Bash, tool_input carries the command; for Edit or Write, the file_path. PostToolUse adds tool_response, so your script can react to what actually happened rather than what was attempted, and PostToolUseFailure adds an error string instead. Stop hooks receive stop_hook_active, which is true when Claude is already continuing because a stop hook sent it back — the flag your verification hooks should check to avoid looping, backed by a hard cap of eight consecutive continuations. Notification hooks receive message, an optional title, and notification_type.

Handlers also inherit useful environment: $CLAUDE_PROJECT_DIR points at the project root, and SessionStart hooks get $CLAUDE_ENV_FILE, a file they can append export lines to in order to set environment variables for later shell commands. Note what is not provided: no environment variable holds the edited file’s path. It lives in tool_input.file_path, on stdin — hooks that look for it in the environment are a recurring source of “does nothing” bugs.

JSON out: decisions, not just exit codes

Output is where hooks graduate from scripts to participants. On stdout, a hook can return structured decisions instead of relying on exit codes alone — printed as one JSON object, alone on stdout, with nothing else mixed in.

For PreToolUse, the important shape is a hookSpecificOutput object naming the event and a permissionDecision of allow, deny, ask, or defer, with a permissionDecisionReason that Claude and you can read. (defer pauses the call for headless and SDK flows; interactive users will live on the first three.) A deny with a good reason beats exit 2 for anything subtle, because the reason travels with the decision. The same object can carry updatedInput, which replaces the tool’s arguments before it runs — the mechanism behind hooks that rewrite a command into its safer form instead of blocking it.

Other events use different shapes, and mixing them up is a classic silent failure:

One discipline covers all of it: never echo the raw input payload back to stdout on an exit-0 hook. It will be parsed as hook output, and malformed output looks, from outside, like the agent misbehaving.

An annotated advanced configuration

This is a realistic project-level config with the defensive habits above built in. Scripts live in .claude/hooks/ inside the repo so the whole team gets them, a pattern that matters in the team setup for shared project rules.

{
  "hooks": {
    "PreToolUse": [
      {
        // Broad matcher on purpose: the script decides precisely.
        "matcher": "Bash|Edit|Write",
        "hooks": [
          {
            "type": "command",
            "command": "\"$CLAUDE_PROJECT_DIR\"/.claude/hooks/guard.mjs",
            "timeout": 10
          }
        ]
      },
      {
        // MCP tools use prefixed names; guard one server's writes.
        // The .* is required — without it the matcher is an exact
        // string and matches no tool at all.
        "matcher": "mcp__database__.*",
        "hooks": [
          {
            "type": "command",
            "command": "\"$CLAUDE_PROJECT_DIR\"/.claude/hooks/guard-db.mjs",
            "timeout": 10
          }
        ]
      }
    ],
    "PostToolUse": [
      {
        "matcher": "Edit|Write",
        "hooks": [
          {
            "type": "command",
            // Logger runs first, appends to .claude/hook-log.jsonl,
            // always exits 0 — this is your debugging evidence.
            "command": "\"$CLAUDE_PROJECT_DIR\"/.claude/hooks/log-edit.mjs",
            "timeout": 5
          },
          {
            "type": "command",
            "command": "\"$CLAUDE_PROJECT_DIR\"/.claude/hooks/format-changed.mjs",
            "timeout": 30
          }
        ]
      }
    ],
    "UserPromptSubmit": [
      {
        "hooks": [
          {
            "type": "command",
            // Emits {"hookSpecificOutput": {"hookEventName":
            // "UserPromptSubmit", "additionalContext": "..."}}
            // with today's handoff note if one exists; silent otherwise.
            "command": "\"$CLAUDE_PROJECT_DIR\"/.claude/hooks/inject-handoff.mjs",
            "timeout": 5
          }
        ]
      }
    ]
  }
}

And the guard script’s decision path, in outline form worth copying:

// guard.mjs — read stdin, decide, speak clearly
const input = JSON.parse(await readStdin());
const cmd = input.tool_input?.command ?? "";
if (isDangerous(cmd)) {
  // Prefer structured deny over exit 2 when a reason helps recovery
  console.log(JSON.stringify({
    hookSpecificOutput: {
      hookEventName: "PreToolUse",
      permissionDecision: "deny",
      permissionDecisionReason:
        "Blocked: force-push to main. Push to a branch and open a PR instead."
    }
  }));
  process.exit(0);
}
process.exit(0); // no opinion: normal permission flow applies

Debugging hooks that do nothing

When a hook misbehaves, work this order. First, prove it fires at all: temporarily make the script append one line with a timestamp to a log file, then trigger the event. If nothing lands, the problem is configuration — wrong settings file, wrong matcher, or a JSON syntax error silently invalidating the block. Validate the JSON mechanically; do not eyeball it.

Second, read the evidence Claude Code already keeps. Start a session with claude --debug and the log lands at ~/.claude/debug/<session-id>.txt; hook runs appear as Hooks: lines carrying the event, the matched value, the command, how the run ended, and its duration — the direct way to find a slow hook. A transcript notice saying Failed with non-blocking status code tells you the hook ran and failed open, which for a guard means it protected nothing.

Third, run the script by hand, piping it a saved payload — the logging hook above gives you real payloads to replay — and check the exit code and both output streams. Most “does nothing” cases were a script expecting a field the payload spells differently, or looking for the file path in an environment variable that does not exist.

Fourth, check the timeout and the failure posture: a killed PreToolUse hook is not a considered decision, and a crashed one fails open unless the handler sets onFailure: "block". Keep guards in the low seconds; move anything heavy to PostToolUse or a Stop hook — and remember a blocking Stop hook with vague feedback manufactures an agent that loops on its own completion check.

Finally, if the hook fires but the agent ignores the output, inspect the shape: structured output must be valid JSON, printed alone on stdout — no debug prints mixed in. And check you used the right shape for the event: a permissionDecision returned on PermissionRequest, or a top-level decision returned on PreToolUse, is well-formed JSON that the event simply does not read.

How we researched this

meetBlogging is a desk-research site. The mechanics above were compiled from Anthropic’s official Claude Code hooks reference — matcher evaluation, handler fields, exit-code behaviour, and the per-event decision formats — checked against the reference’s November 2026 revision. Where the docs contradict older community guides, this article follows the docs.

Verdict

Hooks earn complexity slowly. Beyond the shortlist in the hooks that catch actual mistakes, every hook should justify itself with a logged incident, not a hypothetical. Add the logging hook first, learn to read the debug log, and treat every silent hook as unproven until a log line says otherwise. For the event map these mechanics plug into, keep the hooks by event reference open while you configure.

FAQ

What does exit code 2 do in a Claude Code hook? On events that can block, it stops the action — a PreToolUse tool call, a submitted prompt, a stop — and the script’s stderr is shown to Claude as the reason, so write a reason it can act on. Two exceptions: PermissionRequest does not read exit codes as decisions, and on context-only events like SessionStart an exit 2 is just rendered as an error notice.

What is the if field for, if matchers exist? Matchers filter on the tool name alone. The if field filters on the tool name and its arguments, using permission rule syntax — "Edit(*.ts)" or "Bash(git *)". It is only evaluated on the tool events, holds exactly one rule, and is best-effort, so hard enforcement still belongs in permissions or a PreToolUse script.

Why is my hook not firing at all? Usually a configuration fault, not a logic fault: a JSON error in settings, a matcher stuck on the exact-match path (the classic case is an MCP matcher missing its .*), or the hook living in the wrong settings file. Add a one-line logging version first and prove it fires, then check the debug log’s Hooks: lines.

Should a hook return JSON or use exit codes? Use structured JSON when Claude needs a reason, rewritten input, or added context; use exit 2 for a simple hard block. Exit 0 when you print JSON — a JSON decision printed alongside a non-zero, non-2 exit code counts as a failed run, not a decision. Never mix debug output into stdout.

Category: Claude Code & Context Engineering · Tags: #claude-code #hooks #automation #testing #starters

Next step: this article is part of Claude Code guides, which covers the full topic from first setup to advanced use.

Related guides