Study FAQ
How do I use a Claude Code hook to enforce a check before a tool runs?
Also asked as 2
- Which Claude Code hook should I choose to run and enforce a pre-tool policy check?
- How can I make a Claude Code PreToolUse check block the call when the check fails?
Answer
For a deterministic pre-execution check, use a Claude Code PreToolUse command hook matched to the intended tool. It receives event JSON on stdin and can allow the call to proceed through permissions or block it before execution. A command hook can signal a deliberate block with exit code 2. Use a later event for validation or auditing after execution.
Prefer a command for a fast, reproducible rule. Prompt and agent hooks use model judgment, and agent hooks are experimental. Current versions also support HTTP and MCP tool handlers for appropriate events. Check event support, timeout, data exposure and permissions before selecting a handler.
A missing script, crash or timeout can let an action proceed. For a blocking command hook with Claude Code v2.1.295 or later, set onFailure: "block" and verify deliberate rejection, a valid call, a missing checker and a timeout in a test repository. On other event types, check the reference for what can be blocked. Keep hook configuration trusted, restrict hook process credentials, bound timeouts and avoid recursive chains. Keep checks small and explicit about any effects. Log the hook and event, duration, decision and sanitized outcome. An advisory check can report a warning with a successful result.
Claude Code hooks reference · Claude Code hooks guide · Claude Code permission rules · Claude Code shell sandboxing
Full explanation
Claude Code Hooks, Plan Mode, Automation, and CI Workflows
Study guide · CCAR-F
Read the full explanation