Commands Claude Intermediate

Hooks in Claude Code

Run custom scripts before or after Claude uses tools for validation and automation

30 of 66

What are hooks?

Hooks are scripts that run automatically when Claude Code performs specific actions. They can validate, log, or transform tool calls.

Hook types

HookRuns when
PreToolUseBefore Claude calls a tool (can block it)
PostToolUseAfter a tool call completes
NotificationWhen Claude sends a notification
StopWhen Claude finishes a turn

Configuration

Add hooks to .claude/settings.json:

{
  "hooks": {
    "PreToolUse": [
      {
        "matcher": "Write",
        "hooks": [{
          "type": "command",
          "command": "python3 .claude/hooks/validate.py"
        }]
      }
    ]
  }
}

Example: block writes to protected files

import sys, json

input_data = json.load(sys.stdin)
file_path = input_data.get("tool_input", {}).get("file_path", "")

protected = [".env", "secrets.json", "credentials.yml"]
if any(file_path.endswith(p) for p in protected):
    print(json.dumps({"decision": "block", "reason": "Protected file"}))
else:
    print(json.dumps({"decision": "approve"}))

Use cases

  • Block writes to sensitive files
  • Auto-format code after edits
  • Log all tool calls for audit
  • Run linters after file changes

Source: docs.anthropic.com/en/docs/claude-code/hooks

Working out which model to run this on? See The Codex. Packaging it as a reusable skill? See The Armory.