
Claude Code Hook Not Blocking? I Tested 16 Failures
A Claude Code PreToolUse hook only blocks a tool call when it exits 2 or prints a JSON deny. Every other failure, including exit 1, a crash, a missing script and a timeout, is a non-blocking error, so the tool runs anyway. "onFailure": "block" fixes most of that, but not all of it. I broke the same Bash hook 16 different ways this morning on Claude Code 2.1.325 and on 2.1.328, which shipped today. Three of the failures got past onFailure: "block"too. Here's the table, why those three slip through, and two hook templates that failed closed in every test.
Which Hook Failures Let the Tool Run?
Each run asked Claude to touch a marker file through Bash, with one PreToolUse command hook in front of it. If the file existed afterwards, the hook failed open. I ran every case twice, once with onFailure unset and once set to "block", on both versions. Both versions gave identical results. The last column marks the cases where claude -p emitted a warning event, which I cover further down.
| What the hook did | onFailure unset | onFailure: block | Warning event |
|---|---|---|---|
| Exit 0, no output (control) | Tool ran | Tool ran | none |
| Exit 2, reason on stderr | Blocked | Blocked | none |
| Exit 0, deny JSON on one line | Blocked | Blocked | none |
| Exit 0, deny JSON pretty-printed | Blocked | Blocked | none |
| Exit 1, deny JSON | Blocked | Blocked | none |
| Exit 1, reason on stderr | Tool ran | Blocked | none |
| Python crash (KeyError, exit 1) | Tool ran | Blocked | none |
| Exit 1, allow JSON | Tool ran | Blocked | none |
| Script path missing (shell form) | Tool ran | Blocked | hook_no_verdict |
| node script missing (exec form) | Tool ran | Blocked | none |
| Timeout (3 s limit, script sleeps 20 s) | Tool ran | Blocked | hook_no_verdict |
| Invalid JSON with closing brace | Tool ran | Blocked | hook_no_verdict |
| Valid JSON, decision "maybe" | Tool ran | Blocked | hook_no_verdict |
| JSON cut off, no closing brace | Tool ran | Tool ran | none |
| Log line on stdout, then deny JSON | Tool ran | Tool ran | none |
| jq missing inside script, exits 0 | Tool ran | Tool ran | none |
With onFailure unset, all 11 of the genuinely broken hooks let the command through. Only exit 2 and a JSON denystopped it. That includes the one I see most in real repos: a script that prints its reason and exits 1, because 1 is what every Unix tool uses for "no". The hooks reference does say this, in a callout: exit 1 without valid JSON is a non-blocking error. The GitHub issue tracker is full of people who found out the hard way.
One row is the other way around. A hook that prints a deny JSON and exits 1 still blocked. When the JSON is valid, Claude Code reads the decision field and ignores the odd exit code. So the JSON path is a little more forgiving than the exit code path.
What Does onFailure: "block" Change?
It turns a hook failure into an exit 2. The field landed in 2.1.295 (October 8) for command and HTTP hooks, and today's 2.1.328 added it for mcp_toolhooks too (I didn't test that type). A failure here means the hook couldn't start, exited with something other than 0 or 2, timed out, or printed JSON that didn't parse or validate. With the field set, all eight of those rows flipped to blocked, and the tool result Claude got back named the cause:
PreToolUse:Bash hook error: [.../hooks/exit1.sh]: failed; blocking because onFailure is "block"
policy: touch is not allowedA timeout says timed out instead of failed. Compare that with what Claude saw when the same exit-1 hook ran with the field unset: (Bash completed with no output). Nothing else. Claude's final answer was "The command ran successfully and created the marker file." Neither the model nor the person reading the output gets told a policy check was skipped.
Put onFailure: "block" on every hook that enforces policy. Leave it off for hooks that only format, log or notify. A broken formatter shouldn't stop Claude from editing files. It has no effect on async hooks or on Stop and SubagentStop hooks, which the docs call out.
Why Do 3 Failures Get Past onFailure: "block"?
Because Claude Code doesn't see them as failures. From where it sits, the hook exited 0 and printed some plain text, and plain text from an exit-0 PreToolUse hook means "fine, carry on".
A log line before the JSON.This is the one that worries me, because it's so easy to add while debugging:
#!/bin/sh
echo "checking command against policy..." # <- this line kills the deny
echo '{"hookSpecificOutput":{"hookEventName":"PreToolUse","permissionDecision":"deny","permissionDecisionReason":"policy"}}'
exit 0The docs spell out the rule. Stdout counts as JSON only when it's one object with nothing around it but whitespace. One echo above the object turns the whole stdout into plain text, so the deny is never read. The tool ran in both modes. Pretty-printed JSON across several lines was fine. Only extra text broke it.
JSON cut off before the closing brace. A script that dies halfway through writing its output, or a printf missing its last }, leaves stdout starting with { but not ending with }. Claude Code only treats text as broken JSON when it starts with { and ends with }. Mine didn't, so it counted as plain text and the tool ran. The same JSON with a trailing comma and both braces was caught as invalid and blocked.
An error the script swallows. My jq-missing hook ran cmd=$(jq_not_installed -r .tool_input.command) in plain sh. The command failed, $cmd came back empty, nothing matched the blocklist and the script exited 0. This is how most hooks break when they move from a laptop to a CI image without jq. No setting in Claude Code can catch it, because the script itself reported success. That's the hook's job to handle, and it's what the templates below do.
What Happens When a Claude Code Hook Times Out?
Claude Code cancels it, throws away anything it printed, and on PreToolUse lets the call continue through the normal permission flow. With a 3-second timeout, the run took 5.5 seconds against about 2.5 for the others, so the cost is just the wait. Then the command ran.
The default is the problem. Command hooks get 600 seconds unless you set timeout. A policy hook that calls an internal API which hangs will freeze the tool call for ten minutes and then let it through. I didn't wait out a real 600-second run, but the 3-second case behaved the way the docs describe, and nothing suggests the default works differently. Set timeout to 5-10 seconds on policy hooks and add onFailure: "block", so a hang costs seconds and fails closed.
Can You Detect a Skipped Hook in claude -p?
Partly. In --output-format stream-json, four of the failure types produced a system event like this one:
{"type":"system","subtype":"informational","level":"warning","tag":"hook_no_verdict",
"content":"A hook didn't answer in time, so it didn't check this action.",
"hook_no_verdict":{"hook_event":"PreToolUse","timed_out":true}}The missing shell script, the timeout, the invalid JSON and the schema-invalid JSON each emitted it. Exit 1, the Python crash and the missing node script didn't. Neither did any of the three silent cases. The process exit code was 0 for all 69 runs, blocked or not, which fits what I found when I tested claude -p exit codes.
Alert on hook_no_verdict in CI logs, but don't rely on it.It missed the most common failure, exit 1. The only reliable fix is a hook that can't fail open.
How Do You Make a PreToolUse Hook Fail Closed?
Two layers. Claude Code's onFailurecovers the hook not running properly. The script covers its own mistakes. Here's the bash version I tested:
#!/bin/bash
# PreToolUse guard for Bash. Fails closed: any error in here becomes exit 2.
set -euo pipefail
trap 'echo "guard.sh crashed at line $LINENO, blocking to be safe" >&2; exit 2' ERR
cmd=$(jq -er '.tool_input.command') # -e: null or missing = error
echo "guard: checking $cmd" >&2 # logs go to stderr, never stdout
case "$cmd" in
*"rm -rf"*|*"git push --force"*)
echo "Blocked by policy: $cmd" >&2
exit 2 ;;
esac
exit 0set -euo pipefail plus the ERR trap turns any failed command into exit 2. jq -e matters more than it looks: without it, a payload with no command field gives you the string null, which passes the blocklist. I hit that in my first draft. The Python version does the same with a try:
#!/usr/bin/env python3
"""PreToolUse guard for Bash. Fails closed: any crash becomes exit 2."""
import json, sys
BLOCKED = ("rm -rf", "git push --force")
def main() -> int:
data = json.load(sys.stdin)
cmd = data["tool_input"]["command"]
print(f"guard: checking {cmd}", file=sys.stderr) # stderr only
if any(b in cmd for b in BLOCKED):
print(f"Blocked by policy: {cmd}", file=sys.stderr)
return 2
return 0
if __name__ == "__main__":
try:
sys.exit(main())
except Exception as e: # bad input, typo, missing key: block
print(f"guard.py crashed ({e!r}), blocking to be safe", file=sys.stderr)
sys.exit(2)I piped four payloads into each one: a normal command, an rm -rf, a payload missing command, and plain garbage. The normal command got exit 0. The other three got exit 2, with nothing on stdout. The bash guard also exited 2 with jq removed from PATH. Wired into Claude Code with the settings below, both let a normal touchthrough. Versions of both that I broke on purpose (a missing binary, a typo'd key) blocked the call with onFailure unset, so the script layer works on its own.
{
"hooks": {
"PreToolUse": [
{
"matcher": "Bash",
"hooks": [
{
"type": "command",
"command": "${CLAUDE_PROJECT_DIR}/.claude/hooks/guard.sh",
"timeout": 10,
"onFailure": "block"
}
]
}
]
}
}The checklist, short version: exit 2 to block, logs to stderr, fail closed inside the script, onFailure: "block", short timeout.And when you add a policy hook, test it broken. Rename the script and confirm the call gets blocked. That takes 30 seconds, and it's how I'd have caught every case above.
Hooks are one layer. For file writes I'd still pair them with the deny rules from blocking writes outside the working directory and the OS-level Claude Code sandbox, so one broken script isn't the only thing in the way.
Claude Code Hook FAQ
Why doesn't my Claude Code PreToolUse hook block the tool?
Most often it exits 1. Only exit code 2, or exit 0 with JSON that sets permissionDecision to deny, blocks a PreToolUse call. Exit 1, a crash, a missing script, a timeout and invalid JSON are all non-blocking errors, so the tool runs unless the hook has onFailure set to block.
What does onFailure block do in Claude Code hooks?
It makes a hook failure act like exit 2. If the hook can't start, exits with a code other than 0 or 2, times out, or prints invalid JSON, the action is blocked and the tool result says 'failed; blocking because onFailure is "block"' or 'timed out'. It needs Claude Code 2.1.295 or later and has no effect on async hooks or Stop hooks.
Can a hook still fail open with onFailure block set?
Yes. In my tests three cases let the tool run anyway: a log line printed to stdout before the deny JSON, JSON cut off before its closing brace, and a script that hit an error and still exited 0. Claude Code reads all three as plain-text output from a successful hook.
What happens when a Claude Code hook times out?
Claude Code cancels it and discards its output. On PreToolUse the tool call then goes ahead unless onFailure is block. The default timeout for command hooks is 600 seconds, so a hung policy hook can hold a tool call for 10 minutes and then let it run.
Do PreToolUse hooks run in bypassPermissions mode?
Yes. Every test in this post ran claude -p with --permission-mode bypassPermissions on Claude Code 2.1.325 and 2.1.328, and exit 2 or a deny JSON blocked the Bash call each time.
How I Tested
November 19, 2026, on a Mac mini in Allen, TX. Claude Code 2.1.325 (my installed build) and 2.1.328 (npm latest, released this morning; stable is still 2.1.311, which already has onFailure), signed in to a Max plan. Every run was claude -p with claude-haiku-5-5 at --effort low, --tools Bash, --permission-mode bypassPermissions, --setting-sources "", the hook passed through --settings, an empty MCP config, and stream-json output. A Python harness ran them with a clean environment and stdin closed, and checked for the marker file after each run. That's 16 cases x 2 modes x 2 versions = 64 runs, plus 5 for the templates, about $0.03 at list price. The prompt told Claude not to retry after a block, and each run made exactly one tool call. I only tested PreToolUse command hooks on Bash, not HTTP or mcp_tool hooks, other events, or subagents.
If you're starting from zero, my six production hooks are a decent base. Run each one through the rename test before you trust it.
Guardrails You Can Actually Trust
I set up Claude Code and agent pipelines that run unattended, with hooks and permissions that fail closed. If you want a second pair of eyes on yours, send me your settings.json.
Related Posts
AI Agents
Claude Code Mods vs Hooks: Which One Should You Use?
Claude Code 2.1.287 added mods: TypeScript handlers that run inside Claude Code. I built the same .env guard as a mod and as a PreToolUse hook, ran both headless, and found the mod runs first and silences your project hooks.
AI Agents
Claude Code Sandbox: What It Actually Blocks
The Claude Code sandbox runs Bash and every process it spawns inside an OS-enforced boundary — Seatbelt on macOS, bubblewrap on Linux and WSL2. Writes are locked to your working directory; network egress is denied until you allow a domain. Reads are not restricted, so a sandboxed command can still open ~/.ssh and ~/.aws/credentials on a default setup. That asymmetry decides how you configure it: deny the credentials explicitly, keep allowedDomains narrow with strictAllowlist on, and set allowUnsandboxedCommands to false before anything runs unattended.
AI Agents
Claude Code Hooks: The 6 I Actually Run in Production (2026)
Hooks are shell commands that fire automatically at lifecycle events — so you enforce a rule instead of hoping the model remembers it. A prompt is a suggestion; a PreToolUse hook is a wall the agent can't walk through. The six I put on every autonomous Claude Code agent: block secret writes, protect .env and migrations, auto-format edited files, run fast tests, inject git context on session start, and ping Telegram when the run finishes.