Skip to content

1.5 Agent SDK Hooks

An Agent SDK hook is code that intercepts a tool call or a tool result. A tool call is the model’s request to run a tool. The tool result is what the tool returns. The model’s choices are probabilistic. A hook is deterministic: it applies the same rule every time, inside an otherwise probabilistic system. Hooks run between the model and the tools it calls. There, they enforce business rules and normalise data (convert it to one consistent format). Hooks implement the programmatic enforcement described in 1.4.

This lesson uses one made-up example throughout: a furniture shop whose support agent finds customers, tracks deliveries, issues refunds and approves discounts. Some of the shop’s rules must apply every time. The shop’s data arrives from three systems in three different formats.

The Agent SDK provides hooks at two points in the tool execution lifecycle. A PostToolUse hook runs after a tool executes and before the model processes the result. It can transform the result, so the model receives clean, normalised data whichever tool produced it. A PreToolUse hook, sometimes described as tool-call interception, runs before a tool executes. It can block the outgoing call, modify it, or redirect it to an alternative workflow. A blocked tool never runs.

In the Agent SDK hooks guide (checked September 2026), a PreToolUse hook answers with a permissionDecision of allow, deny, ask or defer. A deny decision stops the tool call. An optional updatedInput rewrites the tool’s arguments before the tool runs. A PostToolUse hook can set updatedToolOutput to replace what the model sees, for built-in and MCP tools alike. The older updatedMCPToolOutput covered MCP tools only. The docs say to prefer updatedToolOutput. By the time PostToolUse fires, the tool has already run. A block at that point stops the loop but does not undo the side effect. On the furniture shop’s refund tool, a PostToolUse hook would fire after the money had left the shop.

Different MCP tools return data in different formats. The furniture shop’s agent uses three:

  1. get_customer returns dates as Unix timestamps (1710489600) and status as numeric codes (200, 404, 500).
  2. lookup_order returns dates as ISO 8601 strings (“2024-03-15T12:00:00Z”) and status as English strings (“active”, “cancelled”, “pending”).
  3. check_shipping returns dates as “DD/MM/YYYY” and status as single-character codes (“S” for shipped, “P” for pending).

Without normalisation, the model interprets these mixed formats afresh on every iteration, so its readings vary. It might parse a Unix timestamp correctly once and misread it the next time. It might swap the day and month in “DD/MM/YYYY”, or read “P” as “processed” instead of “pending”.

A PostToolUse hook converts every result before the model processes it.

  • Unix timestamps to ISO 8601 dates, such as “2024-03-15T12:00:00Z”
  • Numeric and single-character status codes to human-readable strings, such as “shipped”, “pending” and “delivered”
  • Currency values to a consistent decimal format with a currency code
  • Date strings in various regional formats to a single standard format

The interpretation errors then disappear entirely.

PreToolUse hooks implement the prerequisite gates described in 1.4. The hook checks an outgoing call against a business rule before the tool executes. The hook blocks a call that breaks the rule, so there is no side effect to undo.

Refund threshold. A hook intercepts all calls to process_refund. If the amount exceeds $500, the hook blocks the call and redirects it to a human escalation workflow, and the refund tool never executes. At the furniture shop, the hook sends a $900 refund on a returned dining table to staff.

Compliance prerequisite gate. A hook intercepts calls to transfer_funds. If the agent has not completed the required anti-money laundering (AML) check for this session, the hook blocks the call. The hook’s error message tells the agent to complete the AML check first.

Manager approval. A hook intercepts calls to approve_discount for discounts above 20%. It pauses execution and routes the request to a manager approval queue. The tool executes only after a manager approves, so a 25% discount on a sofa waits for the shop manager.

Requirement Mechanism Guarantee
Must be followed 100% of the time Hooks Deterministic
Preferred but occasional deviation is acceptable Prompts Probabilistic

If a single failure would lose the business money or expose it to legal risk, use a hook. For a formatting preference or style guideline, prompt-based guidance is fine. A prompt is probabilistic, so even a good one sometimes fails. The question is whether the consequence of one failure justifies a deterministic guarantee, not whether prompts are “good enough”.

Refunds above $500. A prompt can say “For refunds above $500, escalate to a human agent”. The prompt works most of the time, but a single failure means that the agent processes a large refund without approval. The process_refund hook above blocks such a refund 100% of the time.

International transfers must pass AML checks. A prompt can say “Always complete AML verification before processing international transfers”. The prompt works 95% of the time. The 5% failure rate means some transfers skip AML checks, which is a regulatory violation. A PreToolUse hook that blocks transfer_funds until aml_check returns a pass works 100% of the time. No transfer can execute without AML verification.

Markdown formatting. A prompt can say “Format all responses using markdown with headers and bullet points”. The prompt works most of the time, and an occasional plain-text reply to a furniture shop customer is not a business risk. A hook would be unnecessary overhead, because formatting preferences do not need deterministic enforcement.

The exam tests when each hook runs. The exam presents PostToolUse hooks as a way to block policy-violating actions. That option is wrong, because the action has already happened. The exam also consistently offers prompt-based solutions as wrong options for scenarios that need deterministic enforcement. For a 100% requirement, the right answer is a hook.

The same hook mechanism covers session events, not only tool calls. PreCompact runs immediately before Claude Code compacts the conversation (replaces it with a shorter summary). It runs in two cases: the user typed /compact (matcher manual), or the context reached the auto-compact window, the size at which Claude Code compacts automatically (matcher auto). The hook receives the transcript path, the trigger, and any custom instructions the user passed to /compact. The hook can therefore archive the full transcript to a log before the summary discards detail. Exit code 2, or "decision": "block" in the hook’s JSON output, blocks the compaction. A PostCompact event fires afterwards. It carries the generated summary. The pattern matches the tool hooks: a Pre event can inspect and block, and a Post event can only observe what has already happened.

Five exam-style multiple-choice questions on Agent SDK Hooks. Pick an answer, then open the explanation.

An agent occasionally processes international transfers without required compliance checks. The compliance team requires 100% enforcement of anti-money laundering (AML) checks before any international transfer is executed. The current system uses prompt instructions that work approximately 95% of the time. What is the correct approach?

  • A. Add detailed AML check instructions to the system prompt with examples of correct behaviour and explicit warnings about penalties for non-compliance
  • B. Add a PostToolUse hook that flags completed transfers that skipped AML checks for manual review
  • C. Implement a PreToolUse hook that blocks the transfer_funds tool from executing until aml_check returns a verified pass result
  • D. Train the agent with few-shot examples demonstrating the correct AML verification workflow before every transfer
Answer & explanation

Correct: C

  • C is correct because a PreToolUse hook intercepts the outgoing tool call before execution and physically blocks it until the AML check passes. This provides the deterministic 100% guarantee that regulatory compliance demands. No transfer can execute without verification.
  • A is wrong because enhanced prompt instructions may improve the rate from 95% to 97-98% but cannot reach 100%. With AML regulations, even a single missed check can result in significant legal penalties. Probabilistic improvement is insufficient.
  • B is wrong because PostToolUse hooks run after execution. By the time the hook detects the missing AML check, the non-compliant transfer has already been processed. Regulatory compliance requires prevention, not post-hoc detection.
  • D is wrong because few-shot examples improve accuracy but remain probabilistic. They cannot guarantee 100% compliance. Regulatory requirements demand deterministic enforcement.

A customer support agent uses three MCP tools that return dates in different formats: Unix timestamps (1710489600), ISO 8601 strings (“2024-03-15T12:00:00Z”), and DD/MM/YYYY format (“15/03/2024”). The model sometimes confuses day/month order. What is the best solution?

  • A. Add instructions to the system prompt explaining the three date formats and how to interpret each one
  • B. Use only one MCP tool to avoid format inconsistency
  • C. Implement a PreToolUse hook that converts dates before sending them to the tools
  • D. Implement a PostToolUse hook that normalises all date formats to ISO 8601 before the model processes them
Answer & explanation

Correct: D

  • D is correct because PostToolUse hooks intercept tool results after execution but before the model processes them. Normalising all dates to ISO 8601 at this point ensures the model always receives consistent data regardless of which tool produced it.
  • A is wrong because relying on the model to correctly interpret three different date formats on every iteration introduces inconsistency. The model may correctly parse a format once and misinterpret it the next time.
  • B is wrong because restricting to one tool limits functionality. The correct approach is to normalise heterogeneous outputs, not to avoid using multiple tools.
  • C is wrong because PreToolUse hooks run before tool execution. Dates are in the tool results (after execution), not in the tool calls (before execution). The hook direction is wrong for this use case.

Which statement correctly describes the difference between PostToolUse hooks and PreToolUse hooks?

  • A. PostToolUse hooks transform results after execution; PreToolUse hooks block or modify calls before execution
  • B. PostToolUse hooks run before tool execution; PreToolUse hooks run after
  • C. Both types run at the same point but PostToolUse handles data while PreToolUse handles errors
  • D. PostToolUse hooks only work with MCP tools; PreToolUse works with all tool types
Answer & explanation

Correct: A

  • A is correct because PostToolUse hooks run after a tool executes but before the model processes the result (correct for data normalisation). PreToolUse hooks run before a tool executes (correct for policy enforcement and blocking actions).
  • B is wrong because it reverses the direction. PostToolUse is after execution, not before. PreToolUse is before execution, not after.
  • C is wrong because the hooks run at different points in the lifecycle, not the same point. Their timing is the fundamental distinction.
  • D is wrong because both hook types can work with any tool type. The distinction is timing (before vs after execution), not tool compatibility.

A developer implements a PostToolUse hook to block refunds above $500. Why is this approach flawed?

  • A. PostToolUse hooks cannot access the refund amount parameter
  • B. The refund has already executed by the time a PostToolUse hook fires
  • C. PostToolUse hooks are only available in the paid tier of the Agent SDK
  • D. PostToolUse hooks can only transform data, not block operations
Answer & explanation

Correct: B

  • B is correct because PostToolUse hooks run after tool execution. By the time the hook fires, the process_refund tool has already executed and the refund has been processed. For blocking actions, you need a PreToolUse hook that intercepts before execution.
  • A is wrong because PostToolUse hooks can access the full tool result, including parameters. The issue is timing, not data access.
  • C is wrong because this is not a pricing tier limitation. The issue is that PostToolUse hooks fundamentally run too late to prevent an action.
  • D is wrong because while PostToolUse hooks are typically used for transformation, the core issue is that they run after execution. Even if they could block, the action has already occurred.

When should you use hooks instead of prompt instructions for enforcing a business rule?

  • A. When the rule is complex and requires multiple steps to verify
  • B. When the rule involves formatting preferences or output style guidelines that readers will notice
  • C. When the agent has access to more than 5 tools
  • D. When a single violation would cause financial loss, legal risk, or security breach
Answer & explanation

Correct: D

  • D is correct because the decision framework is based on consequences. Hooks provide deterministic guarantees (100% enforcement). Prompts provide probabilistic guidance. If a single failure would cause financial loss, legal risk, or security breach, only hooks provide the required level of assurance.
  • A is wrong because complexity of the rule does not determine the mechanism. Simple rules (block refunds above $500) may require hooks due to financial risk, while complex rules (follow a specific formatting convention) may only need prompts.
  • B is wrong because formatting preferences are explicitly low-stakes and appropriate for prompt-based guidance. Hooks would be unnecessary overhead.
  • C is wrong because the number of tools is irrelevant to the hooks vs prompts decision. The consequence of a single violation is the deciding factor.