Single logo
  • Courses
  • Blog
  • About
Join on SkoolJoin on Skool

In this topic

Claude
  • CLAUDE.md, settings.json and Plugins: Which Claude Code File Advises, Which Enforces, Which Packages
  • Authoring a Claude Skill: SKILL.md, Frontmatter, Progressive Disclosure and the Description That Triggers It
  • One Change, Four Environments: Where a Claude Config Edit Lands in Dev, Staging, Prod and CI
  • Claude in the SDLC: Prompts in Git, a Change Gate by Path, a Claude Review That Advises and a Person Who Merges
  • Hooks That Block Destructive Actions: a PreToolUse Gate That Allows, Asks or Denies
  • Choosing a Claude Code Extension: Skill, Hook, Rules File, Subagent, Slash Command or Plugin
  • Rolling Out Claude Code to a Team: Settings Precedence, dontAsk in CI, a Hook for Every-Time Rules and a Plugin for Five Repos
  • A Claude Code Review Bot in CI: Headless -p, JSON Findings, Team Rules in Git and a Person on the Merge
  • Lab: Three Planted Bugs in a Claude Code CI Repo, a Permission Mode, a Plugin Path and an MCP Token Variable
  • Configuring MCP Servers in Claude Code: A Command or a URL, Three Scopes, and Three Moves When One Breaks
  • The Claude Messages API: Your First Call, Field by Field
  • Claude Tool Use: How tool_use and tool_result Work in the Messages API
  • Claude Client SDKs Wrap One REST API: Raw HTTP, Python, TypeScript and Async Calls Compared
  • Anthropic SDK Timeouts, Retries and Error Classes: Configure the Client Once, Then Give 429, 529, 400 and Timeouts Their Own Move
  • Claude Streaming Events: The Event Order, message_stop, Tool Arguments, Stop Reasons and a WebSocket Relay
  • Images, PDFs and Thinking Blocks in the Claude Messages API: Typed Blocks In, Typed Blocks Out
  • Getting Data Into Claude: PDF Documents, the Files API, Search Results and Citations
  • Opus, Sonnet or Haiku: Pick the Claude Model per Job, and Test the Request When a New Release Arrives
  • Adaptive Thinking and Effort in Claude: Two Dials, Set per Workload, and the Thinking Block You Must Pass Back
  • Claude Cost Tracking From usage: Count Before, Cap During, Read After, Then Find the Line That Drives the Bill
  • Claude Cache Breakpoints: Where to Put cache_control, How to Move It With the Chat, and Why the Reads Stay at Zero
  • Claude Message Batches or Real Time: Choose by Who Is Waiting, Match by custom_id, Resend Only the Failures
  • Calling Claude Through Amazon Bedrock, Google Cloud and Microsoft Foundry: Same Call, Different Door
  • The Life Cycle of a Claude App: Six Phases, a Model That Retires, and a Release Gate for Every Change
  • Pinning Claude Model IDs and Upgrading Safely: One Change at a Time, a Golden-Set Replay and a Staged Rollout
  • Content Boundaries and Schema Design for Claude: Fence the Input in a Tag, Let the Output Say I Don't Know
  • The Agentic Loop and stop_reason: Keep Turning on tool_use, Stop on end_turn, Cap the Turns
  • The Claude Agent SDK: query(), ClaudeAgentOptions and @tool, in Python and TypeScript
  • Fix the Agent: Four Broken Claude Agent SDK Configs, From the Symptom to the One Wrong Line
  • Claude Managed Agents: Cloud Sandbox, Self-Hosted Sandbox or Self-Hosted Service
  • Agent SDK Hooks for Deterministic Actions: PreToolUse, PostToolUse, and Four Hooks That Fail Silently
  • Memory and Context-Window Patterns for Claude Agents: Context Editing, Compaction and the Memory Tool
  • Reading an Agent Trace: Five Signatures, Five Missing Patterns, and How Long a Fact Must Live
  • Tool Descriptions for Claude: How Claude Picks a Tool, and How to Stop It Picking the Wrong One
  • Tool Input Schemas and Error Responses for Claude: Required Fields, Enums, is_error and a Retry Flag
  • Tool Response Shaping and a Lean Tool Set: Give Claude a Sticky Note, Not the Filing Cabinet
  • Fix the Tool Schema: Read the Trace, Fix the Card, Re-Run (Four Real Schema Bugs)
  • Client Tools, Server Tools and Approval Gates: Who Runs the Tool, and Who Says Yes First
  • Built-in Tool, Custom Tool, Skill or MCP Server? Pick the Lightest One That Fits
  • System Prompt or User Turn: Where Each Instruction Goes, and Output Limits Your Code Enforces
  • Refine the Prompt One Line at a Time, Then Clean and Fence the Customer's Text
  • Prompt Revision Driven by Evals: Name the Cause, Change One Thing, Rerun the Whole Suite
  • Long-Running Sessions: Compact, Prune, Isolate or Start Fresh, Decided by Naming the Failure
  • Context Isolation Through Subagents: Read the Logs Elsewhere, Keep One Line
  • Defensive Parsing of Claude Replies: Check the Stop Reason, Read the Block or the Text, Then Validate the Values
  • Full Context or Retrieval: Choose by Corpus Size, Cost and Freshness
  • Skepticism Toward Confident Output: Check the Quote, the Record and the Sum Before You Send
  • Debugging a Claude App: Three Error Types, the Recovery Each One Earns, and the First Failing Row
  • Six Ways a 200 Can Still Be Wrong: Hallucination, Refusal, Under-Acting, Context Loss, Format Drift and Inconsistency
  • Fix the Cause, Not the Symptom: Four Recovery Drills for an LLM App, Each Checked on a New Input
  • Integration Layer or Model Output? Three Taps and Three Questions to Find Where a Wrong Answer Lives
  • Which Test Layer Owns the Failure? Unit, Functional, Integration and End-to-End Tests for a Claude App
  • Designing an Overnight Document Pipeline on Claude: Batch Lane, Live Lane, a Cached Prefix and a custom_id Reconcile
  • Proving a Model Upgrade Is Ready: A Frozen Golden Set, a Calibrated Judge, the Right Layer and a Release Gate
  • From Requirement to Design for a Claude App: Eight Requirements, Five Elements and a Trace With No Gaps
  • Build a Claude Refund App: the Messages API, Two Tools, an MCP Server and a Hook in One Loop
  • Ship a Claude App: an Eval Gate, Two Guardrail Layers, a Cost Check From usage and a Pinned Model
  • Lab: a 30-Case Golden Set, a Calibrated Judge and a Per-Slice CI Gate on a Claude Refund App
  • Lab: Cut a Claude App's Bill by 62 Percent With Usage Data, Layered Cache Breakpoints and a Batch Job
  • Lab: Three Planted Bugs in a Claude App, a Vague Prompt, a Mistyped Tool Schema and a Broken Stream Handler
  • Lab: Three Planted Bugs in a Claude Code CI Repo, a Permission Mode, a Plugin Path and an MCP Token Variable
  • Lab: Harden a Claude App, an Uncalibrated Judge, a Retry Loop That Retries Everything and a Hook Matcher With a Gap
  • Lab: Turn a Claude App Into a Reusable Template, One Pinned Model Id, No Key in Code and Evals Built From Data
  • Building an MCP Server: Tools, Resources and Prompts in Python and TypeScript
  • MCP Transports: stdio or Streamable HTTP, and Who Starts the Server
  • Deploying and Authenticating an MCP Server: Environment Keys for stdio, Bearer Tokens and Scopes for HTTP
  1. Blog
  2. /
  3. Claude
  4. /
  5. Claude Code

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.

Chaand Sheikh

·27 November 2026Claude Code

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 orders removes a table for good;
  • a Write to .env overwrites 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.

A checkpoint before the tool Model tool_use PreToolUse your hook runs first allow: pytest -q the tool runs ask: git push --force a person decides deny: rm -rf data/ reason goes back to the model
PreToolUse sees the call first. It can deny it, ask a person, or let it run.

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 to decide gives a verdict.
  • For allow the hook returns an empty dictionary, and the call goes on.
  • Otherwise it returns a permissionDecision of "deny" or "ask", with a reason. The model reads that reason, so write it as an instruction.
  • The matcher names three tools: Bash, Write and Edit. The hook never wakes up for anything else.
  • The matcher is registered under PreToolUse in ClaudeAgentOptions.

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

AllowAskDeny
What happensThe call runsA person is in the loopThe call never runs
What the model seesThe normal resultThe person's answerThe reason, to plan again
Use it forTests and readsRisky steps that are sometimes neededWhat is never acceptable
Our examplespytest -qgit push --forcerm -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

IdeaIn one line
PreToolUseCheck the call before the tool runs
Deny with a reasonBlock it, and explain so the agent can replan
AskA person decides the risky-but-needed steps
Least privilegeA 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.

Tried the exercise? Share your answer or ask a question.

The StudyEasy AI Community is free to join, with the lesson files, notebooks and code.

Join free on Skool

Keep going in Claude · 5 of 66

Previous
Claude in the SDLC: Prompts in Git, a Change Gate by Path, a Claude Review That Advises and a Person Who Merges
Next post
Choosing a Claude Code Extension: Skill, Hook, Rules File, Subagent, Slash Command or Plugin

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.

On this page

  • Actions that can't be undone
  • The cover stops it, the sign only asks
  • hooks.py: register one hook
  • gate.py: the rules in plain Python
  • Six calls, three verdicts
  • Allow, ask or deny
  • A prompt can be forgotten
  • Common mistakes
  • Recap
  • Try it yourself
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

Learn AI engineering, share what you build, and connect with other learners.

  • Free resources: lesson files, notebooks and code

  • Ask questions and join engineering discussions

  • Meet real people learning and building with AI

Join free on Skool

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)

Single logo

Empowering Education, One Course at a Time

About
About usContact usFAQs
Legal
Terms of ServicePrivacy Policy

© 2026 StudyEasy Organization. All rights reserved.