Hooks That Block Destructive Actions: a PreToolUse Gate That Allows, Asks or Denies
A coding agent is told to clean up the data folder and picks rm -rf data/. A PreToolUse hook sees the call before the tool runs: tests and single-file deletes pass, a force push asks a person, and rm -rf, DROP TABLE and a write to .env are denied with a reason.
What you will learn
- Explain why a system prompt rule can't guarantee a destructive command never runs
- Register a PreToolUse hook in the Claude Agent SDK with a matcher for Bash, Write and Edit
- Return allow, ask or deny with a reason the model can act on
- Keep the rules in plain Python so they can be tested without a key
Before you start
- Claude Tool Use: tool_use and tool_result
- Basic Python and regular expressions
A developer says to a coding agent: clean up the data folder. The agent reads that and picks a shell command, rm -rf data/. Nobody can undo that.
In this article we stop it at the door with a PreToolUse hook: your code, sitting between the agent and its tools, that sees every call before the tool runs. It can let the call run, ask a person first, or deny it with a reason.
For the wider picture of hooks in the Agent SDK (PostToolUse, and the configs that fail silently), see Agent SDK hooks for deterministic actions. Here we stay on one job: stopping the actions you can't undo.
Actions that can't be undone
A coding agent has real tools, and some actions are final:
- a Bash command,
rm -rf data/, deletes a whole folder; - a Bash command with
DROP TABLE ordersremoves a table for good; - a Write to
.envoverwrites a secret.
The tools do exactly what they're told. There's no "are you sure?" inside Bash or Write. So the check has to happen before the tool runs. Afterwards is too late.
The cover stops it, the sign only asks
Think of a big red button. A sign next to it says please do not press the red button. Someone presses it anyway. The sign only asked, and nobody checked. Now put a locked cover over the button. The same person tries, and is blocked, because the cover checks every press. A rule in the system prompt is the sign. A hook is the cover.
hooks.py: register one hook
This is the Claude Agent SDK. In the lecture we only read this file; running it needs the SDK and a key. A hook is an async function with three arguments.
from claude_agent_sdk import ClaudeAgentOptions, HookMatcher
from gate import decide
async def guard(input_data, tool_use_id, context):
name = input_data["tool_name"]
verdict, reason = decide(name, input_data["tool_input"])
if verdict == "allow":
return {}
return {"hookSpecificOutput": {
"hookEventName": "PreToolUse",
"permissionDecision": verdict,
"permissionDecisionReason": reason}}
gate = HookMatcher(matcher="Bash|Write|Edit", hooks=[guard])
options = ClaudeAgentOptions(hooks={"PreToolUse": [gate]})
- The rules live in a separate file,
gate.py. One call todecidegives a verdict. - For allow the hook returns an empty dictionary, and the call goes on.
- Otherwise it returns a
permissionDecisionof"deny"or"ask", with a reason. The model reads that reason, so write it as an instruction. - The
matchernames three tools: Bash, Write and Edit. The hook never wakes up for anything else. - The matcher is registered under
PreToolUseinClaudeAgentOptions.
gate.py: the rules in plain Python
No SDK, no key. That's on purpose: rules you can run on their own are rules you can test.
"""Destructive-action rules in plain Python (no SDK, no key)."""
import re
BLOCK = [
(r"\brm\s+-\w*r", "rm -r deletes folders for good"),
(r"\bDROP\s+(TABLE|DATABASE)\b", "DROP removes data for good"),
]
ASK = [(r"\bgit\s+push\b.*--force", "A force push rewrites shared history")]
PROTECTED = (".env", "prod.db")
def hit(rules, command):
for pattern, why in rules:
if re.search(pattern, command, re.IGNORECASE):
return why
return ""
def decide(tool_name, tool_input):
"""Outgoing call: allow, ask a person, or deny with a reason."""
if tool_name == "Bash":
command = tool_input["command"]
why = hit(BLOCK, command)
if why:
return "deny", f"Blocked: {why}. Try a narrower step."
why = hit(ASK, command)
if why:
return "ask", why
if tool_name in ("Write", "Edit"):
if tool_input["file_path"].endswith(PROTECTED):
return "deny", "Blocked: protected file. Ask the user instead."
return "allow", ""
The first pattern catches rm with a recursive flag. A single-file delete like rm temp.txt doesn't match, so it's allowed. A force push goes on the ask list, because sometimes it's needed and a person should decide. A short list of protected files covers .env.
Six calls, three verdicts
run_all.py feeds six tool calls through decide. A stand-in gives one scripted reply, so no key is needed.
call 1 Bash: pytest -q -> allow
call 2 Bash: rm temp.txt -> allow
call 3 Bash: rm -rf data/ -> deny
reason: Blocked: rm -r deletes folders for good. Try a narrower step.
test model reply: I will list data/ and ask which files can go.
call 4 Bash: sqlite3 shop.db "DROP TABLE orders" -> deny
reason: Blocked: DROP removes data for good. Try a narrower step.
call 5 Bash: git push --force origin main -> ask
asks the user: A force push rewrites shared history
call 6 Write: config/.env -> deny
reason: Blocked: protected file. Ask the user instead.
Look at call 3. The reason Try a narrower step gives the agent somewhere to go, and the (scripted) reply does exactly that: list the folder and ask.
Allow, ask or deny
| Allow | Ask | Deny | |
|---|---|---|---|
| What happens | The call runs | A person is in the loop | The call never runs |
| What the model sees | The normal result | The person's answer | The reason, to plan again |
| Use it for | Tests and reads | Risky steps that are sometimes needed | What is never acceptable |
| Our examples | pytest -q | git push --force | rm -rf, DROP TABLE, .env |
Pick the lightest answer that still keeps the data safe.
A prompt can be forgotten
In the lecture's scripted illustration (not a measurement), the rule lives only in the system prompt: Never delete data, be careful. The task says free up space, clear the data folder. The scripted model runs rm -rf, and the folder is gone, because nothing checked the call. With the hook in place, the same call is denied, and the agent lists the folder and asks first. A reminder isn't a lock.
Common mistakes
- Repeating the rule at the top and bottom of the prompt. Still only a request.
- Asking the model to double-check each command. The model checks itself, so the same weakness remains.
- Switching to a larger model. Not a guarantee either.
- A deny with no reason. The agent can't plan a safer step if it doesn't know why it was stopped.
- Treating the hook as the only layer. Give the agent only the tools and access it needs as well. See Guardrails for an LLM Agent for the layers around it.
When a question says destructive, must never or guaranteed, it wants code that decides before the tool runs, not more prompt.
Recap
| Idea | In one line |
|---|---|
| PreToolUse | Check the call before the tool runs |
| Deny with a reason | Block it, and explain so the agent can replan |
| Ask | A person decides the risky-but-needed steps |
| Least privilege | A hook is one layer; grant only what the job needs |
To see where hooks fit next to skills, rules files and subagents, read Choosing a Claude Code Extension. For a hook that checks refund arguments against the order, see the injection exposure review.
Try it yourself
Add two rules to gate.py: deny git reset --hard, and ask before any Bash command containing curl piped to a shell. Then add a call for each to the run and check the verdicts and reasons are what you expect.
Related course on Udemy
Claude Certified Developer - Foundations (CCDV-F) Exam Prep
Build and ship Claude apps: the API, agents, tools and MCP, prompts, evals, security and model choice.View on Udemy ↗: Claude Certified Developer - Foundations (CCDV-F) Exam Prep (paid course, opens in a new tab)Related posts
CLAUDE.md, settings.json and Plugins: Which Claude Code File Advises, Which Enforces, Which Packages
Three needs in one repo: a test command, a rule that Claude must never read .env, and a shared deploy skill. See which file each belongs in, how the settings layers merge, and what a plugin manifest carries.
Authoring a Claude Skill: SKILL.md, Frontmatter, Progressive Disclosure and the Description That Triggers It
Pack a support team's ticket-triage routine into one skill folder, then watch three requests load one, two or all three levels: the catalog, the SKILL.md body, and a script whose code never enters the context.
One Change, Four Environments: Where a Claude Config Edit Lands in Dev, Staging, Prod and CI
Change one line in a repo and ask where it lands. A small resolver for bookshop-bot shows that a new model id in settings.json reaches only CI, a prompt bump reaches dev and CI, and a prod block edit reaches only prod.
Claude in the SDLC: Prompts in Git, a Change Gate by Path, a Claude Review That Advises and a Person Who Merges
Follow one prompt edit from a branch to a merge: version prompts and the model pin like code, keep the API key in GitHub Secrets, gate changes by path, let Claude review the diff, and leave the merge to a person.