Use when creating or publishing Claude Code hooks - covers executable format, event types, JSON I/O, exit codes, security requirements, and PRPM package structure
Use this skill when creating, improving, or publishing Claude Code hooks. Provides essential guidance on hook format, event handling, I/O conventions, and package structure.
Activate this skill when:
Method 1: JSON Configuration (Recommended)
.claude/settings.json, ~/.claude/settings.json, or plugin's hooks.jsonMethod 2: Executable Files (Legacy)
.claude/hooks/<event-name>| Type | Description | Speed | Use Case | |------|-------------|-------|----------| | Command | Runs external script | Fast (ms) | Formatting, logging, file checks | | Prompt | Uses LLM reasoning | Slow (2-10s) | Complex validation, security analysis |
| Event | When It Fires | Can Block? | Common Use Cases |
|-------|---------------|------------|------------------|
| PreToolUse | Before tool execution | Yes (exit 2) | Validation, permission checks, input modification |
| PostToolUse | After tool completes | No | Formatting, logging, cleanup |
| UserPromptSubmit | Before user input processes | Yes | Prompt validation, enhancement |
| SessionStart | New session begins | No | Environment setup, context loading |
| Stop | When assistant finishes | No | Cleanup, summary, verification |
| SubagentStop | When subagent finishes | No | Subagent result processing |
| PreCompact | Before context compaction | No | Save important context |
| Notification | During alerts | No | Desktop notifications, logging |
| PermissionRequest | When permission needed | Yes | Custom permission handling |
| Code | Meaning | Behavior |
|------|---------|----------|
| 0 | Success | Continue normally |
| 2 | Block | Stop operation (PreToolUse only) |
| 1 or other | Error | Log error, continue |
Configure hooks in .claude/settings.json (project) or ~/.claude/settings.json (global):
{
"hooks": {
"PreToolUse": [{
"matcher": "Write|Edit",
"hooks": [{
"type": "command",
"command": "/path/to/validate-write.sh",
"timeout": 5000
}]
}],
"PostToolUse": [{
"matcher": "Write|Edit",
"hooks": [{
"type": "command",
"command": "/path/to/format-file.sh"
}]
}],
"Stop": [{
"matcher": "*",
"hooks": [{
"type": "prompt",
"prompt": "Verify all requested changes were completed."
}]
}]
}
}
For PRPM packages, use hook.json:
{
"hooks": {
"PreToolUse": [{
"matcher": "Write",
"hooks": [{
"type": "command",
"command": "${CLAUDE_PLUGIN_ROOT}/scripts/validate.sh",
"timeout": 5000
}]
}]
}
}
| Pattern | Matches |
|---------|---------|
| "Write" | Only Write tool |
| "Write\|Edit" | Write OR Edit tools |
| "Bash" | Only Bash tool |
| "mcp__github__*" | All GitHub MCP tools |
| "*" | All tools (use sparingly) |
{
"type": "command",
"command": "./my-hook.sh",
"timeout": 5000,
"once": true,
"continue": true,
"stopReason": "Message when blocked",
"suppressOutput": false,
"systemMessage": "Warning to show user"
}
| Option | Type | Default | Description |
|--------|------|---------|-------------|
| timeout | number | 60000 | Max execution time in ms |
| once | boolean | false | Run only once per session |
| continue | boolean | true | Continue after hook completes |
| stopReason | string | - | Message when continue=false |
| suppressOutput | boolean | false | Hide stdout from transcript |
| systemMessage | string | - | Warning message to user |
Command hooks run external scripts. They're fast and deterministic.
#!/bin/bash
set -euo pipefail
# Read JSON input
INPUT=$(cat)
FILE=$(echo "$INPUT" | jq -r '.input.file_path // empty')
# Validate
[[ -n "$FILE" ]] || exit 0
[[ -f "$FILE" ]] || exit 0
# Block sensitive files
case "$FILE" in
*.env|*.pem|*.key)
echo "Blocked: $FILE is sensitive" >&2
exit 2
;;
esac
exit 0
#!/usr/bin/env node
import { readFileSync } from 'fs';
const input = JSON.parse(readFileSync(0, 'utf-8'));
const filePath = input.input?.file_path;
if (!filePath) process.exit(0);
// Block .env files
if (filePath.endsWith('.env')) {
console.error('Blocked: Cannot modify .env files');
process.exit(2);
}
process.exit(0);
Prompt hooks use LLM reasoning for complex validation. Use sparingly - they take 2-10 seconds.
{
"hooks": {
"PreToolUse": [{
"matcher": "Write",
"hooks": [{
"type": "prompt",
"prompt": "Check if the content being written contains hardcoded secrets, API keys, or credentials. If found, block the operation."
}]
}]
}
}
{
"hooks": {
"PreToolUse": [{
"matcher": "Write|Edit",
"hooks": [{
"type": "prompt",
"prompt": "Analyze the file content for security issues. Return your decision.",
"schema": {
"type": "object",
"properties": {
"decision": {
"type": "string",
"enum": ["allow", "block"]
},
"reason": {
"type": "string"
},
"severity": {
"type": "string",
"enum": ["low", "medium", "high", "critical"]
}
},
"required": ["decision"]
}
}]
}]
}
}
Good use cases:
Avoid for:
Simpler approach - place executables directly in hooks directory.
Project hooks:
.claude/hooks/PreToolUse
.claude/hooks/PostToolUse
.claude/hooks/SessionStart
User-global hooks:
~/.claude/hooks/PreToolUse
~/.claude/hooks/Stop
Every file-based hook MUST:
#!/bin/bash
#!/usr/bin/env node
#!/usr/bin/env python3
chmod +x .claude/hooks/PreToolUse
Handle JSON input from stdin
Exit with appropriate code
Hooks receive JSON via stdin:
{
"session_id": "abc123",
"transcript_path": "/path/to/transcript.jsonl",
"current_dir": "/path/to/project",
"tool_name": "Write",
"input": {
"file_path": "/path/to/file.ts",
"content": "file contents...",
"command": "npm test",
"old_string": "...",
"new_string": "..."
}
}
| Tool | Available Fields |
|------|------------------|
| Write | file_path, content |
| Edit | file_path, old_string, new_string |
| Read | file_path |
| Bash | command |
| Glob | pattern, path |
| Grep | pattern, path |
Available in hook execution:
| Variable | Description |
|----------|-------------|
| CLAUDE_PROJECT_DIR | Project root directory |
| CLAUDE_CURRENT_DIR | Current working directory |
| CLAUDE_PLUGIN_ROOT | Hook installation directory |
| CLAUDE_ENV_FILE | File for persisting variables |
| SESSION_ID | Current session identifier |
{
"hooks": {
"PostToolUse": [{
"matcher": "Write|Edit",
"hooks": [{
"type": "command",
"command": "${CLAUDE_PLUGIN_ROOT}/scripts/format.sh",
"timeout": 5000
}]
}]
}
}
{
"hooks": {
"PreToolUse": [{
"matcher": "Write|Edit|Read",
"hooks": [{
"type": "command",
"command": "${CLAUDE_PLUGIN_ROOT}/scripts/block-sensitive.sh"
}]
}]
}
}
{
"hooks": {
"Stop": [{
"matcher": "*",
"hooks": [{
"type": "prompt",
"prompt": "Before finishing, verify: 1) All tests pass 2) No linting errors 3) Types check. If any issues, list them."
}]
}]
}
}
{
"hooks": {
"SessionStart": [{
"matcher": "*",
"hooks": [{
"type": "command",
"command": "${CLAUDE_PLUGIN_ROOT}/scripts/load-context.sh",
"once": true
}]
}]
}
}
Combine PreToolUse (validate) with PostToolUse (verify):
{
"hooks": {
"PreToolUse": [{
"matcher": "Write",
"hooks": [{
"type": "command",
"command": "./validate-before.sh"
}]
}],
"PostToolUse": [{
"matcher": "Write",
"hooks": [{
"type": "command",
"command": "./verify-after.sh"
}]
}]
}
}
| Mistake | Problem | Solution |
|---------|---------|----------|
| Not quoting variables | Breaks on spaces | Always use "$VAR" |
| Missing shebang | Won't execute | Add #!/bin/bash |
| Not executable | Permission denied | Run chmod +x hook-file |
| Logging to stdout | Clutters transcript | Use stderr: echo "log" >&2 |
| Wrong exit code | Doesn't block when needed | Use exit 2 to block |
| No input validation | Security risk | Always validate JSON fields |
| Slow operations | Blocks Claude | Run in background or use PostToolUse |
| Absolute paths missing | Can't find scripts | Use ${CLAUDE_PLUGIN_ROOT} |
| Using * matcher | Runs on everything | Be specific: Write\|Edit |
| Prompt hooks everywhere | Slow experience | Use only for complex logic |
Target < 100ms for PreToolUse hooks:
# Check dependencies exist
if ! command -v jq &> /dev/null; then
echo "jq not installed, skipping" >&2
exit 0
fi
# Validate input
FILE=$(echo "$INPUT" | jq -r '.input.file_path // empty')
if [[ -z "$FILE" ]]; then
echo "No file path provided" >&2
exit 1
fi
Always start with shebang:
#!/bin/bash
#!/usr/bin/env node
#!/usr/bin/env python3
BLOCKED=(".env" ".env.*" "*.pem" "*.key")
for pattern in "${BLOCKED[@]}"; do
case "$FILE" in
$pattern)
echo "Blocked: $FILE is sensitive" >&2
exit 2
;;
esac
done
# WRONG - breaks on spaces
prettier --write $FILE
# RIGHT - handles spaces
prettier --write "$FILE"
LOG_FILE=~/.claude-hooks/debug.log
# Log to file
echo "[$(date)] Processing $FILE" >> "$LOG_FILE"
# Log to stderr (shows in transcript)
echo "Hook running..." >&2
my-hook/
├── prpm.json # Package manifest
├── HOOK.md # Hook documentation
└── hook-script.sh # Hook executable
{
"name": "@username/hook-name",
"version": "1.0.0",
"description": "Brief description shown in search",
"author": "Your Name",
"format": "claude",
"subtype": "hook",
"tags": ["automation", "security", "formatting"],
"main": "HOOK.md"
}
---
name: session-logger
description: Logs session start/end times for tracking
event: SessionStart
language: bash
hookType: hook
---
# Session Logger Hook
Logs Claude Code session activity for tracking and debugging.
## Installation
This hook will be installed to `.claude/hooks/session-start`.
## Behavior
- Logs session start time to `~/.claude/session.log`
- Displays environment status
- Runs silent dependency checks
## Requirements
- bash 4.0+
- write access to `~/.claude/`
## Source Code
\`\`\`bash
#!/bin/bash
echo "Session started at $(date)" >> ~/.claude/session.log
echo "Environment ready"
exit 0
\`\`\`
# Test locally first
prpm test
# Publish to registry
prpm publish
# Version bumps
prpm publish patch # 1.0.0 -> 1.0.1
prpm publish minor # 1.0.0 -> 1.1.0
prpm publish major # 1.0.0 -> 2.0.0
# Parse JSON safely
INPUT=$(cat)
if ! FILE=$(echo "$INPUT" | jq -r '.input.file_path // empty' 2>&1); then
echo "JSON parse failed" >&2
exit 1
fi
# Validate field exists
[[ -n "$FILE" ]] || exit 1
# Prevent directory traversal
if [[ "$FILE" == *".."* ]]; then
echo "Path traversal detected" >&2
exit 2
fi
# Keep in project directory
if [[ "$FILE" != "$CLAUDE_PROJECT_DIR"* ]]; then
echo "File outside project" >&2
exit 2
fi
Claude Code automatically:
| Feature | Hooks | Skills | Commands |
|---------|-------|--------|----------|
| Format | Executable code | Markdown | Markdown |
| Trigger | Automatic (events) | Automatic (context) | Manual (/command) |
| Language | Any executable | N/A | N/A |
| Use Case | Automation, validation | Reference, patterns | Quick tasks |
| Security | Requires confirmation | No special permissions | Inherits from session |
Examples:
/review-pr quick code reviewBefore publishing:
chmod +x)Search for places (restaurants, cafes, etc.) via Google Places API proxy on localhost.
Interact with GitHub using the `gh` CLI. Use `gh issue`, `gh pr`, `gh run`, and `gh api` for issues, PRs, CI runs, and advanced queries.
Create or update AgentSkills. Use when designing, structuring, or packaging skills with scripts, references, and assets.
Start voice calls via the OpenClaw voice-call plugin.
Notion API for creating and managing pages, databases, and blocks.
Gemini CLI for one-shot Q&A, summaries, and generation.
Category:developer