Skip to content
CCAR-F Prep

Task Statement 1.5·Domain 1 — 27% of exam

Agent SDK Hooks

Apply Agent SDK hooks for tool call interception and data normalization

Jump to practice →

Official Exam Guide Objectives

The objectives below are quoted from Anthropic's Claude Certified Architect – Foundations exam guide, v1.1. Read the exam guide summary for the full blueprint.

Task 1.5: Apply Agent SDK hooks for tool call interception and data normalization.

Knowledge of

  • Hook patterns (e.g., PostToolUse) that intercept tool results for transformation before the model processes them
  • Hook patterns that intercept outgoing tool calls to enforce compliance rules (e.g., blocking refunds above a threshold)
  • The distinction between using hooks for deterministic guarantees versus relying on prompt instructions for probabilistic compliance

Skills in

  • Implementing PostToolUse hooks to normalize heterogeneous data formats (Unix timestamps, ISO 8601, numeric status codes) from different MCP tools before the agent processes them
  • Implementing tool call interception hooks that block policy-violating actions (e.g., refunds exceeding $500) and redirect to alternative workflows (e.g., human escalation)
  • Choosing hooks over prompt-based enforcement when business rules require guaranteed compliance

What You Need to Know

Agent SDK hooks inject deterministic behaviour into an otherwise probabilistic system. They sit on the boundary between what the model decided and what actually happens, intercepting tool calls on the way out and tool results on the way back, so business rules and data shape stop depending on the model's cooperation. Task Statement 1.4 argued that some requirements need a guarantee; hooks are how that guarantee is built.

Two Types of Hooks

The Agent SDK provides hooks at two points in the tool execution lifecycle:

PostToolUse hooks sit between the tool returning and the model reading — the work is done, the result exists, and nothing has been shown to the model yet. That window is where a result can be rewritten, so what the model reads has a consistent shape whichever backend produced the underlying value.

PreToolUse hooks (sometimes described as tool-call interception) sit on the other side, between the model requesting a tool and the tool running. The call is visible and has not yet taken effect, so it can be passed through, altered, or refused outright. Refusal here means the action never happens, rather than happening and being unwound afterwards.

Prevent before execution, reshape after — never reverse The model requests process_refund($750); nothing has happened yet. PreToolUse sits here, before execution, and can allow, deny, or rewrite the call — refusal here means the action never happens. Allowed, the call reaches the tool, which executes, and the refund is issued: the result now exists. PostToolUse sits here, after execution, and can normalise or append to that result — but it cannot undo what already happened, only reshape what the model reads next. Choosing between them is a question of whether you are stopping something or reshaping something. tool executes process_refund($750) PreToolUse ✓ allow, deny, or rewrite before it happens refund issued: $750 PostToolUse ✓ normalise or append ✕ cannot undo it prevent before execution, reshape after — never the reverse
1 / 6Swipe diagram ↔

Prevent before execution, reshape after — never reverse, step 1: The model requests process_refund($750) — nothing has happened yet

Put in one line: PreToolUse guards the action; PostToolUse shapes the perception. Almost every question on this task statement reduces to which of the two applies, and then which output it returns.

HookFiresThe question it answersWhat it can return
PreToolUseAfter the model requests a tool, before the tool runsShould this run, and with what arguments?A decision (allow, deny, ask or defer), or rewritten arguments
PostToolUseAfter the tool has run, before the model reads the resultWhat should the model actually see?A replacement result, or text appended to the result

PostToolUse Hooks: Data Normalisation

Backends disagree about formats and will not stop disagreeing because an agent is now reading them. One backend hands back Unix timestamps such as 1710504000. Another expresses the same instant as an ISO 8601 string, "2024-03-15T12:00:00Z". Status is worse: one service answers with numeric codes — 200, 404, 500 — while its neighbour answers with words like "active", "cancelled" and "pending".

Left alone, the model performs a small format conversion on every iteration, from memory, while holding everything else the task requires. Most conversions will be correct. The incorrect ones do not announce themselves — they produce a confident answer built on a misread value.

Normalising in a PostToolUse hook removes the ambiguity before it ever reaches the model:

  • Unix timestamps → ISO 8601 dates
  • Numeric status codes → human-readable strings
  • Currency values → consistent decimal format with currency code
  • Date strings in various regional formats → a single standard format

The model then reads one vocabulary, every time, regardless of which tool or backend produced the value — and the interpretation step that could go wrong no longer exists.

Replace the ambiguous result, don't just annotate it get_customer returns a numeric status, lookup_order returns an ISO date, check_shipping returns a DD/MM/YYYY date and a single-letter status — three dialects the model would otherwise reconcile itself, imperfectly. A PostToolUse hook using additionalContext appends a clarifying note but leaves the three raw dialects in place, so the same ambiguity is available to be misread again next time. The same hook using updatedToolOutput replaces the result outright: one vocabulary, ISO dates and plain-English status, and nothing raw left for the model to misinterpret. three tools, three dialects get_customer → status: 200 lookup_order → 2024-03-15T12:00Z check_shipping → 15/03/2024, S what the model reads — additionalContext same three raw dialects, unchanged + a note explaining them ✕ still three formats to misread what the model reads — updatedToolOutput one vocabulary: ISO dates, plain English all three tools now match ✓ nothing raw left to misread replace what's ambiguous — don't just annotate it
1 / 6Swipe diagram ↔

Replace the ambiguous result, don't just annotate it, step 1: Three tools, three date formats, three status vocabularies

Replace, trim or append: three jobs, two outputs

A PostToolUse hook has two ways to change what the model reads, and choosing between them is itself tested. The field names are updatedToolOutput (replace) and additionalContext (append); the Deep Dive covers their mechanics.

JobOutput to useWhy
Normalise mixed formatsReplace the resultAppending leaves the raw, inconsistent values in context beside the clean ones, where they can still be misread
Trim a verbose result down to the fields the task needsReplace the resultThe same mechanism: the model receives the smaller payload instead of the full one (Task Statement 5.1 covers why this matters for context)
Attach a fact the tool did not returnAppend to the resultThe raw result is correct and stays intact; the hook adds derived context beside it

A worked case of the third job: an order lookup returns a delivery date 34 days in the past, and the standard return window is 30 days. A hook can append "this order was delivered 34 days ago; the standard return window is 30 days, so a return needs a policy exception" to the result. Nothing in the result is wrong, so nothing is replaced. The rule: adding a fact, append; correcting or shrinking the payload, replace.

Why a hook, and not one of the alternatives

Leaving the conversion to the model, guided by format notes in the system prompt, is the model-side transformation trap set out under Exam Traps. The other alternatives fail for different reasons:

AlternativeWhy it loses
Add few-shot examples of each formatExamples teach the model to recognise a format; they do not guarantee the conversion
Normalise inside each MCP serverSound when you own every server. The tested scenario has different, often third-party, servers, and the same logic would be repeated in each one
Clean the data up after the agent finishesToo late: the agent has already reasoned on the inconsistent values

What the conversion looks like

The conversion is ordinary code with no model involved. A sketch of two functions a normalising hook would call:

from datetime import datetime, timezone

STATUS_WORDS = {0: "pending", 1: "processing", 2: "shipped", 3: "delivered"}

def to_iso(value):
    # Unix seconds or milliseconds become one ISO 8601 UTC string.
    if isinstance(value, (int, float)):
        seconds = value / 1000 if value > 10_000_000_000 else value
        return datetime.fromtimestamp(seconds, tz=timezone.utc).isoformat()
    return value  # date strings are parsed by a rule fixed per source

def to_status_word(code):
    if isinstance(code, int):
        return STATUS_WORDS.get(code, f"unknown_{code}")
    return code

to_iso(1710504000) and to_iso(1710504000000) both return 2024-03-15T12:00:00+00:00. Three properties matter more than the code itself: every source ends in one shape; a timestamp in milliseconds is detected rather than read as seconds; and a status code with no mapping is surfaced as unknown_7 rather than guessed at or passed through raw.

PreToolUse Hooks: Policy Enforcement

The prerequisite gates described in 1.4 are built from PreToolUse hooks — the hook is where the gate's condition is actually evaluated, against a call that has not yet taken effect:

Use case: Refund threshold enforcement. A hook intercepts all calls to process_refund. Where the amount exceeds $500, the call is blocked and the request routed into a human escalation workflow. The refund is not issued and then reversed — it is never issued.

Use case: Compliance prerequisite gates. A hook intercepts calls to transfer_funds. Where the required anti-money laundering (AML) check has not completed for this session, the call is blocked and an error returned directing the agent to complete the AML check first, which it can then act on without human involvement.

Use case: Manager approval workflow. A hook intercepts calls to approve_discount for discounts above 20%, pauses execution, and routes the request to a manager approval queue. The tool executes only once approval returns, so the discount cannot be granted while the request is still pending.

The redirect is half the pattern

The guide's wording is "block policy-violating actions (e.g., refunds exceeding $500) and redirect to alternative workflows (e.g., human escalation)". A hook that only refuses leaves the agent to guess what to do next, and the usual guess is to retry the same call. The reason attached to a denial is read by the model, so that is where the redirect goes: say what was refused and why, name the tool to call instead, and say what to tell the customer. For example: "Refunds above $500 require human approval and cannot be processed autonomously. Call escalate_to_human with the customer ID, order ID, requested amount, root cause and recommended action, then tell the customer a specialist is reviewing the request."

The rule is "exceeding $500", so the boundary matters:

Requested refundHook result
$250.00Allowed
$500.00Allowed: the rule blocks amounts above the threshold, not at it
$900.00Denied, with the escalation redirect

Deny, ask, rewrite or pause: choose deliberately

A PreToolUse hook has four decisions and one rewrite available. Each fits a different situation:

SituationDecision
The rule is absolute and the agent must take a different pathDeny, with a reason that names the alternative
A person could approve this particular call, and can answer while the agent waitsAsk: the call waits for a human's confirmation
The call is fine but its arguments must be corrected or scopedRewrite the arguments (updatedInput), usually together with allow
Approval will arrive later, out of band, and the process should not sit waitingDefer: the turn ends and the call is resumed later

The manager-approval use case above is the ask row or the defer row, depending on whether the approver answers while the process is still running.

Rewriting is for arguments that are mechanically wrong or need scoping, such as redirecting a file path into a sandbox directory or adding a safety flag to a command. It is the right mechanism only when the stated requirement is itself to correct the argument, and it is not a way to take a business decision on someone's behalf: capping a refund at the limit instead of escalating it is a trap, set out under Exam Traps.

A gate on an earlier step needs state that something writes

The AML gate has to know whether aml_check passed. The reliable design uses each hook for the one thing only it can do: a PostToolUse hook on aml_check sees the result and records the pass in state held per session, and the PreToolUse hook on transfer_funds reads that state and denies while it is unset. Three weaker designs appear as wrong answers:

  • Scanning the conversation history for an earlier pass. It avoids extra state, but it makes the gate depend on parsing an unstructured transcript, where a pass is far easier to miss or misread than a flag your own code wrote.
  • Trusting the prompt to have ordered the calls. A gate that trusts a prompt is not a gate.
  • Reading state that nothing writes. The gate then refuses every transfer for ever, or, if it defaults to open, refuses none.

The Decision Framework

This framework is the core mental model for the exam:

RequirementMechanismGuarantee
Must be followed 100% of the timeHooksDeterministic
Preferred but occasional deviation is acceptablePromptsProbabilistic

The question is not whether prompts are good enough in general, because usually they are. It is what a single failure costs. Where one miss loses money, use a hook. Where one miss creates legal exposure, use a hook. Where one miss produces a slightly untidy response, a prompt is proportionate and a hook is overhead built to enforce a preference.

What the hook buys beyond certainty

Take the rule "never refund more than $500" and compare the two places it can live:

PropertyAs a prompt instructionAs a hook
ComplianceProbabilisticTotal: the tool cannot execute
Long conversations, unusual phrasing, customer pressureCompliance degradesUnaffected, because the check is code
Audit trailA skipped rule leaves no traceEvery denial is an event your code can log
"And then do this instead"Followed only as reliably as the rule itselfThe denial reason carries the redirect

Hooks vs Prompts: Side-by-Side Comparison

Scenario: International transfers must pass AML checks.

  • Prompt approach: "Always complete AML verification before processing international transfers." Holds roughly 95% of the time, so the residual 5% are transfers that left without an AML check — a regulatory finding rather than a quality issue.
  • Hook approach: transfer_funds is gated on aml_check having returned a pass, evaluated before the call runs. The unchecked transfer stops being rare and becomes impossible.

Scenario: Responses should be formatted in markdown.

  • Prompt approach: "Format all responses using markdown with headers and bullet points." Holds most of the time, and an occasional plain-text response costs nothing anyone will notice.
  • Hook approach: unnecessary overhead. Building enforcement machinery for a formatting preference spends engineering effort on a risk that does not exist.

Scenario: Refunds above $500 require human approval.

  • Prompt approach: "For refunds above $500, escalate to a human agent." Holds most of the time, and each miss is a large refund issued with nobody having approved it.
  • Hook approach: intercept process_refund, inspect the amount, block above $500 and route to human escalation. Approval stops being something the model can overlook.

Hooks and the Other Enforcement Surfaces

A hook is one of several places a rule can live. Wrong answers often offer a real mechanism that works at the wrong scope.

SurfaceGuaranteeScopeUse it for
System prompt or CLAUDE.mdProbabilisticWhole sessionPreferences, conventions, judgement
Few-shot examplesProbabilisticWhole sessionJudgement in ambiguous cases, output format
tool_choiceDeterministicOne API requestForcing which tool a single response starts with
Tool availability (which tools the agent is given)DeterministicSession or agentWhether a tool exists for this agent at all
HooksDeterministicEvery matching callOrdering, thresholds, rewriting arguments, normalising results
Permission callback (can_use_tool in Python, canUseTool in TypeScript)Deterministic, but only for the calls that reach itCalls that fall through to a permission promptCustom approval prompts

Two rows are easy to confuse with hooks:

  • Availability is not ordering. If an agent should never have a tool, remove the tool rather than denying every call to it with a hook. If the rule is about when a tool may run or with what arguments, removing the tool is the wrong instrument and a hook is the right one. Official sample question 1 turns on this: its explanation rejects a routing classifier because it "addresses tool availability rather than tool ordering, which is not the actual problem."
  • The permission callback is not a compliance gate. It runs only when permission evaluation ends in a prompt. A call already approved by an allow rule or by a permissive permission mode never reaches it, so a refund limit placed there is skipped without any error. It looks sophisticated and is the wrong place for a business invariant.

Practical Example: Data Format Chaos

A customer support agent uses three MCP tools:

  1. get_customer — timestamps arrive as Unix epoch integers, status as numeric codes.
  2. lookup_order — timestamps arrive as ISO 8601 strings, status spelled out in English.
  3. check_shipping — dates arrive as "DD/MM/YYYY", status compressed to one letter: "S" for shipped, "P" for pending.

Every iteration, the model reconciles three date formats and three status vocabularies alongside the actual task. Usually it manages. Then it reads "03/04/2024" as March the fourth, or takes "P" for processed rather than pending, and reports an order as complete when it has not shipped. Nothing raised an error, because no component failed — the model simply resolved an ambiguity the wrong way.

Routing every result through a normalising hook first collapses all three dialects into one:

  • All dates → ISO 8601 ("2024-03-15T12:00:00Z")
  • All status codes → human-readable strings ("shipped", "pending", "delivered")

The reconciliation step disappears from the model's work entirely, which removes the class of error rather than reducing its frequency.

Proving a Hook Works

Each kind of hook has one check that separates success from failure, and several tempting checks that cannot.

  • Normalisation: run one query that touches all three tools, then inspect the results the model actually received. A fluent final answer proves nothing, because a misread date also produces a fluent answer; an error-free run proves nothing either, because it is consistent with the hook never having fired.
  • Blocking: assert that the guarded tool does not appear among the tools that ran. An error message, an unchanged refund total and a denial in the log are all worth having, but each is also consistent with a refund that was issued and then reversed or merely reported.

Deep Dive

The full hook event list, and which are SDK-available

"Hooks are callback functions that run your code in response to agent events, like a tool being called, a session starting, or execution stopping." This lesson concentrates on PreToolUse and PostToolUse, but the SDK exposes many more events: "Some hooks are available in both SDKs, while others are TypeScript-only." Available in both Python and TypeScript (ten events): PreToolUse, PostToolUse, PostToolUseFailure, UserPromptSubmit, Stop, SubagentStart, SubagentStop, PreCompact, PermissionRequest, and Notification. Every other event in the availability table is TypeScript-only. There are 23 of them today, including PostToolBatch, PostCompact, StopFailure, PermissionDenied, and the two session-boundary events: "SessionStart | No | Yes | Session initialization | Initialize logging and telemetry ... SessionEnd | No | Yes | Session termination | Clean up temporary resources."

The Python gap concerns SDK callbacks specifically: "SessionStart and SessionEnd can be registered as SDK callback hooks in TypeScript, but aren't available in the Python SDK because its HookEvent type omits them. In Python, they are only available as shell command hooks defined in settings files such as .claude/settings.json." For start-up logic written as a Python callback, the docs say to "use the first message from client.receive_response() as your trigger."

Sourcecode.claude.com › hooksfetched 2026-11-19

HookMatcher — scoping a hook to specific tools

The hooks option maps each hook event to a list of matcher configurations: it is "a dictionary in Python or an object in TypeScript", whose keys are "hook event names such as 'PreToolUse', 'PostToolUse', and 'Stop'" and whose values are "arrays of matchers, each containing an optional filter pattern and your callback functions." The matcher field is what scopes it: "If a hook has a matcher pattern (like "Write|Edit"), the SDK tests it against the event's target (for example, the tool name). Hooks without a matcher run for every event of that type."

How a matcher is read depends on its characters. A value made only of letters, digits, _, -, spaces, , and | is compared as an exact name or a list of exact names, so Write|Edit matches those two tools and nothing else. A value containing any other character is a "JavaScript regular expression, unanchored", so ^mcp__ catches every MCP tool.

MCP tool names carry their server: "MCP tools use the pattern mcp__<server>__<action>, where <server> is the key you use in the mcpServers configuration". This lesson calls its tools process_refund and transfer_funds for short, as the exam guide does, but a matcher has to carry the full name. If the refund tool comes from a server registered as support, the matcher is mcp__support__process_refund; a matcher of process_refund is an exact comparison that matches no tool. Every tool from one server is mcp__support__.*, and the .* is required: "a matcher like mcp__memory or mcp__brave-search contains only exact-match characters, so it is compared as an exact string and matches no tool."

from claude_agent_sdk import ClaudeAgentOptions, HookMatcher

options = ClaudeAgentOptions(
    hooks={
        "PreToolUse": [
            HookMatcher(matcher="mcp__support__process_refund", hooks=[enforce_refund_limit]),
        ],
        "PostToolUse": [
            HookMatcher(matcher="mcp__orders__.*", hooks=[normalise_orders]),
        ],
    }
)

Two limits follow. "Matchers only match tool names, not file paths or other arguments", so the matcher selects the refund tool and the $500 comparison happens inside the callback. And a hook registered with no matcher runs "for every occurrence of the event", so a threshold hook left without one starts judging tools it was never meant to touch.

Sourcescode.claude.com › hookscode.claude.com › hooksfetched 2026-11-19

What a hook callback receives

"Every hook callback receives three arguments": the input data, a tool use ID that "correlates PreToolUse and PostToolUse events for the same tool call", and a context argument (an AbortSignal holder in TypeScript; in Python "this argument is reserved for future use"). In Python the signature is async def my_hook(input_data, tool_use_id, context).

"All hook inputs share session_id, cwd, and hook_event_name." Tool hooks add tool_name and tool_input, and a PostToolUse input "includes both tool_input, the arguments sent to the tool, and tool_response, the result it returned." agent_id and agent_type "are populated when the hook fires inside a subagent."

These fields are what the patterns in this lesson read: session_id keys the per-session state an AML gate depends on, tool_input holds the refund amount a threshold hook compares, and tool_response is what a normalising hook rewrites.

Sourcescode.claude.com › hookscode.claude.com › hooksfetched 2026-11-19

PreToolUse output — the exact JSON shape of a block or allow

A PreToolUse hook does not just return true/false. Its hookSpecificOutput sets three fields: "For PreToolUse hooks, this is where you set permissionDecision ("allow", "deny", "ask", or "defer"), permissionDecisionReason, and updatedInput." The decision is a four-value enum rather than a boolean, and the minimal "allow, unchanged" response is an empty object rather than false.

Who reads permissionDecisionReason depends on the decision: "For "ask", shown to the user in the permission prompt ... For "deny", shown to Claude. For "allow" and "defer", written to the debug log only". That is why the redirect to escalation belongs in the reason of a deny. A threshold hook with its redirect:

REFUND_LIMIT_CENTS = 50_000  # $500.00, compared as an integer

async def enforce_refund_limit(input_data, tool_use_id, context):
    # "amount_cents" stands for whatever field your refund tool defines.
    amount = input_data["tool_input"].get("amount_cents")
    if isinstance(amount, int) and amount <= REFUND_LIMIT_CENTS:
        return {}  # allow unchanged
    return {
        "hookSpecificOutput": {
            "hookEventName": "PreToolUse",
            "permissionDecision": "deny",
            "permissionDecisionReason": (
                "Refunds above $500 require human approval and cannot be processed "
                "autonomously. Call escalate_to_human with the customer ID, order ID, "
                "requested amount, root cause and recommended action, then tell the "
                "customer a specialist is reviewing the request."
            ),
        }
    }

The hook allows only what it can positively identify as within the limit; an amount that is missing or unreadable is denied along with one that is too large.

defer is the fourth option, and it does not mean "fall through to the next permission step": "If you return "defer", the turn ends with a result message whose stop_reason is "tool_deferred", so you can resume the call later." The tool does not run, and any updatedInput returned with it is ignored. It suits approvals that take longer than a process should wait: where a user might take longer to respond than the process can stay running, the docs say to return the defer decision "so the process can exit and resume later from the persisted session." It has limits: "Claude Code honors "defer" only in non-interactive mode with the -p flag, and only when Claude makes a single tool call in the turn"; with "several tool calls at once" it "is ignored with a warning and the tool proceeds through the normal permission flow."

Sourcescode.claude.com › hookscode.claude.com › hookscode.claude.com › user-inputfetched 2026-11-19

PreToolUse can rewrite the call, not just block it

Beyond allow and deny, a PreToolUse hook can modify the tool call before it runs by returning updatedInput: "Pair updatedInput with permissionDecision: 'allow' to auto-approve the modified input, or permissionDecision: 'ask' to show it to the user. If you omit permissionDecision, the modified input still applies and flows through the normal permission evaluation. With 'defer', updatedInput is ignored. Always return a new object rather than mutating the original tool_input." The documented example rewrites a Write call's file_path to sit under a sandbox directory and auto-approves the rewritten call.

Three details decide whether a rewrite applies at all:

  • Placement. updatedInput must be "inside hookSpecificOutput, not at the top level"; the docs list a top-level updatedInput under "Modified input not applied".
  • Completeness. It "replaces the entire input object, so include unchanged fields alongside modified ones."
  • Pairing. "Don't pair updatedInput with permissionDecision: 'defer', which drops the modified input."

The mechanism is general, and that is the hazard: nothing in the SDK stops a hook from rewriting a refund amount down to the limit and approving it. Whether that is correct is a policy question, and for a rule that requires approval or escalation it is the silent-clamping trap set out under Exam Traps.

Sourcescode.claude.com › hookscode.claude.com › hooksfetched 2026-11-19

PostToolUse output — normalisation via additionalContext or updatedToolOutput

The lesson's normalisation use case has two distinct implementation options, not one. "For PostToolUse hooks, you can set additionalContext to append information to the tool result. To replace the tool's output before Claude sees it, set updatedToolOutput, which works for built-in and MCP tools in both SDKs. The older updatedMCPToolOutput field replaces MCP tool output only." For the Unix-timestamp, ISO 8601 and status-code scenario, updatedToolOutput is the match: it replaces the raw heterogeneous result with the normalised version, rather than appending a note alongside the original raw data. Prefer it over updatedMCPToolOutput even for MCP tools.

async def normalise_orders(input_data, tool_use_id, context):
    # normalise() is your conversion; it returns the same shape the tool returns.
    cleaned = normalise(input_data["tool_response"])
    return {
        "hookSpecificOutput": {
            "hookEventName": "PostToolUse",
            "updatedToolOutput": cleaned,
        }
    }

Four properties of this event bound what it can do:

  • It fires on success only. PostToolUse "runs immediately after a tool completes successfully." A failed call fires PostToolUseFailure instead, which "can't rewrite a result, so a failing command's output reaches Claude unchanged."
  • The replacement must keep the tool's shape. "The replacement value must match the tool's output shape ... For built-in tools, a value that doesn't match the tool's output schema is ignored and the original output is used. MCP tool output is passed through without schema validation."
  • It changes perception, not history. "updatedToolOutput only changes what Claude sees. The tool has already run by the time the hook fires, so any files written, commands executed, or network requests sent have already taken effect."
  • Its "block" does not block. A PostToolUse hook can return decision: "block", but that only "adds the reason next to the tool result. Claude still sees the original output". Nothing is prevented or undone.

additionalContext reaches the model: it "passes a string from your hook into Claude's context window", placed "next to the tool result" for tool events. The docs advise writing it "as factual statements rather than imperative system instructions."

Sourcescode.claude.com › hookscode.claude.com › hooksfetched 2026-11-19

Decision priority when multiple hooks disagree

Real systems often have more than one hook that could apply to the same call. The precedence is fixed: "When multiple PreToolUse hooks return different decisions, deny takes priority over defer, which takes priority over ask, which takes priority over allow." The hooks do not run in sequence: "When an event fires, the matching hooks run in parallel. For permission decisions, the most restrictive result applies. One hook's deny blocks the tool call. Because completion order is non-deterministic, write each hook to act independently rather than relying on another hook having run first."

Decisions returned by the matching hooksResult
allow, allowallow
allow, askask
ask, denydeny
deny, allow, deferdeny

So a refund-threshold hook and an AML-check hook can both watch transfer_funds independently. If either denies, the call is blocked, even if the other would have allowed it, and neither may assume the other has already run. Registration order plays no part in the result.

Sourcecode.claude.com › hooksfetched 2026-11-19

Any deny wins — regardless of what other hooks decide PreToolUse hooks return one of four decisions, in fixed priority: deny, then defer, then ask, then allow — if any hook returns deny, the operation is blocked regardless of what any other hook returns. Two independent PreToolUse hooks watch the same transfer_funds call: an AML gate, which returns deny because the check has not passed, and a rate-limit check, which returns allow. The combined result is deny — one refusal is enough, even though the other hook was satisfied. Beyond allow or deny, a hook can also rewrite the call by returning updatedInput, for example redirecting a file path into a sandbox directory and then allowing the rewritten call through. priority order deny > defer > ask > allow deny beats all — regardless of other hooks transfer_funds($10,000) AML gate checks aml_check rate-limit check checks call frequency → deny → allow combined: deny still blocks, either way a hook can also rewrite the call — updatedInput + allow
1 / 6Swipe diagram ↔

Any deny wins — regardless of what other hooks decide, step 1: Four decisions, in priority order: deny, defer, ask, allow

Allowing unchanged, shared fields, and what happens when a hook fails

The minimal allow response is an empty object: "Return {} to allow the operation without changes." It has to be returned explicitly, because "a callback that returns nothing, such as a path with no return, also counts as failing."

Two top-level fields are accepted on every hook event: "systemMessage shows a message to the user, and continue (continue_ in Python) determines whether the agent keeps running after this hook. Some events discard them or deliver them elsewhere." Each has a limit worth knowing:

  • systemMessage is for the user. "The systemMessage field shows a message to the user, not the model ... To pass context to the model instead, return additionalContext."
  • continue: false halts the run, not the pending call. "If false, Claude stops processing entirely after the hook runs. It doesn't block a PreToolUse tool call, so to do that, also return permissionDecision: "deny"." It is the field for a hook that must stop the whole agent run rather than refuse one tool call.

Two behaviours matter for a hook that is meant to be a guarantee:

  • A fire-and-forget hook cannot guard anything. A hook may return an async output (async_ in Python, async in TypeScript, with an optional asyncTimeout in milliseconds) so the agent does not wait for it, but "async outputs can't block, modify, or inject context into the operation since the agent has already moved on. Use them only for side effects like logging, metrics, or notifications."
  • A crashing guard fails open by default. "On most events, if a callback throws or returns output that fails validation, the action goes ahead ... A PreToolUse guard that crashes then lets the tool call reach the normal permission flow." To block instead, "set onFailure: "block" in TypeScript or on_failure="block" in Python on the matcher."

Sourcescode.claude.com › hookscode.claude.com › hooksfetched 2026-11-19

Where hooks sit in permission evaluation, and why the permission callback is not a gate

When Claude requests a tool, the SDK checks the call in six steps: hooks, deny rules, ask rules, permission mode, allow rules, and finally the canUseTool callback (can_use_tool in Python). Hooks run first, and a hook's deny is final: "A hook deny applies even in bypassPermissions mode." A hook's allow is not: "A hook that returns allow doesn't skip the deny-rule and ask-rule steps, which are evaluated regardless of the hook result."

The callback is the last step, reached only "if no earlier step resolves the request". The docs warn: "Auto-approved tools never reach canUseTool. A tool call approved at any earlier step, by acceptEdits or bypassPermissions, or by an allow rule, skips your canUseTool callback, so permission checks you put there are silently bypassed for that tool." They also name the fix: "To check calls that an allow rule, acceptEdits, or bypassPermissions approves, use a PreToolUse hook, which runs for those calls too."

Availability is a separate control. A bare tool name in disallowed_tools removes the tool altogether: with disallowed_tools=["Bash"], "the Bash tool definition is removed from the request." Use that when the agent should not have the tool, and a hook when it may have the tool under conditions.

Sourcecode.claude.com › permissionsfetched 2026-11-19

Quick Reference

FactValue
Hook events in BOTH Python and TypeScriptPreToolUse, PostToolUse, PostToolUseFailure, UserPromptSubmit, Stop, SubagentStart, SubagentStop, PreCompact, PermissionRequest, Notification
TypeScript-only hook eventsEvery other event (23 today), including SessionStart and SessionEnd; in Python those two exist only as shell command hooks in a settings file
hooks option shapedict[HookEvent, list[HookMatcher]]
Python callback signatureasync def hook(input_data, tool_use_id, context), returning a dict
HookMatcher.matcherTested against the event's target (the tool name for tool hooks); exact names or lists (Write|Edit), or an unanchored regex (^mcp__); omitted = runs for every event of that type
MCP tool name in a matchermcp__<server>__<tool>, for example mcp__support__process_refund; a whole server is mcp__support__.*
What a matcher cannot seeArguments. Check tool_input inside the callback
PreToolUse permissionDecision valuesallow, deny, ask, defer
PreToolUse other output fieldspermissionDecisionReason, updatedInput
Who reads permissionDecisionReasondeny: the model. ask: the user. allow and defer: the debug log only
updatedInput + permissionDecision: "allow"Auto-approves the modified input
updatedInput + permissionDecision: "ask"Shows the modified input to the user
updatedInput with no permissionDecisionModified input still applies, flows through normal permission evaluation
updatedInput + permissionDecision: "defer"The modified input is ignored
updatedInput placement and contentInside hookSpecificOutput, never top-level; a new object that replaces the whole input, so include the unchanged fields
deferThe tool does not run; the turn ends with stop_reason "tool_deferred" and the call is resumed later
PostToolUse additionalContextAppends information to the tool result (original stays intact); read by the model
PostToolUse updatedToolOutputReplaces the tool's output before Claude sees it (built-in and MCP tools, both SDKs); must match the tool's output shape
PostToolUse updatedMCPToolOutputOlder field, MCP tools only; prefer updatedToolOutput
When PostToolUse firesAfter a successful call only; a failed call fires PostToolUseFailure, which cannot rewrite the result
Several hooks on one callRun in parallel, completion order non-deterministic; the most restrictive decision applies
Decision prioritydeny > defer > ask > allow; one hook's deny blocks the tool call
Minimal "allow, no change" response{}, returned explicitly
Fields accepted on every hook outputsystemMessage (message to the user, not the model), continue/continue_ (whether the agent keeps running)
continue: falseStops the agent run; does not by itself block the pending PreToolUse call
Async hook output (async_ in Python)Fire-and-forget; cannot block, modify or inject context
A callback that throwsThe action goes ahead by default; on_failure="block" (onFailure in TypeScript) on the matcher blocks instead
Permission callback (can_use_tool / canUseTool)Last step of permission evaluation; skipped for calls approved by an allow rule, acceptEdits or bypassPermissions
Hook deny under bypassPermissionsStill applies

Exam Traps

More wrong answers, and why each fails

Tempting answerWhy it failsChoose instead
Use systemMessage to give the model informationIt is shown to the user, not the modeladditionalContext, or the denial reason on a refusal
Return updatedInput at the top level of the output, or together with deferNeither applies: it must sit inside hookSpecificOutput, and defer drops itNest it, with allow, ask or no decision
Write a hook that relies on another hook having run firstMatching hooks run in parallel and finish in no fixed orderMake each hook stand alone
Enforce an ordering or a threshold with tool_choiceIt shapes one request: which tool a single response starts with. It says nothing about later calls or about argumentsA PreToolUse hook

How This Is Tested

Items on this task statement describe a production system that is already misbehaving and ask for the best response. The signal is usually in the stem's own nouns: money, law or a stated failure rate points to a hook; mixed formats point to PostToolUse; a preference points back to the prompt.

Stem signalAnswerThe wrong-answer pattern beside it
"Refunds over $500 must never be issued autonomously, and the agent occasionally does"PreToolUse hook: deny, and redirect to escalationStronger prompt wording or few-shot examples; a PostToolUse alert or reversal; capping the amount
"Three MCP servers return dates in three formats and the agent miscalculates return eligibility"PostToolUse hook that replaces the result (updatedToolOutput)Describing the formats in the system prompt; additionalContext; a PreToolUse hook on the arguments; dropping a tool
"The agent needs to see a policy note attached to every order lookup"PostToolUse additionalContextsystemMessage, which goes to the user; replacing a result that was correct
"Which hook, and which field?"Recall: four PreToolUse decisions, two PostToolUse outputsFields on the wrong event, such as updatedToolOutput to change an outgoing call or permissionDecision to shape a result
"Compliance is at 95%; why not just instruct the model more firmly?"Deterministic versus probabilistic: a hook, because one miss is unacceptableA more emphatic or more detailed instruction
"Two hooks watch the same call and disagree"The most restrictive decision applies: deny, then defer, then ask, then allowRegistration order decides; one approval is enough; an operator adjudicates
A formatting or style preference with no cost when it is missedLeave it to the prompt; a hook is overheadA hook for every rule

The official sample questions use the same reasoning. Sample question 1, keyed to Task Statement 1.4, offers as its option B: "Enhance the system prompt to state that customer verification via get_customer is mandatory before any order operations." The official explanation rejects it together with the few-shot option: "Options B and C rely on probabilistic LLM compliance, which is insufficient when errors have financial consequences." That sentence decides every hook-versus-prompt item on this task statement as well.

Practice Scenario

get_customer returns account_status as a number (0 = standard, 1 = flagged), while lookup_order returns a string ("standard" or "flagged"). Your escalation check treats anything other than the string "flagged" as standard, so a numeric 1 from get_customer is read as standard and a flagged account's refund proceeds without escalation. What's the most effective first step?

Practice Questions

Exam simulator

Question 1 of 13

Scenario · Customer Support Resolution Agent

get_customer returns the customer's full card number among its fields, and the payments team owns that MCP server and won't change it this quarter. Security requires that your support agent never processes full card numbers. A prompt rule against repeating them is already in place, but transcripts show the agent quoting them back. What change would most effectively meet the requirement?

Sources