Sub topic 2
Scoping a Hook with Matchers
Assume you know basic shell commands, JSON, and Python. Also assume the agent sends a tool-call event to the hook as JSON on standard input.
A matcher limits when a hook runs. Match the tool name first, then inspect its input. For example, a command hook should run for shell, while a path hook should run for file-writing tools. This keeps unrelated tool calls fast and avoids applying the wrong checks.
{
"hooks": [
{
"event": "before_tool_use",
"matcher": "shell",
"command": "python3 guard.py"
}
]
}Matcher syntax differs between agent systems. Treat the configuration above as a model. Check your agent’s documentation for the exact event and field names.
Blocking Dangerous Shell Commands
The hook can inspect the proposed command and deny known-dangerous patterns. Exit code 0 allows the call. Exit code 2 blocks it. The message on standard error tells the agent what to change.
#!/usr/bin/env python3
import json
import re
import sys
BLOCKED = [
r"\brm\s+-[a-zA-Z]*r[a-zA-Z]*f[a-zA-Z]*\s+/",
r"\bgit\s+push\b.*--force",
r"\bdrop\s+table\b",
]
try:
event = json.load(sys.stdin)
command = event["tool_input"]["command"]
except (json.JSONDecodeError, KeyError, TypeError):
print("Blocked: invalid or incomplete tool event.", file=sys.stderr)
sys.exit(2)
for pattern in BLOCKED:
if re.search(pattern, command, re.IGNORECASE):
print(f"Blocked: command matches risky pattern {pattern}.", file=sys.stderr)
sys.exit(2)
sys.exit(0)Protecting Files and Directories
For write tools, normalize the requested path before comparing it with protected locations. Resolve .. segments and symlinks, then reject paths outside the project root as well as paths inside .env, .git, or production infrastructure.
Allow, Deny, or Ask
Use allow for routine, low-risk actions. Use deny for actions that must never happen automatically. Use ask when a human can make the decision with context. Some hook systems support an explicit ask result; others require the hook to deny and let the agent request approval separately.
Telling the Agent Why It Was Blocked
A useful denial names the matched rule and suggests a safe next step. “Blocked” alone causes poor recovery. For example: “Blocked force push to protect shared history. Create a normal push or ask the user.”
Exercise
Why should a hook matcher select shell before checking the command?
Show answer
It limits the hook to the tool whose input has the expected command field and avoids unnecessary checks on unrelated calls.