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
What this skill does
# 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
| Event | When It Fires | Can Block? | Supports Matchers? |
|-------|--------------|------------|-------------------|
| **PreToolUse** | Before tool executes | YES | YES (tool names) |
| **PermissionRequest** | Permission dialog shown | YES | YES (tool names) |
| **PostToolUse** | After tool succeeds | No | YES (tool names) |
| **Notification** | Claude sends notification | No | YES |
| **UserPromptSubmit** | User submits prompt | YES | No |
| **Stop** | Claude finishes responding | Can force continue | No |
| **SubagentStop** | Subagent finishes | Can force continue | No |
| **PreCompact** | Before context compaction | No | YES (manual/auto) |
| **SessionStart** | Session begins | No | YES (startup/resume/clear/compact) |
| **SessionEnd** | Session ends | No | No |
### Exit Code Semantics
| Exit Code | Meaning | Effect |
|-----------|---------|--------|
| **0** | Success | stdout parsed as JSON for control |
| **2** | Blocking error | **VETO** — stderr shown to Claude |
| **Other** | Non-blocking error | stderr 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
| Variable | Description |
|----------|-------------|
| `$CLAUDE_PROJECT_DIR` | Project root directory |
| `$CLAUDE_CODE_REMOTE` | Remote/local indicator |
| `$CLAUDE_ENV_FILE` | Environment persistence path (SessionStart) |
| `$CLAUDE_PLUGIN_ROOT` | Plugin directory (plugin hooks) |
### Key Commands
```bash
/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 Case | Best Event |
|----------|-----------|
| Block dangerous operations | PreToolUse |
| Auto-format code after writes | PostToolUse |
| Validate user prompts | UserPromptSubmit |
| Setup environment | SessionStart |
| Ensure task completion | Stop |
| Log all tool usage | PostToolUse with `"*"` matcher |
| Protect sensitive files | PreToolUse for Write/Edit |
| Add project context | UserPromptSubmit |
**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:**
```json
// 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:**
| Pattern | Matches |
|---------|---------|
| `"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):
```json
{
"type": "command",
"command": "echo \"$(date) | $tool_name\" >> ~/.claude/audit.log"
}
```
2. **External script** (complex logic, reusable):
```json
{
"type": "command",
"command": "\"$CLAUDE_PROJECT_DIR\"/.claude/hooks/validate.sh"
}
```
3. **Prompt-based** (LLM evaluation, intelligent decisions):
```json
{
"type": "prompt",
"prompt": "Analyze if all tasks are complete: $ARGUMENTS",
"timeout": 30
}
```
**Script Template (Bash):**
```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):**
```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:**
```bash
# 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**
```bash
# 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**
```bash
# Start Claude with debug mode
claude --debug
# Trigger the tool your hook targets
# Watch debug output for hook execution
```
**Step 4: Verification**
```bash
# Check hooks are registered
/hooks
# Watch hook execution
claude --debug 2>&1 | grep -i hook
```
---
## Hook Patterns
### Observer Pattern
LoRelated in AI Agents
skill-development
IncludedComprehensive meta-skill for creating, managing, validating, auditing, and distributing Claude Code skills and slash commands (unified in v2.1.3+). Provides skill templates, creation workflows, validation patterns, audit checklists, naming conventions, YAML frontmatter guidance, progressive disclosure examples, and best practices lookup. Use when creating new skills, validating existing skills, auditing skill quality, understanding skill architecture, needing skill templates, learning about YAML frontmatter requirements, progressive disclosure patterns, tool restrictions (allowed-tools), skill composition, skill naming conventions, troubleshooting skill activation issues, creating custom slash commands, configuring command frontmatter, using command arguments ($ARGUMENTS, $1, $2), bash execution in commands, file references in commands, command namespacing, plugin commands, MCP slash commands, Skill tool configuration, or deciding between skills vs slash commands. Delegates to docs-management skill for official documentation.
reprompter
IncludedTransform messy prompts into well-structured, effective prompts — single or multi-agent. Use when: "reprompt", "reprompt this", "clean up this prompt", "structure my prompt", rough text needing XML tags and best practices, "reprompter teams", "repromptception", "run with quality", "smart run", "smart agents", multi-agent tasks, audits, parallel work, anything going to agent teams. Don't use when: simple Q&A, pure chat, immediate execution-only tasks. See "Don't Use When" section for details. Outputs: Structured XML/Markdown prompt, quality score (before/after), optional team brief + per-agent sub-prompts, agent team output files. Success criteria: Single mode quality score ≥ 7/10; Repromptception per-agent prompt quality score 8+/10; all required sections present, actionable and specific.
adaptive-compaction
IncludedAdaptive add-on policy and recovery layer that decides WHEN to compact, prune, snapshot, or fork -- replacing fixed-percent auto-compaction across Claude Code, Codex, and MCP-capable hosts. Trigger on auto-compact timing or damage: "when should I compact", "is it safe to compact now or start a fresh session", "auto-compact fires too early/mid-task", "switching to an unrelated task but the window still has space", "context rot", "answers get worse the longer the session runs", "the agent forgot the plan or my decisions after it summarized", "add a layer on top that manages context without changing the agent", raising autoCompactWindow to give the policy room, or installing/tuning a cross-tool compaction policy or PreCompact hook -- even when "compaction" is never said but the problem is context-window pressure or post-summarization memory loss. Do NOT use to summarize a conversation, build RAG, write a summarization prompt (decides WHEN not HOW), or answer max-context-length trivia.
agent-skill-creator
IncludedCreate cross-platform agent skills from workflow descriptions. Activates when users ask to create an agent, automate a repetitive workflow, create a custom skill, or need advanced agent creation. Triggers on phrases like create agent for, automate workflow, create skill for, every day I have to, daily I need to, turn process into agent, need to automate, create a cross-platform skill, validate this skill, export this skill, migrate this skill. Supports single skills, multi-agent suites, transcript processing, template-based creation, interactive configuration, cross-platform export, and spec validation.
llm-wiki
IncludedUse when building or maintaining a persistent personal knowledge base (second brain) in Obsidian where an LLM incrementally ingests sources, updates entity/concept pages, maintains cross-references, and keeps a synthesis current. Triggers include "second brain", "Obsidian wiki", "personal knowledge management", "ingest this paper/article/book", "build a research wiki", "compound knowledge", "Memex", or whenever the user wants knowledge to accumulate across sessions instead of being re-derived by RAG on every query.
skill-master
IncludedAgent Skills authoring, evaluation, and optimization. Create, edit, validate, benchmark, and improve skills following the agentskills.io specification. Use when designing SKILL.md files, structuring skill folders (references, scripts, assets), ingesting external documentation into skills, running trigger evals, benchmarking skill quality, optimizing descriptions, or performing blind A/B comparisons. Keywords: agentskills.io, SKILL.md, skill authoring, eval, benchmark, trigger optimization.