How Claude Code hooks work, with examples for edits, Bash and MCP tools
On this page
Claude Code hooks are handlers that Claude Code runs automatically at fixed points in a session: before a tool call, after a file edit, when Claude stops, when a session starts. You define them under hooks in a settings.json file. A command hook receives the event as JSON on stdin and answers with an exit code or a JSON object, and on events such as PreToolUse that answer can block the action. Unlike an instruction in CLAUDE.md, a hook runs every time its event fires, whatever the model decides.
Checked as of November 2026 against Anthropic’s hooks reference and hooks guide.
Claude Code hook events
The reference documents a long list of events. These are the ones most setups use:
| Event | Fires | Can block |
|---|---|---|
SessionStart | When a session starts or resumes | No; can add context |
UserPromptSubmit | When you submit a prompt, before Claude sees it | Yes, rejects the prompt |
PreToolUse | After Claude builds a tool call, before it runs | Yes |
PermissionRequest | When a call needs a permission decision | Through its decision object, not exit 2 |
PostToolUse | After a tool call succeeds | No, the tool already ran |
PostToolUseFailure | After a tool call fails | No |
Notification | When Claude Code sends a notification | No |
Stop / SubagentStop | When Claude or a subagent finishes responding | Yes, keeps it working |
PreCompact | Before context compaction | Yes |
Elicitation | When an MCP server asks for user input during a tool call | Yes, declines the request |
SessionEnd | When the session ends | No |
Others cover subagents, tasks, worktrees, config changes, file changes, model switches and more. A handler can be a shell command (type: "command"), an HTTP endpoint (http), a tool on a configured MCP server (mcp_tool), a single-turn model prompt (prompt) or a subagent (agent). This post sticks to command hooks.
Where hooks are configured
| File | Scope |
|---|---|
~/.claude/settings.json | All your projects on this machine |
.claude/settings.json | One project; can be committed |
.claude/settings.local.json | One project, only you |
| Managed policy settings | The whole organization |
A plugin’s hooks/hooks.json | While the plugin is enabled |
| Skill or subagent frontmatter | While that skill or subagent is active |
Hook entries merge across files instead of replacing each other, and a handler defined identically in two files runs once. Type /hooks to see every configured hook and which file it came from; the menu is read-only, so edit the files to change anything. "disableAllHooks": true turns hooks off without deleting them, though it can’t disable managed hooks from outside managed settings. Administrators can set allowManagedHooksOnly in managed settings to block user, project, local and plugin hooks.
Matcher syntax
Each event holds matcher groups, and each group holds handlers:
{
"hooks": {
"PostToolUse": [
{
"matcher": "Edit|Write",
"hooks": [{ "type": "command", "command": "/path/to/lint-check.sh" }]
}
]
}
}
For tool events the matcher is tested against the tool name. How it’s read depends on its characters:
"*",""or no matcher matches everything.- Letters, digits,
_,-, spaces,,and|only: an exact name or a list of exact names.Edit|WriteandEdit, Writematch those two tools. - Anything else: an unanchored JavaScript regular expression.
Edit.*matchesNotebookEdittoo, so write^Edit$for an exact match.
MCP tools are named mcp__<server>__<tool>, so mcp__github__.* matches every tool from a server you added as github. The .* is required: mcp__github contains only exact-match characters and matches no tool at all.
For finer filtering, a handler’s if field takes one permission rule, such as "Bash(git *)" or "Edit(*.ts)", and the handler only spawns when the call matches. The docs call if best-effort for Bash: when Claude Code can’t split a command into subcommands, the hook runs anyway.
The JSON a hook receives
Command hooks get the event on stdin. A PreToolUse hook for Bash receives roughly this (trimmed):
{
"session_id": "abc123",
"cwd": "/home/user/my-project",
"permission_mode": "default",
"hook_event_name": "PreToolUse",
"tool_name": "Bash",
"tool_input": { "command": "npm test", "description": "Run test suite" },
"tool_use_id": "toolu_01ABC123..."
}
tool_input follows the tool’s own schema. For file tools, tool_input.file_path is always absolute, which stops a path check being dodged with ~ or a relative path. For MCP tools, recent versions (v2.1.274 and later) add an mcp_server object with the server’s name and a source such as user, project or plugin. The docs say to base trust decisions on source rather than on the name.
Exit codes and JSON output
The exit code decides the outcome when stdout isn’t a valid JSON object:
0: success. Nothing printed means “no decision”, and the normal permission flow continues. A silent hook doesn’t approve anything.2: blocking error on events that can block. Claude Code stops the action and shows Claude your stderr as the reason.- Any other code: non-blocking error. The action goes ahead and you see a hook error notice.
That last one catches people. Exit 1 is the usual Unix failure code, and in a hook it lets the call through. Use exit 2 for policy.
For more control, exit 0 and print one JSON object. PreToolUse uses hookSpecificOutput:
{
"hookSpecificOutput": {
"hookEventName": "PreToolUse",
"permissionDecision": "deny",
"permissionDecisionReason": "Writes to the production database are not allowed"
}
}
permissionDecision can be allow, deny, ask (show the permission prompt) or defer (only in -p runs). The hook can also return updatedInput to rewrite the call’s arguments. When several hooks answer, the most restrictive wins: deny, then defer, then ask, then allow. Other events such as PostToolUse and Stop use a top-level "decision": "block" with a reason.
Two failure cases matter for guard hooks. A hook that can’t start, crashes or times out doesn’t block by default, so a typo in the script path silently disables your policy. Setting "onFailure": "block" on the handler (v2.1.295 and later) turns those failures into a block. Command hooks time out after 600 seconds (30 on UserPromptSubmit) unless you set timeout.
Format files after every edit
From the hooks guide: run Prettier on each file Claude writes or edits.
{
"hooks": {
"PostToolUse": [
{
"matcher": "Edit|Write",
"hooks": [
{
"type": "command",
"command": "f=$(jq -r '.tool_input.file_path') && npx prettier --write --ignore-unknown \"$f\""
}
]
}
]
}
}
It won’t fire when a Bash command rewrites the file. For that, the docs point to the FileChanged event.
Block a dangerous Bash command
Save this as .claude/hooks/bash-guard.sh and make it executable:
#!/bin/bash
cmd=$(jq -r '.tool_input.command')
if grep -Eq 'rm -rf|git push (.* )?(--force|-f)( |$)' <<<"$cmd"; then
echo "Blocked by bash-guard: $cmd" >&2
exit 2
fi
exit 0
Register it in .claude/settings.json. Exec form (args present) runs the script without a shell, so the path needs no quoting:
{
"hooks": {
"PreToolUse": [
{
"matcher": "Bash",
"hooks": [
{
"type": "command",
"command": "${CLAUDE_PROJECT_DIR}/.claude/hooks/bash-guard.sh",
"args": [],
"onFailure": "block"
}
]
}
]
}
}
--force-with-lease passes; --force and -f don’t. Treat this as a guardrail: a string match is easy to sidestep with /bin/rm or a script file. The Claude Code permissions guide explains why command-text rules have the same weakness and where the sandbox fits.
A PreToolUse hook on MCP tools
Permission rules can allow or deny a GitHub MCP tool by name, but not by argument. A hook can. This one, matched on mcp__github__.*, logs every GitHub call, refuses file writes straight to main or master, and forces a prompt before merges:
#!/bin/bash
# .claude/hooks/github-guard.sh
input=$(cat)
tool=$(jq -r '.tool_name' <<<"$input")
branch=$(jq -r '.tool_input.branch // empty' <<<"$input")
printf '%s %s\n' "$(date -u +%FT%TZ)" "$tool" >> "$HOME/.claude/github-mcp.log"
case "$tool" in
mcp__github__push_files|mcp__github__create_or_update_file|mcp__github__delete_file)
if [[ "$branch" == "main" || "$branch" == "master" ]]; then
echo "Direct writes to $branch are blocked. Use a feature branch and a pull request." >&2
exit 2
fi
;;
mcp__github__merge_pull_request)
jq -n '{hookSpecificOutput: {hookEventName: "PreToolUse", permissionDecision: "ask", permissionDecisionReason: "Merging a pull request"}}'
;;
esac
exit 0
{
"hooks": {
"PreToolUse": [
{
"matcher": "mcp__github__.*",
"hooks": [
{
"type": "command",
"command": "${CLAUDE_PROJECT_DIR}/.claude/hooks/github-guard.sh",
"args": [],
"onFailure": "block"
}
]
}
]
}
}
The tool and argument names come from GitHub’s server (push_files takes a branch argument); check /mcp for the names your server exposes. The GitHub integration page lists that server’s tools and setup.
How hooks relate to permission rules
Hooks and allow/ask/deny rules are separate layers, and the docs are specific about how they meet:
- A hook’s
denyholds in every permission mode, includingbypassPermissionsand--dangerously-skip-permissions.PreToolUsefires before the permission mode is checked. - A hook’s
allowskips the prompt but doesn’t override deny or ask rules from settings, which are still evaluated. It also can’t skip the prompt for MCP tools a server marks as requiring user interaction. - A hook that exits 0 with no output leaves the decision to the normal rules.
So use permission rules for decisions by tool name, and hooks for decisions that depend on arguments, files or outside state. A hook can tighten what your rules allow; it can’t loosen what they deny. If you run with prompts off, what –dangerously-skip-permissions skips covers what still applies.
Security cautions
- Hooks run as you. Anthropic’s warning is direct: command hooks execute with your full user permissions and can read, change or delete anything your account can.
- Repositories can ship hooks. In an interactive session, Claude Code holds back hooks from settings files until you accept the workspace trust dialog. A
-por SDK run never shows that dialog and treats the folder as trusted, so a cloned repository’s.claude/settings.jsonhooks run. Before scriptingclaude -pover code you didn’t write, review its.claude/directory or pass--settings '{"disableAllHooks": true}'. - Treat input as untrusted. Quote shell variables, use absolute paths through
${CLAUDE_PROJECT_DIR}, reject..in paths and skip.env,.git/and key files, as the reference recommends. - Fail closed where it matters. Set
onFailure: "block"on policy hooks, and watch for a hook error notice the first time one runs. - Hooks only see Claude Code. The same MCP server added to Cursor or Codex on the same laptop gets none of these checks.
That last limit is where a gateway fits for remote servers. Toolstile applies Allow, Require approval or Block per tool for each agent before forwarding a call, and logs every call, whichever app made it; it doesn’t cover local tools like Bash. Permissions describes the rules.