jpskill.com
🛠️ 開発・MCP コミュニティ

hooks-manager

Claude Codeにおけるワークフロー自動化のために、イベント発生時にコードを実行する「hooks」を作成・検証・デプロイし、コード整形やセキュリティチェック、監視連携などを自動化するSkill。

📜 元の英語説明(参考)

Create, validate, and deploy Claude Code hooks for workflow automation. Hooks enable event-driven automation at 8 lifecycle points (PreToolUse, PostToolUse, UserPromptSubmit, etc.) with structured JSON control. Use when automating code formatting, security gates, observability integration, validation enforcement, or any event-driven workflow automation in Claude Code.

🇯🇵 日本人クリエイター向け解説

一言でいうと

Claude Codeにおけるワークフロー自動化のために、イベント発生時にコードを実行する「hooks」を作成・検証・デプロイし、コード整形やセキュリティチェック、監視連携などを自動化するSkill。

※ jpskill.com 編集部が日本のビジネス現場向けに補足した解説です。Skill本体の挙動とは独立した参考情報です。

⚡ おすすめ: コマンド1行でインストール(60秒)

下記のコマンドをコピーしてターミナル(Mac/Linux)または PowerShell(Windows)に貼り付けてください。 ダウンロード → 解凍 → 配置まで全自動。

🍎 Mac / 🐧 Linux
mkdir -p ~/.claude/skills && cd ~/.claude/skills && curl -L -o hooks-manager.zip https://jpskill.com/download/9436.zip && unzip -o hooks-manager.zip && rm hooks-manager.zip
🪟 Windows (PowerShell)
$d = "$env:USERPROFILE\.claude\skills"; ni -Force -ItemType Directory $d | Out-Null; iwr https://jpskill.com/download/9436.zip -OutFile "$d\hooks-manager.zip"; Expand-Archive "$d\hooks-manager.zip" -DestinationPath $d -Force; ri "$d\hooks-manager.zip"

完了後、Claude Code を再起動 → 普通に「動画プロンプト作って」のように話しかけるだけで自動発動します。

💾 手動でダウンロードしたい(コマンドが難しい人向け)
  1. 1. 下の青いボタンを押して hooks-manager.zip をダウンロード
  2. 2. ZIPファイルをダブルクリックで解凍 → hooks-manager フォルダができる
  3. 3. そのフォルダを C:\Users\あなたの名前\.claude\skills\(Win)または ~/.claude/skills/(Mac)へ移動
  4. 4. Claude Code を再起動

⚠️ ダウンロード・利用は自己責任でお願いします。当サイトは内容・動作・安全性について責任を負いません。

🎯 このSkillでできること

下記の説明文を読むと、このSkillがあなたに何をしてくれるかが分かります。Claudeにこの分野の依頼をすると、自動で発動します。

📦 インストール方法 (3ステップ)

  1. 1. 上の「ダウンロード」ボタンを押して .skill ファイルを取得
  2. 2. ファイル名の拡張子を .skill から .zip に変えて展開(macは自動展開可)
  3. 3. 展開してできたフォルダを、ホームフォルダの .claude/skills/ に置く
    • · macOS / Linux: ~/.claude/skills/
    • · Windows: %USERPROFILE%\.claude\skills\

Claude Code を再起動すれば完了。「このSkillを使って…」と話しかけなくても、関連する依頼で自動的に呼び出されます。

詳しい使い方ガイドを見る →
最終更新
2026-05-18
取得日時
2026-05-18
同梱ファイル
1

📖 Skill本文(日本語訳)

※ 原文(英語/中国語)を Gemini で日本語化したものです。Claude 自身は原文を読みます。誤訳がある場合は原文をご確認ください。

Hooks Manager

概要

hooks-manager は、Claude Code の hooks システム(2025年6月リリース)を通じて、洗練されたワークフロー自動化を可能にします。

目的: コードのフォーマット、セキュリティゲート、可観測性、および検証のためのイベント駆動型自動化の作成

パターン: タスクベース(8つの操作、hook イベントごとに1つ + 管理)

主なイノベーション: Hooks は Claude Code をインタラクティブから自動化へと変革し、手作業を最大92%削減します。

利用可能な Hook イベント (8):

  1. UserPromptSubmit - Claude がプロンプトを見る前
  2. PreToolUse - ツールの実行前
  3. PostToolUse - ツールの実行後
  4. PermissionRequest - 権限が要求されたとき
  5. Notification - 重要なイベント
  6. SessionStart - セッションの初期化
  7. SessionEnd - セッションのクリーンアップ
  8. Stop - 会話の終了

どのような時に使うか

hooks-manager は、以下の場合に使用します。

  • コードの自動フォーマット (Write/Edit 後の PostToolUse)
  • セキュリティゲート (危険な操作をブロックするための PreToolUse)
  • 可観測性の統合 (すべてのツール呼び出しでテレメトリを送信)
  • 検証の強制 (無効な操作をブロック)
  • ワークフローの自動化 (イベント時にアクションをトリガー)
  • チームの標準化 (コーディング標準の強制)

本番環境への影響: 企業は、PostToolUse フォーマット hooks により、スタイルレビュー時間を92%削減したと報告しています。


前提条件

必須

  • Claude Code (hooks のサポートは2025年6月に追加)
  • イベント駆動型プログラミングの基本的な理解

推奨

  • Linter/formatter のインストール (ESLint, Prettier, Black)
  • セキュリティツール (セキュリティ hooks を使用する場合)
  • 可観測性プラットフォーム (テレメトリ hooks を使用する場合)

Hook の操作

操作 1: フォーマット Hook の作成 (PostToolUse)

目的: AI がファイルを書き込み/編集した後に、コードを自動フォーマットする

ユースケース: 手動介入なしにコーディング標準を強制する

プロセス:

  1. Formatter の選択:

    # JavaScript/TypeScript
    npm install --save-dev prettier
    
    # Python
    pip install black
    
    # Multi-language
    npm install --save-dev prettier @prettier/plugin-python
  2. Hook の設定の作成:

    {
      "event": "PostToolUse",
      "tools": ["Write", "Edit"],
      "description": "Claude がファイルを書き込み/編集した後に、コードを自動フォーマットする",
      "handler": {
        "command": "npx prettier --write \"$FILE\"",
        "timeout": 5000
      },
      "filters": {
        "filePatterns": ["**/*.{ts,tsx,js,jsx,py}"],
        "excludePatterns": ["node_modules/**", "*.min.js"]
      }
    }
  3. Hook のインストール:

    # グローバル hook (すべてのプロジェクト)
    mkdir -p ~/.claude/hooks
    echo '[above-json]' > ~/.claude/hooks/auto-format.json
    
    # プロジェクト固有
    mkdir -p .claude/hooks
    echo '[above-json]' > .claude/hooks/auto-format.json
  4. Hook のテスト:

    # Claude にフォーマットされていないコードを書かせる
    # Hook は Write/Edit 後に自動的にフォーマットするはずです
    # 正しくフォーマットされていることを確認してください

出力:

  • Hook 設定ファイル
  • すべてのコード変更に対する自動フォーマット
  • スタイルレビュー時間の92%削減

検証:

  • [ ] Hook ファイルが作成された
  • [ ] Formatter が正しく設定された
  • [ ] ファイルパターンが適切である
  • [ ] Claude Code でテスト済み
  • [ ] フォーマットが自動的に動作する

見積もり時間: 30-45 分


操作 2: セキュリティ Hook の作成 (PreToolUse)

目的: 危険な操作を実行前にブロックする

ユースケース: 誤った本番環境ファイルの変更、破壊的なコマンドを防止する

プロセス:

  1. セキュリティルールの定義:

    {
      "event": "PreToolUse",
      "tools": ["Write", "Edit", "Bash"],
      "description": "危険な操作をブロックする",
      "handler": {
        "command": ".claude/hooks/security-check.sh \"$TOOL\" \"$FILE\" \"$COMMAND\""
      },
      "structuredOutput": true
    }
  2. セキュリティチェック スクリプトの作成:

    #!/bin/bash
    # .claude/hooks/security-check.sh
    
    TOOL=$1
    FILE=$2
    COMMAND=$3
    
    # 本番環境ファイルの変更をブロックする
    if [[ "$FILE" == "/etc/"* ]] || [[ "$FILE" == "/usr/"* ]]; then
      echo '{"continue": false, "stopReason": "システムファイルを変更できません", "suppressOutput": true}'
      exit 1
    fi
    
    # 破壊的なコマンドをブロックする
    if [[ "$COMMAND" =~ rm\ -rf\ / ]] || [[ "$COMMAND" =~ dd\ if ]]; then
      echo '{"continue": false, "stopReason": "破壊的なコマンドがブロックされました", "suppressOutput": true}'
      exit 1
    fi
    
    # curl/wget をブロックする (セキュリティリスク)
    if [[ "$COMMAND" =~ curl|wget ]]; then
      echo '{"continue": false, "stopReason": "ネットワークコマンドは無効です", "suppressOutput": false}'
      exit 1
    fi
    
    # 操作を許可する
    echo '{"continue": true}'
    exit 0
  3. セキュリティ Hook のインストール:

    chmod +x .claude/hooks/security-check.sh
    # Hook JSON はステップ 1 で既に設定済み

出力:

  • 危険な操作をブロックするセキュリティ hook
  • 偶発的な損害からの保護
  • ブロックされた操作の監査証跡

検証:

  • [ ] Hook はシステムファイルの変更をブロックする
  • [ ] Hook は破壊的なコマンドをブロックする
  • [ ] Hook は安全な操作を許可する
  • [ ] 構造化された JSON 出力が正しい

見積もり時間: 45-60 分


操作 3: 可観測性 Hook の作成 (Notification)

目的: 重要なイベントに関するテレメトリを可観測性プラットフォームに送信する

ユースケース: AI エージェントの決定、ツールの使用状況、エラーを追跡する

プロセス:

  1. テレメトリ Hook の作成:

    {
      "event": "Notification",
      "description": "テレメトリを可観測性プラットフォームに送信する",
      "handler": {
        "command": ".claude/hooks/send-telemetry.sh \"$EVENT_TYPE\" \"$MESSAGE\""
      }
    }
  2. テレメトリ スクリプトの作成:

    
    #!/bin/bash
    # .claude/hooks/send-telemetry.sh
    
    EVENT_TYPE=$1
    MESSAGE=$2
    
    # 可観測性プラットフォームに送信する (例: Victoria Metrics)
    curl -X POST http://localhost:8428/api/v1/write \
      -d "claude_event{type=\"$EVENT_TYPE\"} 1" \
      -d "claude_message{event=\"$EVENT_TYPE\",msg=\"$MESSAGE\"} 1"
    
    # またはファイルにログを記録する
    echo "$(date -Iseconds) | $EVENT_TYPE | $MESSA

(原文がここで切り詰められています)

📜 原文 SKILL.md(Claudeが読む英語/中国語)を展開

Hooks Manager

Overview

hooks-manager enables sophisticated workflow automation through Claude Code's hooks system (released June 2025).

Purpose: Create event-driven automation for code formatting, security gates, observability, and validation

Pattern: Task-based (8 operations, one per hook event + management)

Key Innovation: Hooks transform Claude Code from interactive to automated - reducing manual work by up to 92%

Hook Events Available (8):

  1. UserPromptSubmit - Before Claude sees prompts
  2. PreToolUse - Before tool execution
  3. PostToolUse - After tool execution
  4. PermissionRequest - When permissions requested
  5. Notification - Important events
  6. SessionStart - Session initialization
  7. SessionEnd - Session cleanup
  8. Stop - Conversation termination

When to Use

Use hooks-manager when:

  • Auto-formatting code (PostToolUse after Write/Edit)
  • Security gates (PreToolUse to block dangerous operations)
  • Observability integration (send telemetry on all tool calls)
  • Validation enforcement (block invalid operations)
  • Workflow automation (trigger actions on events)
  • Team standardization (enforce coding standards)

Production Impact: Companies report 92% reduction in style review time with PostToolUse formatting hooks


Prerequisites

Required

  • Claude Code (hooks support added June 2025)
  • Basic understanding of event-driven programming

Recommended

  • Linter/formatter installed (ESLint, Prettier, Black)
  • Security tools (if using security hooks)
  • Observability platform (if using telemetry hooks)

Hook Operations

Operation 1: Create Formatting Hook (PostToolUse)

Purpose: Auto-format code after AI writes/edits files

Use Case: Enforce coding standards without manual intervention

Process:

  1. Choose Formatter:

    # JavaScript/TypeScript
    npm install --save-dev prettier
    
    # Python
    pip install black
    
    # Multi-language
    npm install --save-dev prettier @prettier/plugin-python
  2. Create Hook Configuration:

    {
      "event": "PostToolUse",
      "tools": ["Write", "Edit"],
      "description": "Auto-format code after Claude writes/edits files",
      "handler": {
        "command": "npx prettier --write \"$FILE\"",
        "timeout": 5000
      },
      "filters": {
        "filePatterns": ["**/*.{ts,tsx,js,jsx,py}"],
        "excludePatterns": ["node_modules/**", "*.min.js"]
      }
    }
  3. Install Hook:

    # Global hook (all projects)
    mkdir -p ~/.claude/hooks
    echo '[above-json]' > ~/.claude/hooks/auto-format.json
    
    # Project-specific
    mkdir -p .claude/hooks
    echo '[above-json]' > .claude/hooks/auto-format.json
  4. Test Hook:

    # Have Claude write unformatted code
    # Hook should auto-format after Write/Edit
    # Verify formatted correctly

Outputs:

  • Hook configuration file
  • Auto-formatting on all code changes
  • 92% reduction in style review time

Validation:

  • [ ] Hook file created
  • [ ] Formatter configured correctly
  • [ ] File patterns appropriate
  • [ ] Tested with Claude Code
  • [ ] Formatting works automatically

Time Estimate: 30-45 minutes


Operation 2: Create Security Hook (PreToolUse)

Purpose: Block dangerous operations before execution

Use Case: Prevent accidental production file modifications, destructive commands

Process:

  1. Define Security Rules:

    {
      "event": "PreToolUse",
      "tools": ["Write", "Edit", "Bash"],
      "description": "Block dangerous operations",
      "handler": {
        "command": ".claude/hooks/security-check.sh \"$TOOL\" \"$FILE\" \"$COMMAND\""
      },
      "structuredOutput": true
    }
  2. Create Security Check Script:

    #!/bin/bash
    # .claude/hooks/security-check.sh
    
    TOOL=$1
    FILE=$2
    COMMAND=$3
    
    # Block production file modifications
    if [[ "$FILE" == "/etc/"* ]] || [[ "$FILE" == "/usr/"* ]]; then
      echo '{"continue": false, "stopReason": "Cannot modify system files", "suppressOutput": true}'
      exit 1
    fi
    
    # Block destructive commands
    if [[ "$COMMAND" =~ rm\ -rf\ / ]] || [[ "$COMMAND" =~ dd\ if ]]; then
      echo '{"continue": false, "stopReason": "Destructive command blocked", "suppressOutput": true}'
      exit 1
    fi
    
    # Block curl/wget (security risk)
    if [[ "$COMMAND" =~ curl|wget ]]; then
      echo '{"continue": false, "stopReason": "Network commands disabled", "suppressOutput": false}'
      exit 1
    fi
    
    # Allow operation
    echo '{"continue": true}'
    exit 0
  3. Install Security Hook:

    chmod +x .claude/hooks/security-check.sh
    # Hook JSON already configured in step 1

Outputs:

  • Security hook blocking dangerous operations
  • Protection against accidental damage
  • Audit trail of blocked operations

Validation:

  • [ ] Hook blocks system file modifications
  • [ ] Hook blocks destructive commands
  • [ ] Hook allows safe operations
  • [ ] Structured JSON output correct

Time Estimate: 45-60 minutes


Operation 3: Create Observability Hook (Notification)

Purpose: Send telemetry to observability platform on important events

Use Case: Track AI agent decisions, tool usage, errors

Process:

  1. Create Telemetry Hook:

    {
      "event": "Notification",
      "description": "Send telemetry to observability platform",
      "handler": {
        "command": ".claude/hooks/send-telemetry.sh \"$EVENT_TYPE\" \"$MESSAGE\""
      }
    }
  2. Create Telemetry Script:

    #!/bin/bash
    # .claude/hooks/send-telemetry.sh
    
    EVENT_TYPE=$1
    MESSAGE=$2
    
    # Send to observability platform (example: Victoria Metrics)
    curl -X POST http://localhost:8428/api/v1/write \
      -d "claude_event{type=\"$EVENT_TYPE\"} 1" \
      -d "claude_message{event=\"$EVENT_TYPE\",msg=\"$MESSAGE\"} 1"
    
    # Or log to file
    echo "$(date -Iseconds) | $EVENT_TYPE | $MESSAGE" >> .claude/telemetry.log
    
    # Or send to webhook
    # curl -X POST https://your-webhook.com/telemetry \
    #   -H "Content-Type: application/json" \
    #   -d "{\"event\": \"$EVENT_TYPE\", \"message\": \"$MESSAGE\"}"
  3. Test Telemetry:

    # Trigger notification in Claude Code
    # Check telemetry.log or observability platform
    cat .claude/telemetry.log

Outputs:

  • Telemetry hook sending data
  • Observability integration
  • Decision tracking

Validation:

  • [ ] Hook configured
  • [ ] Telemetry script working
  • [ ] Data reaches destination
  • [ ] No performance impact

Time Estimate: 30-45 minutes


Operation 4: Create Validation Hook (PreToolUse)

Purpose: Validate inputs before tool execution

Use Case: Ensure files exist, validate JSON, check permissions

Process:

  1. Create Validation Hook:

    {
      "event": "PreToolUse",
      "tools": ["Write"],
      "description": "Validate JSON before writing",
      "handler": {
        "command": ".claude/hooks/validate-json.sh \"$FILE\" \"$CONTENT\""
      },
      "structuredOutput": true
    }
  2. Create Validation Script:

    #!/bin/bash
    # .claude/hooks/validate-json.sh
    
    FILE=$1
    CONTENT=$2
    
    # Only validate .json files
    if [[ "$FILE" != *.json ]]; then
      echo '{"continue": true}'
      exit 0
    fi
    
    # Validate JSON syntax
    if echo "$CONTENT" | jq empty 2>/dev/null; then
      echo '{"continue": true}'
      exit 0
    else
      echo '{"continue": false, "stopReason": "Invalid JSON syntax", "suppressOutput": false}'
      exit 1
    fi

Outputs:

  • Validation hook preventing invalid writes
  • JSON syntax enforcement
  • Error prevention

Validation:

  • [ ] Hook validates JSON files
  • [ ] Hook allows non-JSON files
  • [ ] Invalid JSON blocked
  • [ ] Valid JSON allowed

Time Estimate: 20-30 minutes


Operation 5: Create MCP Tool Hook (PreToolUse)

Purpose: Control MCP tool access granularly

Use Case: Block specific MCP servers or tools

Process:

  1. MCP Tool Targeting:

    {
      "event": "PreToolUse",
      "tools": ["mcp__filesystem__*"],
      "description": "Block all filesystem MCP operations",
      "handler": {
        "command": "echo '{\"continue\": false, \"stopReason\": \"Filesystem MCP disabled\"}'"
      },
      "structuredOutput": true
    }
  2. Selective MCP Control:

    {
      "event": "PreToolUse",
      "tools": ["mcp__github__delete_repository"],
      "description": "Block dangerous GitHub operations",
      "handler": {
        "command": "echo '{\"continue\": false, \"stopReason\": \"Repository deletion disabled\"}'"
      },
      "structuredOutput": true
    }

Outputs:

  • Fine-grained MCP control
  • Security for MCP operations
  • Prevent accidental damage

Validation:

  • [ ] MCP tools blocked correctly
  • [ ] Tool targeting works (mcpservertool pattern)
  • [ ] Safe operations allowed

Time Estimate: 20-30 minutes


Operation 6: Create Comprehensive Hook (SessionStart)

Purpose: Initialize environment on session start

Use Case: Load context, set variables, validate environment

Process:

  1. Session Start Hook:

    {
      "event": "SessionStart",
      "description": "Initialize session with context and validation",
      "handler": {
        "command": ".claude/hooks/session-init.sh"
      }
    }
  2. Initialization Script:

    #!/bin/bash
    # .claude/hooks/session-init.sh
    
    echo "🚀 Claude Code Session Starting..."
    
    # Load project context
    if [ -f ".claude/PROJECT_CONTEXT.md" ]; then
      echo "📋 Project context available"
    fi
    
    # Check git status
    if git status --porcelain | grep -q .; then
      echo "⚠️  Uncommitted changes detected"
    fi
    
    # Load environment
    if [ -f ".env" ]; then
      echo "🔐 Environment variables available"
    fi
    
    # Run pre-flight checks
    if [ -f ".claude/hooks/pre-flight-check.sh" ]; then
      bash .claude/hooks/pre-flight-check.sh
    fi
    
    echo "✅ Session initialized"

Outputs:

  • Session initialization automation
  • Context loading
  • Environment validation

Validation:

  • [ ] Hook runs on session start
  • [ ] Context loaded correctly
  • [ ] Environment validated

Time Estimate: 15-20 minutes


Operation 7: Deploy and Manage Hooks

Purpose: Install, update, remove, and audit hooks

Process:

  1. Deploy Hook (global or project):

    # Deploy to global (~/.claude/hooks/)
    deploy-hook --global formatting-hook.json
    
    # Deploy to project (.claude/hooks/)
    deploy-hook --project security-hook.json
  2. List Active Hooks:

    # List all hooks
    ls -la ~/.claude/hooks/
    ls -la .claude/hooks/
    
    # Parse and display
    for hook in .claude/hooks/*.json; do
      echo "Hook: $(basename $hook)"
      jq '.event, .description' $hook
    done
  3. Validate Hook:

    # Test hook in safe environment
    validate-hook formatting-hook.json
    
    # Expected:
    # ✅ JSON valid
    # ✅ Handler command exists
    # ✅ Event type valid
    # ✅ Structured output correct
  4. Remove Hook:

    # Disable hook
    rm .claude/hooks/formatting-hook.json
    
    # Or rename to .disabled
    mv .claude/hooks/security-hook.json .claude/hooks/security-hook.json.disabled

Outputs:

  • Hook deployment automation
  • Hook management interface
  • Validation before deployment

Validation:

  • [ ] Can deploy hooks globally and per-project
  • [ ] Can list active hooks
  • [ ] Can validate hooks safely
  • [ ] Can remove/disable hooks

Time Estimate: 30-45 minutes


Operation 8: Security Audit Hooks

Purpose: Review all active hooks for security issues

Process:

  1. Audit All Hooks:

    # Scan all hook files
    for hook in ~/.claude/hooks/*.json .claude/hooks/*.json; do
      echo "Auditing: $hook"
    
      # Check for dangerous patterns
      if grep -q "rm -rf\|dd if\|curl.*sudo" $hook; then
        echo "⚠️  Dangerous command detected"
      fi
    
      # Check for credential leaks
      if grep -q "password\|secret\|token\|api_key" $hook; then
        echo "⚠️  Potential credential exposure"
      fi
    
      # Validate JSON structure
      jq empty $hook 2>/dev/null || echo "❌ Invalid JSON"
    done
  2. Generate Security Report:

    # Hook Security Audit
    
    ## Hooks Scanned: 8
    
    ### HIGH RISK
    None
    
    ### MEDIUM RISK
    1. observability-hook.json
       - Issue: Sends data to external URL
       - Recommendation: Validate URL is trusted
    
    ### LOW RISK
    2. formatting-hook.json
       - Info: Executes npx prettier (safe)
    
    ## Recommendations
    - Review observability destination
    - Consider encrypting telemetry data

Outputs:

  • Security audit report
  • Risk assessment
  • Recommendations

Validation:

  • [ ] All hooks scanned
  • [ ] Security issues identified
  • [ ] Recommendations provided

Time Estimate: 20-30 minutes


Hook Templates

Template 1: Auto-Format (PostToolUse)

{
  "event": "PostToolUse",
  "tools": ["Write", "Edit"],
  "description": "Auto-format code after Claude writes",
  "handler": {
    "command": "npx prettier --write \"$FILE\"",
    "timeout": 5000
  },
  "filters": {
    "filePatterns": ["**/*.{ts,tsx,js,jsx}"],
    "excludePatterns": ["node_modules/**", "dist/**", "build/**"]
  }
}

Impact: 92% reduction in style review time


Template 2: Security Gate (PreToolUse)

{
  "event": "PreToolUse",
  "tools": ["Write", "Edit", "Bash"],
  "description": "Block modifications to production files",
  "handler": {
    "command": ".claude/hooks/security-gate.sh \"$TOOL\" \"$FILE\" \"$COMMAND\""
  },
  "structuredOutput": true
}

Impact: Prevents accidental production damage


Template 3: Telemetry (Notification)

{
  "event": "Notification",
  "description": "Send telemetry on important events",
  "handler": {
    "command": ".claude/hooks/telemetry.sh \"$EVENT_TYPE\" \"$MESSAGE\""
  }
}

Impact: Full observability of AI agent behavior


Template 4: Validation (PreToolUse)

{
  "event": "PreToolUse",
  "tools": ["Write"],
  "description": "Validate JSON/YAML before writing",
  "handler": {
    "command": ".claude/hooks/validate-syntax.sh \"$FILE\" \"$CONTENT\""
  },
  "structuredOutput": true
}

Impact: Prevent invalid file writes


Template 5: Context Loading (SessionStart)

{
  "event": "SessionStart",
  "description": "Load project context on session start",
  "handler": {
    "command": ".claude/hooks/load-context.sh"
  }
}

Impact: Automatic context initialization


Template 6: Cleanup (SessionEnd)

{
  "event": "SessionEnd",
  "description": "Save state and cleanup on session end",
  "handler": {
    "command": ".claude/hooks/session-cleanup.sh"
  }
}

Impact: Automatic state preservation


Best Practices

1. Structured JSON Output (For Control)

Standard Exit Codes (Simple):

  • 0: Continue
  • Non-zero: Block

Structured JSON (Advanced):

{
  "continue": false,
  "stopReason": "Custom blocking reason shown to user",
  "suppressOutput": true
}

When to Use:

  • Need custom error messages
  • Want to suppress default output
  • Complex control flow

2. MCP Tool Targeting

Patterns:

  • mcp__*: All MCP tools
  • mcp__server__*: All tools from specific server
  • mcp__server__tool: Specific tool only

Examples:

// Block all filesystem MCP
"tools": ["mcp__filesystem__*"]

// Block specific GitHub operation
"tools": ["mcp__github__delete_repository"]

// Allow specific, block others
"tools": ["mcp__github__*"],
"handler": "allow-list-check.sh"

3. File Pattern Filters

{
  "filePatterns": [
    "src/**/*.ts",           // Include source files
    "tests/**/*.test.ts"     // Include tests
  ],
  "excludePatterns": [
    "node_modules/**",       // Exclude dependencies
    "**/*.min.js",           // Exclude minified
    ".git/**"                // Exclude git internals
  ]
}

Tip: Start inclusive, add exclusions as needed


4. Performance Considerations

Hook Execution:

  • Hooks run synchronously (blocking)
  • Keep handlers fast (<5 seconds)
  • Use timeouts to prevent hangs
  • Async operations: spawn background process, return immediately

Example (Fast hook):

#!/bin/bash
# Quick validation
if [ ! -f "$FILE" ]; then
  echo '{"continue": false, "stopReason": "File does not exist"}'
  exit 1
fi
echo '{"continue": true}'
exit 0

Example (Slow operation - backgrounded):

#!/bin/bash
# Start slow operation in background
(sleep 10 && heavy-operation.sh "$FILE") &

# Return immediately
echo '{"continue": true}'
exit 0

5. Security Best Practices

Never in hooks:

  • Hardcode credentials
  • Execute untrusted input
  • Modify critical system files
  • Expose sensitive data in logs

Always in hooks:

  • Validate all inputs
  • Use allowlists (not denylists)
  • Log security events
  • Fail securely (deny by default)

Common Hook Patterns

Pattern 1: Code Quality Enforcement

PostToolUse Chain:

Write/Edit → Prettier (format) → ESLint (lint) → TypeScript (type check)

Implementation:

[
  {
    "event": "PostToolUse",
    "tools": ["Write", "Edit"],
    "handler": "npx prettier --write \"$FILE\""
  },
  {
    "event": "PostToolUse",
    "tools": ["Write", "Edit"],
    "handler": "npx eslint --fix \"$FILE\""
  }
]

Result: All AI code automatically meets quality standards


Pattern 2: Test-on-Save

PostToolUse Test Runner:

{
  "event": "PostToolUse",
  "tools": ["Write", "Edit"],
  "description": "Run tests after code changes",
  "handler": {
    "command": ".claude/hooks/run-tests.sh \"$FILE\""
  },
  "filters": {
    "filePatterns": ["src/**/*.ts"]
  }
}

run-tests.sh:

#!/bin/bash
FILE=$1

# Find corresponding test file
TEST_FILE="${FILE/.ts/.test.ts}"
TEST_FILE="${TEST_FILE/src\//tests\/}"

if [ -f "$TEST_FILE" ]; then
  npm test -- "$TEST_FILE" --silent
fi

Result: Immediate test feedback on every change


Pattern 3: Security Guardrails

Multi-Layer Security:

PreToolUse → Path traversal check → Permission check → Allowlist check → Allow/Block

Result: Comprehensive security enforcement


Pattern 4: Observability Pipeline

Multi-Hook Telemetry:

SessionStart → Log session init
PreToolUse → Log tool attempts
PostToolUse → Log tool results + timing
Notification → Log important events
SessionEnd → Log session summary + metrics

Result: Complete observability of AI behavior


Troubleshooting

Hook Not Firing

Checklist:

  • [ ] Hook file in correct location (~/.claude/hooks/ or .claude/hooks/)
  • [ ] Hook file is valid JSON (test with jq empty hook.json)
  • [ ] Event type correct (UserPromptSubmit, PreToolUse, etc.)
  • [ ] Tool name matches (case-sensitive)
  • [ ] Claude Code version supports hooks (June 2025+)

Debug:

# Test hook JSON
jq empty .claude/hooks/my-hook.json

# Check hook location
ls -la .claude/hooks/

# Test handler command manually
bash .claude/hooks/handler.sh "test args"

Hook Blocking Everything

Issue: PreToolUse hook with {"continue": false} blocks all operations

Fix:

  • Check handler script logic
  • Ensure conditions are correct
  • Add fallback: if unsure, allow (fail open vs. fail closed)
  • Test with specific files before deploying

Performance Impact

Issue: Hook adds 2-5 seconds to every operation

Solutions:

  • Optimize handler script (remove slow operations)
  • Use background processes for slow tasks
  • Add caching (don't re-validate unchanged files)
  • Set timeout limits
  • Consider removing hook if not valuable

Appendix A: Hook Event Reference

UserPromptSubmit

Trigger: Before Claude processes user prompt Use: Validate prompts, inject context, enhance prompts Variables: $PROMPT

PreToolUse

Trigger: Before tool execution Use: Security gates, validation, logging Variables: $TOOL, $FILE, $COMMAND, $CONTENT Control: Can block operation

PostToolUse

Trigger: After tool execution Use: Auto-format, linting, testing, cleanup Variables: $TOOL, $FILE, $RESULT

PermissionRequest

Trigger: When Claude requests permissions Use: Auto-approve safe operations, log requests Variables: $PERMISSION_TYPE

Notification

Trigger: Important events Use: Telemetry, alerting, logging Variables: $EVENT_TYPE, $MESSAGE

SessionStart

Trigger: Session initialization Use: Load context, validate environment Variables: None

SessionEnd

Trigger: Session termination Use: Save state, cleanup, metrics Variables: None

Stop

Trigger: Conversation stop Use: Final cleanup, state saving Variables: $REASON


Appendix B: Structured JSON Control

Basic Control (Exit Codes)

# Allow
exit 0

# Block
exit 1

Advanced Control (JSON)

{
  "continue": boolean,        // Allow operation?
  "stopReason": "string",     // Why blocked (shown to user)
  "suppressOutput": boolean   // Hide default blocking message?
}

When to Use JSON:

  • Custom error messages
  • Silent blocking
  • Complex control logic

Quick Reference

The 8 Hook Events

Event When Use For Can Block?
UserPromptSubmit Before prompt processed Prompt validation/enhancement Yes
PreToolUse Before tool runs Security, validation Yes
PostToolUse After tool runs Format, lint, test No
PermissionRequest Permissions requested Auto-approve, logging Yes
Notification Important events Telemetry, alerts No
SessionStart Session begins Init, context load No
SessionEnd Session ends Cleanup, save state No
Stop Conversation stops Final cleanup No

Common Use Cases

Use Case Hook Event Typical Impact
Auto-format code PostToolUse 92% style review reduction
Security gates PreToolUse Prevent production damage
Run tests on save PostToolUse Immediate feedback
Observability Notification Full behavior tracking
JSON validation PreToolUse Prevent invalid writes
Context loading SessionStart Auto-initialization
State saving SessionEnd Preserve progress
MCP control PreToolUse Granular tool access

hooks-manager enables transformative automation in Claude Code through event-driven hooks, reducing manual work by up to 92% while enforcing security, quality, and observability standards.

For templates, see examples/. For troubleshooting, see Troubleshooting section.