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.
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.
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
permissionDecisionofdenywith a reason, insidehookSpecificOutput. To allow, it returns an empty dict. - In the PostToolUse hook,
updatedToolOutputis 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 prompt | Rule in a hook | |
|---|---|---|
| Who enforces it | The model chooses to follow it | Your code, on every call |
| Can it be skipped | A pushy customer can wear it down | The tool waits for the hook |
| Same input, same result | Probabilistic | Deterministic |
| Good for | Tone and style | Money, 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
| Need | Hook | Get it right |
|---|---|---|
| Stop a call before it runs | PreToolUse | Deny inside hookSpecificOutput, with a reason the model can act on |
| Clean a result before the model sees it | PostToolUse | Return updatedToolOutput |
| Record what ran | PostToolUse | The result exists only after the tool runs |
| Match an MCP tool | any | Full 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.
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.