PreToolUse Hook

Agent SDK

Definition

An Agent SDK lifecycle hook that intercepts tool calls before execution. Can inspect, modify, or block the call. Used for access control, parameter sanitization, rate limiting, and audit logging. Runs synchronously before the tool executes.

Example Usage

Use PreToolUse to block any file write operations outside the designated working directory, regardless of what the agent requests.

Why It Matters for the CCA-F Exam

The CCA-F exam tests whether candidates understand when to use PreToolUse versus other safety mechanisms. The key distinction: PreToolUse is the correct answer whenever a question involves intercepting a call **before** execution for access control or parameter-level gating. If the question asks about validation or transformation of tool *results*, PostToolUse is the answer.

In Depth

The PreToolUse hook is the Agent SDK's first line of defense in a tool invocation sequence. It fires before a tool begins executing, giving the orchestrator an opportunity to inspect the pending call, mutate its parameters, or cancel it entirely — without the tool ever running.

This positioning is critical. By the time PostToolUse runs, the action has already happened; any destructive side-effects are already in motion. PreToolUse is where you prevent that from happening in the first place. The hook receives the tool name and the full input object that the agent constructed, letting you make decisions based on exact parameters rather than post-hoc output.

Common patterns for PreToolUse:

  • Access control: Block calls to bash_execute whose command argument tries to reach outside a sandboxed directory
  • Parameter sanitization: Strip or rewrite dangerous arguments (e.g., remove --force flags before a git push)
  • Rate limiting: Track call counts per tool per minute; reject calls once a threshold is exceeded and return a structured error to the agent
  • Audit logging: Write an immutable record of every tool call — who triggered it, what parameters were passed, at what timestamp — before the tool can succeed or fail
  • Dynamic permission checks: Query an external policy service with the tool name and parameters; only allow if the service approves

Because PreToolUse runs synchronously in the agentic loop, blocking it does halt the loop. The hook should return quickly and fail fast rather than performing slow I/O inline. For expensive policy checks, cache results aggressively.

In Claude Code, the PreToolUse hook entry in .claude/settings.json maps to a shell command or script that receives tool context on stdin. The exit code signals allow (0) or block (non-zero). In the broader Agent SDK, the hook is a callback registered on the AgentDefinition that receives a typed event object and can return a modified input or raise a ToolBlockedError.

Compared to setting tool_choice: none or limiting allowed-tools, PreToolUse offers runtime, parameter-aware control — you can allow a tool in principle but block specific invocations. That runtime granularity is what makes it irreplaceable for security-critical agentic workflows. See also: Subagent Invocation & the Task Tool for how hooks compose with multi-agent pipelines.

How It Compares

HookFiresCan Block ExecutionHas Access ToTypical Use
PreToolUseBefore tool runsYes — prevent the callTool name + input paramsAccess control, sanitization, audit logging
PostToolUseAfter tool returnsNo (already ran)Tool result / outputNormalization, enrichment, validation of output
StopAgent reaches end_turnYes — force continuationFinal response textQuality gates, completeness checks
SubagentStopSubagent finishesYes — block result propagationSubagent's full resultSchema validation, result merging across subagents

Example

Claude Code settings.json wiring a PreToolUse hook on the Write tool. The script receives the tool input via stdin and exits non-zero to block the call.

json
# .claude/settings.json — block writes outside /workspace
{
  "hooks": {
    "PreToolUse": [
      {
        "matcher": "Write",
        "hooks": [
          {
            "type": "command",
            "command": "python3 /scripts/check_path.py"
          }
        ]
      }
    ]
  }
}

How It's Tested & Common Confusions

Exam questions on PreToolUse typically present a scenario (e.g., "an agent may call a file-write tool with arbitrary paths") and ask which hook prevents the destructive action. Expect:

  • Scenario matching: identify the lifecycle point (before execution) that maps to PreToolUse
  • Contrast questions: given that PostToolUse already ran, what hook should have been used instead?
  • Ordering questions: list the sequence — PreToolUse → tool executes → PostToolUse — and identify which stage a given intervention belongs to
  • True/False: "PreToolUse can modify the tool input before execution" (True) vs. "PreToolUse can inspect the tool result" (False — that's PostToolUse)

Frequently Asked Questions

Can PreToolUse modify the tool's input parameters, or can it only allow or block?

In the Agent SDK callback model, PreToolUse can return a modified input object — the tool then executes with those altered parameters instead of the original ones. In the Claude Code shell-hook model, the hook can only allow or block; input rewriting requires a callback-style integration.

What happens to the agent loop if a PreToolUse hook blocks a call?

The tool call is cancelled and the agent receives a structured error indicating the call was blocked. The agent can then attempt a different tool, reformulate its approach, or surface the blocked action to the user — it does not hard-crash unless the error propagates without a handler.