Sub topic 3
Failing Closed in Agent Hooks
Assume you know basic Python, JSON, shell commands, and how an agent sends tool calls to hooks. This chapter focuses on safe failure, local testing, and the limits of hooks.
Fail Closed When the Hook Breaks
A hook should fail closed: if it cannot parse the event or find the expected fields, it denies the action. A broken guard must not become an open gate.
import json
import sys
try:
event = json.load(sys.stdin)
command = event["tool_input"]["command"]
except (json.JSONDecodeError, KeyError, TypeError):
print("Blocked: invalid tool-call event.", file=sys.stderr)
sys.exit(2)
if command.strip() == "":
print("Blocked: empty command.", file=sys.stderr)
sys.exit(2)
sys.exit(0)Use a consistent contract so the agent can recover:
| Result | Exit code | Meaning |
|---|---|---|
| Allow | 0 | The tool call may continue. |
| Deny | 2 | Stop the call and show the reason. |
Test With Sample Events
Test the hook without running an agent. Pipe representative JSON into the program and inspect its exit code.
echo '{"tool_input":{"command":"ls -la"}}' | python3 guard.py
echo "exit code: $?"
echo '{"tool_input":{"command":"rm -rf /"}}' | python3 guard.py
echo "exit code: $?"
echo '{"tool_input":{}}' | python3 guard.py
echo "exit code: $?"Test allowed, denied, malformed, empty, and unexpected inputs. Check both the exit code and the error text.
Log Decisions for Review
Logs help explain why an action was denied and reveal repeated false positives. Record the tool name, decision, rule, and timestamp. Avoid recording secrets, full environment variables, or sensitive command arguments.
Use structured logs such as JSON Lines when another system will process them. Keep logs separate from the message sent to the agent.
Keep Hooks Fast
A hook runs in the agent's critical path. Prefer local parsing and bounded regular expressions. Set a timeout in the host agent when supported. If a check needs network access or a long scan, move it to a later review step.
Understand the Limits
Hooks inspect the event they receive. They may miss obfuscated commands, shell expansions, aliases, races, or actions performed by another process. They are policy checks, not complete isolation.
Layer them with least-privilege permissions, protected credentials, filesystem permissions, and a sandbox. The sandbox limits what a process can do even when a hook misses a case.
Exercise
What should a hook do when it cannot parse the tool-call JSON?
Show answer
Deny the action with a clear stderr message and a nonzero denial exit code.