Claude Agent SDK Hooks, Prerequisite Gates and Human Handoffs
👋 In plain words: You can tell Claude 'always verify the customer before a refund', and it will usually obey, but usually is not good enough for money. Hooks and gates are code that enforces rules every time. This lesson shows when a rule belongs in code instead of in a prompt.
Prompt instructions are probabilistic: even a well-written rule fails a small percentage of the time. When a business rule must always hold — verify identity before a refund, never refund over a limit — the exam expects programmatic enforcement (Task Statements 1.4 and 1.5).
🔑 Key terms
- Prompt instruction: A rule written in words for Claude. It works most of the time, not every time.
- Hook: Your code that runs automatically before or after a tool call, and can block, change or clean up that call.
- Prerequisite gate: A check that blocks a tool until an earlier step has succeeded.
- PostToolUse hook: A hook that runs after a tool and tidies its result before Claude sees it.
- Handoff: Passing a case to a human agent, with a summary of what happened so far.
📖 The story in this lesson
ShopNest's support bot can issue refunds. Asha's rules: never refund before the customer is verified, and send any refund over $500 to a human. This lesson turns both rules into code.
💡 Think of it like this
A prompt is like a sign saying 'Staff only' on a door: most people obey. A hook is the lock on that door: nobody gets through without a key. For money, identity and safety, use the lock.
✍️ Prompt guidance vs programmatic enforcement
| Prompt guidance | Programmatic enforcement | |
|---|---|---|
| Examples | System-prompt rules, few-shot examples | Hooks, prerequisite gates, removing tools |
| Guarantee | Probabilistic (non-zero failure rate) | Deterministic |
| Use for | Style, preferences, judgement | Money, identity, compliance, destructive actions |
🌍 Real-world example: The 1-in-200 mistake
Asha's system prompt says 'verify identity before refunds'. In testing, about 1 refund in 200 still skipped verification. For tone of voice that would be fine. For money it isn't, so she moves the rule into code, where it holds every single time.
🚧 Prerequisite gates
A gate blocks a downstream tool until an upstream step has succeeded — for example, process_refund is rejected unless get_customer returned a verified customer ID in this session.
def guard(tool_name, tool_input, session):
if tool_name in {"lookup_order", "process_refund"} and not session.verified_customer_id:
return deny("Verify the customer with get_customer first.")
if tool_name == "process_refund" and tool_input["amount"] > 500:
return redirect("escalate_to_human", reason="Refund above $500 needs approval")
return allow()
🌍 Real-world example: No refund without verification
The gate checks the session before process_refund runs. If get_customer hasn't returned a verified ID yet, the call is refused with a clear message, and Claude then asks the customer for their details first.
🪝 The two hook patterns the exam tests
- Tool-call interception (pre-tool) — inspects outgoing calls and blocks or redirects policy-violating ones (refunds over a threshold,
rm -rf, writes to production paths). - PostToolUse — transforms tool results before the model sees them, e.g. normalising Unix epochs, ISO-8601 strings and numeric status codes from different MCP servers into one format, or trimming verbose results to the relevant fields.
🌍 Real-world example: Blocking big refunds and tidying dates
A pre-tool hook sees process_refund for $750 and redirects it to escalate_to_human. A PostToolUse hook converts the warehouse system's Unix timestamps, such as 1731000000, into readable dates before Claude reads them, so Claude never confuses two date formats.
if tool == "process_refund" and amount > 500:
return redirect("escalate_to_human")📘 Multi-concern requests
“My item arrived broken, I was double-charged, and my address is wrong” is three concerns. Decompose them, investigate each (in parallel where possible) using shared context, then send one combined resolution. Having several issues is not, by itself, a reason to escalate.
🌍 Real-world example: Three problems in one message
A customer writes: 'Broken kettle, charged twice, and my address is wrong.' The bot splits this into three issues, checks each (in parallel where it can), and sends one reply that covers all three. Three routine issues are still routine: no escalation needed.
🤝 Structured human handoffs
Human agents usually can’t see the bot transcript. When escalating, pass a structured summary: customer ID, the issue, the root cause found, actions already taken, amounts, and the recommended next step.
🌍 Real-world example: A handoff a human can act on
Escalating the $750 refund, the bot sends: customer ID C-1042 (verified), order #48213, kettle arrived broken, photo received, refund of $750 requested, above the $500 limit, recommend approving. The human agent acts in 30 seconds without reading the whole chat.
🛠️ Try it yourself (about 10 minutes)
- Write a Python function
guard(tool_name, amount, verified). - Return 'deny' if the tool is
process_refundandverifiedis False. - Return 'escalate' if the amount is over 500.
- Test it with three cases: unverified, $499 verified, and $501 verified.
✅ You are done when: the three cases return deny, allow and escalate, in that order.
🧪 Exam-Style Practice Questions
Try these before opening the answers. They use the same scenario style as the real exam.
Question 1. Identity must be verified before any refund. What's the strongest implementation?
- A. Few-shot examples
- B. A post-hoc audit log
- C. A system-prompt rule
- D. A programmatic gate that rejects
process_refundunlessget_customerreturned a verified ID in this session
Show answer
Answer: D. A deterministic guarantee for a financial operation. A and C are probabilistic. B detects the problem afterwards; it doesn't prevent it.
Question 2. What does a PostToolUse hook typically do in this exam's context?
- A. Blocks dangerous outgoing tool calls
- B. Compacts the conversation
- C. Transforms or normalises tool results before the model processes them
- D. Selects which tool to call
Show answer
Answer: C. It runs after the tool, on the result. A describes pre-call interception. D is the model's job. B is a different mechanism.
Question 3. When should you choose a hook over a prompt instruction?
- A. Whenever you want shorter prompts
- B. When a business rule needs a guaranteed outcome
- C. Never; hooks add latency
- D. Only for logging
Show answer
Answer: B. Hooks give deterministic compliance. A is a side benefit, not the reason. C and D are wrong.
📝 Assignment
Do these tasks in order. Each one has a Done when check, so you know when it is complete. The stretch task is optional but close to what the exam expects from an architect. Keep your answers in one notes file or Git repository, and revisit them in your final week of revision together with the cheat sheet in the last lesson of this course.
- Task 1: Write pseudo-code for a gate that blocks process_refund until get_customer has verified the customer.
✅ Done when: Your gate denies the refund call when verification is missing and allows it once get_customer has returned verified. - Task 2: Add a threshold rule that redirects refunds over $500 to escalate_to_human.
✅ Done when: A refund of $501 is redirected to escalation, while a refund of $499 goes through unchanged. - Stretch: write a PostToolUse function that converts Unix epochs and ISO-8601 strings into one date format.
✅ Done when: Both 1731000000 and '2024-11-07T17:20:00Z' come out of your function in the same format.
❓ Frequently Asked Questions
🤔 When should I use a hook instead of a prompt instruction?
When a rule must hold every time, such as identity checks, refund limits or blocking destructive commands. Prompts are probabilistic.
🤔 What does a PostToolUse hook do?
It transforms a tool's result before Claude sees it, for example normalising formats or trimming irrelevant fields.
🤔 Should a multi-issue request be escalated?
Not automatically. Split it into separate concerns, investigate each, and send one combined resolution.
🤔 What should a human handoff include?
Customer ID, the issue, the root cause found, actions taken, amounts involved and the recommended next step.
🏁 Summary
- “Must always” → hooks and gates. “Should usually” → prompts.
- Pre-tool interception blocks or redirects calls; PostToolUse normalises results.
- Escalations carry a structured handoff summary.
Next, continue with Task Decomposition and Session Management in Claude Code.
Independent study material by SQA Tools. Not affiliated with, endorsed by or sponsored by Anthropic. Claude is a trademark of Anthropic. Mock questions are original practice items, not real exam content. Exam facts checked against Anthropic's official exam guides and certification FAQ on 11 November 2026.