CertSafari
    Anthropic Claude Certified Architect – Foundations (CCAR-F)· Lessons

    Domain 1 · Lesson 5/30

    Agent SDK hooks for blocking tool calls and normalizing tool results

    Apply Agent SDK hooks for tool call interception and data normalization

    16 min read
    3.86% of exam
    5 sources
    Published 20 Oct 2026
    Docs as of 14 Oct 2026

    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.

    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?

    Sources123

    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.

    Tool-related hook events and the moment each one fires
    EventWhen it firesWhat it can do
    PreToolUseBefore a tool call executesAllow, deny, ask, or defer the call; rewrite its input with updatedInput
    PostToolUseAfter a tool call succeedsAppend to the result with additionalContext, or replace it with updatedToolOutput
    PostToolUseFailureAfter a tool call failsHandle or log tool errors
    PostToolBatchAfter a full batch of parallel tool calls resolves, before the next model callAct 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.

    Sources451

    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.

    Registering a PreToolUse callback scoped to one tool by namepython
    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:

    A PreToolUse callback that reads tool_input and denies a policy-violating callpython
    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"?

    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?

    Sources145

    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.

    The input a PostToolUse callback receives: the original arguments and the tool's raw responsetypescript
    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.

    PostToolUse output fields and what Claude ends up reading
    FieldEffectUse it when
    updatedToolOutputReplaces the tool output before Claude sees it; works for any tool in both SDKsNormalizing formats across built-in and MCP tools
    updatedMCPToolOutputOlder field; replaces MCP tool output onlyExisting hooks that only touch MCP tools
    additionalContextAppends information to the tool result; the original staysAdding a note without hiding the raw data
    systemMessageShows a message to the userTelling 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.

    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?

    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?

    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?

    Sources1

    Sources

    (5)

    Every claim above is drawn from one of these pages, quoted as it was written on the date shown.

    1. 1.
      “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. 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. 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. 4.
      “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. 5.
      “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

    Spotted a mistake, or was something unclear? Tell us.