MCPInstall

hooks-builder

Create event-driven hooks for Claude Code automation. Use when the user wants to create hooks, automate tool validation, add pre/post processing, enforce security policies, or configure settings.json hooks. Triggers: create hook, build hook, PreToolUse, PostToolUse, event automation, tool validation, security hook

Installs
46
Last 24h
—
Trending rank
—
Security
Not audited

Install

Works with every agent the skills CLI supports.

npx skills add https://github.com/mike-coulbourn/claude-vibes --skill hooks-builder
  1. 01

    Install

    Run the command in your project. The CLI asks which agents to install for.

  2. 02

    Describe the task

    Ask your agent for something this skill covers. It loads hooks-builder automatically when relevant.

  3. 03

    Review the result

    The agent follows the SKILL.md steps, scripts and references bundled with the skill.

SKILL.md

The instructions your agent reads when the skill is triggered.

Hooks Builder

A comprehensive guide for creating Claude Code hooks — event-driven automation that monitors and controls Claude's actions.

Quick Reference

The 10 Hook Events

EventWhen It FiresCan Block?Supports Matchers?
PreToolUseBefore tool executesYESYES (tool names)
PermissionRequestPermission dialog shownYESYES (tool names)
PostToolUseAfter tool succeedsNoYES (tool names)
NotificationClaude sends notificationNoYES
UserPromptSubmitUser submits promptYESNo
StopClaude finishes respondingCan force continueNo
SubagentStopSubagent finishesCan force continueNo
PreCompactBefore context compactionNoYES (manual/auto)
SessionStartSession beginsNoYES (startup/resume/clear/compact)
SessionEndSession endsNoNo

Exit Code Semantics

Exit CodeMeaningEffect
0Successstdout parsed as JSON for control
2Blocking errorVETO — stderr shown to Claude
OtherNon-blocking errorstderr logged in debug mode

Configuration Locations

~/.claude/settings.json          → Personal hooks (all projects)
.claude/settings.json            → Project hooks (team, committed)
.claude/settings.local.json      → Local overrides (not committed)

Essential Environment Variables

VariableDescription
$CLAUDE_PROJECT_DIRProject root directory
$CLAUDE_CODE_REMOTERemote/local indicator
$CLAUDE_ENV_FILEEnvironment persistence path (SessionStart)
$CLAUDE_PLUGIN_ROOTPlugin directory (plugin hooks)

Key Commands

/hooks              # View active hooks
claude --debug      # Enable debug logging
chmod +x script.sh  # Make script executable

6-Phase Workflow

Phase 1: Requirements Gathering

Use AskUserQuestion to clarify:

  1. What event should trigger this hook?

    • Tool execution (Pre/Post/Permission) → PreToolUse, PostToolUse, PermissionRequest
    • User input → UserPromptSubmit
    • Response completion → Stop, SubagentStop
    • Session lifecycle → SessionStart, SessionEnd
    • Context management → PreCompact
    • Notifications → Notification
  2. What should happen when triggered?

    • Observe only (logging, metrics)
    • Block/allow based on conditions
    • Modify inputs before execution
    • Add context to prompts
    • Force continuation
  3. Should it block, modify, or just observe?

    • Observer: PostToolUse, Notification, SessionEnd (can't block)
    • Gatekeeper: PreToolUse, PermissionRequest, UserPromptSubmit (can block)
    • Transformer: PreToolUse with updatedInput (can modify)
    • Controller: Stop, SubagentStop (can force continue)
  4. What are the security implications?

    • Will it handle untrusted input?
    • Could it expose sensitive data?
    • Does it need to access external systems?

Phase 2: Event Selection

Match event to use case:

Use CaseBest Event
Block dangerous operationsPreToolUse
Auto-format code after writesPostToolUse
Validate user promptsUserPromptSubmit
Setup environmentSessionStart
Ensure task completionStop
Log all tool usagePostToolUse with "*" matcher
Protect sensitive filesPreToolUse for Write/Edit
Add project contextUserPromptSubmit

Determine if matchers are needed:

  • Specific tools? → Use matcher: "Write|Edit"
  • All tools? → Use "*" or omit matcher
  • MCP tools? → Use mcp__server__tool pattern
  • Bash commands? → Use Bash(git:*) pattern

Phase 3: Matcher Design

Matcher Pattern Syntax:

// Exact match (case-sensitive!)
"matcher": "Write"

// OR pattern
"matcher": "Write|Edit"

// Prefix match
"matcher": "Notebook.*"

// Contains match
"matcher": ".*Read.*"

// All tools
"matcher": "*"

// MCP tools
"matcher": "mcp__memory__.*"

// Bash sub-patterns
"matcher": "Bash(git:*)"

Common Matcher Patterns:

PatternMatches
"Write"Only Write tool
"Write|Edit"Write OR Edit
"Bash"All Bash commands
"Bash(git:*)"Only git commands
"Bash(npm:*)"Only npm commands
"mcp__.*__.*"All MCP tools
".*" or "*"Everything

Phase 4: Implementation

Choose implementation approach:

  1. Inline command (simple, no external file):

    {
      "type": "command",
      "command": "echo \"$(date) | $tool_name\" >> ~/.claude/audit.log"
    }
    
  2. External script (complex logic, reusable):

    {
      "type": "command",
      "command": "\"$CLAUDE_PROJECT_DIR\"/.claude/hooks/validate.sh"
    }
    
  3. Prompt-based (LLM evaluation, intelligent decisions):

    {
      "type": "prompt",
      "prompt": "Analyze if all tasks are complete: $ARGUMENTS",
      "timeout": 30
    }
    

Script Template (Bash):

#!/bin/bash
set -euo pipefail

# Read JSON input from stdin
input=$(cat)

# Parse fields with jq
tool_name=$(echo "$input" | jq -r '.tool_name // empty')
file_path=$(echo "$input" | jq -r '.tool_input.file_path // empty')

# Your logic here
if [[ "$file_path" == *".env"* ]]; then
    echo "BLOCKED: Cannot modify .env files" >&2
    exit 2
fi

# Success - output decision
echo '{"decision": "approve"}'
exit 0

Script Template (Python):

#!/usr/bin/env python3
import sys
import json

# Read JSON input from stdin
data = json.load(sys.stdin)

# Extract fields
tool_name = data.get('tool_name', '')
tool_input = data.get('tool_input', {})
file_path = tool_input.get('file_path', '')

# Your logic here
if '.env' in file_path:
    print("BLOCKED: Cannot modify .env files", file=sys.stderr)
    sys.exit(2)

# Success - output decision
output = {"decision": "approve"}
print(json.dumps(output))
sys.exit(0)

Phase 5: Security Hardening

CRITICAL: Hooks execute shell commands with YOUR permissions.

Security Checklist:

  • All variables quoted: "$VAR" not $VAR
  • JSON parsed with jq or json.load (not grep/sed)
  • Paths validated (no .., normalized)
  • No sensitive data in logs/output
  • No sudo or privilege escalation
  • Script tested manually first
  • Project hooks audited before running
  • Timeout set appropriately
  • Error handling for all failure modes

Secure Patterns:

# UNSAFE - injection risk
rm $file_path

# SAFE - quoted, prevents flag injection
rm -- "$file_path"

# UNSAFE - parsing risk
cat "$input" | grep "field"

# SAFE - proper JSON parsing
echo "$input" | jq -r '.field'

Defense in Depth:

  1. Input validation (parse JSON properly)
  2. Path sanitization (normalize, check boundaries)
  3. Output sanitization (no sensitive data)
  4. Fail-safe defaults (block on error, not allow)
  5. Timeout protection (prevent infinite loops)

Phase 6: Testing

Step 1: Manual Script Testing

# Create mock input
cat > /tmp/mock-input.json << 'EOF'
{
  "session_id": "test-123",
  "hook_event_name": "PreToolUse",
  "tool_name": "Write",
  "tool_input": {
    "file_path": "/path/to/file.txt",
    "content": "test content"
  }
}
EOF

# Test script
cat /tmp/mock-input.json | ./my-hook.sh
echo "Exit code: $?"

Step 2: Edge Case Testing

  • Empty inputs: {}
  • Missing fields: {"tool_name": "Write"}
  • Malicious inputs: {"tool_input": {"file_path": "; rm -rf /"}}
  • Large inputs: 10KB+ content
  • Unicode: paths with special characters

Step 3: Integration Testing

# Start Claude with debug mode
claude --debug

# Trigger the tool your hook targets
# Watch debug output for hook execution

Step 4: Verification

# Check hooks are registered
/hooks

# Watch hook execution
claude --debug 2>&1 | grep -i hook

Hook Patterns

Observer Pattern

Log without blocking — use PostToolUse or Notification.

{
  "hooks": {
    "PostToolUse": [{
      "matcher": "*",
      "hooks": [{
        "type": "command",
        "command": "echo \"$(date) | $tool_name\" >> ~/.claude/audit.log"
      }]
    }]
  }
}

Gatekeeper Pattern

Block dangerous actions — use PreToolUse or PermissionRequest.

{
  "hooks": {
    "PreToolUse": [{
      "matcher": "Write|Edit",
      "hooks": [{
        "type": "command",
        "command": "python3 ~/.claude/hooks/file-protector.py"
      }]
    }]
  }
}

Transformer Pattern

Modify inputs before execution — use PreToolUse with updatedInput.

# In script, output:
output = {
    "hookSpecificOutput": {
        "hookEventName": "PreToolUse",
        "permissionDecision": "allow",
        "updatedInput": {
            "content": add_license_header(original_content)
        }
    }
}
print(json.dumps(output))

Orchestrator Pattern

Coordinate multiple events — combine SessionStart + PreToolUse + PostToolUse.

{
  "hooks": {
    "SessionStart": [{
      "matcher": "startup",
      "hooks": [{"type": "command", "command": "~/.claude/hooks/setup-env.sh"}]
    }],
    "PreToolUse": [{
      "matcher": "Write|Edit",
      "hooks": [{"type": "command", "command": "~/.claude/hooks/validate.sh"}]
    }],
    "PostToolUse": [{
      "matcher": "Write|Edit",
      "hooks": [{"type": "command", "command": "~/.claude/hooks/format.sh"}]
    }]
  }
}

Common Pitfalls

1. Forgetting Exit Code 2 for Blocking

# WRONG - exit 1 doesn't block
echo "Error" >&2
exit 1

# RIGHT - exit 2 blocks Claude
echo "BLOCKED: reason" >&2
exit 2

2. Case Sensitivity in Matchers

// WRONG - won't match "Write" tool
"matcher": "write"

// RIGHT - case-sensitive match
"matcher": "Write"

3. Unquoted Variables (Injection Risk)

# WRONG - command injection vulnerability
rm $file_path

# RIGHT - properly quoted
rm -- "$file_path"

4. Missing Shebang in Scripts

# WRONG - no shebang, may fail
set -euo pipefail

# RIGHT - explicit interpreter
#!/bin/bash
set -euo pipefail

5. Not Making Scripts Executable

# Don't forget!
chmod +x ~/.claude/hooks/my-hook.sh

6. Forgetting to Quote Paths in JSON

// WRONG - spaces in path will break
"command": "$CLAUDE_PROJECT_DIR/.claude/hooks/script.sh"

// RIGHT - quoted path
"command": "\"$CLAUDE_PROJECT_DIR\"/.claude/hooks/script.sh"

7. No Error Handling

# WRONG - silent failures
input=$(cat)
tool=$(echo "$input" | jq -r '.tool_name')

# RIGHT - handle errors
input=$(cat) || { echo "Failed to read input" >&2; exit 1; }
tool=$(echo "$input" | jq -r '.tool_name') || { echo "Failed to parse JSON" >&2; exit 1; }

8. Logging Sensitive Data

# WRONG - may log secrets
echo "Processing: $input" >> /tmp/debug.log

# RIGHT - sanitize before logging
echo "Processing tool: $tool_name" >> /tmp/debug.log

When to Use Hooks

USE hooks for:

  • Security enforcement (block dangerous operations)
  • Code quality automation (format, lint on save)
  • Compliance and auditing (log all actions)
  • Environment setup (consistent configuration)
  • Workflow automation (notifications, integrations)
  • Input validation (prompt checking)
  • Task completion verification

DON'T use hooks for:

  • Adding new capabilities (use Skills)
  • Delegating complex work (use Agents)
  • User-invoked prompts (use Commands)
  • Simple one-off tasks (just ask Claude)

Files in This Skill

Templates (Progressive Complexity)

  • templates/basic-hook.md — Single event, inline command
  • templates/with-scripts.md — External shell scripts
  • templates/with-decisions.md — Permission control, input modification
  • templates/with-prompts.md — LLM-based evaluation
  • templates/production-hooks.md — Complete multi-event system

Examples (18 Complete Hooks)

  • examples/security-hooks.md — Protection, validation, auditing
  • examples/quality-hooks.md — Formatting, linting, testing
  • examples/workflow-hooks.md — Setup, context, notifications

Reference

  • reference/syntax-guide.md — Complete JSON schemas, all events
  • reference/best-practices.md — Security, design, team deployment
  • reference/troubleshooting.md — 10 common issues, testing methodology

FAQ

What does the hooks-builder skill do?

Create event-driven hooks for Claude Code automation. Use when the user wants to create hooks, automate tool validation, add pre/post processing, enforce security policies, or configure settings.json hooks. Triggers: create hook, build hook, PreToolUse, PostToolUse, event automation, tool validation, security hook

How do I install hooks-builder?

Run npx skills add https://github.com/mike-coulbourn/claude-vibes --skill hooks-builder in your project. The skills CLI detects the agents you use and copies the skill into the right folder. For Claude Code you can also place the skill folder at ~/.claude/skills/hooks-builder/ (personal) or .claude/skills/hooks-builder/ (project).

Which AI agents can use hooks-builder?

Any agent that supports the open Agent Skills format (a folder with a SKILL.md file), including Claude Code, Codex, Cursor, GitHub Copilot, Gemini CLI, Windsurf, Cline, OpenCode and more.

Is hooks-builder safe to install?

No partner security audit is available yet. Skills can run commands and scripts, so read the SKILL.md and any bundled files before installing.

Who maintains hooks-builder?

It is published by mike-coulbourn in mike-coulbourn/claude-vibes. It has 46 recorded installs.

More from mike-coulbourn/claude-vibes

View all →

conversion-psychology

mike-coulbourn/claude-vibes

Use when optimizing sponsored or affiliate video scripts to convert, diagnosing why content is not driving action, or choosing which persuasion lever fits an offer. Keywords - buyer psychology, emotional triggers, social proof, scarcity, urgency, authority, reciprocity, loss aversion, why people buy.

Marketing & SEO516 installs

brand-naming-strategies

mike-coulbourn/claude-vibes

Use when naming or renaming a company, product, or startup, generating or scoring name candidates, or checking domain and trademark availability for a name. Keywords - brand name, naming strategy, SMILE and SCRATCH test, descriptive vs invented vs abstract names, sound symbolism, naming matrix, domain availability, trademark screening.

Marketing & SEO389 installs

ai-writing-detection

mike-coulbourn/claude-vibes

Comprehensive AI writing detection patterns and methodology. Provides vocabulary lists, structural patterns, model-specific fingerprints, and false positive prevention guidance. Use when analyzing text for AI authorship or understanding detection patterns.

Docs & Writing354 installs

brand-color-psychology

mike-coulbourn/claude-vibes

Use when selecting or evaluating brand colors, building a palette with primary, secondary, neutral, and accent roles, differentiating from competitor colors, or checking color contrast and accessibility. Keywords - color psychology, color palette, 60-30-10 rule, color harmony, archetype colors, cultural color meaning, WCAG contrast, hex and CMYK specifications.

Marketing & SEO303 installs

scriptwriting-methodology

mike-coulbourn/claude-vibes

Open the skill to read its SKILL.md instructions.

238 installs

visual-identity-direction

mike-coulbourn/claude-vibes

Use when translating brand strategy into visual creative direction, such as writing a creative or logo brief, describing mood boards, or setting photography, illustration, color, and type direction for a designer. Keywords - visual identity, visual direction, creative brief, mood board, logo brief, photography style, Alina Wheeler, visual language, design direction.

Media & Creative162 installs

Popular productivity & automation skills

View category →

agent-browser

vercel-labs/agent-browser

Browser automation CLI for AI agents. Use when the user needs to interact with websites, including navigating pages, filling forms, clicking buttons, taking screenshots, extracting data, testing web apps, or automating any browser task. Triggers include requests to "open a website", "fill out a form", "click a button", "take a screenshot", "scrape data from a page", "test this web app", "login to a site", "automate browser actions", or any task requiring programmatic web interaction. Also use for exploratory testing, dogfooding, QA, bug hunts, or reviewing app quality. Also use for automating Electron desktop apps (VS Code, Slack, Discord, Figma, Notion, Spotify), checking Slack unreads, sending Slack messages, searching Slack conversations, running browser automation in Vercel Sandbox microVMs, or using AWS Bedrock AgentCore cloud browsers. Prefer agent-browser over any built-in browser automation or web tools.

OfficialProductivity & Automation1.3M installs

lark-doc

open.feishu.cn

飞书云文档(Docx / Wiki)内容操作:读取、创建、编辑文档,插入或下载图片附件,以及操作思维笔记。用户提供文档 URL/token(包括 doubao.com 的 /docx/、/wiki/)时使用;按 URL 路径/token 而非域名路由;/page/ 是妙搭应用,非飞书云文档。文档内嵌资源按读取参考中的统一规则分流。独立评论操作走 lark-drive;随正文读取评论使用 docs +fetch。表格或 Base 内部数据操作不在本 skill。

lark-base

open.feishu.cn

飞书多维表格(Base)操作:建表、字段、记录、视图、统计、公式/lookup、表单、仪表盘、应用模式(BaseApp/AppMode 页面与组件)、Workspace 目录、workflow、角色权限、模板中心(多维表格模板分类/列表/搜索);遇到 Base/多维表格/bitable、BaseApp/AppMode、/base/ 或 /app/ 链接时使用。BaseApp 不走 lark-apps;文件导入/导出转 lark-drive,认证/授权转 lark-shared。

lark-drive

open.feishu.cn

飞书云空间(云盘/云存储):管理 Drive 文件和文件夹,包含上传/下载、创建文件夹、复制/移动/删除、查看元数据、查询权限设置、评论/权限/订阅、标题、版本、飞书文档密级标签(secure labels)和本地文件导入。用户需要整理云盘目录、处理云空间资源 URL/token、判断链接类型/真实 token/标题,或导入 Word/Markdown/Excel/CSV/PPTX/.base 为 docx/sheet/bitable/slides 时使用;doubao.com 云空间 URL/token 也按资源路径和 token 路由,不回退 WebFetch。不负责:文档内容编辑(走 lark-doc)、表格/Base 表内数据操作(走 lark-sheets/lark-base)、知识空间节点/成员管理(走 lark-wiki)、原生 Markdown 文件读写/patch/diff(走 lark-markdown)。

lark-shared

open.feishu.cn

Use for lark-cli setup/auth tasks: auth login/status/logout, user vs bot identity, business-domain permissions (--domain, including all/docs/drive), missing scopes, revoking authorization, or handling notice JSON.

lark-im

open.feishu.cn

飞书即时通讯:收发消息和管理群聊。发送和回复消息、搜索聊天记录、管理群聊成员、上传下载图片和文件、管理表情回复、发送应用内/短信/电话加急、发送和处理交互卡片(Interactive Card)、监听卡片按钮回调(card.action.trigger)。当用户需要发消息、查看或搜索聊天记录、下载聊天中的文件、查看群成员、搜索群、创建群聊或话题群、管理标记数据、管理 Feed 置顶(添加/移除/查询置顶会话)、管理标签数据、处理卡片回调时使用。