claudekit / guides / hooks-automation
[ Guide · Advanced · 12 min ]

Automate Workflows with Hooks

published · updated

How to wire automation into Claude Code with hooks. Covers which events are available, where to configure them, and how to debug when a hook doesn't fire.

What hooks enable

Hooks add an automation layer to Claude Code without modifying its code. Common uses:

  • Auto-format files after writing
  • Block dangerous commands (rm -rf, git push --force)
  • Show a reminder each time Claude finishes responding
  • Preserve key info before compaction
  • Ask an LLM “is this change safe?” and block on the answer

Configuration locations

FileScope
~/.claude/settings.jsonUser-global
.claude/settings.jsonProject (committed)
.claude/settings.local.jsonPersonal local (gitignored)

Basic structure

{
  "hooks": {
    "PostToolUse": [
      {
        "matcher": "Write|Edit",
        "hooks": [
          {
            "type": "command",
            "command": "jq -r '.tool_response.filePath // .tool_input.file_path' | { read -r f; prettier --write \"$f\"; } 2>/dev/null || true"
          }
        ]
      }
    ]
  }
}

Common events

EventWhen it firesUse case
PreToolUseBefore a tool call executesBlock dangerous commands, permission checks
PostToolUseAfter a tool call succeedsAuto-format, run tests
PostToolUseFailureAfter a tool call failsError logging, notifications
PermissionRequestWhen a tool call needs a permission decisionAutomate approval decisions
UserPromptSubmitWhen a prompt is submittedPrompt analysis, context injection
StopWhen Claude finishes responding (every turn)Check whether work is done, reminders
PreCompactBefore context compactionPreserve key info separately
SessionStartWhen a session begins or resumesEnvironment check, intro message
SessionEndWhen a session terminatesCleanup (JSON output such as systemMessage is discarded)

Other events include SubagentStart, SubagentStop, StopFailure, FileChanged, and PreModelSwitch. See the Hooks reference for the full list.

Five hook types

1. command — run a shell command

{
  "type": "command",
  "command": "jq -r '.tool_input.command' >> ~/.claude/bash-log.txt"
}

Receives the event JSON on stdin. Use jq to extract fields.

2. http — POST to a URL

{
  "type": "http",
  "url": "http://localhost:8080/hooks/pre-tool-use",
  "headers": { "Authorization": "Bearer $MY_TOKEN" },
  "allowedEnvVars": ["MY_TOKEN"]
}

Sends the event’s JSON input as the POST request body. The response body uses the same JSON output format as command hooks. Header values only resolve environment variables listed in allowedEnvVars.

3. mcp_tool — call an MCP tool

{
  "type": "mcp_tool",
  "server": "my_server",
  "tool": "security_scan",
  "input": { "file_path": "${tool_input.file_path}" }
}

Calls a tool on a configured MCP server. The tool’s text output is treated like command-hook stdout.

4. prompt — ask an LLM

{
  "type": "prompt",
  "prompt": "Decide if this command makes a destructive system change: $ARGUMENTS. Respond with JSON: {\"ok\": true} if it is safe, or {\"ok\": false, \"reason\": \"your explanation\"} if it is not."
}

$ARGUMENTS is a placeholder for the hook input JSON. The model responds with JSON containing ok and reason, and what happens on ok: false depends on the event. By default the hook uses the model Claude Code uses for background functionality; set model to change it.

5. agent — run an agent

{
  "type": "agent",
  "prompt": "Verify that unit tests were added alongside the file changes"
}

Spawns a subagent that can use tools like Read, Grep, and Glob to verify conditions before returning a decision. Higher token cost. Agent hooks are experimental and may change.

Example: block dangerous commands

{
  "hooks": {
    "PreToolUse": [
      {
        "matcher": "Bash",
        "hooks": [
          {
            "type": "prompt",
            "prompt": "Decide if this shell command permanently deletes data or makes hard-to-reverse changes: $ARGUMENTS. Respond with {\"ok\": true} if not, or {\"ok\": false, \"reason\": \"your explanation\"} if it does.",
            "continueOnBlock": true
          }
        ]
      }
    ]
  }
}

On PreToolUse, ok: false denies the tool call. By default the turn ends; with continueOnBlock: true the reason goes back to Claude as the tool error so it can adjust and continue.

For command and HTTP hooks that act as a gate, add "onFailure": "block" (Claude Code v2.1.295 or later). A hook that can’t start, times out, or exits with an unexpected code then blocks the action instead of letting it through.

Example: auto-format after write

{
  "hooks": {
    "PostToolUse": [
      {
        "matcher": "Write|Edit",
        "hooks": [
          {
            "type": "command",
            "command": "jq -r '.tool_response.filePath // .tool_input.file_path' | { read -r f; case \"$f\" in *.ts|*.tsx|*.js|*.jsx|*.json|*.md) prettier --write \"$f\";; esac; } 2>/dev/null || true"
          }
        ]
      }
    ]
  }
}

Per-extension formatter selection.

Example: message when a response ends

{
  "hooks": {
    "Stop": [
      {
        "hooks": [
          {
            "type": "command",
            "command": "echo '{\"systemMessage\": \"Response finished — review changed files.\"}'"
          }
        ]
      }
    ]
  }
}

Stop runs when Claude finishes responding, on every turn, not when the session ends. JSON output with systemMessage is shown to the user. SessionEnd fires when the session terminates, but Claude Code discards its JSON output fields such as systemMessage, so use it for cleanup only.

Debugging checklist

  1. JSON syntax — jq . settings.json to validate
  2. Matcher pattern — exact tool name (e.g. Write|Edit)
  3. Test the command directly — echo '{"tool_input":{"file_path":"test.ts"}}' | <hook command>
  4. Check registration — /hooks opens a read-only browser that labels each hook with where it comes from (user, project, or local settings, a plugin, and so on). Direct edits to settings files are normally picked up automatically by the file watcher.
  5. Debug mode — claude --debug shows hook execution logs
  6. Disable temporarily — set "disableAllHooks": true in your settings to rule hooks out. There is no way to disable an individual hook while keeping it in the configuration.

Use hookify

hookify generates hooks from natural language. If hand-writing JSON feels heavy, draft with hookify first and apply the result to settings.json.

Next steps

§ 12

Frequently Asked Questions

frequently asked
§ 12.1
What are hooks?
Handlers that run automatically at specific points in Claude Code's lifecycle, such as before or after a tool call, when Claude finishes responding, at session start or end, and around compaction. There are five handler types: command, HTTP, MCP tool, prompt, and agent hooks.
§ 12.2
Where do I configure them?
In the `hooks` field of `~/.claude/settings.json` (user-global), `.claude/settings.json` (project-shared), or `.claude/settings.local.json` (personal local).
§ 12.3
Which events are supported?
More than 30, including PreToolUse, PostToolUse, PostToolUseFailure, PermissionRequest, UserPromptSubmit, Stop, SubagentStop, SessionStart, SessionEnd, PreCompact, and PostCompact. PreToolUse and PostToolUse are the most common for automation around tool calls.
§ 12.4
Can hooks use an LLM instead of running code?
Yes. A `type: "prompt"` hook sends a prompt to a Claude model for single-turn evaluation, and the model returns `{"ok": true}` or `{"ok": false, "reason": "..."}`. A `type: "agent"` hook spawns a subagent that can use tools to verify conditions; agent hooks are experimental.
§ 12.5
How do I debug a hook that isn't firing?
Most issues come from JSON syntax errors or matcher patterns that don't match. Use `/hooks` to confirm the hook is registered and `claude --debug` for execution logs. Direct edits to hooks in settings files are normally picked up automatically by the file watcher, so a restart usually isn't needed.