This skill should be used when the user asks to "create a hook", "configure hooks", "validate hook configuration", "add a PreToolUse hook", "add a PostToolUse hook", "add a SessionStart hook", mentions hook events (PreToolUse, PostToolUse, Stop, SubagentStop, SessionStart, UserPromptSubmit, PermissionRequest, Notification, PreCompact, SessionEnd), or needs help with Claude Code hooks protocol. Provides comprehensive guidance for creating, configuring, and validating hooks following the official protocol specification.
Ships in example-skills. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
Read when SKILL.md points to them; scripts run unread.
Claude Code hooks are event-driven extensions that execute commands or LLM evaluations at specific lifecycle points. This skill provides guidance for creating production-ready hooks following the official protocol specification.
Command Hooks: Execute bash scripts with JSON input via stdin
{
"type": "command",
"command": "python3 /path/to/script.py",
"timeout": 60
}
Prompt-Based Hooks: Use LLM (Haiku) for intelligent evaluation
{
"type": "prompt",
"prompt": "Evaluate if Claude should stop: $ARGUMENTS",
"timeout": 30
}
| Event | Matcher | Purpose | Common Use Cases |
|---|---|---|---|
| PreToolUse | Yes | Before tool execution | Validation, modification, blocking |
| PermissionRequest | Yes | Permission dialog | Auto-approve/deny |
| PostToolUse | Yes | After tool execution | Formatting, validation |
| UserPromptSubmit | No | Before prompt processing | Context injection, validation |
| Stop/SubagentStop | No | Agent finishing | Determine if work complete |
| SessionStart | Yes | Session start/resume | Environment setup, context loading |
| SessionEnd | No | Session end | Cleanup, logging |
| Notification | Yes | Notifications sent | External alerting |
| PreCompact | Yes | Before compact | Validation, logging |
Hooks are configured in settings files (user, project, or local scope):
{
"hooks": {
"PreToolUse": [
{
"matcher": "Bash|Write|Edit",
"hooks": [
{
"type": "command",
"command": "$CLAUDE_PROJECT_DIR/.claude/hooks/validator.py",
"timeout": 30
}
]
}
]
}
}
Identify which lifecycle point to hook into:
Input Protocol: Hooks receive JSON via stdin with these common fields:
{
"session_id": "string",
"transcript_path": "string",
"cwd": "string",
"permission_mode": "default|plan|acceptEdits|bypassPermissions",
"hook_event_name": "EventName",
// Event-specific fields...
}
Output Protocol: Respond via exit codes and stdout:
Exit Code 0 (Success):
Exit Code 2 (Blocking):
Exit Code 1+ (Non-blocking):
Add to appropriate settings file:
~/.claude/settings.json - User-level.claude/settings.json - Project-level (team-shared).claude/settings.local.json - Local (git-ignored)Enable debug mode to see hook execution:
claude --debug
Use verbose mode (Ctrl+O) during session to see hook output.
Validate and potentially block tool calls:
#!/usr/bin/env python3
import json
import sys
# Read input
input_data = json.load(sys.stdin)
# Validate
if should_block(input_data):
print("Validation failed: reason", file=sys.stderr)
sys.exit(2) # Block execution
# Allow with optional modification
output = {
"hookSpecificOutput": {
"hookEventName": "PreToolUse",
"permissionDecision": "allow",
"updatedInput": {
"modified_field": "new_value"
}
}
}
print(json.dumps(output))
sys.exit(0)
Add context before Claude processes prompt:
#!/usr/bin/env python3
import json
import sys
import datetime
input_data = json.load(sys.stdin)
# Add context (plain text stdout with exit 0)
context = f"Current time: {datetime.datetime.now()}\n"
context += f"Current directory: {input_data['cwd']}"
print(context)
sys.exit(0)
Initialize environment variables and context:
#!/bin/bash
# Setup environment
source ~/.nvm/nvm.sh
nvm use 20
# Persist variables
if [ -n "$CLAUDE_ENV_FILE" ]; then
echo 'export NODE_ENV=production' >> "$CLAUDE_ENV_FILE"
echo 'export PATH="$PATH:./node_modules/.bin"' >> "$CLAUDE_ENV_FILE"
fi
# Add context
echo "Environment initialized: Node $(node --version)"
exit 0
Use LLM for context-aware decisions:
{
"hooks": {
"Stop": [
{
"hooks": [
{
"type": "prompt",
"prompt": "Context: $ARGUMENTS\n\nDetermine if all tasks are complete. Check for:\n1. All user requests fulfilled\n2. No errors requiring fixes\n3. Tests passing\n\nRespond: {\"decision\": \"approve\" or \"block\", \"reason\": \"explanation\"}"
}
]
}
]
}
}
Matchers determine when hooks execute (PreToolUse, PostToolUse, PermissionRequest, Notification, PreCompact, SessionStart):
Exact match: "matcher": "Write" - Only Write tool
Regex: "matcher": "Edit|Write" - Multiple tools
All tools: "matcher": "*" or "matcher": ""
MCP tools: "matcher": "mcp__github__.*" - All GitHub server tools
Available in all hooks:
CLAUDE_PROJECT_DIR - Project root directoryCLAUDE_CODE_REMOTE - "true" if web environmentSessionStart hooks only:
CLAUDE_ENV_FILE - File path for persisting environment variablesPlugin hooks only:
CLAUDE_PLUGIN_ROOT - Plugin directoryInput Validation: Always validate and sanitize inputs
if '..' in file_path or file_path.startswith('/'):
print("Path traversal detected", file=sys.stderr)
sys.exit(2)
Shell Safety: Quote all variables
command="$CLAUDE_PROJECT_DIR/script.sh"
Sensitive Files: Skip .env, .git/, keys, etc.
sensitive = ['.env', '.git/', 'id_rsa', '*.pem']
if any(p in file_path for p in sensitive):
sys.exit(2)
Hook not executing:
/hooks commandclaude --debugHook timing out:
JSON parsing errors:
jqPermission denied:
chmod +x script.sh$CLAUDE_PROJECT_DIR| Event | Allow Action | Block Action | Modify Input |
|---|---|---|---|
| PreToolUse | permissionDecision: "allow" | permissionDecision: "deny" | updatedInput: {} |
| PermissionRequest | behavior: "allow" | behavior: "deny" | updatedInput: {} |
| PostToolUse | - | decision: "block" | - |
| UserPromptSubmit | - | decision: "block" | - |
| Stop/SubagentStop | - | decision: "block" | - |
| Code | stdout | stderr | Continues |
|---|---|---|---|
| 0 | Parsed as JSON/text | Ignored | Yes |
| 2 | Ignored | Fed to Claude/User | Depends |
| Other | Ignored | Logged | Yes |
For detailed protocol specifications:
references/protocol-specification.md - Complete protocol documentationreferences/event-reference.md - Detailed event specificationsFor working examples:
examples/pretooluse-validator/ - Bash command validationexamples/userprompt-enricher/ - Context injectionexamples/sessionstart-setup/ - Environment initializationexamples/stop-evaluator/ - Prompt-based decision makingFor validation and testing:
scripts/validate-hook-config.py - Validate hooks.json against schemascripts/test-hook-io.py - Test hook input/output locallyscripts/generate-hook-template.sh - Generate hook boilerplateFor schema validation:
assets/hooks-schema.json - JSON schema for hooks configurationINSTALLATION.md (opens in a new tab)README.md (opens in a new tab)SKILL_SUMMARY.md (opens in a new tab)TEST_RESULTS.md (opens in a new tab)assets/hooks-schema.json (opens in a new tab)examples/pretooluse-validator/README.md (opens in a new tab)examples/pretooluse-validator/validator.py (opens in a new tab)examples/sessionstart-setup/README.md (opens in a new tab)examples/sessionstart-setup/setup.sh (opens in a new tab)examples/stop-evaluator/README.md (opens in a new tab)examples/userprompt-enricher/README.md (opens in a new tab)examples/userprompt-enricher/enricher.py (opens in a new tab)references/event-reference.md (opens in a new tab)references/protocol-specification.md (opens in a new tab)scripts/generate-hook-template.sh (opens in a new tab)scripts/test-hook-io.py (opens in a new tab)scripts/validate-hook-config.py (opens in a new tab)tests/README.md (opens in a new tab)tests/fixtures/invalid/extra-properties.json (opens in a new tab)tests/fixtures/invalid/hooks-not-array.json (opens in a new tab)What SKILL.md sets; muted values are Claude Code's defaults
Other plugins' skills for the same job
12 skills in this plugin
/claude-subagent-developmentThis skill should be used when the user asks to "create a subagent", "validate a subagent", "generate subagent schema", "check subagent configuration", "write subagent specification", or mentions subagent development, validation, or protocol documentation for Claude Code./codex-cliUse when the user asks to run Codex CLI (codex exec, codex resume) or references OpenAI Codex for code analysis, refactoring, or automated editing/fabric-aiGuides pattern selection through decomposition, exploration, and diverse approach generation/rafaelcalleja-example-skills-skills:hooks-masteryfrom example-skills
Claude Code refuses to install this plugin
Claude Code refuses to add this marketplace: name: Marketplace name impersonates an official Anthropic/Claude marketplace
Checked against Claude Code 2.1.332's install rules. The listing below is what the repository ships; Claude Code cannot install it as published.