What you will be able to do
- Decide when a business rule needs a hook rather than a prompt instruction
- Place PreToolUse and PostToolUse correctly in the tool-call path of the agentic loop
- Write a matcher that scopes a hook to exactly the right tools, including every tool of one MCP server
- Block a policy-violating tool call in the callback and send the agent to an alternative workflow such as human escalation
- Replace heterogeneous tool output with one normalized format using updatedToolOutput
Key concept
Deterministic enforcement through hooks — A hook is your own code that runs at a fixed point in the agent lifecycle and returns a decision the SDK acts on. A prompt instruction depends on the model following it, so it can fail. A hook does not depend on the model at all.
1.Guaranteed compliance belongs in code, not in the prompt
A system prompt that says "never issue a refund above $500" is a request the model usually honors. Usually is the problem. Any instruction the model reads can still be misread, outweighed by a persuasive customer message, or lost in a long context. Prompt instructions therefore always carry a non-zero failure rate. That is acceptable for tone and formatting. It is not acceptable for a rule whose single violation costs money or breaks a regulation.
A hook moves the decision out of the model and into your application. The SDK calls your callback at a fixed point, for example just before a tool executes. The callback inspects the call and returns a decision. Whatever the model intended, a refund call that your code denies does not run. This is the core use case for interception: block dangerous operations before they execute, and audit or transform what passes through.
Choose between the two by asking what one failure costs. Use the prompt for guidance the agent should generally follow: preferred phrasing, which tool to try first, how to summarize. Use a hook when the business needs the rule to hold every time: spending limits, protected files, data that must never leave a system. The two often work together. The prompt explains the policy so the agent rarely tries to break it, and the hook catches the cases where it does.
A stronger instruction can lower the failure rate, but it cannot make the rate zero, because the model still decides whether to comply. A PreToolUse hook that checks the amount and denies the call removes the model from that decision, so the rule holds on every call.
Checkpoint 1 of 8· Check yourself
A finance team says a single refund above $500 is unacceptable, even if it happens in only one conversation out of thousands. Which design actually guarantees the limit holds?
Only a PreToolUse hook takes the decision away from the model and stops the call before it runs, so the rule holds every time. Prompt-based options, including a reviewing agent, still rely on a model choosing to comply. A PostToolUse hook runs after the refund has already gone through.
“Block dangerous operations before they execute, like destructive shell commands or unauthorized file access”Source: code.claude.com
2.Where PreToolUse and PostToolUse fire in the tool-call path
In the Agentic loop driven by stop_reason, a tool_use response means your application executes the requested tool and returns a tool_result. Tool hooks attach to both sides of that execution. PreToolUse fires after Claude has produced the tool_use block but before the tool runs, so it can still stop or rewrite the call. PostToolUse fires after the tool has run and before the tool_result goes back to Claude, so it can change what Claude reads. Both run on every tool call inside the loop.
| Event | When it fires | What it can do |
|---|---|---|
| PreToolUse | Before a tool call executes | Allow, deny, ask, or defer the call; rewrite its input with updatedInput |
| PostToolUse | After a tool call succeeds | Append to the result with additionalContext, or replace it with updatedToolOutput |
| PostToolUseFailure | After a tool call fails | Handle or log tool errors |
| PostToolBatch | After a full batch of parallel tool calls resolves, before the next model call | Act once per batch (TypeScript SDK only) |
PostToolUse only sees successes. A failed call goes to PostToolUseFailure, so a normalizing PostToolUse hook never runs on error results, and error handling needs its own hook. To connect the two sides of one call, use the tool use ID that every callback receives. It is the same for the PreToolUse and PostToolUse events of a single call, so a hook can, for example, record a call's arguments before execution and match them to its result afterwards.
Checkpoint 2 of 8· Match them up
An agent calls several MCP tools. Match each requirement to the hook event that should handle it.
Tap a term, then the definition that fits it.
PreToolUse runs before execution, so it can still block or change the call. PostToolUse runs only on successful results and can rewrite them before Claude sees them. Failed calls go to PostToolUseFailure instead, which is why a PostToolUse normalizer never sees errors. PostToolBatch runs once per batch of parallel calls.
“PostToolUseFailure | Yes | Yes | Tool execution failure | Handle or log tool errors”Source: code.claude.com
3.PreToolUse: scope with a matcher, decide in the callback
In the SDK you register a hook as an array of matchers under an event name. Each matcher has three options: matcher (a pattern), hooks (the callbacks to run) and timeout (in seconds). For tool events, the matcher pattern is checked against one thing only: the tool name. Built-in tools have plain names like Bash or Write. MCP tools are named mcp__<server>__<action>, where the server part is the key you used in the mcpServers configuration.
options = ClaudeAgentOptions(
hooks={"PreToolUse": [HookMatcher(matcher="Bash", hooks=[my_callback])]}
)The characters in a matcher decide how it is read. *, an empty string, or no matcher at all matches every tool. A pattern made only of letters, digits, _, -, spaces, commas and | is an exact name or a list of exact names, so Edit|Write matches those two tools and nothing else. Any other character turns the pattern into an unanchored JavaScript regular expression. To cover every tool of one server, write mcp__billing__.*. Compare the near misses: billing is an exact name no tool has. ^mcp__ matches every MCP server, including inventory. ^mcp__billing__$ is anchored at both ends, so it matches only the literal string mcp__billing__, which is not a tool.
Conditions on arguments go in the callback. No matcher option filters on arguments, and putting argument text into the regex does not help, because the pattern is only ever tested against the tool name. The callback receives the full call: tool_name and tool_input, the arguments Claude passed. A rule such as "block refunds over $500 in a restricted category" therefore uses matcher="refund_customer" to scope the hook. Inside the callback, it reads input_data["tool_input"]["amount"] and input_data["tool_input"]["category"] and decides there. This file-protection callback has the same shape:
async def protect_env_files(input_data, tool_use_id, context):
# Extract the file path from the tool's input arguments
file_path = input_data["tool_input"].get("file_path", "")
file_name = file_path.split("/")[-1]
# Block the operation if targeting a .env file
if file_name == ".env":
return {
"hookSpecificOutput": {
"hookEventName": input_data["hook_event_name"],
"permissionDecision": "deny",
"permissionDecisionReason": "Cannot modify .env files",
}
}
# Return empty object to allow the operation
return {}The decision goes in hookSpecificOutput.permissionDecision. "deny" cancels the call and sends permissionDecisionReason to Claude. "ask" shows the user the normal permission prompt. "allow" skips that prompt, although deny and ask rules still apply. "defer" ends the turn with stop_reason tool_deferred, so the call can be resumed later. An empty object returns no decision, and the call proceeds through the normal permission flow. Alongside the decision, the top-level systemMessage field tells the user what happened. Claude does not see it.
Redirecting the agent is done through the reason text. Claude reads the reason so it knows why the call failed and does not try it again. A bare "Refund denied" gives the agent nothing to work with, and the likely result is a retry of the same call. A reason such as "Refunds over $500 need human approval; call escalate_refund with the order ID and amount" names the alternative workflow, and the agent takes it. When a human can approve at call time, "ask" is the alternative. Under a hard rule that no prompt may appear, deny with a specific reason is the right choice. To change a call instead of stopping it, return "allow" with updatedInput. The SDK's sandbox example uses this to rewrite a Write's file_path under /sandbox.
Checkpoint 3 of 8· Check yourself
Your policy is to block refund_customer calls over $500 when the category is "restricted". A teammate registers HookMatcher(matcher="refund_customer.*category=restricted", hooks=[check_refund]) under PreToolUse. What happens when the agent calls refund_customer with amount 900 and category "restricted"?
For tool hooks, the matcher is compared only with the tool name, so text about arguments in the pattern makes it match nothing. Use matcher="refund_customer" to scope the hook, then read tool_input["amount"] and tool_input["category"] in the callback.
“For tool hooks, this is the tool name.”Source: code.claude.com
Checkpoint 4 of 8· Check yourself
An unattended support agent, where no permission prompt may ever appear, has a PreToolUse hook that denies refunds over $500 with the reason "Refund denied". In the logs, the agent keeps calling refund_customer again with the same amount. Which change stops the retries and still keeps the limit guaranteed?
The deny is what guarantees the limit. Claude reads the reason to understand the block, so a reason that names the escalation tool sends the agent to that workflow instead of a retry. "ask" breaks the no-prompt rule, Claude never sees systemMessage, and a prompt-only rule loses the guarantee.
“permissionDecisionReason tells the model why, so it avoids retrying.”Source: code.claude.com
4.PostToolUse: normalize tool results before Claude reads them
Different tools describe the same thing in different shapes. An order-history agent might call one MCP server that returns Unix epoch integers, another that returns ISO 8601 strings, and a third that reports status as numeric codes. Each time the model compares these, it has to convert them in its head, and a misread date leads to wrong reasoning about which order came first. A PostToolUse hook removes that work. It receives the raw result in tool_response, along with the tool's name and input, and can rewrite the result into one format before Claude sees it.
type PostToolUseHookInput = BaseHookInput & {
hook_event_name: "PostToolUse";
tool_name: string;
tool_input: unknown;
tool_response: unknown;
tool_use_id: string;
duration_ms?: number;
mcp_server?: McpServerProvenance;
};A normalizer is registered under PostToolUse with a matcher covering the tools whose output varies, such as mcp__.* for every MCP tool or a list of exact names. The callback branches on tool_name and converts each timestamp to one representation, for example ISO 8601 in UTC. It also maps numeric status codes to readable labels. It then returns the rewritten payload. Because the hook only fires on success, it never has to handle error shapes.
Which output field you use determines what Claude ends up reading. additionalContext appends to the tool result, so Claude still sees the original mixed formats with your version added after them. updatedToolOutput replaces the result before Claude sees it, and it works for any tool, built-in or MCP, in both SDKs. The older updatedMCPToolOutput replaces MCP tool output only. A single hook that normalizes both kinds of tool should therefore use updatedToolOutput. systemMessage goes to the user and does not change what Claude reads.
| Field | Effect | Use it when |
|---|---|---|
| updatedToolOutput | Replaces the tool output before Claude sees it; works for any tool in both SDKs | Normalizing formats across built-in and MCP tools |
| updatedMCPToolOutput | Older field; replaces MCP tool output only | Existing hooks that only touch MCP tools |
| additionalContext | Appends information to the tool result; the original stays | Adding a note without hiding the raw data |
| systemMessage | Shows a message to the user | Telling the user what the hook did |
Checkpoint 5 of 8· Match them up
Your PostToolUse normalizer has already converted the Unix timestamps and numeric status codes from several tools into ISO 8601 dates and readable labels. Which output field you return it in decides what Claude reads next. Match each field to the result.
Tap a term, then the definition that fits it.
updatedToolOutput replaces the result for any tool, so it is the right field for a normalizer that covers both built-in and MCP tools. updatedMCPToolOutput replaces MCP output only. additionalContext keeps the raw data and adds your note after it, and systemMessage only goes to the user.
“set updatedToolOutput, which works for any tool in both SDKs. The older updatedMCPToolOutput field replaces MCP tool output only.”Source: code.claude.com
Checkpoint 6 of 8· Exam question
A PreToolUse hook needs to block refunds above $500 only when they target a specific merchant category, based on a field named category inside the refund tool's arguments. The hook is registered with matcher="refund_customer". Where should the category check be implemented?
Correct answer: D — Inside the callback function itself, by reading input_data["tool_input"]["category"] and applying the conditional logic there, since matchers only filter by tool name
- A. PreToolUse hooks do receive tool_input, including arbitrary arguments like category, inside the callback; the claim that arguments can never be inspected is incorrect.
- B. HookMatcher does not expose a separate argument_matcher field; the only filtering field for tool hooks is the tool-name matcher.
- C. Matchers are compared against the tool name only; they have no visibility into tool_input fields, so embedding an argument condition in the matcher string would not work as intended.
- D. Correct. Matchers only filter on the event's target field, which for tool-based hooks is the tool name, not its arguments. Any argument-level condition, like a category field, must be evaluated inside the callback by reading tool_input directly.
Checkpoint 7 of 8· Exam question
A support agent built with the Agent SDK calls several MCP tools that return dates as Unix timestamps, ISO 8601 strings and numeric status codes. The team needs every tool result converted to one canonical format, guaranteed rather than left to prompt instructions, and the model must never see the original heterogeneous values. Which approach meets these requirements?
Correct answer: B — A PostToolUse hook that returns the converted result as updatedToolOutput, replacing the raw result.
- A. Appending context leaves the raw result in place. The model would still receive the Unix timestamps, ISO 8601 strings and numeric status codes alongside the converted values, so the requirement that it never sees the original heterogeneous values is not met.
- B. The Agent SDK hooks documentation says that to replace a tool's output before Claude sees it, a PostToolUse hook sets
updatedToolOutput. The model then reasons only over the canonical format, and because a hook is deterministic code the normalization is guaranteed rather than dependent on model compliance. - C. A PreToolUse hook runs before the tool executes and can only modify or block the call's arguments. It cannot change what the tool returns, so the heterogeneous formats in the results would reach the model unchanged.
- D. Prompt instructions are probabilistic: the model may skip or misapply a conversion, and it still receives the raw heterogeneous results. This approach cannot provide the guaranteed normalization the team requires, which is what hooks are for.
Checkpoint 8 of 8· Exam question
Assume MCP tools are exposed to hooks under names of the form mcp__<server>__<tool> (for example mcp__billing__create_invoice), and that a hook matcher made only of letters, digits, underscores, hyphens, spaces, commas and pipes is compared as an exact string, while a matcher containing any other character is treated as an unanchored regular expression. An agent connects to two MCP servers named "billing" and "inventory". An architect wants a single PreToolUse hook to run for every tool exposed by the "billing" server, without matching any tool from "inventory" or any built-in tool like Bash or Read. Which matcher achieves this?
Correct answer: C — mcp__billing__.*
- A. This matches only a tool literally named "billing", which does not exist; MCP tool names always include the mcp__ prefix and server name as part of a longer string.
- B. This regex matches every tool name starting with mcp__, which includes both billing and inventory tools, so it fails to isolate billing-only calls as required.
- C. Correct. MCP tools are named mcp__<server>__<action>. Because this pattern contains a regex metacharacter (.*), it's evaluated as an unanchored regex and matches every tool name beginning with mcp__billing__, covering all billing tools without matching inventory or built-in tools.
- D. This adds explicit anchors, so it is evaluated as a regular expression rather than an exact string, but the anchors force it to require an exact match against the literal string mcp__billing__ with nothing following. Real MCP tool names always continue past the server's double underscore with an action name, for example mcp__billing__create_invoice, so no tool name equals this pattern exactly and it matches nothing.
Sources1
Sources
(5)
Every claim above is drawn from one of these pages, quoted as it was written on the date shown.
- 1.https://code.claude.com/docs/en/agent-sdk/hooksOfficial docs
“Block dangerous operations before they execute, like destructive shell commands or unauthorized file access”
↩︎ Guaranteed compliance belongs in code, not in the prompt“correlates PreToolUse and PostToolUse events for the same tool call”
↩︎ Where PreToolUse and PostToolUse fire in the tool-call path“MCP tools use the pattern mcp__<server>__<action>, where <server> is the key you use in the mcpServers configuration.”
↩︎ PreToolUse: scope with a matcher, decide in the callback“PreToolUseHookInput includes tool_name and tool_input”
↩︎ PreToolUse: scope with a matcher, decide in the callback“permissionDecisionReason tells the model why, so it avoids retrying.”
↩︎ PreToolUse: scope with a matcher, decide in the callback“set updatedToolOutput, which works for any tool in both SDKs”
↩︎ PostToolUse: normalize tool results before Claude reads them“you can set additionalContext to append information to the tool result”
↩︎ PostToolUse: normalize tool results before Claude reads them“Transform inputs and outputs to sanitize data, inject credentials, or redirect file paths”
↩︎ PostToolUse: normalize tool results before Claude reads them“For tool hooks, this is the tool name.”
↩︎ Exam trap 2“permissionDecisionReason tells the model why, so it avoids retrying.”
↩︎ Exam trap 4“The older updatedMCPToolOutput field replaces MCP tool output only.”
↩︎ Exam trap 5“PostToolUseFailure | Yes | Yes | Tool execution failure | Handle or log tool errors”
↩︎ Checkpoint“For tool hooks, this is the tool name.”
↩︎ Checkpoint“set updatedToolOutput, which works for any tool in both SDKs. The older updatedMCPToolOutput field replaces MCP tool output only.”
↩︎ Checkpoint - 2.
“Hooks let you deterministically run logic at points in the agent lifecycle.”
↩︎ Guaranteed compliance belongs in code, not in the prompt“Hooks let you deterministically run logic at points in the agent lifecycle.”
↩︎ Key concept - 3.
“Hooks run deterministically, making them perfect for validation and audit trails.”
↩︎ Guaranteed compliance belongs in code, not in the prompt“Hooks run deterministically, making them perfect for validation and audit trails.”
↩︎ Exam trap 1 - 4.https://code.claude.com/docs/en/hooksOfficial docs
“on every tool call inside the agentic loop: PreToolUse and PostToolUse, except EndConversation calls, which skip both”
↩︎ Where PreToolUse and PostToolUse fire in the tool-call path“JavaScript regular expression, unanchored”
↩︎ PreToolUse: scope with a matcher, decide in the callback“mcp__memory__.* matches every tool from the memory server”
↩︎ Exam trap 3“Exact string, or list of exact strings separated by | or , with optional surrounding whitespace”
↩︎ Prediction - 5.https://code.claude.com/docs/en/hooks-guideOfficial docs
“After a full batch of parallel tool calls resolves, before the next model call”
↩︎ Where PreToolUse and PostToolUse fire in the tool-call path“cancel the tool call and send the reason to Claude”
↩︎ PreToolUse: scope with a matcher, decide in the callback