Claude Code hooks and subagents: what they are and how to use them
Claude Code hooks are commands that Claude Code runs automatically at fixed points in a session, such as before a tool call, and they can block the action. Subagents are specialized assistants that run in their own context window with their own tools and permissions, and return only a summary. Use hooks to enforce rules the model must never break, and subagents to isolate research, review or parallel work from the main conversation.

Why hooks exist
Instructions in a prompt or in CLAUDE.md shape what Claude tries to do. They do not guarantee it. A model that follows a rule on most runs will, sooner or later, miss it on one.
Hooks close that gap. A hook is your code, run by Claude Code itself at a fixed point, with the power to stop an action. The model does not decide whether the hook runs.
The details below were checked against the official Claude Code documentation as of November 2026. The feature set changes often, so confirm names against the current hooks reference before relying on them.
Hook events
Claude Code fires events throughout a session, and a hook attaches to one of them. The current reference lists more than 30 events. These are the ones most teams use:
| Event | When it fires | Typical use |
|---|---|---|
SessionStart |
A session begins | Load context, set up the environment |
UserPromptSubmit |
The user sends a prompt | Add context, validate the prompt |
PreToolUse |
Before a tool call runs | Block dangerous commands or edits |
PostToolUse |
After a tool call succeeds | Run a formatter or linter on changed files |
PermissionRequest |
A permission prompt would appear | Approve or deny automatically |
Notification |
Claude Code sends a notification | Forward alerts to your own channel |
SubagentStart, SubagentStop |
A subagent starts or finishes | Log or check subagent work |
Stop |
Claude finishes responding | Check that the work is complete |
PreCompact |
Before context is compacted | Save state |
SessionEnd |
A session ends | Clean up, write logs |
Other events cover worktree creation and removal, configuration changes, file changes and more.
How a hook is configured
Hooks live under the hooks key of a settings file. The structure has three levels: the event, a matcher group that filters when it applies, and one or more handlers.
{
"hooks": {
"PreToolUse": [
{
"matcher": "Bash",
"hooks": [
{
"type": "command",
"command": "${CLAUDE_PROJECT_DIR}/.claude/hooks/block-force-push.sh"
}
]
}
]
}
}
matcherfilters by tool name for tool events."Bash"matches shell commands.typeis the handler type.commandruns a shell command. The reference also listshttp,mcp_tool,promptandagenthandlers.commandis what to run.${CLAUDE_PROJECT_DIR}resolves to the project root where the session started, so the path works from any directory.
Handlers accept optional fields too, including timeout and an if condition written in permission rule syntax, such as "Bash(rm *)".
Where the file lives decides who gets the hook: ~/.claude/settings.json applies to all your projects, .claude/settings.json is the project file you commit, and .claude/settings.local.json is the project file you keep out of git.
What a hook receives and returns
A command hook receives a JSON object on stdin. For PreToolUse, the fields include session_id, cwd, permission_mode, hook_event_name, tool_name and tool_input. For a Bash call, the command text is at tool_input.command.
The hook answers through its exit code:
- Exit 0. Success. If stdout is a single JSON object, Claude Code applies its fields. With no output, no decision is made and the normal permission flow continues.
- Exit 2. A blocking error. On
PreToolUse, the tool call is blocked and the text on stderr is passed to Claude as the reason. - Any other code. A non-blocking error. The action proceeds and a hook error notice is shown.
That last point catches people out. A guard script that crashes with exit code 1 does not block anything. Blocking requires exit code 2 or a JSON decision.
For finer control, exit 0 and print JSON. A PreToolUse hook can set permissionDecision to allow, deny, ask or defer, with a reason:
{
"hookSpecificOutput": {
"hookEventName": "PreToolUse",
"permissionDecision": "deny",
"permissionDecisionReason": "Destructive command blocked by hook"
}
}
A working PreToolUse guard hook
This hook blocks git push --force and git push -f. A force push can overwrite other people’s commits, and an agent that hits a rejected push may try it as a fix.
Save this as .claude/hooks/block-force-push.sh:
#!/bin/bash
# .claude/hooks/block-force-push.sh
COMMAND=$(jq -r '.tool_input.command // empty')
if echo "$COMMAND" | grep -Eq 'git[[:space:]]+push.*(--force|[[:space:]]-f([[:space:]]|$))'; then
echo "Blocked: force push is not allowed in this repo. Push a new commit instead." >&2
exit 2
fi
exit 0
Make it executable:
chmod +x .claude/hooks/block-force-push.sh
Then register it with the settings block shown in the configuration section above. The script needs jq on the PATH.
How it works: the script reads the event JSON from stdin, extracts the command, and tests it against a pattern. On a match it writes the reason to stderr and exits with code 2, which blocks the call. Claude reads the reason and chooses another route. On no match it exits 0 and the normal permission flow continues. The pattern also matches --force-with-lease. Narrow it if your team allows that variant.
Test it without Claude Code by piping sample input:
echo '{"tool_name":"Bash","tool_input":{"command":"git push --force origin main"}}' \
| .claude/hooks/block-force-push.sh; echo "exit: $?"
This prints the block message and exit: 2. The same test with git push origin main prints exit: 0.
Limits of pattern-matching hooks
A text pattern catches the form of the command the model usually writes. It will not catch every way to reach the same effect, for example a script that runs the push internally. Treat guard hooks as one layer. Pair them with permission deny rules, branch protection on the server, and credentials that cannot do the dangerous thing at all.
How hooks interact with permissions
Two rules from the permissions documentation are worth knowing:
- A hook that blocks wins over allow rules. A hook that exits with code 2 stops the call before permission rules are evaluated.
- A hook that returns
allowdoes not override deny rules. A matching deny rule still blocks the call.
So hooks can tighten the rules freely but cannot loosen a deny. That is the right shape for a safety layer.
Hooks from real incidents
The most useful hooks come from things that went wrong. Shai’s production codebase has guard hooks that block two SQL patterns that caused real incidents. Once the hook existed, the pattern could not be written again by any agent, in an interactive session, an overnight run or CI.
The method is general. After an incident, ask whether a check before the tool call could have stopped it. If yes, write the hook the same day and commit it. Our Claude Code best practices post covers how hooks fit with permission envelopes and worktrees, and Supabase Row Level Security covers the database side of those guardrails.
What subagents are
A subagent is a specialized assistant that Claude can delegate a task to. Each subagent runs in its own context window with a custom system prompt, specific tool access and independent permissions. It does not see your conversation history. Claude writes it a task message, it does the work, and only its summary comes back.
That last property is the main benefit. A search across 200 files produces a lot of output. Done in the main session, it fills the context. Done in a subagent, the main session receives a few paragraphs.
Claude Code ships with built-in subagents, including Explore (a fast, read-only agent for searching code), Plan (used in plan mode to gather context) and a general-purpose agent for multi-step tasks.
Defining a subagent
A custom subagent is a Markdown file with YAML frontmatter, stored in .claude/agents/ for the project or ~/.claude/agents/ for all your projects. Only name and description are required.
---
name: code-reviewer
description: Reviews code for quality and best practices
tools: Read, Glob, Grep
model: sonnet
---
You are a code reviewer. When invoked, analyze the code and provide
specific, actionable feedback on quality, security, and best practices.
The description tells Claude when to delegate. The tools list limits what the subagent can do. This reviewer can read and search but cannot edit or run commands. Other supported fields include disallowedTools, permissionMode, maxTurns, skills, mcpServers, hooks and isolation.
Claude delegates automatically when a task matches a description. You can also ask by name (“use the code-reviewer subagent on the auth changes”).
Two fields connect to the rest of this post. isolation: worktree runs the subagent in a temporary git worktree, so parallel subagents do not edit the same files. hooks attaches hooks that run only while that subagent is active, so a database-migration subagent can carry its own SQL guard.
When to use subagents
| Situation | Main session | Subagent |
|---|---|---|
| Quick lookup in a known file | Yes | No |
| Broad search across the codebase | No | Yes, read-only |
| Independent review of a change | No | Yes, with restricted tools |
| Several independent tasks at once | No | Yes, in worktrees |
| A task that needs the conversation’s full history | Yes | No |
| Small edit you want to watch | Yes | No |
Subagents have costs. Each starts without your conversation’s context, so the delegation message must carry everything it needs. They count toward the same usage limits. And a summary can leave out a detail you needed. For a handful of tool calls, do the work in the main session.
What to do next
Write one guard hook this week for the worst thing an agent could do in your repository, and commit it. Then add a read-only reviewer subagent. If you want hooks, permission envelopes and subagents set up across your team’s repositories, our Claude Code training program does that in 4 to 8 weeks at a fixed price, quoted after a 30-minute scoping call. For a review of what agents have already written, see our security audit.