Generated banner for Hook Development
Generated logo for Hook Development

Hook Development

AnthropicOfficialPublished by Anthropic

  • Skill
  • Tool integration
  • Agent tooling
  • Apache-2.0
  • Low risk
  • Has scripts

From the author

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.
— the description by Anthropic

AutoGineer summary

Written by AutoGineer from the skill’s own files, not by the author

This skill provides a framework for developing event-driven hooks for Claude Code. It covers both prompt-based hooks, which leverage LLM reasoning for context-aware validation, and command-based hooks for deterministic bash-scripted checks. The guide details configuration formats for plugins and user settings, event types, input/output structures, and security best practices for building robust, portable automation.

What it does

  • Defines event-driven hooks for Claude Code lifecycle events like PreToolUse and SessionStart.
  • Supports prompt-based hooks for intelligent, context-aware decision making.
  • Supports command-based hooks for fast, deterministic bash-scripted validations.
  • Provides configuration patterns for both plugin-specific and user-level settings.
  • Outlines security practices for input validation and path safety in hooks.
  • Offers debugging techniques and lifecycle management for hook development.

When to use it

  • When you need to validate or modify tool calls before they execute.
  • When you want to enforce project-specific policies or security constraints.
  • When you need to automate environment setup or cleanup at session start/end.
  • When you want to add context-aware reasoning to agent workflows.
  • When you need to block dangerous commands or prevent unauthorized file access.

Advantages

  • Enables flexible, context-aware validation using LLM reasoning.
  • Supports portable configurations using environment variables like CLAUDE_PLUGIN_ROOT.
  • Allows for layered validation by combining command and prompt hooks.
  • Provides structured output formats for clear agent-hook communication.
  • Facilitates robust security enforcement through customizable hook logic.

Usage examples

“How do I create a PreToolUse hook to block dangerous bash commands?”
The agent will guide you to define a PreToolUse hook in your hooks.json, using either a prompt-based hook to analyze command intent or a command-based hook to run a validation script.
“How can I load project-specific environment variables when a session starts?”
The agent will explain how to implement a SessionStart hook using a command script that writes to the $CLAUDE_ENV_FILE.
“What is the difference between the plugin hooks.json and user settings format?”
The agent will clarify that plugin hooks require a 'hooks' wrapper field, while user settings in .claude/settings.json use a direct event-based structure.
“How do I test my hook configuration before deploying it?”
The agent will instruct you to use the provided test scripts and run Claude Code with the --debug flag to inspect hook execution logs.

Install

  1. Download the skill as a ZIP:

    https://mp-staging.autogineer.com/agent-skills/anthropics/hook-development/download
  2. Unzip it into the cross-client skills folder of your project:

    mkdir -p .agents/skills && unzip hook-development.zip -d .agents/skills

Documentation by Anthropic

Hook Development for Claude Code Plugins

Overview

Hooks are event-driven automation scripts that execute in response to Claude Code events. Use hooks to validate operations, enforce policies, add context, and integrate external tools into workflows.

Key capabilities:

  • Validate tool calls before execution (PreToolUse)

  • React to tool results (PostToolUse)

  • Enforce completion standards (Stop, SubagentStop)

  • Load project context (SessionStart)

  • Automate workflows across the development lifecycle

Hook Types

Use LLM-driven decision making for context-aware validation:

{
  "type": "prompt",
  "prompt": "Evaluate if this tool use is appropriate: $TOOL_INPUT",
  "timeout": 30
}

Supported events: Stop, SubagentStop, UserPromptSubmit, PreToolUse

Benefits:

  • Context-aware decisions based on natural language reasoning

  • Flexible evaluation logic without bash scripting

  • Better edge case handling

  • Easier to maintain and extend

Command Hooks

Execute bash commands for deterministic checks:

{
  "type": "command",
  "command": "bash ${CLAUDE_PLUGIN_ROOT}/scripts/validate.sh",
  "timeout": 60
}

Use for:

  • Fast deterministic validations

  • File system operations

  • External tool integrations

  • Performance-critical checks

Hook Configuration Formats

Plugin hooks.json Format

For plugin hooks in hooks/hooks.json, use wrapper format:

{
  "description": "Brief explanation of hooks (optional)",
  "hooks": {
    "PreToolUse": [...],
    "Stop": [...],
    "SessionStart": [...]
  }
}

Key points:

  • description field is optional

  • hooks field is required wrapper containing actual hook events

  • This is the plugin-specific format

Example:

{
  "description": "Validation hooks for code quality",
  "hooks": {
    "PreToolUse": [
      {
        "matcher": "Write",
        "hooks": [
          {
            "type": "command",
            "command": "${CLAUDE_PLUGIN_ROOT}/hooks/validate.sh"
          }
        ]
      }
    ]
  }
}
Settings Format (Direct)

For user settings in .claude/settings.json, use direct format:

{
  "PreToolUse": [...],
  "Stop": [...],
  "SessionStart": [...]
}

Key points:

  • No wrapper - events directly at top level

  • No description field

  • This is the settings format

Important: The examples below show the hook event structure that goes inside either format. For plugin hooks.json, wrap these in {"hooks": {...}}.

Hook Events

PreToolUse

Execute before any tool runs. Use to approve, deny, or modify tool calls.

Example (prompt-based):

{
  "PreToolUse": [
    {
      "matcher": "Write|Edit",
      "hooks": [
        {
          "type": "prompt",
          "prompt": "Validate file write safety. Check: system paths, credentials, path traversal, sensitive content. Return 'approve' or 'deny'."
        }
      ]
    }
  ]
}

Output for PreToolUse:

{
  "hookSpecificOutput": {
    "permissionDecision": "allow|deny|ask",
    "updatedInput": {"field": "modified_value"}
  },
  "systemMessage": "Explanation for Claude"
}
PostToolUse

Execute after tool completes. Use to react to results, provide feedback, or log.

Example:

{
  "PostToolUse": [
    {
      "matcher": "Edit",
      "hooks": [
        {
          "type": "prompt",
          "prompt": "Analyze edit result for potential issues: syntax errors, security vulnerabilities, breaking changes. Provide feedback."
        }
      ]
    }
  ]
}

Output behavior:

  • Exit 0: stdout shown in transcript

  • Exit 2: stderr fed back to Claude

  • systemMessage included in context

Stop

Execute when main agent considers stopping. Use to validate completeness.

Example:

{
  "Stop": [
    {
      "matcher": "*",
      "hooks": [
        {
          "type": "prompt",
          "prompt": "Verify task completion: tests run, build succeeded, questions answered. Return 'approve' to stop or 'block' with reason to continue."
        }
      ]
    }
  ]
}

Decision output:

{
  "decision": "approve|block",
  "reason": "Explanation",
  "systemMessage": "Additional context"
}
SubagentStop

Execute when subagent considers stopping. Use to ensure subagent completed its task.

Similar to Stop hook, but for subagents.

UserPromptSubmit

Execute when user submits a prompt. Use to add context, validate, or block prompts.

Example:

{
  "UserPromptSubmit": [
    {
      "matcher": "*",
      "hooks": [
        {
          "type": "prompt",
          "prompt": "Check if prompt requires security guidance. If discussing auth, permissions, or API security, return relevant warnings."
        }
      ]
    }
  ]
}
SessionStart

Execute when Claude Code session begins. Use to load context and set environment.

Example:

{
  "SessionStart": [
    {
      "matcher": "*",
      "hooks": [
        {
          "type": "command",
          "command": "bash ${CLAUDE_PLUGIN_ROOT}/scripts/load-context.sh"
        }
      ]
    }
  ]
}

Special capability: Persist environment variables using $CLAUDE_ENV_FILE:

echo "export PROJECT_TYPE=nodejs" >> "$CLAUDE_ENV_FILE"

See examples/load-context.sh for complete example.

SessionEnd

Execute when session ends. Use for cleanup, logging, and state preservation.

PreCompact

Execute before context compaction. Use to add critical information to preserve.

Notification

Execute when Claude sends notifications. Use to react to user notifications.

Hook Output Format

Standard Output (All Hooks)
{
  "continue": true,
  "suppressOutput": false,
  "systemMessage": "Message for Claude"
}
  • continue: If false, halt processing (default true)

  • suppressOutput: Hide output from transcript (default false)

  • systemMessage: Message shown to Claude

Exit Codes
  • 0 - Success (stdout shown in transcript)

  • 2 - Blocking error (stderr fed back to Claude)

  • Other - Non-blocking error

Hook Input Format

All hooks receive JSON via stdin with common fields:

{
  "session_id": "abc123",
  "transcript_path": "/path/to/transcript.txt",
  "cwd": "/current/working/dir",
  "permission_mode": "ask|allow",
  "hook_event_name": "PreToolUse"
}

Event-specific fields:

  • PreToolUse/PostToolUse: tool_name, tool_input, tool_result

  • UserPromptSubmit: user_prompt

  • Stop/SubagentStop: reason

Access fields in prompts using $TOOL_INPUT, $TOOL_RESULT, $USER_PROMPT, etc.

Environment Variables

Available in all command hooks:

  • $CLAUDE_PROJECT_DIR - Project root path

  • $CLAUDE_PLUGIN_ROOT - Plugin directory (use for portable paths)

  • $CLAUDE_ENV_FILE - SessionStart only: persist env vars here

  • $CLAUDE_CODE_REMOTE - Set if running in remote context

Always use ${CLAUDE_PLUGIN_ROOT} in hook commands for portability:

{
  "type": "command",
  "command": "bash ${CLAUDE_PLUGIN_ROOT}/scripts/validate.sh"
}

Plugin Hook Configuration

In plugins, define hooks in hooks/hooks.json:

{
  "PreToolUse": [
    {
      "matcher": "Write|Edit",
      "hooks": [
        {
          "type": "prompt",
          "prompt": "Validate file write safety"
        }
      ]
    }
  ],
  "Stop": [
    {
      "matcher": "*",
      "hooks": [
        {
          "type": "prompt",
          "prompt": "Verify task completion"
        }
      ]
    }
  ],
  "SessionStart": [
    {
      "matcher": "*",
      "hooks": [
        {
          "type": "command",
          "command": "bash ${CLAUDE_PLUGIN_ROOT}/scripts/load-context.sh",
          "timeout": 10
        }
      ]
    }
  ]
}

Plugin hooks merge with user's hooks and run in parallel.

Matchers

Tool Name Matching

Exact match:

"matcher": "Write"

Multiple tools:

"matcher": "Read|Write|Edit"

Wildcard (all tools):

"matcher": "*"

Regex patterns:

"matcher": "mcp__.*__delete.*"  // All MCP delete tools

Note: Matchers are case-sensitive.

Common Patterns
// All MCP tools
"matcher": "mcp__.*"

// Specific plugin's MCP tools
"matcher": "mcp__plugin_asana_.*"

// All file operations
"matcher": "Read|Write|Edit"

// Bash commands only
"matcher": "Bash"

Security Best Practices

Input Validation

Always validate inputs in command hooks:

#!/bin/bash
set -euo pipefail

input=$(cat)
tool_name=$(echo "$input" | jq -r '.tool_name')

# Validate tool name format
if [[ ! "$tool_name" =~ ^[a-zA-Z0-9_]+$ ]]; then
  echo '{"decision": "deny", "reason": "Invalid tool name"}' >&2
  exit 2
fi
Path Safety

Check for path traversal and sensitive files:

file_path=$(echo "$input" | jq -r '.tool_input.file_path')

# Deny path traversal
if [[ "$file_path" == *".."* ]]; then
  echo '{"decision": "deny", "reason": "Path traversal detected"}' >&2
  exit 2
fi

# Deny sensitive files
if [[ "$file_path" == *".env"* ]]; then
  echo '{"decision": "deny", "reason": "Sensitive file"}' >&2
  exit 2
fi

See examples/validate-write.sh and examples/validate-bash.sh for complete examples.

Quote All Variables
# GOOD: Quoted
echo "$file_path"
cd "$CLAUDE_PROJECT_DIR"

# BAD: Unquoted (injection risk)
echo $file_path
cd $CLAUDE_PROJECT_DIR
Set Appropriate Timeouts
{
  "type": "command",
  "command": "bash script.sh",
  "timeout": 10
}

Defaults: Command hooks (60s), Prompt hooks (30s)

Performance Considerations

Parallel Execution

All matching hooks run in parallel:

{
  "PreToolUse": [
    {
      "matcher": "Write",
      "hooks": [
        {"type": "command", "command": "check1.sh"},  // Parallel
        {"type": "command", "command": "check2.sh"},  // Parallel
        {"type": "prompt", "prompt": "Validate..."}   // Parallel
      ]
    }
  ]
}

Design implications:

  • Hooks don't see each other's output

  • Non-deterministic ordering

  • Design for independence

Optimization
  1. Use command hooks for quick deterministic checks

  2. Use prompt hooks for complex reasoning

  3. Cache validation results in temp files

  4. Minimize I/O in hot paths

Temporarily Active Hooks

Create hooks that activate conditionally by checking for a flag file or configuration:

Pattern: Flag file activation

#!/bin/bash
# Only active when flag file exists
FLAG_FILE="$CLAUDE_PROJECT_DIR/.enable-strict-validation"

if [ ! -f "$FLAG_FILE" ]; then
  # Flag not present, skip validation
  exit 0
fi

# Flag present, run validation
input=$(cat)
# ... validation logic ...

Pattern: Configuration-based activation

#!/bin/bash
# Check configuration for activation
CONFIG_FILE="$CLAUDE_PROJECT_DIR/.claude/plugin-config.json"

if [ -f "$CONFIG_FILE" ]; then
  enabled=$(jq -r '.strictMode // false' "$CONFIG_FILE")
  if [ "$enabled" != "true" ]; then
    exit 0  # Not enabled, skip
  fi
fi

# Enabled, run hook logic
input=$(cat)
# ... hook logic ...

Use cases:

  • Enable strict validation only when needed

  • Temporary debugging hooks

  • Project-specific hook behavior

  • Feature flags for hooks

Best practice: Document activation mechanism in plugin README so users know how to enable/disable temporary hooks.

Hook Lifecycle and Limitations

Hooks Load at Session Start

Important: Hooks are loaded when Claude Code session starts. Changes to hook configuration require restarting Claude Code.

Cannot hot-swap hooks:

  • Editing hooks/hooks.json won't affect current session

  • Adding new hook scripts won't be recognized

  • Changing hook commands/prompts won't update

  • Must restart Claude Code: exit and run claude again

To test hook changes:

  1. Edit hook configuration or scripts

  2. Exit Claude Code session

  3. Restart: claude or cc

  4. New hook configuration loads

  5. Test hooks with claude --debug

Hook Validation at Startup

Hooks are validated when Claude Code starts:

  • Invalid JSON in hooks.json causes loading failure

  • Missing scripts cause warnings

  • Syntax errors reported in debug mode

Use /hooks command to review loaded hooks in current session.

Debugging Hooks

Enable Debug Mode
claude --debug

Look for hook registration, execution logs, input/output JSON, and timing information.

Test Hook Scripts

Test command hooks directly:

echo '{"tool_name": "Write", "tool_input": {"file_path": "/test"}}' | \
  bash ${CLAUDE_PLUGIN_ROOT}/scripts/validate.sh

echo "Exit code: $?"
Validate JSON Output

Ensure hooks output valid JSON:

output=$(./your-hook.sh < test-input.json)
echo "$output" | jq .

Quick Reference

Hook Events Summary
EventWhenUse For
PreToolUseBefore toolValidation, modification
PostToolUseAfter toolFeedback, logging
UserPromptSubmitUser inputContext, validation
StopAgent stoppingCompleteness check
SubagentStopSubagent doneTask validation
SessionStartSession beginsContext loading
SessionEndSession endsCleanup, logging
PreCompactBefore compactPreserve context
NotificationUser notifiedLogging, reactions
Best Practices

DO:

  • ✅ Use prompt-based hooks for complex logic

  • ✅ Use ${CLAUDE_PLUGIN_ROOT} for portability

  • ✅ Validate all inputs in command hooks

  • ✅ Quote all bash variables

  • ✅ Set appropriate timeouts

  • ✅ Return structured JSON output

  • ✅ Test hooks thoroughly

DON'T:

  • ❌ Use hardcoded paths

  • ❌ Trust user input without validation

  • ❌ Create long-running hooks

  • ❌ Rely on hook execution order

  • ❌ Modify global state unpredictably

  • ❌ Log sensitive information

Additional Resources

Reference Files

For detailed patterns and advanced techniques, consult:

  • references/patterns.md - Common hook patterns (8+ proven patterns)

  • references/migration.md - Migrating from basic to advanced hooks

  • references/advanced.md - Advanced use cases and techniques

Example Hook Scripts

Working examples in examples/:

  • validate-write.sh - File write validation example

  • validate-bash.sh - Bash command validation example

  • load-context.sh - SessionStart context loading example

Utility Scripts

Development tools in scripts/:

  • validate-hook-schema.sh - Validate hooks.json structure and syntax

  • test-hook.sh - Test hooks with sample input before deployment

  • hook-linter.sh - Check hook scripts for common issues and best practices

External Resources

Implementation Workflow

To implement hooks in a plugin:

  1. Identify events to hook into (PreToolUse, Stop, SessionStart, etc.)

  2. Decide between prompt-based (flexible) or command (deterministic) hooks

  3. Write hook configuration in hooks/hooks.json

  4. For command hooks, create hook scripts

  5. Use ${CLAUDE_PLUGIN_ROOT} for all file references

  6. Validate configuration with scripts/validate-hook-schema.sh hooks/hooks.json

  7. Test hooks with scripts/test-hook.sh before deployment

  8. Test in Claude Code with claude --debug

  9. Document hooks in plugin README

Focus on prompt-based hooks for most use cases. Reserve command hooks for performance-critical or deterministic checks.

Files

references/advanced.md

Advanced Hook Use Cases

This reference covers advanced hook patterns and techniques for sophisticated automation workflows.

Multi-Stage Validation

Combine command and prompt hooks for layered validation:

{
  "PreToolUse": [
    {
      "matcher": "Bash",
      "hooks": [
        {
          "type": "command",
          "command": "bash ${CLAUDE_PLUGIN_ROOT}/scripts/quick-check.sh",
          "timeout": 5
        },
        {
          "type": "prompt",
          "prompt": "Deep analysis of bash command: $TOOL_INPUT",
          "timeout": 15
        }
      ]
    }
  ]
}

Use case: Fast deterministic checks followed by intelligent analysis

Example quick-check.sh:

#!/bin/bash
input=$(cat)
command=$(echo "$input" | jq -r '.tool_input.command')

# Immediate approval for safe commands
if [[ "$command" =~ ^(ls|pwd|echo|date|whoami)$ ]]; then
  exit 0
fi

# Let prompt hook handle complex cases
exit 0

The command hook quickly approves obviously safe commands, while the prompt hook analyzes everything else.

Conditional Hook Execution

Execute hooks based on environment or context:

#!/bin/bash
# Only run in CI environment
if [ -z "$CI" ]; then
  echo '{"continue": true}' # Skip in non-CI
  exit 0
fi

# Run validation logic in CI
input=$(cat)
# ... validation code ...

Use cases:

  • Different behavior in CI vs local development

  • Project-specific validation

  • User-specific rules

Example: Skip certain checks for trusted users:

#!/bin/bash
# Skip detailed checks for admin users
if [ "$USER" = "admin" ]; then
  exit 0
fi

# Full validation for other users
input=$(cat)
# ... validation code ...

Hook Chaining via State

Share state between hooks using temporary files:

# Hook 1: Analyze and save state
#!/bin/bash
input=$(cat)
command=$(echo "$input" | jq -r '.tool_input.command')

# Analyze command
risk_level=$(calculate_risk "$command")
echo "$risk_level" > /tmp/hook-state-$$

exit 0
# Hook 2: Use saved state
#!/bin/bash
risk_level=$(cat /tmp/hook-state-$$ 2>/dev/null || echo "unknown")

if [ "$risk_level" = "high" ]; then
  echo "High risk operation detected" >&2
  exit 2
fi

Important: This only works for sequential hook events (e.g., PreToolUse then PostToolUse), not parallel hooks.

Dynamic Hook Configuration

Modify hook behavior based on project configuration:

#!/bin/bash
cd "$CLAUDE_PROJECT_DIR" || exit 1

# Read project-specific config
if [ -f ".claude-hooks-config.json" ]; then
  strict_mode=$(jq -r '.strict_mode' .claude-hooks-config.json)

  if [ "$strict_mode" = "true" ]; then
    # Apply strict validation
    # ...
  else
    # Apply lenient validation
    # ...
  fi
fi

Example .claude-hooks-config.json:

{
  "strict_mode": true,
  "allowed_commands": ["ls", "pwd", "grep"],
  "forbidden_paths": ["/etc", "/sys"]
}

Context-Aware Prompt Hooks

Use transcript and session context for intelligent decisions:

{
  "Stop": [
    {
      "matcher": "*",
      "hooks": [
        {
          "type": "prompt",
          "prompt": "Review the full transcript at $TRANSCRIPT_PATH. Check: 1) Were tests run after code changes? 2) Did the build succeed? 3) Were all user questions answered? 4) Is there any unfinished work? Return 'approve' only if everything is complete."
        }
      ]
    }
  ]
}

The LLM can read the transcript file and make context-aware decisions.

Performance Optimization

Caching Validation Results
#!/bin/bash
input=$(cat)
file_path=$(echo "$input" | jq -r '.tool_input.file_path')
cache_key=$(echo -n "$file_path" | md5sum | cut -d' ' -f1)
cache_file="/tmp/hook-cache-$cache_key"

# Check cache
if [ -f "$cache_file" ]; then
  cache_age=$(($(date +%s) - $(stat -f%m "$cache_file" 2>/dev/null || stat -c%Y "$cache_file")))
  if [ "$cache_age" -lt 300 ]; then  # 5 minute cache
    cat "$cache_file"
    exit 0
  fi
fi

# Perform validation
result='{"decision": "approve"}'

# Cache result
echo "$result" > "$cache_file"
echo "$result"
Parallel Execution Optimization

Since hooks run in parallel, design them to be independent:

{
  "PreToolUse": [
    {
      "matcher": "Write",
      "hooks": [
        {
          "type": "command",
          "command": "bash check-size.sh",      // Independent
          "timeout": 2
        },
        {
          "type": "command",
          "command": "bash check-path.sh",      // Independent
          "timeout": 2
        },
        {
          "type": "prompt",
          "prompt": "Check content safety",     // Independent
          "timeout": 10
        }
      ]
    }
  ]
}

All three hooks run simultaneously, reducing total latency.

Cross-Event Workflows

Coordinate hooks across different events:

SessionStart - Set up tracking:

#!/bin/bash
# Initialize session tracking
echo "0" > /tmp/test-count-$$
echo "0" > /tmp/build-count-$$

PostToolUse - Track events:

#!/bin/bash
input=$(cat)
tool_name=$(echo "$input" | jq -r '.tool_name')

if [ "$tool_name" = "Bash" ]; then
  command=$(echo "$input" | jq -r '.tool_result')
  if [[ "$command" == *"test"* ]]; then
    count=$(cat /tmp/test-count-$$ 2>/dev/null || echo "0")
    echo $((count + 1)) > /tmp/test-count-$$
  fi
fi

Stop - Verify based on tracking:

#!/bin/bash
test_count=$(cat /tmp/test-count-$$ 2>/dev/null || echo "0")

if [ "$test_count" -eq 0 ]; then
  echo '{"decision": "block", "reason": "No tests were run"}' >&2
  exit 2
fi

Integration with External Systems

Slack Notifications
#!/bin/bash
input=$(cat)
tool_name=$(echo "$input" | jq -r '.tool_name')
decision="blocked"

# Send notification to Slack
curl -X POST "$SLACK_WEBHOOK" \
  -H 'Content-Type: application/json' \
  -d "{\"text\": \"Hook ${decision} ${tool_name} operation\"}" \
  2>/dev/null

echo '{"decision": "deny"}' >&2
exit 2
Database Logging
#!/bin/bash
input=$(cat)

# Log to database
psql "$DATABASE_URL" -c "INSERT INTO hook_logs (event, data) VALUES ('PreToolUse', '$input')" \
  2>/dev/null

exit 0
Metrics Collection
#!/bin/bash
input=$(cat)
tool_name=$(echo "$input" | jq -r '.tool_name')

# Send metrics to monitoring system
echo "hook.pretooluse.${tool_name}:1|c" | nc -u -w1 statsd.local 8125

exit 0

Security Patterns

Rate Limiting
#!/bin/bash
input=$(cat)
command=$(echo "$input" | jq -r '.tool_input.command')

# Track command frequency
rate_file="/tmp/hook-rate-$$"
current_minute=$(date +%Y%m%d%H%M)

if [ -f "$rate_file" ]; then
  last_minute=$(head -1 "$rate_file")
  count=$(tail -1 "$rate_file")

  if [ "$current_minute" = "$last_minute" ]; then
    if [ "$count" -gt 10 ]; then
      echo '{"decision": "deny", "reason": "Rate limit exceeded"}' >&2
      exit 2
    fi
    count=$((count + 1))
  else
    count=1
  fi
else
  count=1
fi

echo "$current_minute" > "$rate_file"
echo "$count" >> "$rate_file"

exit 0
Audit Logging
#!/bin/bash
input=$(cat)
tool_name=$(echo "$input" | jq -r '.tool_name')
timestamp=$(date -Iseconds)

# Append to audit log
echo "$timestamp | $USER | $tool_name | $input" >> ~/.claude/audit.log

exit 0
Secret Detection
#!/bin/bash
input=$(cat)
content=$(echo "$input" | jq -r '.tool_input.content')

# Check for common secret patterns
if echo "$content" | grep -qE "(api[_-]?key|password|secret|token).{0,20}['\"]?[A-Za-z0-9]{20,}"; then
  echo '{"decision": "deny", "reason": "Potential secret detected in content"}' >&2
  exit 2
fi

exit 0

Testing Advanced Hooks

Unit Testing Hook Scripts
# test-hook.sh
#!/bin/bash

# Test 1: Approve safe command
result=$(echo '{"tool_input": {"command": "ls"}}' | bash validate-bash.sh)
if [ $? -eq 0 ]; then
  echo "✓ Test 1 passed"
else
  echo "✗ Test 1 failed"
fi

# Test 2: Block dangerous command
result=$(echo '{"tool_input": {"command": "rm -rf /"}}' | bash validate-bash.sh)
if [ $? -eq 2 ]; then
  echo "✓ Test 2 passed"
else
  echo "✗ Test 2 failed"
fi
Integration Testing

Create test scenarios that exercise the full hook workflow:

# integration-test.sh
#!/bin/bash

# Set up test environment
export CLAUDE_PROJECT_DIR="/tmp/test-project"
export CLAUDE_PLUGIN_ROOT="$(pwd)"
mkdir -p "$CLAUDE_PROJECT_DIR"

# Test SessionStart hook
echo '{}' | bash hooks/session-start.sh
if [ -f "/tmp/session-initialized" ]; then
  echo "✓ SessionStart hook works"
else
  echo "✗ SessionStart hook failed"
fi

# Clean up
rm -rf "$CLAUDE_PROJECT_DIR"

Best Practices for Advanced Hooks

  1. Keep hooks independent: Don't rely on execution order

  2. Use timeouts: Set appropriate limits for each hook type

  3. Handle errors gracefully: Provide clear error messages

  4. Document complexity: Explain advanced patterns in README

  5. Test thoroughly: Cover edge cases and failure modes

  6. Monitor performance: Track hook execution time

  7. Version configuration: Use version control for hook configs

  8. Provide escape hatches: Allow users to bypass hooks when needed

Common Pitfalls

❌ Assuming Hook Order
# BAD: Assumes hooks run in specific order
# Hook 1 saves state, Hook 2 reads it
# This can fail because hooks run in parallel!
❌ Long-Running Hooks
# BAD: Hook takes 2 minutes to run
sleep 120
# This will timeout and block the workflow
❌ Uncaught Exceptions
# BAD: Script crashes on unexpected input
file_path=$(echo "$input" | jq -r '.tool_input.file_path')
cat "$file_path"  # Fails if file doesn't exist
✅ Proper Error Handling
# GOOD: Handles errors gracefully
file_path=$(echo "$input" | jq -r '.tool_input.file_path')
if [ ! -f "$file_path" ]; then
  echo '{"continue": true, "systemMessage": "File not found, skipping check"}' >&2
  exit 0
fi

Conclusion

Advanced hook patterns enable sophisticated automation while maintaining reliability and performance. Use these techniques when basic hooks are insufficient, but always prioritize simplicity and maintainability.

Requirements and compatibility

Written for: Claude Code, Claude apps

Works with: Claude Code, Claude apps, OpenAI Codex, GitHub Copilot, Cursor, Gemini CLI, Kiro, OpenCode, Goose, Amp, Roo Code, JetBrains Junie, Factory Droid, Devin (ex-Windsurf), Mistral Vibe, OpenHands, Letta

“Works with” means the tool reads the open Agent Skills format; a skill written for one tool may use features others lack.

Security

What our scanner noticed· Low risk

  • Scripts that your agent may run

This skill includes scripts that your agent may run. Read them before you use it.

A static scan is not a guarantee. Skills are third-party content: review a skill before you let an agent use it.

Attribution and licence

Published by
Anthropic
Publisher
Anthropic (Official)
Source
anthropics/claude-plugins-official · plugins/plugin-dev/skills/hook-development · commit 0412be7
Licence
Apache License 2.0 (redistribution allowed)
  • LICENSE (added by AutoGineer from plugins/plugin-dev/LICENSE)
  • ATTRIBUTION.md (written by AutoGineer)
Synced

AutoGineer is not affiliated with or endorsed by Anthropic.

Download ZIP

The ZIP holds the skill’s files, its licence files and an ATTRIBUTION.md. Download hook-development.zip