cc-hooks-creator
This skill should be used when users want to create, configure, or debug Claude Code hooks. Hooks are shell commands that execute at various points in Claude Code's lifecycle (PreToolUse, PostToolUse, Stop, SessionStart, etc.). Use this skill when users ask to create custom automation, file protection, code formatting hooks, notifications, or any lifecycle-based triggers for Claude Code.
What this skill does
# Claude Code Hooks Creator
## Overview
This skill provides guidance for creating effective Claude Code hooks - shell commands that execute automatically at specific points in Claude Code's lifecycle. Hooks enable deterministic control over Claude's behavior, ensuring certain actions always happen rather than relying on the LLM to choose them.
## When to Use This Skill
- User wants to create a new hook for Claude Code
- User needs to automate actions before/after tool execution
- User wants file protection, code formatting, or notification hooks
- User needs to debug or fix existing hooks
- User wants to understand hook configuration and lifecycle events
## Hook Creation Workflow
### Phase 1: Understand Requirements
Before creating a hook, gather information:
1. **What action should happen?** (log, format, block, notify, validate)
2. **When should it trigger?** (before/after tool, on stop, session start/end)
3. **Which tools should it affect?** (Bash, Write, Edit, Read, all tools)
4. **What conditions apply?** (file types, patterns, always)
### Phase 2: Select Hook Event
Choose the appropriate hook event based on timing needs:
| Event | When It Runs | Common Use Cases |
|-------|--------------|------------------|
| `PreToolUse` | Before tool executes | Block operations, validate inputs, auto-approve |
| `PostToolUse` | After tool completes | Format files, log operations, validate output |
| `Stop` | When Claude finishes | Remind to store learnings, validate completion |
| `SubagentStop` | When subagent completes | Validate subagent output |
| `UserPromptSubmit` | When user submits prompt | Add context, validate prompts |
| `Notification` | On notifications | Custom notifications |
| `SessionStart` | Session begins | Load context, set environment |
| `SessionEnd` | Session ends | Cleanup, logging |
| `PreCompact` | Before context compact | Save important context |
### Phase 3: Design Hook Logic
#### Input Format (JSON via stdin)
All hooks receive JSON input with common fields:
```json
{
"session_id": "abc123",
"transcript_path": "/path/to/transcript.jsonl",
"cwd": "/current/directory",
"permission_mode": "default",
"hook_event_name": "EventName",
// Event-specific fields...
}
```
#### Output Format
**Simple: Exit Codes**
- Exit 0: Success (stdout shown in verbose mode)
- Exit 2: Blocking error (stderr shown to Claude)
- Other: Non-blocking error (stderr logged)
**Advanced: JSON Output** (exit code 0)
```json
{
"decision": "block",
"reason": "Explanation for Claude",
"hookSpecificOutput": {
"hookEventName": "PostToolUse",
"additionalContext": "Extra info for Claude"
}
}
```
### Phase 4: Implement the Hook
#### Option A: Inline Command (Simple)
For simple operations, use inline bash/jq:
```json
{
"hooks": {
"PreToolUse": [
{
"matcher": "Bash",
"hooks": [
{
"type": "command",
"command": "jq -r '.tool_input.command' >> ~/.claude/bash-log.txt"
}
]
}
]
}
}
```
#### Option B: Python Script (Complex)
For complex logic, create a Python script:
```python
#!/usr/bin/env python3
"""Hook script template for Claude Code."""
import json
import sys
def main():
try:
input_data = json.load(sys.stdin)
except json.JSONDecodeError as e:
print(f"Invalid JSON: {e}", file=sys.stderr)
sys.exit(1)
# Extract common fields
hook_event = input_data.get("hook_event_name", "")
tool_name = input_data.get("tool_name", "")
tool_input = input_data.get("tool_input", {})
# Your logic here...
# Option 1: Allow (exit 0, no output)
sys.exit(0)
# Option 2: Block with message to Claude (exit 2)
# print("Error message for Claude", file=sys.stderr)
# sys.exit(2)
# Option 3: JSON output for advanced control
# output = {"decision": "block", "reason": "My reason"}
# print(json.dumps(output))
# sys.exit(0)
if __name__ == "__main__":
main()
```
### Phase 5: Configure Hook in Settings
Add hook to `~/.claude/settings.json` (user) or `.claude/settings.json` (project):
```json
{
"hooks": {
"EventName": [
{
"matcher": "ToolPattern",
"hooks": [
{
"type": "command",
"command": "/path/to/hook-script.py",
"timeout": 30
}
]
}
]
}
}
```
**Matcher patterns:**
- Exact match: `"Write"` matches only Write tool
- Regex: `"Edit|Write"` matches Edit or Write
- All tools: `"*"` or `""`
### Phase 6: Test and Debug
1. Make script executable: `chmod +x /path/to/hook.py`
2. Test manually: `echo '{"tool_name":"Write"}' | /path/to/hook.py`
3. Run with debug: `claude --debug`
4. Check verbose output: `Ctrl+O` in Claude Code
## Common Hook Patterns
### File Protection Hook (PreToolUse)
Block edits to sensitive files:
```python
#!/usr/bin/env python3
import json
import sys
PROTECTED_PATTERNS = ['.env', 'package-lock.json', '.git/', 'credentials']
input_data = json.load(sys.stdin)
file_path = input_data.get('tool_input', {}).get('file_path', '')
if any(p in file_path for p in PROTECTED_PATTERNS):
print(f"Protected file: {file_path}", file=sys.stderr)
sys.exit(2)
sys.exit(0)
```
### Code Formatter Hook (PostToolUse)
Auto-format files after editing:
```python
#!/usr/bin/env python3
import json
import sys
import subprocess
input_data = json.load(sys.stdin)
file_path = input_data.get('tool_input', {}).get('file_path', '')
if file_path.endswith('.py'):
subprocess.run(['black', file_path], capture_output=True)
elif file_path.endswith(('.ts', '.tsx', '.js', '.jsx')):
subprocess.run(['npx', 'prettier', '--write', file_path], capture_output=True)
sys.exit(0)
```
### Stop Reminder Hook (Stop)
Remind to store learnings:
```python
#!/usr/bin/env python3
import json
import sys
import random
input_data = json.load(sys.stdin)
# Prevent infinite loops
if input_data.get('stop_hook_active'):
sys.exit(0)
# Trigger 30% of the time
if random.random() < 0.3:
output = {
"decision": "block",
"reason": "Consider storing any valuable learnings from this session using --store"
}
print(json.dumps(output))
sys.exit(0)
```
### Context Loader Hook (SessionStart)
Load context at session start:
```python
#!/usr/bin/env python3
import json
import sys
import os
# Read recent git changes
result = os.popen('git log --oneline -5 2>/dev/null').read()
output = {
"hookSpecificOutput": {
"hookEventName": "SessionStart",
"additionalContext": f"Recent commits:\\n{result}"
}
}
print(json.dumps(output))
sys.exit(0)
```
## Decision Control Reference
### PreToolUse Decisions
```json
{
"hookSpecificOutput": {
"hookEventName": "PreToolUse",
"permissionDecision": "allow|deny|ask",
"permissionDecisionReason": "Reason shown to user/Claude",
"updatedInput": {"field": "modified_value"}
}
}
```
### PostToolUse Decisions
```json
{
"decision": "block",
"reason": "Reason shown to Claude",
"hookSpecificOutput": {
"hookEventName": "PostToolUse",
"additionalContext": "Extra context for Claude"
}
}
```
### Stop/SubagentStop Decisions
```json
{
"decision": "block",
"reason": "Must continue because..."
}
```
## State Management Pattern
For hooks that need to track state across invocations:
```python
#!/usr/bin/env python3
import json
import sys
import os
from datetime import datetime
STATE_FILE = os.path.expanduser("~/.claude/hook_state.json")
def load_state():
if os.path.exists(STATE_FILE):
with open(STATE_FILE) as f:
return json.load(f)
return {"invocations": 0, "last_run": None}
def save_state(state):
with open(STATE_FILE, 'w') as f:
json.dump(state, f)
state = load_state()
state["invocations"] += 1
state["last_run"] = datetime.now().isoformat()
save_state(state)
# Use state in hook logic...
```
## Production-Ready Examples
This skill includes **reaRelated 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.