An instruction in the agent’s memory is a request; a hook is a lock. The case after which practitioners install hooks for everyone: an agent in auto-approval mode promised a client a 30% discount — and nothing stopped it. A hooks config with a guard script closes off this entire class of incidents physically: the script runs before the tool executes and never lets a dangerous call reach the system. Below is the full assembly: settings, ready-made scripts, and a double-locking scheme.
The hooks config: where it lives and how to connect it
The hooks mechanism exists in Claude Code and compatible wrappers: at the moment the agent is about to call a tool, the wrapper launches your script, hands it a JSON payload with the call details, and waits for a verdict. The PreToolUse event fires BEFORE the tool executes — a block physically stops the action: the agent never gets to delete the file or send the email.
{
"hooks": {
"PreToolUse": [
{
"matcher": "Bash",
"hooks": [{ "type": "command", "command": "python guard.py" }]
},
{
"matcher": "Write|Edit",
"hooks": [{ "type": "command", "command": "python guard_write.py" }]
}
]
}
}The matcher is a regular expression over the tool name: Bash catches commands, Write|Edit catches file edits. The timeout field sets a time limit for the script in seconds (60 by default as of fall 2026): a lexical guard fits into it with room to spare, while a semantic layer that calls a model is better off with an explicit limit. A lock differs from a request elsewhere in the wrapper too: the agent follows rules kept in memory as long as the context is fresh; where instructions fall short, see our piece on agent memory.
Three settings levels
- .claude/settings.json — project settings; the file is committed to the repository, and every member of the team gets the hooks.
- .claude/settings.local.json — personal project settings; it never reaches git.
- ~/.claude/settings.json — the user level; it applies in all your projects.
Team guard scripts naturally belong in the repository — they codify the rules of the game: what the agent may touch and what it may not. Personal restrictions live in settings.local.json.
Installation in five steps
- Create a .claude/hooks folder and put guard.py there — the script from the next section.
- Add the hooks block to .claude/settings.json.
- In the hook command, use the $CLAUDE_PROJECT_DIR variable:
python "$CLAUDE_PROJECT_DIR"/.claude/hooks/guard.py— then the script is found from any directory. - Restart the session and verify registration with the /hooks command.
- Test it: ask the agent to run
rm -rfon a test folder — the guard must block the call.
If a hook does not fire, run claude with the –debug flag: the log shows every call, the incoming JSON, and the script’s response.
A guard script for Bash: the full example
The script reads the call from stdin, checks the patterns, and prints its decision to stdout:
# guard.py — blocking destructive commands
import json, re, sys
data = json.load(sys.stdin)
cmd = (data.get("tool_input") or {}).get("command", "")
DANGER = [
r"\brm\s+-rf?\s", # recursive deletion
r"\bgit\s+push\s+.*--force", # force push
r"\bgit\s+reset\s+--hard", # hard reset
r"\bdrop\s+(table|database)", # destructive SQL
r"\bsk-[A-Za-z0-9]{20,}", # keys in a command
r"\bshutdown|\breboot", # machine shutdown
]
for pat in DANGER:
if re.search(pat, cmd, re.I):
print(json.dumps({
"decision": "block",
"reason": "Blocked by guard script: destructive command"
}))
sys.exit(0)
print(json.dumps({"decision": "approve"}))The exchange format is simple. On input: a JSON object with the fields tool_name, tool_input, and cwd; tool_input.command holds the string the agent was about to execute. On output: a JSON object with the decision field: “block” stops the call, and the agent receives reason as its explanation and can rework the plan; “approve” permits execution. The alternative protocol is exit codes: code 2 with text on stderr also blocks the call, which is handy for bash one-liners without json.dumps. The exact set of fields in the input JSON depends on the wrapper version, but tool_name and tool_input are stable as of fall 2026.
A separate note on the sk-… pattern: it catches an attempt to slip an API key directly into a command. Keys should never appear in commands or repositories at all — only in environment variables. And when the agent needs external services, hand out access under the same principle of least privilege described in our piece on the first MCP connections.
A guard for file edits: a blacklist of zones
The second hook covers Write and Edit: the agent cannot write into forbidden zones — .env, keys, deploy configs, other people’s folders. A path blacklist takes a minute of configuration and protects against the classic beginner incident of “accidentally overwrote .env”. Zones rarely change, and when they do, you edit a single FORBIDDEN list instead of prompts and reminders.
# guard_write.py — protecting forbidden zones
import json, re, sys
data = json.load(sys.stdin)
path = (data.get("tool_input") or {}).get("file_path", "")
norm = path.replace("\\", "/")
FORBIDDEN = [
r"\.env($|\.)", # environment secrets
r"\.pem$|id_rsa", # keys
r"secrets", # secret folders
r"docker-compose", # deploy configs
r"(^|/)ci(/|$)|deploy", # pipelines and deploy
r"\.claude/settings", # the hooks config itself — meta-protection
]
for pat in FORBIDDEN:
if re.search(pat, norm, re.I):
print(json.dumps({
"decision": "block",
"reason": "Forbidden zone: " + norm + ". Edit code, not secrets."
}))
sys.exit(0)
print(json.dumps({"decision": "approve"}))The .claude/settings pattern is “meta-protection” from practice: the agent cannot edit the very config that holds the restrictions, which means it cannot unlock itself. An instruction like “don’t touch the settings” in memory is a request; an entry in a hook is a prohibition.
Double locking: words plus meaning
A lexical filter is instant, free, and catches everything already known. But the 30% discount case cannot be caught with patterns: the agent could have written “offer the client favorable terms on the invoice” — the word “discount” never appears in the command. Hence the rule from that incident: anything critical is covered by TWO hooks.
- Lexical filter: the patterns above — milliseconds and zero cost; it catches what is already known.
- Semantic filter: a call to a small model with the question “is this dangerous” — it catches paraphrased versions. The 30% discount case is caught precisely by the semantic layer — no pattern can guess the word “discount”.
The skeleton of the semantic hook:
# guard_semantic.py — second layer: assessment by a small model
import json, os, sys, urllib.request
data = json.load(sys.stdin)
cmd = (data.get("tool_input") or {}).get("command", "")
prompt = (
"Assess the agent's CLI command. Could it cause tangible damage: "
"deleting or publishing data, sending money, making promises to a client, "
"leaking secrets? Answer strictly in JSON: "
'{"danger": true/false, "why": "briefly"}' + "\n\n" + "Command: " + cmd
)
req = urllib.request.Request(
os.environ["GUARD_API_URL"] + "/chat/completions",
headers={"Authorization": "Bearer " + os.environ["GUARD_API_KEY"]},
data=json.dumps({
"model": os.environ["GUARD_MODEL"],
"messages": [{"role": "user", "content": prompt}],
"temperature": 0,
}).encode(),
)
answer = json.load(urllib.request.urlopen(req, timeout=20))
verdict = json.loads(answer["choices"][0]["message"]["content"])
if verdict.get("danger"):
print(json.dumps({
"decision": "block",
"reason": "Semantic filter: " + verdict.get("why", "damage risk"),
}))
else:
print(json.dumps({"decision": "approve"}))Any cheap, fast model with an OpenAI-compatible API will do: keep the URL, the key, and the model name in the GUARD_API_URL, GUARD_API_KEY, and GUARD_MODEL environment variables. The semantic layer plays the same role as the fresh-eyed observer in role and subagent schemes: the model sees only the call, without the execution context, and judges the fact itself. Two caveats. First: command strings go to an external provider — check in advance which providers log prompts, and never push commands containing secrets through the filter. Second: set the hook timeout with headroom for the model’s speed.
The rule from the incident: where a mistake is expensive, use two layers; where it is cheap, a single lexical layer is enough.
What else hooks cover: PostToolUse, Notification, Stop
PreToolUse is only the beginning. Hook events cover the agent’s entire working cycle:
| Event | When it fires | Typical use case |
|---|---|---|
| PostToolUse | after a file edit or a command | auto-running tests or a linter; the agent sees the result immediately |
| Notification | the agent needs permission or is waiting for input | a Telegram notification — control from your smartphone |
| Stop | the agent has finished its response | a forced git checkpoint before exiting |
"PostToolUse": [
{ "matcher": "Write|Edit",
"hooks": [{ "type": "command", "command": "npx eslint src --fix" }] }
],
"Notification": [
{ "hooks": [{ "type": "command", "command": "bash .claude/hooks/notify.sh" }] }
]Inside, notify.sh calls the Telegram Bot API and takes the token from environment variables — the config holds no secrets. A Stop hook can lock in the work: git add -A && git commit -m "agent checkpoint" — every session ends with a commit, and a rollback is possible at any moment. Advice on rollout order: start with the PostToolUse linter — it does not block, it teaches: the agent sees formatting errors immediately and stops making them.
Common questions about guard hooks
Do hooks slow things down? The script takes milliseconds; the semantic layer takes about a second per call to a small model. For destructive operations this is imperceptible.
Can the agent bypass a hook? Wrappers enforce hooks; the only workaround is editing the config directly, and that is hookable too (the meta-protection from guard_write.py).
Where is the config stored? Project settings live in the repository, for the team; user settings are personal. Team hooks go in the repo, secrets in the environment. Keep the settings change history in git: hook modifications go through review like ordinary code.
Where to start? The Bash guard from the example takes an hour of work and closes 80% of incidents. If you have only just discovered Claude Code, first go through the Claude Code starter guide, then come back to the locks.
Hooks are the transition from “hopefully the agent will obey” to “physically cannot”. The guard scripts above are a starter kit; double locking is the standard for expensive mistakes. Your action for today: copy guard.py into .claude/hooks, add the PreToolUse block to settings.json, and get your first rm -rf blocked. Config current as of fall 2026.
