Sub topic 10
Failing closed when the hook breaks
This chapter assumes you can write a basic hook that reads a tool-call event from stdin and exits with code 2 to block it. It also assumes you can read Python tracebacks and run shell pipes.
Why hooks break
A hook is a program, so it can fail. The input may not be valid JSON. A field you expected may be missing. A regex may raise an error, or the script may hit a bug or a timeout.
When this happens, the hook has to choose between two outcomes:
- Fail open: the action runs without being checked.
- Fail closed: the action is blocked until the hook works again.
For a hook that guards against destructive actions, fail closed is the safer default. A broken guard that lets everything through gives you no protection, and nothing tells you it stopped working.
The default is often fail open
Many agents, including Claude Code and Kiro CLI, treat exit code 2 as "block". They treat other non-zero codes as a non-blocking error. The agent shows a warning and runs the tool anyway. Check your agent's documentation for the exact rule.
An uncaught Python exception exits with code 1. A hook that crashes on malformed input therefore lets the action through. You must catch errors yourself and convert them into exit code 2.
A fail-closed hook
This version separates the work into main and wraps the call in a catch-all handler. sys.exit raises SystemExit, which except Exception does not catch. Deliberate exits therefore pass through unchanged.
#!/usr/bin/env python3
import json
import re
import sys
FORCE_PUSH = re.compile(r"\bgit\s+push\b.*--force", re.IGNORECASE)
def block(reason):
print(f"Blocked: {reason}", file=sys.stderr)
sys.exit(2)
def main():
try:
event = json.load(sys.stdin)
command = event["tool_input"]["command"]
except (json.JSONDecodeError, KeyError, TypeError):
block("hook could not read the tool call, so it was not allowed.")
if not isinstance(command, str):
block("the command field was not text, so it was not allowed.")
if FORCE_PUSH.search(command):
block("force push is not allowed. Use a normal push or ask the user.")
try:
main()
except Exception as exc:
block(f"hook crashed with {type(exc).__name__}, so the action was not allowed.")
sys.exit(0)The hook checks the type of command because a number or null would make re.search raise an error. The final handler catches any bug you did not anticipate.
Do not over-block
Failing closed is not the same as blocking everything. If you attach this hook to every tool, file edits have no command field. The hook then blocks every edit as "unreadable".
Use a matcher to scope the hook to the shell tool, so a missing field really is abnormal. Make each message specific enough that the agent can recover, for example by telling it to try a different approach.
Test the failure paths
Pipe bad input into the script and confirm each case gives exit code 2.
echo 'not json' | python3 guard.py
echo "exit code: $?"
echo '{"tool_name":"shell"}' | python3 guard.py
echo "exit code: $?"
echo '{"tool_name":"shell","tool_input":{"command":"ls -la"}}' | python3 guard.py
echo "exit code: $?"The first two should print a "Blocked" message and exit code: 2. The third should print exit code: 0.
Exercise
A hook script has a bug and raises an uncaught KeyError. It exits with code 1. What is likely to happen to the tool call, and how do you change the hook so the action is blocked instead?
Show answer
With most agent hook systems, only exit code 2 blocks. Code 1 is treated as a non-blocking error, so the tool call runs unchecked. Wrap the hook's main logic in try/except Exception and call sys.exit(2) with a clear stderr message from the handler. Then confirm with a test that bad input gives exit code 2.