Claude Code Hooks: Wetin Dem Dey Do and How E Work
Claude Code hooks dey run whether model agree or no. Learn where dem live, event names, stdin JSON, and how exit code 2 fit stop tool call.
Wetin Claude Code hook be
Claude Code hooks na shell commands wey Claude Code dey run by itself for fixed points inside im own lifecycle. Na this be the main difference between hook and rules file. Instruction for CLAUDE.md na advice, and model dey weigh am against everything else wey dey im context. Hook na code, and e go run whether model agree or not. If your agent dey skip formatter wey you don tell am about twice, you no need stronger instruction. You need hook.
The mechanism small. You register command for settings file under event name. When that event happen, Claude Code go run your command and write event data to im standard input (stdin) as JSON (JavaScript object notation). Your command go read the data, do im work, then answer with exit status. Exit 2 from PreToolUse hook go cancel the tool call before e run, and anything wey your script write to standard error (stderr) go return to model as the reason, unless the hook also print JSON wey contain blocking decision. For that case, the reason inside the JSON get priority.
Event names and field names for here come from Claude Code hooks reference, wey dem check on November 12, 2026. This surface dey change quickly, so check the reference for your own version before you copy JSON from any blog post, including this one. Print your own with claude --version.
Hook configuration dey live for where
Hook na JSON block wey dey inside settings file. Six locations fit hold am, and the file scope na the hook scope.
~/.claude/settings.json: every project for your machine, but e no affect anybody else's..claude/settings.json: one project, committed to the repository, so everybody wey clone am go get the hook..claude/settings.local.json: one project, na your machine only.- Managed policy settings: e cover the whole organisation, and administrator dey set am.
hooks/hooks.jsoninside plugin, e dey active as long as that plugin dey enabled.- Skill or subagent frontmatter. Skill hooks remain active for the rest of the session once you invoke the skill, while subagent hooks dey active as long as that subagent dey run.
Hook entries from these files dey merge instead of overriding each other. Project settings file adds its hooks to the ones for your user settings instead of replacing dem. So one event fit get several hooks from different files. Setting "disableAllHooks": true switches dem off, but one exception dey: hooks from managed policy settings continue to run unless you also apply that setting inside managed settings.
Run /hooks inside a session to list every hook wey dey registered currently. E go group dem by event, and show the source file plus matcher for each one. The menu na read-only, so you need edit the settings file to change a hook. File watcher usually go detect the edit without restart.
Wetin be the Claude Code hook events wey dey exist
The hooks reference list thirty three events, starting from SessionStart reach SessionEnd. Dem cover compaction, subagents, worktrees, and configuration files. Server work dey use some of dem.
PreToolUse: before tool call execute, exceptEndConversation. Na this one fit block the call.PostToolUse: after tool call succeed, exceptEndConversation.PostToolUseFailurego fire when e fail instead. So, if hook must see every outcome, e need both.PermissionRequest: when tool call need permission decision. Na that time approval prompt for show.UserPromptSubmit: when you submit prompt, before Claude process am. Plain-text stdout from successful hook dey add to model context.SessionStartandSessionEnd: for each end of session.SessionStartstill go fire after compaction, under matcher valuecompact.Stop: when Claude finish response. This one na once per turn, no be once per completed task.
For events wey support matchers, group fit carry matcher wey decide which occurrences go run the hook. For tool events, e dey filter by tool name. So, "Edit|Write" go fire for file edits and nothing else. Matchers dey case sensitive. Empty matcher go fire for every occurrence. Tools from MCP (model context protocol) server get names like mcp__<server>__<tool>. So matcher of "mcp__github__.*" go catch tools from one server and leave the others alone.
Stop hooks get one trap wey you need know before you write one. A Stop hook wey block sends the model back to work. By default, Claude Code go override the next block after eight consecutive continuations. The count go reset whenever Claude call tool. Read the stop_hook_active field from hook input and exit 0 when e dey true. Otherwise, your hook fit continue sending Claude back to work.
Wetin hook dey receive for stdin
When Claude wan run npm test, one PreToolUse hook for Bash go read this from stdin:
{
"session_id": "abc123",
"cwd": "/home/deploy/myproject",
"hook_event_name": "PreToolUse",
"tool_name": "Bash",
"tool_input": {
"command": "npm test"
}
}The common input fields na session_id, cwd, transcript_path and hook_event_name; permission_mode no dey send for every event. The tool events add tool_name, tool_input and tool_use_id. Other events get their own fields: UserPromptSubmit get the prompt text, while SessionStart get one source of startup, resume, clear, compact or fork.
jq na the normal way to read this inside shell script, and minimal server image no get am. Install am first with sudo apt install -y jq for Ubuntu and Debian.
Exit status fit do wetin to the tool call wey dey run
There be three possible outcomes.
- Exit 0 mean success, and any valid JSON decision fields still apply, including block or denial. For
PreToolUse, exit 0 without decision no be approval, and the normal permission flow still runs. ForUserPromptSubmit,UserPromptExpansion,SessionStartandPostModelSwitch, plain-text stdout dey added to the model context. For most other events, stdout dey go only to the debug log. - Exit 2 blocks the action for events wey fit block, including
PreToolUse, and stderr becomes the message wey comes with the block unless JSON output contains a blocking decision, where the reason inside the JSON takes priority. Who go read that message depend on the event. ForPreToolUseandStop, the model sees am as the reason. ForUserPromptSubmitandPreModelSwitch, e dey shown to you and e no dey added to the model context. ForPostToolUseandPostToolUseFailure, wey no fit block, the block dey ignored, but stderr still reaches the model as feedback. For most other events wey no fit block, stderr dey shown to you only or dey ignored. ForStop,SubagentStop,TaskCompletedand plugin'sUserPromptSubmithook, exit 2 with empty stdout and missing-file error for stderr dey treated as non-blocking error. - Any other exit code with plain-text or empty stdout normally be non-blocking error. The transcript shows hook error notice wey carries the first line of stderr after the text
Failed with non-blocking status code:. Valid JSON fit still decide the outcome for events likePreToolUse, unless the hook failure blocks the action.WorktreeCreatefails for any nonzero exit, andWorktreeRemovefails for nonzero exit if the directory still dey exist afterward.
For anything beyond block or stay quiet, use exit 0 and print JSON object to stdout instead. A PreToolUse hook makes decision with permissionDecision:
{
"hookSpecificOutput": {
"hookEventName": "PreToolUse",
"permissionDecision": "deny",
"permissionDecisionReason": "Database drops go through a migration, not through the agent."
}
}"allow" skips the interactive prompt where permission rules and the tool approval requirements allow am, "deny" cancels the call and sends the reason to the model, and "ask" requests confirmation. Choose one style for each hook. If you mix exit 2 with JSON decision for stdout, the block still remains, even if the JSON says "allow".
When several hooks match one event, dem run in parallel, while prompt and agent hooks get limited to twelve running at once. A deny from one hook no stop the other hooks, so logging hook still writes its line while guardrail hook denies the same call. For PreToolUse, Claude Code then merges the answers and keeps the most restrictive one, in this order: deny, defer, ask, allow.
Example 1: block destructive command before e run
Save this as .claude/hooks/block-destructive.sh for your project:
#!/bin/bash
# Deny a Bash tool call whose command matches a banned pattern.
INPUT=$(cat)
COMMAND=$(echo "$INPUT" | jq -r '.tool_input.command // empty')
for pattern in 'rm -rf /' 'mkfs' 'dd if=' 'DROP TABLE'; do
if printf '%s' "$COMMAND" | grep -qiF -- "$pattern"; then
echo "Blocked by policy: the command matches '$pattern'. A human runs this one." >&2
exit 2
fi
done
exit 0Make am executable, then register am for PreToolUse inside .claude/settings.json:
chmod +x .claude/hooks/block-destructive.sh{
"hooks": {
"PreToolUse": [
{
"matcher": "Bash",
"hooks": [
{
"type": "command",
"command": "${CLAUDE_PROJECT_DIR}/.claude/hooks/block-destructive.sh",
"timeout": 10,
"statusMessage": "Checking the command against policy"
}
]
}
]
}
}Test the script by hand before you trust am, because hook wey crash on its own input normally fail open when onFailure no set. For Windows without Git Bash, shell-form PreToolUse or PermissionRequest command hook wey fail fit instead block the tool call:
echo '{"tool_name":"Bash","tool_input":{"command":"rm -rf /var/lib/postgresql"}}' \
| .claude/hooks/block-destructive.sh
echo $?You suppose see the Blocked by policy: line for stderr and exit code of 2. Feed am harmless command like ls -la and you suppose see no output and exit code of 0. For a session, the denied call go appear for the transcript with your message as the reason, and the model go read the message and adjust.
One property make this useful: PreToolUse hooks dey fire before permission-mode check, for every permission mode, so deny still hold even under bypassPermissions. Na this make hook useful together with Claude Code auto mode and im permission settings, where prompts don reduce but the hook still dey fire.
Make you understand wetin this be. Pattern matching on command string na guardrail against agent wey dey careless, but e no be boundary against agent wey dey clever, because the same command fit dey written for a form wey your grep no go see. Hard rules belong for permission system and for the account wey the process dey run under.
Example 2: format and lint after every edit
PostToolUse wey get Edit|Write matcher go run after either of those file-editing tools succeed. Save this as .claude/hooks/after-edit.sh:
#!/bin/bash
# Format the edited file, then report lint failures back to the model.
INPUT=$(cat)
FILE=$(echo "$INPUT" | jq -r '.tool_input.file_path // empty')
[ -z "$FILE" ] && exit 0
case "$FILE" in
*.py)
ruff format "$FILE" >/dev/null 2>&1
if ! ruff check "$FILE" >&2; then
exit 2
fi
;;
*.sh)
if ! shellcheck "$FILE" >&2; then
exit 2
fi
;;
esac
exit 0{
"hooks": {
"PostToolUse": [
{
"matcher": "Edit|Write",
"hooks": [
{
"type": "command",
"command": "${CLAUDE_PROJECT_DIR}/.claude/hooks/after-edit.sh",
"timeout": 60
}
]
}
]
}
}Ask Claude make e add one badly indented function to a Python file, then open the file. E go come back formatted. Na your check be say the hook run, because successful hook no show anything for the conversation.
The exit 2 for here no undo anything. PostToolUse dey fire after the tool don already execute, so the edit dey disk either way. Wetin exit 2 give you be say the ruff check output reach the model as feedback, so e fit fix the error wey e just introduce instead make e move on. Na the difference be this between lint failure wey you discover for commit time and one wey the agent repair for the same turn.
Two matcher limits matter for here. Edit|Write no dey see files wey shell command change, and Claude dey write files through Bash often enough make that gap real. For coverage on every call, match Bash too and make the script list changed files with git status --porcelain. For coverage once for every turn, put the scan inside Stop hook instead.
Example 3: audit sake log every tool call
Empty matcher for PostToolUse go fire for every successful tool call except EndConversation. If you send the record go system journal instead of file for home directory, e no mean say the agent own shell no fit reach am: access depend on the account permissions. Users fit read their private per-user journals, while root and members of systemd-journal, adm or wheel fit read all journal files:
{
"hooks": {
"PostToolUse": [
{
"matcher": "",
"hooks": [
{
"type": "command",
"command": "jq -c '{time: now|todate, session: .session_id, cwd: .cwd, tool: .tool_name, input: .tool_input}' | logger -t claude-code -p local0.info"
}
]
}
]
}
}Use journalctl -t claude-code -o cat | tail -n 5 to read am back. If you get permission to read the records, you suppose see one JSON line for every successful tool call apart from EndConversation, with the newest one last. If nothing show, check journal access and whether the hook run; the troubleshooting section below explain the hook.
Add the same block under PostToolUseFailure to capture calls wey fail, because PostToolUse only fire on success and failed command usually na the one wey matter pass. The reason for using logger instead of appending to file for your home directory na ownership: hook dey run as the same user as the agent shell, so anything wey that user fit append to, that user fit also truncate. systemd-journald dey write the journal; protecting am from deletion still depend on the agent account privileges.
Hook run fit last how long
Di data wey dey behind dis chart
[
{
"label": "command, http or mcp_tool hook",
"default_timeout_seconds": 600
},
{
"label": "agent hook",
"default_timeout_seconds": 60
},
{
"label": "prompt hook",
"default_timeout_seconds": 30
},
{
"label": "command, http or mcp_tool on UserPromptSubmit, PreModelSwitch or PostModelSwitch",
"default_timeout_seconds": 30
},
{
"label": "command, http or mcp_tool on MessageDisplay",
"default_timeout_seconds": 10
},
{
"label": "any hook on SessionEnd",
"default_timeout_seconds": 1.5
}
]A command hook get 600 seconds by default, wey be ten minutes. Some events fit reduce this time sharply. SessionEnd hooks dey share 1.5 seconds budget between all of dem, so end-of-session cleanup must quick. But if you set longer timeout for one hook inside your settings files, the shared budget go increase to match am, up to 60 seconds.
If synchronous command, HTTP, or MCP tool hook reach timeout, the system go cancel am and normally e no go produce any decision. For PreModelSwitch, timeout blocks the switch. For PreToolUse guardrail, timeout normally allow the tool call continue into the normal permission flow. The Windows exception wey dey above still apply when onFailure no dey set. Because of this, make guardrail scripts small. Since release 2.1.295, you fit reverse this default for command or http hook with "onFailure": "block". This one turns timeout, crash, or unexpected exit code into a block. But e no affect Stop, SubagentStop, TaskCompleted, TeammateIdle, or background command hooks. For slow work wey nobody dey wait for, like shipping a log somewhere, set "async": true. The hook go run for background and e no go hold the tool call.
Hooks, rules files, skills and MCP servers
People dey confuse four things because all of dem fit change wetin agent dey do. But na only one of dem no be suggestion.
A rules file (CLAUDE.md, or file wey dey under .claude/rules/) na text wey model load into e context. E dey shape behaviour, but e no enforce anything. If long conversation, big diff, and fresh user request dey compete with am, one line from the file fit lose relevance. Na this ordinary mechanism dey make agents ignore the instructions wey you write down.
A skill na folder wey contain instructions and scripts wey model load when e judge say the skill relevant. That judgement na the main purpose of skill, and na there the limit dey too: model still dey decide. You fit see both sides for skill like Ponytail, wey dey push agent towards the smallest change wey go work, because e dey shape how model approach complete task in a way no hook fit do, and na only when model choose to load am.
An MCP (model context protocol) server dey give model new tools wey e fit call. E dey expand wetin agent fit reach. E no make agent use anything, and e na separate process wey you must operate. That one na work by itself: see running MCP servers on a VPS.
Hook na the only one among the four wey runs without model choosing am. Use rules file for preference, and use skill for procedure wey model suppose follow when e apply. Use hook for step wey must happen every time, or for thing wey must never happen. The deeper comparison, including when skill better pass rules file, dey for the skills, MCP and rules files comparison.
Plugin na packaging, no be fifth mechanism. E dey bundle hooks together with skills into one installable unit. Na so team fit ship the same guardrail to every machine: see how Claude Code plugins work.
The security decision for shared VPS
Hook na code wey agent dey trigger, and e dey run as the user wey start Claude Code. E inherit that user's file permissions and environment. For laptop, na workflow question. For VPS wey agent dey run unattended, na security question with four practical parts.
Hook wey dey repository na code wey you no write. .claude/settings.json dey committed, so when you clone repository and start session inside am, e fit register hooks wey come with the repository. For interactive session, Claude Code dey put project hooks behind workspace trust dialog for that folder. This mean say accepting trust na the moment wey you decide to run dem. Read hooks block first. claude -p or SDK session, wey na how unattended agent normally dey run, no dey show that dialog and e dey treat the folder as trusted, so repository hooks go run without asking. Review im .claude/ files before you script against am, or run with --settings '{"disableAllHooks": true}'.
Hook dey see the complete tool input. Audit hook wey dey log tool_input go write every argument of every command inside log, including any token wey happen to dey command line. That log then need the same protection as the secret, and this na part of the bigger problem of keeping secrets away from AI agent.
Hook fit write inside model context. Plain-text stdout from successful SessionStart or UserPromptSubmit hook dey add to the conversation. Hook wey pipe text from outside, issue tracker, or log file dey hand untrusted text to model as if na you type am yourself. Hook wey forward note from another Claude Code session for the same VPS dey do the same thing, and output from one agent no get more reason for trust than output from issue tracker. Treat that stdout as input, no be output.
Privilege na the real control. Run agent as dedicated unprivileged user with only the sudo rules wey e need. PreToolUse deny worth having, and e dey best effort by design: reference talk the same thing about if filter and tell you to use permission system when you need hard deny. Permission rules and account wey process dey run under na the parts wey go hold when pressure come.
One property dey hold for every permission mode. PreToolUse hooks dey fire before permission-mode check for every permission mode, so hook wey return deny go block the tool even under bypassPermissions. Hooks fit make wetin permission rules allow more strict. Dem no fit make am less strict. The exception na mod. For machine wey no get managed settings and no managed-mcp.json file, for session wey no sign in through /login to Team or Enterprise plan, installed mod wey handle tool.check fit approve call wey your PreToolUse hook block. With managed settings, managed-mcp.json file, or Team or Enterprise /login as session credential, call wey PreToolUse hook block go remain blocked by default, no matter which settings file the hook come from. Session wey run with API key or long-lived CLAUDE_CODE_OAUTH_TOKEN, as many servers dey run am, count as not signed in even when login dey stored. Check wetin Claude Code mods fit change before you install one for server.
Why my hook no dey fire?
Work through this one after the other. Each step name the symptom wey you go actually see.
- Run
/hooksand check say the hook dey appear under the event wey you expect. If hook no dey for the menu, e usually mean say the settings file get JSON syntax error, because trailing commas and comments no dey allowed, or the file no dey inside one of the six locations above. - Compare the matcher with the tool name exactly. Matchers dey case sensitive, so
"bash"no go ever matchBashtool. - Run the script by hand with sample input, like example 1 above. If exit code no be the one you expect, na bug dey your script; check the stdout too, because valid JSON still fit provide decision for events like
PreToolUse. - Notice wey read
jq: command not foundmean sayjqdey missing for that machine. Acommand not foundfor your own script mean say the path no resolve, so use${CLAUDE_PROJECT_DIR}or an absolute path. If the script no run at all, e probably no be executable. - The hook print valid JSON but nothing happen. For macOS and Linux, shell-form hook dey run through
sh -cinside non-interactive shell, but some setups still source your profile, likeBASH_ENVwey dey point to~/.bashrc. If that profile print banner, the banner go come before your JSON. Stdout no longer start with{, so Claude Code go read everything as plain text and ignore the decision. Because the hook exit 0, the transcript no show any error. For most events, that text dey go only to the debug log, but forUserPromptSubmit,UserPromptExpansion,SessionStartandPostModelSwitch, e dey add am to the model context, including the banner. Wrap anyechofor your profile so e only run for interactive shells. - You still dey stuck: start the session with
claude --debug-file /tmp/claude.logand runtail -f /tmp/claude.logfor second terminal. The debug log go record which hooks match, the exit code wey each one return, and everything wey dem write to stdout and stderr.
FAQ
CLAUDE.md hook and CLAUDE.md instruction get difference na wetin?
A CLAUDE.md instruction na text wey dey inside model context, so e dey compete for attention with the conversation and current request, and model fit weigh am against dem. A hook na shell command wey Claude Code dey run for one fixed point for e lifecycle, so e go execute every time the event happen, no matter wetin model decide. Use instruction for preference. Use hook for step wey must always happen or action wey must never happen.
How I fit stop Claude Code from running one specific shell command?
Register PreToolUse hook with Bash matcher wey read command from .tool_input.command, write reason to stderr, then exit 2. Claude Code go cancel the call and show model your reason. This one happen before permission-mode check, so the deny still hold even for bypassPermissions mode. Pattern matching for command string na guardrail, no be security boundary, because person fit write the same command for form wey pattern no catch. So support am with permission rules and unprivileged account.
My hook dey print valid JSON but nothing dey happen. Why?
Check your shell profile for text wey e print before the JSON. For macOS and Linux, hook wey no get args field dey run through sh -c. For setups wey still source your profile, like BASH_ENV pointing to ~/.bashrc, profile wey print banner go put am for stdout before your JSON. Because output no longer start with {, Claude Code go treat everything as plain text and ignore the decision. And because hook exit 0, transcript no go show error. Put interactive-shell test around any echo for your profile. Then confirm the fix by reading debug log from claude --debug-file /tmp/claude.log.
E safe to run Claude Code hooks for shared server?
Hooks dey run as the user wey start Claude Code, with that user file permissions. So hook fit do anything wey that account fit do. Two habits cover most of the risk: run the agent with dedicated unprivileged account wey get narrow sudo policy, and read the hooks block for any repository before you accept its workspace trust dialog or run claude -p inside am. This na because project hooks dey inside .claude/settings.json, and -p mode never show that dialog. Set "disableAllHooks": true for your settings file to disable hooks, except managed hooks wey require the setting for managed level. Project setting of false fit override user setting of true.