Skip to main content
skill CX Codex

hook-development · josiahsiegel — Claude Code skill: hooks and installation

hook-development — a practical guide to building Claude Code hooks, from checks before a tool runs to tests after file changes. Use it to configure hook behavior or investigate why one does not fire.

MIT 112 installs ★ 66 updated 2026-06-18

Install into Claude Code · Skills CLI (Vercel) All methods and platforms ↓
npx skills add JosiahSiegel/claude-plugin-marketplace --skill hook-development -a claude-code
Open on GitHub

What hook-development does

The skill covers hook events, tool matchers, and two execution styles: prompts that judge a request in context, or shell commands for deterministic checks. Its examples show how to review file writes, run tests after edits, and check whether a task is ready to stop.

It includes configuration layouts for hooks/hooks.json and .claude/settings.json, plus examples of hook input, output, and environment variables. The layouts differ: plugin configuration nests events under hooks, while user settings put events at the top level.

Claude Code loads hooks when a session starts, so configuration edits require a restart. Matching hooks run in parallel, not one after another.

What it helps with

  • add a check before a tool call
  • run tests after file edits
  • block writes to sensitive paths
  • filter hooks by tool name
  • debug a hook that fails to fire

Example prompts for the agent

  • Set up a PreToolUse hook to review file writes and reject unsafe paths.
  • Add a PostToolUse hook for Write|Edit that runs the test command after edits.
  • Check why my hook does not fire and review hooks/hooks.json.

How to install hook-development

1Skills CLI (Vercel)

npx skills add JosiahSiegel/claude-plugin-marketplace --skill hook-development -a claude-code

2Manually: put the files in place

~/.claude/skills/hook-development/SKILL.md

Copy the whole skill folder; for one project use .claude/skills/hook-development/

Step by step, with commands for each platform: How to install skills in Claude Code: five ways

Questions about hook-development

How do I install hook-development in Claude Code?

Run npx skills add JosiahSiegel/claude-plugin-marketplace --skill hook-development -a claude-code. The skill file is placed at ~/.claude/skills/hook-development/SKILL.md.

What does the hook-development skill do?

It guides you through Claude Code hook events, matchers, and checks implemented with prompts or shell commands. It also explains hook input and output formats.

Do hook configuration edits take effect in the current session?

No. Claude Code loads hooks at session start, so restart it after changing the configuration. Hooks with matching filters run in parallel.

Source text

SKILL.md · MIT
---
name: hook-development
description: |
  Canonical guide to authoring Claude Code hooks, both prompt-based and command-based.
  PROACTIVELY activate for: (1) creating a hook, (2) adding PreToolUse or PostToolUse hooks, (3) validating tool use, (4) implementing prompt-based hooks, (5) blocking dangerous commands, (6) event-driven automation, (7) configuring hooks.json, (8) using ${CLAUDE_PLUGIN_ROOT}, (9) hook matchers and filtering, (10) debugging hooks that do not fire.
  Provides: hooks.json schema, event reference, security guidance, and examples.
---

# Hook Development for Claude Code Plugins

## Overview

Hooks are event-driven automation that execute in response to Claude Code events. Use hooks to validate operations, enforce policies, load context, and integrate external tools.

**Two hook types:**
- **Prompt-based** (recommended): LLM-driven, context-aware decisions
- **Command-based**: Shell commands for fast, deterministic checks

## Hook Events Reference

| Event | When | Common Use |
|-------|------|------------|
| PreToolUse | Before tool executes | Validate, approve/deny, modify input |
| PostToolUse | After tool completes | Test, lint, log, provide feedback |
| Stop | Main agent stopping | Verify task completeness |
| SubagentStop | Subagent stopping | Validate subagent work |
| UserPromptSubmit | User sends prompt | Add context, validate, preprocess |
| SessionStart | Session begins | Load context, set environment |
| SessionEnd | Session ends | Cleanup, logging |
| PreCompact | Before context compaction | Preserve critical information |
| Notification | Notification shown | Custom alert reactions |

## Configuration Formats

### Plugin hooks.json (in `hooks/hooks.json`)

**Uses wrapper format with `hooks` field:**

```json
{
  "description": "What these hooks do (optional)",
  "hooks": {
    "PreToolUse": [
      {
        "matcher": "Write|Edit",
        "hooks": [
          {
            "type": "command",
            "command": "${CLAUDE_PLUGIN_ROOT}/scripts/validate.sh",
            "timeout": 10
          }
        ]
      }
    ]
  }
}
```

### User settings format (in `.claude/settings.json`)

**Direct format, no wrapper:**

```json
{
  "PreToolUse": [
    {
      "matcher": "Write|Edit",
      "hooks": [{ "type": "command", "command": "script.sh" }]
    }
  ]
}
```

**Critical difference:** Plugin hooks.json wraps events inside `{"hooks": {...}}`. Settings format puts events at top level.

## Prompt-Based Hooks (Recommended)

Use LLM reasoning for context-aware decisions:

```json
{
  "type": "prompt",
  "prompt": "Evaluate if this tool use is appropriate. Check for: system paths, credentials, path traversal. Return 'approve' or 'deny'.",
  "timeout": 30
}
```

**Supported events:** PreToolUse, PostToolUse, Stop, SubagentStop, UserPromptSubmit

**Benefits:** Context-aware, flexible, better edge case handling, easier to maintain.

## Command Hooks

Execute shell commands for deterministic checks:

```json
{
  "type": "command",
  "command": "bash ${CLAUDE_PLUGIN_ROOT}/scripts/validate.sh",
  "timeout": 60
}
```

**Always use `${CLAUDE_PLUGIN_ROOT}` for portable paths.**

### Exit Codes

| Code | Meaning |
|------|---------|
| 0 | Success (stdout shown in transcript) |
| 2 | Blocking error (stderr fed back to Claude) |
| Other | Non-blocking error |

## Matchers

Control which tools trigger hooks:

```json
"matcher": "Write"              // Exact match
"matcher": "Write|Edit|Bash"    // Multiple tools
"matcher": "mcp__.*__delete.*"  // Regex (all MCP delete tools)
"matcher": "*"                  // All tools (use sparingly)
```

Matchers are case-sensitive.

## Hook Input/Output

### Input (all hooks receive via stdin)

```json
{
  "session_id": "abc123",
  "transcript_path": "/path/to/transcript.txt",
  "cwd": "/current/working/dir",
  "hook_event_name": "PreToolUse",
  "tool_name": "Write",
  "tool_input": { "file_path": "/path/to/file" }
}
```

Event-specific fields: `tool_name`, `tool_input`, `tool_result`, `user_prompt`, `reason`

Access in prompts: `$TOOL_INPUT`, `$TOOL_RESULT`, `$USER_PROMPT`

### Output

**Standard (all hooks):**
```json
{
  "continue": true,
  "suppressOutput": false,
  "systemMessage": "Message for Claude"
}
```

**PreToolUse decisions:**
```json
{
  "hookSpecificOutput": {
    "permissionDecision": "allow|deny|ask",
    "updatedInput": { "field": "modified_value" }
  }
}
```

**Stop/SubagentStop decisions:**
```json
{
  "decision": "approve|block",
  "reason": "Explanation"
}
```

## Environment Variables

| Variable | Available | Purpose |
|----------|-----------|---------|
| `$CLAUDE_PLUGIN_ROOT` | All hooks | Plugin directory (portable paths) |
| `$CLAUDE_PROJECT_DIR` | All hooks | Project root path |
| `$CLAUDE_ENV_FILE` | SessionStart only | Persist env vars for session |

**SessionStart can persist variables:**
```bash
echo "export PROJECT_TYPE=nodejs" >> "$CLAUDE_ENV_FILE"
```

## Common Patterns

### Validate file writes (PreToolUse)

```json
{
  "PreToolUse": [{
    "matcher": "Write|Edit",
    "hooks": [{
      "type": "prompt",
      "prompt": "Check if this file write is safe. Deny writes to: .env, credentials, system paths, or files with path traversal (..). Return 'approve' or 'deny' with reason."
    }]
  }]
}
```

### Auto-test after changes (PostToolUse)

```json
{
  "PostToolUse": [{
    "matcher": "Write|Edit",
    "hooks": [{
      "type": "command",
      "command": "npm test -- --bail",
      "timeout": 60
    }]
  }]
}
```

### Verify task completion (Stop)

```json
{
  "Stop": [{
    "matcher": "*",
    "hooks": [{
      "type": "prompt",
      "prompt": "Verify: tests run, build succeeded, all questions answered. Return 'approve' to stop or 'block' with reason to continue."
    }]
  }]
}
```

### Load project context (SessionStart)

```json
{
  "SessionStart": [{
    "matcher": "*",
    "hooks": [{
      "type": "command",
      "command": "bash ${CLAUDE_PLUGIN_ROOT}/scripts/load-context.sh",
      "timeout": 10
    }]
  }]
}
```

## Security Best Practices

### In command hook scripts:

```bash
#!/bin/bash
set -euo pipefail

input=$(cat)
file_path=$(echo "$input" | jq -r '.tool_input.file_path')

# Always validate inputs
if [[ ! "$file_path" =~ ^[a-zA-Z0-9_./-]+$ ]]; then
  echo '{"decision": "deny", "reason": "Invalid path"}' >&2
  exit 2
fi

# Block path traversal
if [[ "$file_path" == *".."* ]]; then
  echo '{"decision": "deny", "reason": "Path traversal detected"}' >&2
  exit 2
fi

# Block sensitive files
if [[ "$file_path" == *".env"* ]]; then
  echo '{"decision": "deny", "reason": "Sensitive file"}' >&2
  exit 2
fi

# Always quote variables
echo "$file_path"
```

## Lifecycle and Limitations

**Hooks load at session start.** Changes to hook configuration require restarting Claude Code.

- Editing `hooks/hooks.json` won't affect the current session
- Adding new hook scripts won't be recognized until restart
- All matching hooks run **in parallel** (not sequentially)
- Hooks don't see each other's output - design for independence

**To test changes:** Exit Claude Code, restart with `claude` or `claude --debug`.

## Debugging

```bash
# Enable debug mode to see hook execution
claude --debug

# Test hook scripts directly
echo '{"tool_name": "Write", "tool_input": {"file_path": "/test"}}' | \
  bash ${CLAUDE_PLUGIN_ROOT}/scripts/validate.sh

# Validate hook JSON output
output=$(./hook-script.sh < test-input.json)
echo "$output" | jq .

# View loaded hooks in session
# Use /hooks command
```

## Validation Checklist

- [ ] hooks.json uses correct format (plugin wrapper or settings direct)
- [ ] All script paths use `${CLAUDE_PLUGIN_ROOT}` (no hardcoded paths)
- [ ] Scripts are executable and handle errors (`set -euo pipefail`)
- [ ] Scripts validate all inputs and quote all variables
- [ ] Matchers are specific (avoid `*` unless necessary)
- [ ] Timeouts are set appropriately (default: command 60s, prompt 30s)
- [ ] Hook output is valid JSON
- [ ] Tested with `claude --debug`

© JosiahSiegel · MIT · JosiahSiegel/claude-plugin-marketplace

Similar skills

All skills for Agent setup: memory, context, orchestration →

hook-development by other authors comes first.

hook-development official Anthropic Guides the development of Claude Code plugin hooks to intercept tool calls, validate output, and enforce task completion checks. CX Codex +1 7,028installs doubt-driven-development addyosmani The doubt-driven-development skill sends non-trivial decisions to a fresh-context reviewer looking for flaws. Use it before changes that are hard to undo or costly to debug later. CX Codex +1 72,600installs backend-development-feature-development sickn33 The backend-development-feature-development skill coordinates feature work from requirements and architecture through implementation, testing, and rollout. Use it for changes spanning services or teams. CX Codex +1 2installs constraint-driven-development addyosmani constraint-driven-development turns vague quality expectations into a written contract for your project. Interviews you about which dimensions matter, then records them in CONSTRAINTS.md as numbers a check can verify. CX Codex +1 49,100installs wp-plugin-development WordPress wp-plugin-development is a skill for Claude Code, Codex, Cursor and other platforms covering plugin architecture, hooks, Settings API and security. It triggers for plugin setup, admin UI or vulnerability fixes. CX Codex +1 9,300installs unix-goto-development manutej unix-goto-development walks an agent through adding features to the unix-goto navigation tool: a 9-step workflow, 100% test coverage, and sub-100ms cached navigation. CX Codex +1 428installs iterative-development alinaqi iterative-development is a Claude Code skill that runs tests after each response, feeds failures back to the model, and continues the TDD loop until tests pass. CX Codex +1 286installs

From the same set96

The whole set →
viral-video-long-form The viral-video-long-form Claude Code skill supports planning long YouTube videos and improving their SEO, audience retention, and thumbnails. It activates for video strategy, content planning, and analytics interpretation. CX Codex +1 114installs power-query-m This skill helps write Power Query M, diagnose query folding, and build ETL transformations. Use it for parameters, dynamic sources, and connector work. CX Codex +1 114installs adf-ml-analytics adf-ml-analytics — a skill that maps Azure Data Factory onto Azure ML, Databricks and AI Services: batch scoring, notebook runs, SQL archival. Useful when a pipeline still sits on SDK v1. CX Codex +1 113installs ffmpeg-filter-complex-patterns The ffmpeg-filter-complex-patterns Claude Code skill explains FFmpeg’s complex filter syntax. It activates for multi-source video layouts, transitions, audio mixing, and stream routing questions. CX Codex +1 112installs ffmpeg-video-analysis The ffmpeg-video-analysis Claude Code skill uses FFmpeg filters to inspect video and measure quality. It activates for checks such as black or frozen frames, blur, scene changes, and crop detection. CX Codex +1 111installs viral-video-platform-specs The viral-video-platform-specs Claude Code skill selects export settings for social video platforms. It activates for upload specs, aspect-ratio changes, and multi-platform exports. CX Codex +1 108installs ffmpeg-glitch-distortion-effects ffmpeg-glitch-distortion-effects — a Claude Code skill for FFmpeg glitch effects and video distortion. It activates for datamosh, VHS looks, color shifts, pixelation, and related edits. CX Codex +1 107installs ffmpeg-opencv-integration ffmpeg-opencv-integration — a skill for Claude Code and Codex guides video processing pipelines using FFmpeg and OpenCV. Prevents RGB/BGR mismatches, pipe stalls, and dropped audio tracks. CX Codex +1 107installs

Project sponsors

Companies that keep this analytics open