# Apply Agent SDK hooks for tool call interception and data normalization

Place pre-action gates and post-result normalization in an explicit application control flow.
Compare pre-tool interception, successful-result processing, and execution-failure handling without assuming a universal SDK contract. A framework-neutral teaching adapter demonstrates timestamp and status normalization, blocked refunds, and separately authorized handoffs with acknowledgements.

Author: LearningPathX Editorial Team
Content version: 1.0
Published: 2026-12-04T00:30:30.852876+00:00
HTML: https://learningpathx.com/material/CCAR-F/apply-agent-sdk-hooks-for-tool-call-interception-and-data-normalization.html

Knowledge domain: Agentic Architecture & Orchestration
Tags: Action Authorization / Error Handling / Data Normalization / Tool Hooks

## Apply Agent SDK hooks for tool call interception and data normalization

## Learning objectives

By the end of this topic, you should be able to:

* Place interception before an action and normalization after an observed result.
* Distinguish trusted code checks from model-based evaluation and advisory prompts.
* Normalize timestamps and status values without inventing missing meaning.
* Test hook coverage, denial behavior and error preservation in the actual harness.

## Match the event to the intervention

A `PreToolUse`\-style event is an opportunity to inspect a proposed call before execution. It can reject an unsupported target, malformed amount or policy violation when the active harness supports that blocking path. A `PostToolUse`\-style event operates after execution and can validate, annotate or normalize the returned data before subsequent reasoning.

In the supplied hook model, `PostToolUse` handles a successful tool result, while `PostToolUseFailure` handles a failed execution. A permission rejection before execution is different from either observed execution outcome. Do not describe a post-action transformation as prevention of the action. Record whether a request was denied, a tool ran and failed, or a tool returned a successful result that failed later validation.

The supplied material describes several hook configuration surfaces. Event names, matcher syntax, decision fields and result-replacement support must match the installed interface. A conceptual hook object is not universally interchangeable among a CLI settings file, an SDK callback and a plugin configuration.

## Enforce the rule in a trusted path

A natural-language request to respect a spending limit helps the model choose appropriate actions. A trusted pre-action check determines whether a proposed operation is allowed to execute. It must use the relevant account, amount, currency, approval and policy state rather than trusting a generated statement that the operation is safe.

Code execution at a known event is different from correctness of the decision. A simple numeric comparison can be deterministic; a hook that asks another model to judge a complex situation remains dependent on that model's judgment. Neither kind of hook guarantees protection beyond its actual tool coverage and failure handling.

Treat timeouts, malformed hook responses and missing deciding data explicitly. Where the rule requires blocking until verified, a failed check must not silently become permission. Check the effective permissions and callback order if the expected approval path does not run. Verify both permitted and denied cases against the actual target tool.

## Normalize meaning, not just appearance

Different tools may return Unix timestamps, ISO 8601 text or source-specific numeric status codes. A normalization layer should produce a documented common representation while preserving the original value, source identity and any parsing failure.

For Unix time, establish whether the value is in seconds or milliseconds. For a textual timestamp, establish its timezone or offset. Do not guess units from magnitude or assign UTC to an ambiguous local time just to make parsing succeed. A source's status code `1` does not mean the same thing as an HTTP status or another tool's code `1`; use that tool's documented mapping.

Preserve unknown and error states. Replacing a timeout with an empty list, or mapping every unfamiliar status to success, destroys information needed for recovery. Normalization should not turn partial results into complete evidence or remove an important error message because the success schema lacks an error field.

## Worked example: two representations of one instant

This invented integration contract says Tool A returns Unix seconds and Tool B is expected to return ISO 8601 with an explicit offset. The first two values identify the same instant. The third illustrates a Tool B response that violates the offset requirement and cannot identify an instant:

| Source value | Declared format | Normalized UTC value |
| --- | --- | --- |
| `0` | Unix seconds | `1970-01-01T00:00:00+00:00` |
| `1970-01-01T01:00:00+01:00` | Offset-aware ISO 8601 | `1970-01-01T00:00:00+00:00` |
| `1970-01-01T01:00:00` | ISO text without a timezone | Unresolved; request the timezone rather than assuming one. |

The following local Python function illustrates these two declared formats. It is normalization logic, not a complete Agent SDK hook configuration:

```python
from datetime import datetime, timezone
from math import isfinite


def normalize_timestamp(value, input_format):
    if input_format == "unix_seconds":
        if type(value) not in (int, float) or not isfinite(value):
            raise ValueError("Expected finite Unix seconds")
        instant = datetime.fromtimestamp(value, tz=timezone.utc)
    elif input_format == "iso8601":
        if not isinstance(value, str):
            raise ValueError("Expected ISO text")
        instant = datetime.fromisoformat(value.replace("Z", "+00:00"))
        if instant.tzinfo is None or instant.utcoffset() is None:
            raise ValueError("Timezone is required")
    else:
        raise ValueError("Unsupported timestamp format")
    return instant.astimezone(timezone.utc).isoformat()
```

The caller must handle invalid or out-of-range inputs as explicit failures and retain the source value for diagnosis. Milliseconds require their own declared conversion; the function does not guess them. A useful normalized record includes `source_tool`, `raw_value`, `input_format`, `normalized_utc` and `normalization_status`. Under this teaching contract, the caller converts the timezone-required exception into an unresolved record while preserving the raw value. The corresponding expected records are:

```json
[
  {
    "source_tool": "Tool A",
    "raw_value": 0,
    "input_format": "unix_seconds",
    "normalized_utc": "1970-01-01T00:00:00+00:00",
    "normalization_status": "normalized"
  },
  {
    "source_tool": "Tool B",
    "raw_value": "1970-01-01T01:00:00+01:00",
    "input_format": "iso8601",
    "normalized_utc": "1970-01-01T00:00:00+00:00",
    "normalization_status": "normalized"
  },
  {
    "source_tool": "Tool B",
    "raw_value": "1970-01-01T01:00:00",
    "input_format": "iso8601",
    "normalized_utc": null,
    "normalization_status": "timezone_required"
  }
]
```

For a separate teaching status contract, suppose Tool A defines `1` as `ready` and `2` as `pending`. Map only those documented values. An unknown `9` should remain `unknown_source_status`, with the raw code preserved. This mapping belongs to that example tool, not to MCP generally.

### Connect the callback to the model-facing result

The next example is an **application-owned, framework-neutral teaching adapter**. Its `register`, `before_dispatch`, `after_success`, envelope keys and `model_inbox` are invented local interfaces, not Agent SDK event fields, registration syntax or a vendor result-replacement schema. It makes the control flow executable without assuming an SDK version. A real integration must translate its installed hook input into this application contract and deliver the returned result through a supported model-facing path; merely printing an arbitrary object does not establish replacement support.

For this example only, `mcp__clock_a__read` returns a dictionary containing `timestamp` in Unix **seconds** and an integer `status_code` (`1` means `ready`; `2` means `pending`). `mcp__clock_b__read` returns the same fields, but its timestamp must be offset-aware ISO 8601 and its integer status codes are `10` for `ready` and `20` for `pending`. These tool names, fields and mappings are invented contracts, not properties of MCP. The dispatcher obtains the tool identity from its own exact-name table. Payload text cannot select a different mapping.

Run this block after the earlier `normalize_timestamp` definition. The adapter publishes one explicit result for each invocation. Execution failure bypasses the success callback; parsing failure after a successful execution remains a normalization problem, with the original response preserved. This fixture records model-facing messages in a list instead of calling a model.

```python
from copy import deepcopy


class TeachingAdapter:
    def __init__(self, tools):
        self.tools = tools
        self.callbacks = {}
        self.model_inbox = []

    def register(self, phase, exact_tool_name, callback):
        self.callbacks[(phase, exact_tool_name)] = callback

    def publish(self, result):
        self.model_inbox.append(deepcopy(result))
        return result

    def invoke(self, name, arguments, trusted):
        if name not in self.tools:
            return self.publish({"tool": name, "execution_status": "denied",
                                 "reason": "unsupported_tool"})
        before = self.callbacks.get(("before_dispatch", name))
        if before is not None:
            try:
                decision = before({"tool": name, "arguments": arguments}, trusted)
                allowed = decision.get("allowed") is True
            except Exception as exc:
                return self.publish({"tool": name, "execution_status": "denied",
                                     "reason": "check_failed", "error": str(exc)})
            if not allowed:
                return self.publish({"tool": name, "execution_status": "denied",
                                     "reason": decision.get("reason", "invalid_guard_response"),
                                     "handoff": {"state": "prepared",
                                                 "receipt": None}})
        try:
            raw = self.tools[name](arguments)
        except Exception as exc:
            return self.publish({"tool": name, "execution_status": "failed",
                                 "error_type": type(exc).__name__, "error": str(exc)})
        after = self.callbacks.get(("after_success", name))
        try:
            data = after({"tool": name, "result": raw}, trusted) if after else raw
        except Exception as exc:
            return self.publish({"tool": name, "execution_status": "succeeded",
                                 "normalization_status": "callback_failed",
                                 "raw_result": deepcopy(raw), "error": str(exc)})
        return self.publish({"tool": name, "execution_status": "succeeded", "data": data})


CONTRACTS = {
    "mcp__clock_a__read": ("unix_seconds", {1: "ready", 2: "pending"}),
    "mcp__clock_b__read": ("iso8601", {10: "ready", 20: "pending"}),
}


def normalize_result(event, trusted):
    name, raw = event["tool"], event["result"]
    input_format, status_map = CONTRACTS[name]
    record = {"source_tool": name, "raw_result": deepcopy(raw),
              "input_format": input_format, "normalized_utc": None,
              "normalization_status": "invalid_timestamp", "normalization_error": None,
              "status": None, "status_normalization_status": "unknown_source_status"}
    if not isinstance(raw, dict):
        record.update(normalization_status="invalid_result",
                      normalization_error="Expected a dictionary result")
        return record
    try:
        record["normalized_utc"] = normalize_timestamp(raw.get("timestamp"), input_format)
        record["normalization_status"] = "normalized"
    except (ValueError, TypeError, OverflowError, OSError) as exc:
        record["normalization_error"] = str(exc)
        if str(exc) == "Timezone is required":
            record["normalization_status"] = "timezone_required"
    code = raw.get("status_code")
    if type(code) is int and code in status_map:
        record.update(status=status_map[code], status_normalization_status="mapped")
    return record


adapter = TeachingAdapter({
    "mcp__clock_a__read": lambda args: {"timestamp": 0, "status_code": 1},
    "mcp__clock_b__read": lambda args: {
        "timestamp": "1970-01-01T01:00:00+01:00", "status_code": 10},
})
for tool_name in CONTRACTS:
    adapter.register("after_success", tool_name, normalize_result)
normalized_message = adapter.invoke("mcp__clock_a__read", {}, {})
assert adapter.model_inbox[-1] == normalized_message
normalized_message_b = adapter.invoke("mcp__clock_b__read", {}, {})
assert normalized_message_b["data"]["normalized_utc"] == normalized_message["data"]["normalized_utc"]
```

For the Tool A call, the complete model-facing message is:

```json
{
  "tool": "mcp__clock_a__read",
  "execution_status": "succeeded",
  "data": {
    "source_tool": "mcp__clock_a__read",
    "raw_result": {"timestamp": 0, "status_code": 1},
    "input_format": "unix_seconds",
    "normalized_utc": "1970-01-01T00:00:00+00:00",
    "normalization_status": "normalized",
    "normalization_error": null,
    "status": "ready",
    "status_normalization_status": "mapped"
  }
}
```

The flow is exact-name registration → successful tool execution → `normalize_result` callback → normalized message → `model_inbox`. A Tool B result of `{"timestamp": "1970-01-01T01:00:00", "status_code": 9}` instead yields the following complete message under the same registration:

```json
{
  "tool": "mcp__clock_b__read",
  "execution_status": "succeeded",
  "data": {
    "source_tool": "mcp__clock_b__read",
    "raw_result": {"timestamp": "1970-01-01T01:00:00", "status_code": 9},
    "input_format": "iso8601",
    "normalized_utc": null,
    "normalization_status": "timezone_required",
    "normalization_error": "Timezone is required",
    "status": null,
    "status_normalization_status": "unknown_source_status"
  }
}
```

The successful execution flag does not mean the timestamp or status is usable. Keep the unresolved record visible and request the missing timezone or documented status mapping before reasoning from it. A timeout raised by a dispatcher instead produces an `execution_status` of `failed`, with the exception type and message; it does not masquerade as an empty successful response. A real adapter must also preserve any structured error metadata its dispatcher supplies. No live SDK, MCP service or model call is exercised by this teaching harness.

## Block the action and route the alternative separately

In a second invented policy, automatic refunds may be no greater than USD 500\. A valid refund amount must be a positive integer number of cents, and other identity and authorization requirements still apply. A pre-action check can use this boundary:

| Input amount | Limit check only | Next step |
| --- | --- | --- |
| 49,999 cents | Within limit | Continue the remaining authorization checks. |
| 50,000 cents | Within limit, including the boundary | Continue the remaining checks. |
| 50,001 cents | Above limit | Block automatic execution and request human review. |
| Missing, zero, negative or malformed | No valid amount established | Block and clarify; do not default to zero. |

A denial message can explain why the call was blocked and propose escalation. It does not itself create an escalation ticket or obtain approval. The workflow must execute the authorized alternative and inspect its result before reporting that handoff completed.

### Implement the pre-action gate and the separate handoff

Continue the same local adapter with an invented `process_refund` tool. Its arguments are `account_id`, `currency` and `amount_cents`. The only supported currency in this example is `USD`. The trusted context comes from the application's authenticated session and authorization checks for the target account, never from model-supplied arguments. `identity_verified` and `refund_authorized` must both be exactly `True`, and the requested account must equal the server-verified `account_id`. These checks illustrate the gate; a production policy must include its own remaining eligibility and approval conditions.

The following guard is registered before dispatch. Denied requests never reach `refund_dispatcher`. A prepared handoff means only that a local review proposal is available. The separate `submit_handoff` function requires its own trusted permission and calls a separately supplied submission function; only an acknowledged receipt establishes submission. Submission requests review and does not approve or execute the refund.

```python
def refund_guard(event, trusted):
    args = event["arguments"]
    if not isinstance(args, dict):
        return {"allowed": False, "reason": "invalid_arguments"}
    if (trusted.get("identity_verified") is not True
            or trusted.get("refund_authorized") is not True
            or not isinstance(trusted.get("account_id"), str)
            or not trusted["account_id"]
            or args.get("account_id") != trusted["account_id"]):
        return {"allowed": False, "reason": "identity_or_permission_not_verified"}
    if args.get("currency") != "USD":
        return {"allowed": False, "reason": "unsupported_currency"}
    cents = args.get("amount_cents")
    if type(cents) is not int or cents <= 0:
        return {"allowed": False, "reason": "invalid_amount_cents"}
    if cents > 50_000:
        return {"allowed": False, "reason": "above_automatic_limit"}
    return {"allowed": True}


def submit_handoff(blocked, trusted, submit):
    # This demo submits a minimal review reason, not sensitive account data.
    result = {"state": "prepared", "receipt": None, "error": None}
    if (blocked.get("tool") != "process_refund"
            or blocked.get("execution_status") != "denied"):
        return dict(result, state="failed", error="Expected a denied refund")
    if (trusted.get("identity_verified") is not True
            or trusted.get("handoff_authorized") is not True):
        return dict(result, error="Handoff submission is not authorized")
    try:
        receipt = submit({"tool": "process_refund", "reason": blocked["reason"]})
        if (not isinstance(receipt, dict) or receipt.get("accepted") is not True
                or not isinstance(receipt.get("receipt_id"), str)
                or not receipt["receipt_id"].strip()):
            raise ValueError("No acknowledged handoff receipt")
    except Exception as exc:
        return dict(result, state="failed", error=str(exc))
    return dict(result, state="submitted", receipt=deepcopy(receipt))


refund_calls = []


def refund_dispatcher(arguments):
    refund_calls.append(deepcopy(arguments))
    return {"refund_id": "demo-refund-1", "status": "processed"}


adapter.tools["process_refund"] = refund_dispatcher
adapter.register("before_dispatch", "process_refund", refund_guard)
trusted_session = {"identity_verified": True, "account_id": "acct-demo",
                   "refund_authorized": True, "handoff_authorized": True}
blocked = adapter.invoke("process_refund", {
    "account_id": "acct-demo", "currency": "USD", "amount_cents": 50_001,
}, trusted_session)
assert refund_calls == []
submitted = submit_handoff(blocked, trusted_session, lambda payload: {
    "accepted": True, "receipt_id": "demo-review-1"})
adapter.publish({"tool": "human_review_handoff", "data": submitted})
```

The attempted USD 500.01 refund above produces these two complete model-facing messages, in order. The second appears only because the final lines explicitly call the authorized handoff function and publish its result:

```json
[
  {
    "tool": "process_refund",
    "execution_status": "denied",
    "reason": "above_automatic_limit",
    "handoff": {"state": "prepared", "receipt": null}
  },
  {
    "tool": "human_review_handoff",
    "data": {
      "state": "submitted",
      "receipt": {"accepted": true, "receipt_id": "demo-review-1"},
      "error": null
    }
  }
]
```

Here both dispatchers are local stubs. `demo-review-1` acknowledges the simulated review request; it proves neither an external ticket exists nor a refund is approved. If `handoff_authorized` is false, the complete handoff result is `{"state": "prepared", "receipt": null, "error": "Handoff submission is not authorized"}` and the submission callback is never invoked. If an authorized callback raises `TimeoutError("review service timed out")`, the result is `{"state": "failed", "receipt": null, "error": "review service timed out"}`. A timeout can leave the external outcome uncertain in a real integration; confirm the request state before retrying rather than assuming no ticket was created.

With the same verified session, USD 499.99 and USD 500.00 reach the refund stub; USD 500.01, missing amounts, `0`, negative values, floats, strings and Boolean values do not. Python treats `bool` as an integer subclass, so `type(cents) is int` deliberately rejects `True` as one cent. Unsupported currencies and unverified identity or account permissions also block execution even below the amount limit. Clarify malformed or incomplete requests before resubmission. A review request can safely report the denial, but it cannot supply missing authorization or change invalid arguments into an executable refund.

If several matching hooks run, do not rely on one denial to cancel side effects in another hook. Keep audit and enforcement operations safe under the harness's actual scheduling rules. A permissive logging result is not permission to ignore a denial.

## Diagnose coverage and context effects

Test the exact tool names, event timing and decision encoding. A broad matcher is not proof that every built-in or remote tool emits the event in the same way. The source notes version-specific coverage limitations; verify the relevant behavior instead of assuming universal interception.

Keep substantial parsing and validation outside the model context where possible, but recognize that additional context, replacement results or model-based hooks can still consume tokens or model calls. Avoid presenting hooks as universally free of context or inference cost.

## Source-specific hook contracts and diagnostic gaps

The exact vendor fields, types, limits and warning names here are attributed to the supplied source snapshot. Its cited original attachments were not supplied, and this article reports no live Agent SDK, CLI, MCP, model or external refund/ticket operation. The preceding adapter is deliberately application-owned; its registration, allowed field, arguments envelope and model\_inbox are not vendor schemas.

The source describes command, http, mcp\_tool and prompt hook routes, plus state-aware agent hooks where supported. A command receives JSON on stdin; an HTTP hook posts event data to its configured endpoint, not automatically to a normalization service with a guaranteed result. Check the actual accepted configuration and available types in the installed interface. For a non-firing handler, check event case (PostToolUse is not postToolUse), actual tool identity/matcher, resolved executable path, interpreter and platform permission. The source POSIX chmod/shebang advice applies where that platform/script requires it; it is not a Windows execution guarantee. A partial event/matcher/type/command object is not a universally runnable SDK/CLI/plugin configuration.

The snapshot's plugin command example quotes ${CLAUDE\_PLUGIN\_ROOT} for a script path. It says shell-executed fields reject ${user\_config.\*} substitutions and recommends CLAUDE\_PLUGIN\_OPTION\_ for nonsensitive option values. These are source-interface restrictions, not universal shell quoting or credential protection. Treat secrets, executable command text and authorized path resolution separately; do not move a credential into an option variable merely because the example mentions environment transport. 

Keep output contracts event-specific. The source gives top-level decision:block for PostToolUse/Stop, hookSpecificOutput.decision.behavior for PermissionRequest, and hookSpecificOutput.additionalContext for UserPromptSubmit. It says top-level additionalContext in that prompt-submit case can be ignored. Do not copy one shape into another event or assume the local adapter's allowed Boolean is accepted by a real hook. A post-result block can affect only its supported continuation/feedback path; it cannot reverse the completed side effect. Host computation differs from tokens in injected context and separate single/multiturn model-evaluation calls.

The source recommends input-only prompt evaluation when supplied data is sufficient and a state-aware agent verifier when actual files/commands/environment need inspection. A validated numeric comparison can simply be trusted code, without a model hook. Its agent-hook snapshot uses ok/reason, a 60-second default and up to 50 tool-use turns; it lacks the prompt-hook impossible and agent continueOnBlock fields. It describes $ARGUMENTS as substitution of actual hook JSON, and ok:false as continuing a conversation on some PreToolUse/PostToolUse paths. Continued reasoning does not permit the denied action. Timeout/limit/false result remains failed/unresolved, and experimental or changing feature support needs actual interface evidence.

The source type:agent plus command:npm test and Stop/command:verify\_tests examples mix conceptual schemas. They do not demonstrate accepted registration or an executed test pass. Establish the real hook type/input/output and record actual test command, code state, exit and relevant assertions; no test or 50-turn allowance proves every business requirement passed.

## Merge policy is separate from individual hook effects

The source says every matching hook can run before results merge. Its stated PreToolUse decision order is deny → defer → ask → allow, with additionalContext accumulated. Apply that only to the actually supported event/type contract. In its illustration, logging exits 0 with no decision while a guard exits 2 with denial and stderr. Logging may already have happened when the main tool is blocked. Exit 0/no-decision is not an explicit allow, and a denial never cancels sibling side effects retroactively. Protect each side effect through its own actual authority and safe replay behavior.

A tool-name matcher such as Write|Edit or mcp\_\_\_\_ selects a supported name pattern; the source separately describes an if filter using permission-rule syntax for tool/argument combinations. Verify actual positive/negative name-and-argument cases after filtering so reduced process spawning does not remove the required gate. A textual wildcard is no proof all event paths fire. 

The source database Bash-hook examples omit the validation script and vary their configuration shape. SELECT-like prefix inspection is not complete SQL read-only enforcement, and detecting an rm -rf substring is not a complete shell-safety policy. Confirm actual evaluated command, database credentials/permissions, alternate execution tools and accepted gate encoding before claiming coverage. For these access checks, retain only the necessary non-secret workspace, account and credential identities, or an approved secret-store reference when a credential is relevant. Never copy actual API keys, tokens or passwords into prompts, logs or handoffs. Sharing configuration does not by itself authorize sharing or using credentials, and knowing a path or secret reference does not grant permission to access it; use the authorized context or report the blocked check. The source logging/deny illustration only shows its narrow matched pending operation, not every destructive command variant.

The source reports some SDK versions where built-in local Read bypasses PreToolUse while SDK-MCP calls differ, and where canUseTool is not consulted for in-cwd reads by default. Its pages:"" example is an invalid empty string, distinct from omitting an optional pages field. Those are scoped issue reports, not proof every installed version has the same blind spot. Test the deployed paths before relying on input rewriting or security hooks. The named TypeScript warning CLAUDE\_SDK\_CAN\_USE\_TOOL\_SHADOWED indicates earlier approval handling can shadow a callback in the described interface. Inspect actual permission resolution/callback evidence; a denied tool does not guarantee canUseTool subsequently runs.

## What the source does and does not implement

MCP means Model Context Protocol. The supplied glossary supports terminology and candidate metadata; the adopted Dxx domain knowledge files remain the factual authority. Neither the glossary's broad JSON-structure wording nor a candidate label establishes semantic normalization, supported hook-result replacement or runtime verification.

The source explicitly says it lacks concrete Unix/ISO/status normalization logic. Its jq -r '.tool\_input.command' reads an input command string, not a returned timestamp or status; extracting it does not convert a result. The preceding converter and complete local delivery fixture are new teaching examples, not an original verified vendor implementation. A real hook must identify actual result fields, validate their meaning and deliver through a supported result-update/context path. Arbitrary stdout JSON plus exit 0 does not universally replace every built-in/MCP response. Source claims about MCP schema bypass or built-in fallback are host/interface-specific, not protocol-wide guarantees; inspect what the model actually received and preserve raw/error fallback if replacement failed.

The source also names Python beta\_tool/beta\_async\_tool wrappers and client.beta.messages.tool\_runner(), plus a ToolError option. These belong to their actually supported Python tool/runner library; they are not interchangeable Agent SDK lifecycle hook names. A wrapper can normalize before its own return, while a post-hook needs actual supported replacement/delivery after a tool result. Sync/async and error-content behavior require the actual library contract, not a decorator name alone.

## Complete additional expected cases for the teaching fixture

For the declared Tool A contract, the missing-timestamp input {"status\_code":1} has this complete expected local model-facing record. It is a successful dispatcher call with invalid timestamp, not failed execution or usable normalized time:

```json
{
  "tool":"mcp__clock_a__read",
  "execution_status":"succeeded",
  "data":{
    "source_tool":"mcp__clock_a__read",
    "raw_result":{"status_code":1},
    "input_format":"unix_seconds",
    "normalized_utc":null,
    "normalization_status":"invalid_timestamp",
    "normalization_error":"Expected finite Unix seconds",
    "status":"ready",
    "status_normalization_status":"mapped"
  }
}
```

The status field ready means only the declared Tool A status code mapped; it does not override unusable time. For an actual result \["unexpected"\] instead of a dictionary, the full data record is {"source\_tool":"mcp\_\_clock\_a\_\_read","raw\_result":\["unexpected"\],"input\_format":"unix\_seconds","normalized\_utc":null,"normalization\_status":"invalid\_result","normalization\_error":"Expected a dictionary result","status":null,"status\_normalization\_status":"unknown\_source\_status"}, inside the same tool/succeeded envelope. A string timestamp "0" is invalid under the seconds-number contract; a missing/Boolean/unknown status remains null/unknown\_source\_status even if the time is valid. Tool B without offset remains timezone\_required as shown earlier. A permitted empty collection would need its own declared result contract; an empty/malformed response is not silently converted into normalized success.

Finite out-of-range epoch values remain invalid\_timestamp with the actual platform conversion error retained; do not promise identical OS error wording. Nonfinite Python values such as float('nan') or infinity fail the finite/type checks. They are not legal JSON numeric inputs: if diagnostics cross a JSON transport, encode that exceptional raw value as an explicit tagged string under a declared adapter policy rather than emitting NaN/Infinity or treating it as zero. The local fixture's Python object inbox is not proof of strict JSON transport support.

For refund input, integer cents are the sole unit. With the same trusted session, {"account\_id":"acct-demo","currency":"USD","amount\_cents":50000} reaches only the remaining permitted refund workflow. The corresponding values 49,999 / 50,000 / 50,001 have the earlier exact boundary outcomes. Supplying amount:500 without amount\_cents is missing required cents and returns invalid\_amount\_cents; amount\_cents:500.0, strings, Booleans, NaN, infinity, zero or negative values also return invalid\_amount\_cents before dispatch. A currency other than USD returns unsupported\_currency. These are decisions about the example's input contract, not proof every external money representation has been supported. A denial gives a prepared review proposal only; the separately permitted acknowledgement path, human decision and actual refund remain distinct.

## Complete successful Tool B message

To complement the full successful Tool A and unresolved Tool B messages, the earlier declared Tool B input {"timestamp":"1970-01-01T01:00:00+01:00","status\_code":10} has this complete EXPECTED local-adapter message. It preserves the different source representation while identifying the same instant as Tool A seconds 0:

```json
{
  "tool":"mcp__clock_b__read",
  "execution_status":"succeeded",
  "data":{
    "source_tool":"mcp__clock_b__read",
    "raw_result":{"timestamp":"1970-01-01T01:00:00+01:00","status_code":10},
    "input_format":"iso8601",
    "normalized_utc":"1970-01-01T00:00:00+00:00",
    "normalization_status":"normalized",
    "normalization_error":null,
    "status":"ready",
    "status_normalization_status":"mapped"
  }
}
```

Both successful tools now have complete consumer records as well as the full timezone-required/unknown-status and missing/invalid cases. The three-message family shares exactly the local envelope/data fields; each per-tool status map remains distinct. This record describes the declared in-memory fixture, not an observed SDK/MCP/model response or proof the current hook interface supports replacement.

## Explicit event roles and the conceptual refund-script defect

In the source event list, UserPromptSubmit supplies prompt-time context; it is not proof that a tool ran. Stop validates the result when the agent finishes and may save session state under its supported contract. Neither prompt submission nor stop-time validation retroactively prevents a completed tool effect. Check the actual result/state rather than treating a Stop notification as a passed verification.

The source refund script reads input\_data.arguments and arguments.amount with a default of zero, then prints a type:deny/message object above 500 or type:allow otherwise. Those are conceptual example fields: they do not establish the real hook input nesting, accepted decision output or amount unit in an installed host. In particular, defaulting a missing amount to zero can bypass that comparison. Verify the actual request envelope and supported enforcement output; reject missing/malformed/nonfinite/wrong-unit amounts explicitly. The earlier teaching guard instead requires amount\_cents, positive integer cents and an acknowledged local before\_dispatch result. Its allowed Boolean is its own invented contract. The source denial message saying Escalating to human review proves no submission, canUseTool invocation, review receipt or approval. Only the separately authorized, actually acknowledged handoff establishes its own submission state.

The supplied glossary uses CLAUDE for persistent instructions in CLAUDE.md and SKILL for SKILL.md content with YAML frontmatter and Markdown, under the described .claude/skills convention. These are written guidance or reusable instruction content. A checklist, file name or prompt instruction does not implement a deterministic predicate at a tool-action boundary, and loading it does not prove that a relevant pre-dispatch gate ran or enforced its policy.

## Summary

Use pre-action checks to govern execution and post-action processing to normalize observed results. Preserve source semantics, timestamps, status mappings and failures. A reliable hook design depends on the actual event contract and coverage; denial, alternate routing and confirmed completion remain separate steps.
