1.5 Apply Agent SDK hooks for tool call interception and data normalization
Use Agent SDK hooks to intercept tool calls and tool results in code: block or redirect policy-violating actions before they execute, and normalise heterogeneous tool output before the model reads it, choosing hooks whenever a rule must hold every time.
Key points
- 1
Hooks are callback functions (Python or TypeScript) registered in
options.hooks, keyed by event name (PreToolUse,PostToolUse,PostToolUseFailure,Stop,SubagentStop,UserPromptSubmit,SessionStart, ...), each with an optionalmatcherand a list of callbacks. They run in your process, so their behaviour is deterministic; prompt instructions are followed probabilistically. - 2
Rule of thumb the exam relies on: if a business rule needs guaranteed compliance (refund thresholds, path restrictions, destructive commands, ordering prerequisites), enforce it with a hook or programmatic gate. Prompt wording such as "MUST", few-shot examples, lower temperature or a bigger model only make compliance more likely.
- 3
PreToolUsefires before the tool executes. The callback returnshookSpecificOutputwithpermissionDecisionset to"allow","deny"or"ask", an optionalpermissionDecisionReason, and optionallyupdatedInputto rewrite the tool's arguments (for example redirecting file writes into a sandbox). - 4
A deny reason is shown to the model, so a blocking hook should say why and what to do instead ("refunds over $500 must go through
escalate_to_human"). Denying without a reason invites blind retries;askneeds an interactive operator and stalls in unattended deployments. - 5
Do not use
updatedInputto silently alter customer-facing financial actions (capping a $740 refund to $500). Rewriting inputs is for sanitising, sandboxing or injecting credentials; policy exceptions should be denied and redirected to the alternative workflow. - 6
PostToolUsefires after the tool has returned. It can appendadditionalContextfor the model or replace the tool output entirely (updatedToolOutput; the olderupdatedMCPToolOutputcovered MCP tools only). It cannot undo a side effect: ablockdecision inPostToolUseonly gives the model feedback after the action already happened. - 7
Classic
PostToolUseuse: normalise heterogeneous data from different MCP servers (Unix timestamps vs ISO 8601 strings, numeric vs named status codes, mixed currencies) into one canonical schema so the model reasons over a single representation. Doing the conversion in code is faster and more reliable than asking the model or a subagent to convert. - 8
Matchers match tool names, not arguments. Built-in tools are
Bash,Read,Write,Edit,Glob,Grep,Agent...; MCP tools are namedmcp__<server>__<tool>(regex such as^mcp__ormcp__orders__.*matches a server's tools). To filter on a path or amount, inspecttool_inputinside the callback. Omitting the matcher runs the hook for every tool call (useful for audit logging). - 9
When several hooks match one event they run in parallel and the most restrictive decision wins (one
denyblocks the call). Completion order is not guaranteed, so each hook must act independently rather than relying on another hook having run first. - 10
Each callback has a timeout (set
timeouton theHookMatcher). If aPostToolUsehook times out the SDK keeps the original tool result and the turn continues, so a normaliser that depends on a slow external service will intermittently let raw data through under load. Keep normalisation hooks fast and self-contained. - 11
systemMessagein hook output is shown to the user, not the model; useadditionalContext(or a deny reason) to inform the model. Hook input includestool_name,tool_input,tool_use_id(to correlate pre and post events), andagent_id/agent_typewhen the hook fires inside a subagent. - 12
Hooks complement, not replace, other controls: tool availability decides what an agent can call, hooks decide whether a particular call may proceed and how its result looks, and the prompt guides judgment (tone, when to ask a clarifying question, coding conventions).
Read the source
Test yourself on 1.5 Apply Agent SDK hooks for tool call interception and data normalization
Ten questions, with the answer and explanation after each one.