RSS
Tips

Claude Code hooks and subagents: a practical guide

How Claude Code hooks and subagents work, checked against Anthropic's docs on Nov 20, 2026: hook events, config format, matchers, exit codes and JSON output, three safe example hooks, subagent files and frontmatter, and when to pick a hook, skill or subagent.

A close up of a metal object on a table illustrating Claude Code hooks and subagents
Photo by Ian Talmacs on Unsplash

Last checked: 2026-11-20, against Anthropic's Claude Code docs: Automate actions with hooks, the Hooks reference, Create custom subagents, Extend Claude Code and Manage costs effectively. The newest Claude Code release that day was 2.1.329. The example hooks and the example subagent are ours, not Anthropic's, and none of them deletes or overwrites anything.

In one sentence each: a hook is a handler, usually a shell command, that Claude Code fires at a fixed point in a session without Claude deciding to. A subagent is a separate Claude worker with its own context window that does a task and hands back a summary.

What are Claude Code hooks?

Hooks are handlers you define in a settings file that Claude Code runs when a lifecycle event fires, such as before a tool call or when Claude finishes a reply. Because the harness runs them, they apply every time, which makes them the tool for rules that must not depend on Claude remembering an instruction.

Most hooks are shell commands (type command). A hook can also POST the event to a URL (http), call a tool on an MCP server (mcp_tool), or ask a Claude model to decide (prompt, or agent, which the docs label experimental). Prompt and agent hooks are not deterministic, because another model makes the call. Command hooks run with your full user permissions, so review any hook before adding it.

Which hook events are there?

The hooks guide listed 33 events on November 20, 2026. These are the ones most setups use:

Selected events from Anthropic's hooks guide.
EventWhen it fires
SessionStartA session begins or resumes, or restarts after /clear or compaction
UserPromptSubmitYou submit a prompt, before Claude processes it
PreToolUseBefore a tool call runs; can block it
PermissionRequestA tool call needs a permission decision
PostToolUseAfter a tool call succeeds
NotificationClaude Code sends a notification, such as a permission prompt
SubagentStart / SubagentStopA subagent is spawned / finishes
StopClaude finishes responding
PreCompact / PostCompactBefore and after context compaction
SessionEndThe session terminates

How is a hook configured?

Under a "hooks" key in a settings file, in three levels: the event name, then a matcher group that filters when it fires, then one or more handlers to run. There is no standalone hooks file for user or project config; only plugins ship a separate hooks/hooks.json.

  • ~/.claude/settings.json: all your projects.
  • .claude/settings.json: one project, can be committed and shared.
  • .claude/settings.local.json: one project, just you.
  • Managed policy settings, plugins, and skill or subagent frontmatter are the other places.

Edits to settings.json reach the running session after a short delay, without a restart. Type /hooks to see every hook loaded for the session, grouped by event. "disableAllHooks": true turns them off, except managed hooks unless that setting is also managed.

How do hook matchers work?

The matcher filters on a field that depends on the event: the tool name for tool events, the start reason for SessionStart, the notification type for Notification. An empty matcher, "*" or no matcher matches everything.

  • A matcher of only letters, digits, _, -, spaces, commas and | is an exact list: "Edit|Write" matches those two tools. Anything else is an unanchored JavaScript regular expression, so Edit.* also matches NotebookEdit; use ^Edit$ for an exact match.
  • Names are case-sensitive: Bash, not bash. MCP tools are named mcp__<server>__<tool>, so mcp__github__.* covers one server; tools from a plugin's server use mcp__plugin_<plugin>_<server>__<tool>.
  • The matcher must be a single string. An array is an invalid setting, and under PreToolUse or PermissionRequest it stops the file's other hooks from loading too.
  • On tool events, an "if" field narrows a handler with permission-rule syntax, such as "Bash(git *)", so the process usually starts only for git commands. The filter is best-effort; use permission rules for a hard allow or deny.

What do hook exit codes 0 and 2 mean?

Exit 0 means no objection and exit 2 means block. Any other exit code is a non-blocking error: the action goes ahead and you see a hook error notice, unless the hook sets onFailure to "block" (v2.1.295 or later). A few events have their own rules; for WorktreeCreate, any non-zero exit fails.

  • Exit 0 from PreToolUse does not approve the call; the normal permission flow still runs.
  • With exit 2, your stderr becomes the reason. On PreToolUse the tool call is cancelled and Claude reads the reason, so it can change approach. Some events cannot be blocked; for SessionStart, exit 2 only shows stderr to you.
  • Plain stdout from SessionStart, UserPromptSubmit, UserPromptExpansion and PostModelSwitch hooks is added to Claude's context. Claude never sees stderr from a hook that exits 0.
  • Default timeouts: 600 seconds for command hooks, 30 seconds on UserPromptSubmit, and a 1.5-second budget for SessionEnd hooks. Set timeout on a handler to change it.

How does hook JSON output work?

For more than block or allow, exit 0 and print one JSON object on stdout. A PreToolUse hook returns hookSpecificOutput.permissionDecision: deny cancels the call and tells Claude why, ask shows the normal prompt, allow skips the prompt, and defer ends the turn but keeps the tool call for later; it works only with -p and a single tool call in the turn. Even with allow, deny and ask rules still apply.

{
  "hookSpecificOutput": {
    "hookEventName": "PreToolUse",
    "permissionDecision": "deny",
    "permissionDecisionReason": "Use rg instead of grep"
  }
}

That shape is from the hooks guide. PostToolUse and Stop hooks use a top-level "decision": "block" instead. UserPromptSubmit hooks add text with additionalContext, which must sit inside hookSpecificOutput; at the top level it is silently ignored. When several hooks match, all of them run in parallel; for PreToolUse decisions the most restrictive answer wins, in the order deny, defer, ask, allow.

Three example hooks you can copy

All three are our examples. The first two only notify or block; the third prints text. Example 1, in ~/.claude/settings.json, sends a macOS notification when a permission prompt has waited about six seconds or Claude has been idle about 60 seconds (on Linux, use notify-send 'Claude Code' 'Needs your input' instead):

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

Example 2 stops Claude's Edit and Write tools from touching secrets. Save the script as .claude/hooks/guard-secrets.sh, run chmod +x on it (it needs jq), and register it under PreToolUse with the matcher "Edit|Write". In the JSON, the command is "\"$CLAUDE_PROJECT_DIR\"/.claude/hooks/guard-secrets.sh", with the inner quotes escaped:

#!/bin/bash
# Our example: block edits to secret files (PreToolUse, Edit|Write)
FILE_PATH=$(jq -r '.tool_input.file_path // empty')
FILE_PATH="${FILE_PATH//\\//}"  # Windows backslashes to /
case "$FILE_PATH" in
  *.env|*.env.*|*.pem|*/secrets/*)
    echo "Blocked: $FILE_PATH is a protected file" >&2
    exit 2 ;;
esac
exit 0

This does not stop shell commands from changing those files; the docs pair it with Edit deny rules or the sandbox. Example 3, in .claude/settings.json, reminds Claude of key rules after every compaction, using the compact matcher on SessionStart:

{
  "hooks": {
    "SessionStart": [
      {
        "matcher": "compact",
        "hooks": [
          { "type": "command", "command": "echo 'Reminder: run the tests before finishing.'; git log --oneline -5 2>/dev/null || true" }
        ]
      }
    ]
  }
}

What are subagents in Claude Code?

A subagent is a separate Claude assistant with its own context window, system prompt, tools and permissions. Claude hands it a task, it works independently and returns only its result, so file contents and logs it reads stay out of your main conversation. Its requests count toward the same usage limits as the rest of your session.

The main built-ins are Explore (read-only codebase search), Plan (research during plan mode) and general-purpose (multi-step work that can edit); helpers such as statusline-setup and claude-code-guide run automatically. Explore and Plan start without your CLAUDE.md files and git status; custom subagents load CLAUDE.md like the main conversation unless they set omitClaudeMd.

How do you write a subagent file?

Create a markdown file with YAML frontmatter in .claude/agents/ for one project or ~/.claude/agents/ for all of them. Only name and description are required, and the body becomes the subagent's system prompt. Claude Code notices new or edited files within a few seconds.

---
name: log-summarizer
description: Reads long test or build logs and reports only the failures. Use proactively when a log is long.
tools: Read, Grep, Glob
model: haiku
---

You read logs and report each failure with its file, line and error
message. Do not edit files. Keep the report under 20 lines.

That is our example: read-only tools and a lower-cost model for a simple job. Other frontmatter fields include disallowedTools, permissionMode, maxTurns, skills (preloaded in full), mcpServers, hooks, memory, effort, background and isolation: worktree. Field names are camelCase and an unknown field is ignored without an error. A file with no name, or a name but no description, does not load.

Claude delegates when your request matches a description; you can also name the subagent in your prompt, @-mention it, or run a whole session as it with claude --agent log-summarizer.

Hooks, skills or subagents: which should you use?

Use a hook when something must happen the same way every time with no judgment, a skill for reusable instructions Claude applies in your main conversation, and a subagent for self-contained work whose details you do not need to see.

Based on Anthropic's Extend Claude Code page.
AspectHookSkillSubagent
RunsA command, HTTP call, MCP tool, LLM prompt or subagentInstructions Claude readsA separate Claude worker
Triggered byLifecycle events/name, or Claude matching its descriptionClaude delegating, or you naming it
Context costZero unless the hook returns outputDescription every session, full text when usedOwn window; only the summary returns
Best forLinting after edits, blocking unsafe commands, logging, notificationsChecklists, style guides, playbooksBig searches, log reading, parallel work, independent review

They combine: a subagent can preload skills, a skill can run in a forked context, and a subagent file can carry its own hooks. CLAUDE.md is for what Claude should always know, but it is guidance; a rule that must hold every time belongs in a hook.

What do hooks and subagents cost?

Hooks add no context unless they return output, and a hook can even save tokens: the costs page shows one that trims test output before Claude reads it. Subagents keep your main context small but send their own requests, which draw on your usage.

  • Anthropic's best-practices page says delegating the same task to a subagent does not produce a better answer; a fresh reviewer helps because it has not seen your reasoning.
  • For simple subagent tasks, the costs page suggests model: haiku.
  • Since v2.1.217, a session can run 20 subagents at once by default (CLAUDE_CODE_MAX_CONCURRENT_SUBAGENTS changes it). Subagents can nest three layers below the main conversation.
  • Subagent descriptions load every session; above 15,000 tokens combined, Claude Code warns at startup.

Why isn't my hook or subagent working?

Run /hooks: if the hook is missing, it was not loaded. The usual causes are a matcher written as an array, a lowercase tool name, or hooks placed in a standalone file instead of settings.json. In interactive sessions, hooks wait until you accept the workspace trust dialog for the folder.

For more detail, start claude --debug and read ~/.claude/debug/<session-id>.txt, which records each hook run, and why a subagent file was skipped. Since v2.1.296 it also names frontmatter fields it did not recognize.

Frequently asked questions

  • Can a hook approve a command automatically? Yes: a PreToolUse hook can return permissionDecision allow, but deny and ask rules still apply.
  • Do my settings.json hooks run inside subagents? Yes. Hooks from settings files, managed policy and plugins also fire for a subagent's tool calls.
  • Do hooks run in claude -p? Yes, and -p treats the folder as trusted, so review a repository's .claude/ settings before scripting claude -p over code you did not write.
  • Where do I see which subagents exist? In .claude/agents/ and ~/.claude/agents/; type @ in a session to pick one from the list.

Source: Automate actions with hooks (Claude Code docs), Hooks reference (Claude Code docs), Create custom subagents (Claude Code docs), Extend Claude Code: hooks, skills, subagents compared (Claude Code docs), Manage costs effectively (Claude Code docs), Extend Claude with skills (Claude Code docs), Best practices for Claude Code (Claude Code docs), Debug your configuration (Claude Code docs), Claude Code changelog