Claude Code PreToolUse hook: allow, block or rewrite a tool call
A PreToolUse hook runs after Claude has built the arguments for a tool call and before the call runs. It can let the call through, stop it, ask you first, or change the arguments.
This page covers the input, the decision fields, a script you can copy, and the traps. Every statement about Claude Code comes from the official hooks reference, linked at the end.
When the hook runs
PreToolUse runs each time Claude calls a tool, before the call is processed. The matcher filters on the tool name. It covers built-in tools such as Bash, PowerShell, Edit, Write, Read, Glob, Grep, Agent, WebFetch and WebSearch, and MCP tools by their mcp__<server>__<tool> names. A matcher such as Edit|Write lists tool names; a pattern with other characters, such as mcp__.*, is read as a regular expression.
The hook does not run in three cases:
- Files you attach with
@in a prompt. Claude Code inserts their contents while it builds the prompt, so no tool call happens, not even for a hook that matchesRead. - Shell commands that a skill injects while it loads. A
PreSkillShellCommandhook covers those. EndConversationcalls.
Settings, managed settings and plugin hooks also run inside subagents. The input then carries agent_id and agent_type.
What arrives on stdin
Claude Code writes one JSON object to the hook's stdin. On top of the common fields (session_id, transcript_path, cwd, permission_mode, hook_event_name) a PreToolUse hook gets tool_name, tool_input and tool_use_id. This is the example from the reference for a Bash call:
{
"session_id": "abc123",
"cwd": "/home/user/my-project",
"permission_mode": "default",
"hook_event_name": "PreToolUse",
"tool_name": "Bash",
"tool_input": {
"command": "npm test",
"description": "Run test suite",
"timeout": 120000,
"run_in_background": false
},
"tool_use_id": "toolu_01ABC123..."
}What sits in tool_input depends on the tool:
- Bash, PowerShell
command, plus optionaldescription,timeout(in milliseconds) andrun_in_background.- Write
file_pathandcontent.- Edit
file_path,old_string,new_stringandreplace_all.- Read
file_path, plus optionaloffsetandlimit.
For an MCP tool, the input also carries mcp_server, an object with the server's name and a source that says where the server's definition came from. The reference advises basing trust decisions on source, not on the name or the mcp__<server>__ prefix. The field needs Claude Code v2.1.274 or later.
For Write, Edit and Read, file_path is always absolute. Claude Code expands ~ and relative paths before the hook runs, so a path check cannot be dodged with another spelling of the same path.
Allow, deny, ask or rewrite
Print one JSON object and exit 0. Unlike most events, PreToolUse returns its decision inside hookSpecificOutput:
{
"hookSpecificOutput": {
"hookEventName": "PreToolUse",
"permissionDecision": "deny",
"permissionDecisionReason": "rm -rf is blocked in this project."
}
}- permissionDecision
"allow"skips the permission prompt,"deny"prevents the call,"ask"sends it to the user,"defer"pauses it (see below).- permissionDecisionReason
- For
"deny", shown to Claude. For"ask", shown to the user in the permission prompt. For"allow"and"defer", written to the debug log only. - updatedInput
- Replaces the tool's whole input object before the call runs, so include the fields you do not change. Pair it with
"allow"to auto-approve, or with"ask"to show the changed input to the user. - additionalContext
- A string added to Claude's context next to the tool result.
- Several hooks can disagree. The order of precedence is
deny, thendefer, thenask, thenallow. - Exit code 2 blocks the call, the same as
deny. Claude sees your stderr message as the reason. "allow"does not skip approval for everything. The reference names actions that no permission mode auto-approves and reads from network paths as exceptions.- The old top-level
decisionandreasonfields are deprecated for this event."approve"and"block"map toallowanddeny. "defer"is for programs that runclaude -pas a subprocess and read its JSON. In an interactive session Claude Code logs a warning and ignores it.continue: falsedoes not block aPreToolUsecall. UsepermissionDecision: "deny".
Example: block rm -rf and .env writes
The script below denies rm -rf in shell commands and writes to files named .env. It runs as it stands: a test in our repository executes this exact code.
1. Add the hook
Save this as .claude/hooks/guard.mjs. It uses only what ships with Node.
import { readFileSync } from "node:fs";
const input = JSON.parse(readFileSync(0, "utf8"));
const tool = input.tool_name;
const args = input.tool_input ?? {};
function deny(reason) {
console.log(
JSON.stringify({
hookSpecificOutput: {
hookEventName: "PreToolUse",
permissionDecision: "deny",
permissionDecisionReason: reason,
},
}),
);
process.exit(0);
}
if (tool === "Bash" || tool === "PowerShell") {
if (/\brm\s+-(rf|fr)\b/.test(args.command ?? "")) {
deny("rm -rf is blocked in this project. Delete files one by one.");
}
}
if (tool === "Write" || tool === "Edit") {
// On Windows the path arrives with backslashes. Normalize before matching.
const path = String(args.file_path ?? "").replaceAll("\\", "/");
if (/\/\.env(\.|$)/.test(path)) {
deny("Files named .env are off limits. Ask the user to change them.");
}
}The pattern catches the plain forms rm -rf and rm -fr. It is a guard rail, not a security boundary: other spellings of the same command get through.
2. Register it
{
"hooks": {
"PreToolUse": [
{
"matcher": "Bash|PowerShell|Write|Edit",
"hooks": [
{
"type": "command",
"command": "node",
"args": [
"${CLAUDE_PROJECT_DIR}/.claude/hooks/guard.mjs"
],
"timeout": 10,
"onFailure": "block"
}
]
}
]
}
}The matcher lists tool names, so the hook starts only for those four tools. command and args are the exec form: Claude Code starts node directly and passes the path as one argument. onFailure: "block" makes a hook that cannot run block the call instead of letting it through (see the traps).
3. The same rule with an exit code
A simpler script skips JSON: it prints the reason to stderr and exits with 2.
import { readFileSync } from "node:fs";
const input = JSON.parse(readFileSync(0, "utf8"));
if (/\brm\s+-(rf|fr)\b/.test(input.tool_input?.command ?? "")) {
console.error("Blocked: rm -rf is not allowed here.");
process.exit(2);
}Claude receives the stderr text as the tool's error, prefixed with the event, the tool name and the hook's command. Choose one style per hook. The reference advises either exit codes alone or exit 0 with JSON.
Traps
- Exit 1 does not block. Only exit code 2 blocks. Any other non-zero code is a non-blocking error: the call goes ahead and you see a
hook failednotice. A policy hook that crashes lets everything through. - A slow hook does not block either. A command hook that reaches its
timeoutis cancelled and its output is discarded, and the call continues through the normal permission flow. To block when the hook fails or times out, set"onFailure": "block". It needs Claude Code v2.1.295 or later. The default timeout for a command hook is 600 seconds, so set a shorter one. - Windows paths use backslashes. A check such as
/src/never matchesC:\project\src\index.ts, and the call goes through. Normalize the separators first, as the example does, and match a path segment instead of anchoring with^. - Match both shells on Windows. Where the PowerShell tool is on, Claude uses it as its main shell. Without Git Bash, Claude Code does not register
Bashat all. A hook that matches onlyBashnever fires there. UseBash|PowerShell. - Print only the JSON object. Any other text on stdout, such as a line from your shell profile, keeps Claude Code from reading the object as JSON.
- Print the decision before you start a background job. If your script prints an allow and then starts a background process without redirecting its output, Claude Code blocks the call.
updatedInputreplaces the whole input. Send the unchanged fields along with the changed ones. In auto mode, a rewritten call with nopermissionDecisioncan be denied, because the check saw the original input, not yours.
How cachly uses it
The cachly project setup adds a PreToolUse hook with the matcher Edit|Write|MultiEdit|NotebookEdit and a timeout of 10 seconds. Before such a call it looks up lessons stored for that file and adds them as additionalContext. It does not block or change the call.
The Claude Code plugin does not ship this hook. It ships SessionStart, UserPromptSubmit and Stop. The file briefing comes with the project setup, because it adds one more hook run before every single edit:
npx @cachly-dev/mcp-server@latest initSources
- Claude Code docs: Hooks reference (PreToolUse, PreToolUse input, PreToolUse decision control, exit codes, timeouts, onFailure)
- Claude Code docs: Automate actions with hooks (background reading)
- cachly-mcp on GitHub (the cachly PreToolUse hook)
Checked against the official docs on .
More: All Claude Code hook events · PostToolUse hook · UserPromptSubmit hook · All docs