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. Building with the Claude API

Agent SDK Hooks for Deterministic Actions: PreToolUse, PostToolUse, and Four Hooks That Fail Silently

A refund of $640 must wait for a human, and three tools return dates in different formats. A PreToolUse hook denies the call, a PostToolUse hook cleans the result, and four hook configs that fail silently are fixed one line each.

Chaand Sheikh

·27 November 2026Building with the Claude API

What you will learn

  • Block a tool call before it runs with a PreToolUse hook that denies with a reason
  • Normalize a tool result before the model sees it with a PostToolUse hook and updatedToolOutput
  • Fix four hook configs that fail with no error: matcher, decision shape, wrong event, rule left in the prompt
  • Decide when a rule belongs in a hook rather than in the system prompt

Before you start

  • The Claude Agent SDK: query and ClaudeAgentOptions
  • Claude tool use: tool_use and tool_result

A customer writes: please refund me $640 for order 1042. Company policy says refunds over $500 need a human, but the refund tool refunds any amount it's given. And on the way back, three tools return dates in three formats (a Unix timestamp, an ISO string) and the order status as a bare number, 3. The agent can misorder events.

Both jobs need a guarantee, and a prompt can't give one. A hook can. In the Claude Agent SDK, a hook is your own function that runs at a fixed point in the loop. Today we use two: PreToolUse for the call going out, and PostToolUse for the result coming back. Then we fix four hooks that look right and do nothing.

The card enforces it, the email only asks

A reminder email says "please keep purchases under $500". The employee buys a $640 laptop, and it's paid: the email only asked. A company card with a $500 limit declines the same laptop, because the card checks every purchase. A system prompt is the email. A hook is the limit on the card.

A checkpoint each way Claude PreToolUse $640 > $500: deny PostToolUse status 3 -> shipped Tool tool_use only if allowed raw result clean result
PreToolUse checks the call going out. PostToolUse cleans the result coming back.

gate.py: the rules, in plain Python

Keep the rules in a plain file with no SDK in it, so you can test them on their own.

"""The two rules a hook applies, in plain Python (no SDK, no key)."""
from datetime import datetime, timezone

LIMIT = 500
TOOL = "mcp__support__process_refund"
STATUS = {1: "pending", 2: "packed", 3: "shipped", 4: "delivered"}
DATE_KEYS = {"last_contact", "placed", "eta"}


def decide(tool_name, tool_input):
    """Outgoing call: allow it, or deny it with a reason the model reads."""
    if tool_name == TOOL and tool_input["amount"] > LIMIT:
        return "deny", (f"Refunds over ${LIMIT} need a human. "
                        "Call escalate_to_human instead.")
    return "allow", ""


def to_date(value):
    if isinstance(value, (int, float)):  # Unix timestamp
        when = datetime.fromtimestamp(value, timezone.utc)
    else:  # ISO 8601 string
        when = datetime.fromisoformat(value)
    return when.astimezone(timezone.utc).strftime("%b %d %H:%M")


def clean(result):
    """Incoming result: one date format, status code turned into a word."""
    out = {}
    for key, value in result.items():
        if key in DATE_KEYS:
            out[key] = to_date(value)
        elif key == "status":
            out[key] = STATUS.get(value, "unknown")
        else:
            out[key] = value
    return out

The deny reason is written as an instruction ("Call escalate_to_human instead"), because the model reads it.

hooks.py: register two hooks

from claude_agent_sdk import ClaudeAgentOptions, HookMatcher
from gate import TOOL, decide, clean

async def refund_gate(input_data, tool_use_id, context):
    verdict, reason = decide(input_data["tool_name"], input_data["tool_input"])
    if verdict == "allow":
        return {}
    return {"hookSpecificOutput": {
        "hookEventName": "PreToolUse",
        "permissionDecision": "deny",
        "permissionDecisionReason": reason}}

async def clean_result(input_data, tool_use_id, context):
    return {"hookSpecificOutput": {
        "hookEventName": "PostToolUse",
        "updatedToolOutput": clean(input_data["tool_response"])}}

options = ClaudeAgentOptions(hooks={
    "PreToolUse": [HookMatcher(matcher=TOOL, hooks=[refund_gate])],
    "PostToolUse": [HookMatcher(matcher="^mcp__support__", hooks=[clean_result])]})
  • A hook is an async function with three arguments: the input, the tool use id and a context.
  • To deny, it returns a permissionDecision of deny with a reason, inside hookSpecificOutput. To allow, it returns an empty dict.
  • In the PostToolUse hook, updatedToolOutput is the result the model sees instead of the raw one.
  • The matcher compares tool names, so an MCP tool carries its server name in front: mcp__support__process_refund. The second matcher is a pattern covering every tool of the support server.

The lecture reads this file rather than running it. run_all.py runs the two rules from gate.py on test data, with scripted stand-in replies:

PreToolUse: the outgoing call
call 1 process_refund $120 -> allow
   refund sent: C-77, 1042
call 2 process_refund $499 -> allow
   refund sent: C-77, 1042
call 3 process_refund $640 -> deny
   reason: Refunds over $500 need a human. Call escalate_to_human instead.
   test model reply: escalate_to_human(C-77, 1042)

PostToolUse: the incoming result
get_customer
  last_contact 951900000                   -> Mar 01 08:40
lookup_order
  placed       2000-03-03T09:15:00Z        -> Mar 03 09:15
  status       3                           -> shipped
track_parcel
  eta          2000-03-06T17:00:00+02:00   -> Mar 06 15:00
  status       2                           -> packed

$120 and $499 pass; $640 is denied and the stand-in escalates. A Unix timestamp and two ISO strings all come out in one format, and the status codes become words.

A prompt rule asks, a hook decides

Rule in the promptRule in a hook
Who enforces itThe model chooses to follow itYour code, on every call
Can it be skippedA pushy customer can wear it downThe tool waits for the hook
Same input, same resultProbabilisticDeterministic
Good forTone and styleMoney, identity, compliance

The lecture shows this with a scripted illustration (not a measurement): with the rule only in the system prompt, an insistent customer gets the refund and the date format drifts between turns; with the hooks, the call is denied and both turns read the same date. For a security-focused version that also uses ask, see hooks that block destructive actions.

Four hooks that fail silently

A hook that's wired wrong raises no error. It's a fire alarm that never rings. A helpdesk agent with three MCP tools shows four symptoms in its log: an account deletion ran, a ticket on legal hold was closed, the audit trail is empty, and an admin password was reset. Each fault is one line in the config.

1. The matcher misses the MCP prefix

# BROKEN: an MCP tool name starts with mcp__<server>__
broken = {"PreToolUse": [
    HookMatcher(matcher="delete_account",
                hooks=[block_delete])]}

# FIXED: match the full tool name
fixed = {"PreToolUse": [
    HookMatcher(matcher="mcp__helpdesk__delete_account",
                hooks=[block_delete])]}

The callback was always fine. A plain name like delete_account is compared as an exact string, so it never equals the real name and the hook never fires. Use the full name (a pattern would work too).

2. The decision is in the wrong shape

async def hold_broken(input_data, tool_use_id, context):
    if input_data["tool_input"]["ticket_id"] == "T-9":
        # BROKEN: top-level keys are not a decision
        return {"permissionDecision": "deny"}
    return {}

async def hold_fixed(input_data, tool_use_id, context):
    if input_data["tool_input"]["ticket_id"] == "T-9":
        # FIXED: the decision lives inside hookSpecificOutput
        return {"hookSpecificOutput": {
            "hookEventName": "PreToolUse",
            "permissionDecision": "deny",
            "permissionDecisionReason":
                "This ticket is on legal hold."}}
    return {}

This hook runs, but its answer isn't used: the SDK reads a permission decision only inside hookSpecificOutput, and other keys aren't an error, so nothing warns you.

3. The audit hook is on the wrong event

AUDIT = []


async def audit(input_data, tool_use_id, context):
    AUDIT.append((tool_use_id, input_data["tool_name"],
                  input_data["tool_response"]))
    return {}


# BROKEN: PreToolUse input has no tool_response yet
broken = {"PreToolUse": [
    HookMatcher(matcher="^mcp__helpdesk__", hooks=[audit])]}

# FIXED: PostToolUse runs after the tool, with its result
fixed = {"PostToolUse": [
    HookMatcher(matcher="^mcp__helpdesk__", hooks=[audit])]}

Before the tool runs there's no result to read, so the callback fails with a KeyError, the call goes ahead anyway, and nothing is recorded. Register the same hook on PostToolUse, which runs after a successful call and carries its result. (Per the lecture, a failed call goes to a separate PostToolUseFailure event.)

4. The rule lives only in the prompt

SYSTEM_PROMPT = (
    "You run the helpdesk. Never reset an admin password.")

# BROKEN: the rule is only a sentence in the prompt
broken = ClaudeAgentOptions(system_prompt=SYSTEM_PROMPT)


async def no_admin_reset(input_data, tool_use_id, context):
    uid = input_data["tool_input"]["user_id"]
    if uid.startswith("admin"):
        return {"hookSpecificOutput": {
            "hookEventName": "PreToolUse",
            "permissionDecision": "deny",
            "permissionDecisionReason":
                "Admins are reset by a human."}}
    return {}

# FIXED: the same sentence, plus a hook that enforces it
fixed = ClaudeAgentOptions(
    system_prompt=SYSTEM_PROMPT,
    hooks={"PreToolUse": [HookMatcher(
        matcher="mcp__helpdesk__reset_password",
        hooks=[no_admin_reset])]})

The four, re-run

The lecture's run_all.py runs every broken config and its fix against a stand-in dispatcher and stand-in tools:

hook 1 - matcher
 broken  matcher=delete_account
   mcp__helpdesk__delete_account(U-31) -> ran
 fixed   matcher=mcp__helpdesk__delete_account
   mcp__helpdesk__delete_account(U-31) -> denied: Deleting accounts needs a human.
hook 2 - decision shape
 broken  permissionDecision at the top level
   mcp__helpdesk__close_ticket(T-9) -> ran
 fixed   inside hookSpecificOutput
   mcp__helpdesk__close_ticket(T-9) -> denied: This ticket is on legal hold.
 fixed   a ticket not on hold
   mcp__helpdesk__close_ticket(T-5) -> ran
hook 3 - audit event
 broken  audit hook on PreToolUse
   warning hook_callback_failed: KeyError: 'tool_response'
   mcp__helpdesk__close_ticket(T-4) -> ran
   audit entries: 0
 fixed   audit hook on PostToolUse
   mcp__helpdesk__close_ticket(T-4) -> ran
   audit entries: 1
   audit: toolu_03 {'closed': 'T-4'}
hook 4 - rule in the prompt
 prompt: You run the helpdesk. Never reset an admin password.
 test model reply: reset_password(admin-1)
 broken  prompt only
   mcp__helpdesk__reset_password(admin-1) -> ran
 fixed   prompt plus PreToolUse hook
   mcp__helpdesk__reset_password(admin-1) -> denied: Admins are reset by a human.
 fixed   a normal user
   mcp__helpdesk__reset_password(U-12) -> ran

Every fix is narrow: a ticket not on hold still closes, and a normal user's password still resets. The fix didn't block everything.

Quick recap

NeedHookGet it right
Stop a call before it runsPreToolUseDeny inside hookSpecificOutput, with a reason the model can act on
Clean a result before the model sees itPostToolUseReturn updatedToolOutput
Record what ranPostToolUseThe result exists only after the tool runs
Match an MCP toolanyFull mcp__server__tool name, or a pattern

A hook can fail without an error, so read the log first. And a rule that must hold belongs in a hook, not in the prompt.

Try it yourself

Add a PostToolUse hook that drops a customer's email address from every get_customer result. Then write the broken version with the matcher "get_customer" and predict what the log shows.

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 · 31 of 66

Previous
Claude Managed Agents: Cloud Sandbox, Self-Hosted Sandbox or Self-Hosted Service
Next post
Memory and Context-Window Patterns for Claude Agents: Context Editing, Compaction and the Memory Tool

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

The Claude Messages API: Your First Call, Field by Field

One request in, one Message out. The four fields of a Messages API call (model, max_tokens, system, messages), how to read content blocks, stop_reason and usage, and why every turn resends the history.

Claude Tool Use: How tool_use and tool_result Work in the Messages API

Follow one order question through Claude's tool round trip: define a tool, read the tool_use block, run your own function and send a matching tool_result back, including parallel calls and is_error.

Claude Client SDKs Wrap One REST API: Raw HTTP, Python, TypeScript and Async Calls Compared

Every Claude client SDK wraps the same REST request: a POST to /v1/messages with a JSON body. See it built by hand, through the Python and TypeScript SDKs, as typed errors, and as async calls that wait together.

Anthropic SDK Timeouts, Retries and Error Classes: Configure the Client Once, Then Give 429, 529, 400 and Timeouts Their Own Move

Configure the Anthropic SDK client (timeout, max_retries, with_options, async, pagination), see which errors it retries by itself, then repair a retry wrapper so a 429, a 529, a 400 and a timeout each get the move the docs support.

On this page

  • The card enforces it, the email only asks
  • gate.py: the rules, in plain Python
  • hooks.py: register two hooks
  • A prompt rule asks, a hook decides
  • Four hooks that fail silently
  • 1. The matcher misses the MCP prefix
  • 2. The decision is in the wrong shape
  • 3. The audit hook is on the wrong event
  • 4. The rule lives only in the prompt
  • The four, re-run
  • Quick 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.