skip to content

In the Claude Agent SDK, how does a PreToolUse hook callback block or rewrite a tool call, and what silently stops it working?

level: seniorimportance: should knowfreq 6%

answer

  1. a function, not a shell script
  2. matcher tests the tool name
  3. decision lives in hookSpecificOutput
  4. deny beats defer beats ask beats allow
  5. empty object means no objection

basics

~20 s

Register the callback under options.hooks.PreToolUse with a matcher on the tool name. Return hookSpecificOutput with permissionDecision deny and a reason to block, or updatedInput to rewrite; return an empty object to let the call proceed.

solid answer

~40 s

SDK hooks are functions passed in `options.hooks`, keyed by event name, each entry a matcher plus a list of callbacks (Python `HookMatcher(matcher="Bash", hooks=[...])`). A `PreToolUse` callback receives the input (`tool_name`, `tool_input`, `session_id`, `cwd`), the tool-use ID and a context. To act, it returns `hookSpecificOutput` with `hookEventName: "PreToolUse"` and `permissionDecision` (`allow`, `deny`, `ask` or `defer`), a `permissionDecisionReason` that Claude reads, and optionally `updatedInput`; `{}` lets the call continue. Across hooks and rules, deny beats defer beats ask beats allow. Things that silently break it: `updatedInput` placed at the top level instead of inside `hookSpecificOutput`, pairing it with `defer`, a matcher written against a file path (matchers test tool names), a wrongly cased event name, an async output (which cannot block), and in Python, events such as `SessionStart` that its callbacks do not support.

code

python · 23 lines
python
from claude_agent_sdk import ClaudeAgentOptions, HookMatcher


async def guard_git(input_data, tool_use_id, context):
    command = input_data["tool_input"].get("command", "")
    if command.startswith("git push"):
        return {"hookSpecificOutput": {
            "hookEventName": "PreToolUse",
            "permissionDecision": "deny",
            "permissionDecisionReason": "The PR summariser reads history; it never pushes.",
        }}
    if command.startswith("git log"):
        rewritten = command.replace("git log", "git --no-pager log", 1)
        return {"hookSpecificOutput": {
            "hookEventName": "PreToolUse",
            "updatedInput": {**input_data["tool_input"], "command": rewritten},
        }}
    return {}


options = ClaudeAgentOptions(
    hooks={"PreToolUse": [HookMatcher(matcher="Bash", hooks=[guard_git], timeout=30)]},
)

go deeper

for a junior

Recall that SDK hooks are callbacks in options.hooks, that PreToolUse runs before a tool, and that returning an empty object lets the call proceed.

for a middle

Explain the hookSpecificOutput fields, how matchers test tool names, the deny over defer over ask over allow precedence, and why updatedInput must sit inside hookSpecificOutput.

for a senior

Debug a hook that never blocks: misplaced updatedInput, a path-shaped matcher, an async output, a Python-unsupported event or a timeout, and know that a PreToolUse timeout skips the tool.

for a principal

Decide which guarantees live in callbacks shipped with the service and which in settings-file hooks shared with interactive users, and how both stay consistent when either changes.

## Hooks as callbacks In Claude Code, a **hook** is code that runs at a fixed point in the agent lifecycle: before a tool runs, after it returns, when the agent stops, and so on. In the CLI, hooks are commands declared in settings files. In the Agent SDK they can also be **callback functions** in your own process, passed in the `hooks` option of `query()`. Both kinds run side by side: settings-file hooks load through the setting sources (on by default), and your callbacks are added on top. SDK callbacks also fire inside subagents; the input then carries `agent_id` and `agent_type`. ## Registering a PreToolUse callback The `hooks` option maps an event name to a list of matchers: - **Key:** the event name, case-sensitive: `PreToolUse`, not `preToolUse`. - **`matcher`:** a pattern tested against the event's target. For tool events that is the **tool name**, for example `"Bash"` or `"Write|Edit"`, and for MCP tools `mcp__<server>__<tool>` where the server is your `mcpServers` key. Omit it to run for every tool call. - **`hooks`:** the callbacks to run when the matcher matches. - **`timeout`:** seconds; if unset, the event default applies (600 seconds for most events). Each callback receives three arguments: the **input** (`tool_name`, `tool_input`, `session_id`, `cwd`, `hook_event_name`), the **tool-use ID** that pairs a `PreToolUse` with its `PostToolUse`, and a **context** that in TypeScript carries an `AbortSignal` and in Python is reserved. ## Deciding: the output shape | Goal | Return | |---|---| | No objection, no change | `{}` | | Block the call | `hookSpecificOutput` with `permissionDecision: "deny"` and a `permissionDecisionReason` | | Rewrite and continue through the normal checks | `hookSpecificOutput` with `updatedInput` and no decision | | Rewrite and approve | `updatedInput` plus `permissionDecision: "allow"` | | Show the call to the approver | `permissionDecision: "ask"` | | Pause the call so the process can exit | `permissionDecision: "defer"`; the turn ends with `stop_reason` `"tool_deferred"` | The reason on a deny is sent to Claude as the tool result, so write it for the model: what was refused and what to do instead. When several hooks or rules apply, **deny beats defer, which beats ask, which beats allow**; one deny blocks the call whatever the others say. A hook's allow does not skip deny or ask rules evaluated after it. ## What silently breaks a hook 1. **`updatedInput` at the top level.** It must sit inside `hookSpecificOutput`, next to `hookEventName`; at the top level it is not applied. 2. **`updatedInput` with `defer`.** The modified input is dropped. 3. **A matcher aimed at arguments.** Matchers only test tool names. To guard `.env` files, match `Write|Edit` and inspect `tool_input.file_path` in the callback. 4. **An async output.** Returning `{ async: true }` (Python `async_`) lets the agent move on immediately, so the hook can log but cannot block, modify or add context. 5. **An unsupported event in Python.** Python callbacks cover `PreToolUse`, `PostToolUse`, `PostToolUseFailure`, `UserPromptSubmit`, `Stop`, `SubagentStart`, `SubagentStop`, `PreCompact`, `Notification` and `PermissionRequest`; `SessionStart` and `SessionEnd` are TypeScript-only callbacks, available to Python only as settings-file hooks. 6. **The turn limit.** Hooks may not fire when the run hits `max_turns`, because the session ends first. ## When a callback is slow If a callback exceeds its timeout, Claude Code cancels it, discards its output and keeps the session going. For `PreToolUse` the tool does **not** run: Claude receives a result saying the hook did not respond, unless another hook explicitly denied, in which case Claude sees that denial. A timeout therefore fails closed for that call. Raise `timeout` on the matcher for slow policy lookups, and in TypeScript honour the `AbortSignal` so cancelled work stops. ## Callbacks versus settings-file hooks | | SDK callback | Settings-file hook | |---|---|---| | Defined in | `options.hooks` in your code | `settings.json`, loaded through setting sources | | Handler | A function in your process | `command`, `http`, `mcp_tool`, `prompt` or `agent` handler | | Shared with interactive Claude Code | No | Yes | | Best for | Application logic, structured decisions, in-process state | Team-wide rules that should apply in the CLI and the SDK alike | Both fire in the main agent and in the subagents it spawns, and both use the same JSON output format. ## Choosing hooks over the permission callback A `PreToolUse` callback runs **before** every other permission step, so it sees calls that `allowedTools`, a mode or a settings rule would approve before `canUseTool` is ever consulted. That makes it the place for audit logging, redirecting paths and rules that must hold even in `bypassPermissions`.

  • What does Claude see when a PreToolUse callback denies a call?
    The `permissionDecisionReason` is sent to Claude as the tool result, so the model learns why the call failed and can choose another approach. `systemMessage`, by contrast, is shown to the user rather than the model; to give Claude extra context without blocking, return `additionalContext`.
  • A Python service needs initialisation logic at session start. SessionStart callbacks are unavailable; what are the options?
    Define `SessionStart` as a settings-file hook in `.claude/settings.json` and load it with `setting_sources=["project"]`, or treat the first message from `client.receive_response()` as the trigger for your own initialisation code.

  • A matcher like .env makes the hook fire only for edits to .env files.
  • updatedInput works anywhere in the returned object.
  • When hooks disagree, the first registered hook's decision wins.
  • An async hook output can still block the tool call.
  • Python SDK callbacks support every hook event TypeScript does.