Create Claude Code hooks with proper patterns, security best practices, and configuration. Use this skill when building PreToolUse, PostToolUse, SessionStart, or other hook types for plugins.
/plugin marketplace add RBozydar/rbw-claude-code/plugin install core@rbw-claude-codeThis skill inherits all available tools. When active, it can use any tool Claude has access to.
templates/posttooluse-edit.pytemplates/pretooluse-bash.pytemplates/pretooluse-read.pytemplates/sessionstart.shThis skill provides comprehensive guidance for creating Claude Code hooks. Hooks intercept events in the Claude Code lifecycle and can validate, modify, or block operations.
Execute a script for deterministic checks. Best for pattern matching, validation, and blocking.
{
"type": "command",
"command": "${CLAUDE_PLUGIN_ROOT}/hooks/my-hook.py",
"timeout": 10
}
Use LLM reasoning for context-aware decisions. More expensive but can understand intent.
{
"type": "prompt",
"prompt": "Check if this operation is safe given the project context..."
}
Leverage agent capabilities for complex workflows requiring multiple steps.
| Event | Trigger | Common Uses |
|---|---|---|
PreToolUse | Before any tool executes | Block dangerous commands, validate inputs |
PostToolUse | After tool completes | Format code, run linters, log results |
SessionStart | When session begins | Check environment, load config |
SessionEnd | When session ends | Cleanup, save state |
Stop | When agent stops | Verify task completion |
SubagentStop | When subagent stops | Validate subagent work |
UserPromptSubmit | When user sends message | Process user input |
PreCompact | Before context compression | Preserve critical info |
Notification | System notifications | React to events |
PermissionRequest | Permission dialogs (v2.1.0) | Custom permission handling |
{
"hooks": {
"PreToolUse": [
{
"matcher": "Bash",
"hooks": [
{
"type": "command",
"command": "${CLAUDE_PLUGIN_ROOT}/hooks/check-bash.py",
"timeout": 10
}
]
}
],
"PostToolUse": [
{
"matcher": "Edit",
"hooks": [
{
"type": "command",
"command": "${CLAUDE_PLUGIN_ROOT}/hooks/format-on-save.py",
"timeout": 30
}
]
}
],
"SessionStart": [
{
"matcher": "*",
"hooks": [
{
"type": "command",
"command": "${CLAUDE_PLUGIN_ROOT}/hooks/init.sh",
"timeout": 5
}
]
}
]
}
}
"Bash" - Match specific tool by name"Edit" - Match Edit tool"Read" - Match Read tool"*" - Match all tools/events| Variable | Description |
|---|---|
CLAUDE_PLUGIN_ROOT | Plugin directory (use for portable paths) |
CLAUDE_PROJECT_DIR | Current project root |
CLAUDE_ENV_FILE | Persist variables from SessionStart |
Critical: Always use ${CLAUDE_PLUGIN_ROOT} in hook commands for portability.
#!/usr/bin/env -S uv run --script
# /// script
# dependencies = ["cchooks"]
# ///
"""Hook description."""
from cchooks import PreToolUseContext, create_context
c = create_context()
assert isinstance(c, PreToolUseContext)
# Check if this is the right tool
if c.tool_name != "Bash":
c.output.exit_success()
# Get tool input
command = c.tool_input.get("command", "")
# Your validation logic here
if is_dangerous(command):
c.output.exit_block("Reason for blocking")
c.output.exit_success()
PreToolUseContext - Before tool executionPostToolUseContext - After tool execution# Allow operation to proceed
c.output.exit_success()
# Block operation with message
c.output.exit_block("Descriptive reason for blocking")
# Modify tool input (PreToolUse only)
c.output.exit_modify({"command": modified_command})
if c.tool_name != "X": exit_success())# Check safe patterns before blocking
SAFE_PATTERNS = [
r"rm\s+-rf\s+/tmp/",
]
BLOCKED_PATTERNS = [
(r"rm\s+-rf\s+", "rm -rf is destructive"),
]
for pattern in SAFE_PATTERNS:
if re.search(pattern, command):
c.output.exit_success()
for pattern, reason in BLOCKED_PATTERNS:
if re.search(pattern, command):
c.output.exit_block(reason)
c.output.exit_block(
f"BLOCKED: {reason}\n"
f"Command: {command}\n"
"If this operation is truly needed, ask the user for permission."
)
Ready-to-use templates are available:
templates/pretooluse-bash.py - PreToolUse hook for Bash commandstemplates/pretooluse-read.py - PreToolUse hook for file readstemplates/posttooluse-edit.py - PostToolUse hook for formattingtemplates/sessionstart.sh - SessionStart initializationCopy and customize for your plugin:
cp ${CLAUDE_PLUGIN_ROOT}/skills/create-hook/templates/pretooluse-bash.py \
your-plugin/hooks/your-hook.py
mkdir -p plugins/my-hook/.claude-plugin
mkdir -p plugins/my-hook/hooks
{
"name": "my-hook",
"version": "1.0.0",
"description": "What this hook does"
}
{
"hooks": {
"PreToolUse": [
{
"matcher": "Bash",
"hooks": [
{
"type": "command",
"command": "${CLAUDE_PLUGIN_ROOT}/hooks/my-hook.py",
"timeout": 10
}
]
}
]
}
}
#!/usr/bin/env -S uv run --script
# /// script
# dependencies = ["cchooks"]
# ///
"""My hook description."""
from cchooks import PreToolUseContext, create_context
c = create_context()
assert isinstance(c, PreToolUseContext)
if c.tool_name != "Bash":
c.output.exit_success()
command = c.tool_input.get("command", "")
# Add your logic here
c.output.exit_success()
chmod +x plugins/my-hook/hooks/my-hook.py
claude plugin validate .
See plugins/safety-guard/hooks/safety_guard_bash.py
See plugins/conventional-commits/hooks/conventional_commits.py
See plugins/python-format/hooks/format_python.py
See plugins/protect-env/hooks/protect_env.py
echo '{"tool_name": "Bash", "tool_input": {"command": "rm -rf /"}}' | \
python plugins/my-hook/hooks/my-hook.py
Hooks should output JSON. Check stdout/stderr for errors.
cat plugins/my-hook/hooks/hooks.json | jq .
This skill should be used when the user asks to "create a slash command", "add a command", "write a custom command", "define command arguments", "use command frontmatter", "organize commands", "create command with file references", "interactive command", "use AskUserQuestion in command", or needs guidance on slash command structure, YAML frontmatter fields, dynamic arguments, bash execution in commands, user interaction patterns, or command development best practices for Claude Code.
This skill should be used when the user asks to "create an agent", "add an agent", "write a subagent", "agent frontmatter", "when to use description", "agent examples", "agent tools", "agent colors", "autonomous agent", or needs guidance on agent structure, system prompts, triggering conditions, or agent development best practices for Claude Code plugins.
This skill should be used when the user asks to "create a hook", "add a PreToolUse/PostToolUse/Stop hook", "validate tool use", "implement prompt-based hooks", "use ${CLAUDE_PLUGIN_ROOT}", "set up event-driven automation", "block dangerous commands", or mentions hook events (PreToolUse, PostToolUse, Stop, SubagentStop, SessionStart, SessionEnd, UserPromptSubmit, PreCompact, Notification). Provides comprehensive guidance for creating and implementing Claude Code plugin hooks with focus on advanced prompt-based hooks API.