AgentSkillsCN

hooks-creator

创建 Claude Code 钩子的指南——用户自定义的 Shell 命令,可在生命周期各阶段执行。当用户希望为 Claude Code 创建、添加或配置钩子时使用,包括 PreToolUse、PostToolUse、Notification、UserPromptSubmit、Stop、SubagentStop、PreCompact、SessionStart 或 SessionEnd 钩子。

SKILL.md
--- frontmatter
name: hooks-creator
description: Guide for creating Claude Code hooks - user-defined shell commands that execute at lifecycle points. Use when the user wants to create, add, or configure a hook for Claude Code, including PreToolUse, PostToolUse, Notification, UserPromptSubmit, Stop, SubagentStop, PreCompact, SessionStart, or SessionEnd hooks.

Hooks Creator

Create Claude Code hooks - shell commands that execute automatically at specific lifecycle points.

Quick Reference: Hook Events

EventWhen it RunsCan BlockMatcherCommon Use
PreToolUseBefore tool callYesYesValidate/block commands, modify inputs
PermissionRequestPermission dialogYesYesAuto-allow/deny permissions
PostToolUseAfter tool succeedsNoYesFormat code, log, provide feedback
NotificationNotification sentNoYesCustom alerts (permission_prompt, idle_prompt)
UserPromptSubmitUser submits promptYesNoValidate prompts, inject context
StopClaude finishesYesNoEvaluate completion, force continue
SubagentStopSubagent finishesYesNoEvaluate subagent completion
PreCompactBefore compactionNoYesPre-compact cleanup (manual, auto)
SessionStartSession beginsNoYesSetup env, load context (startup, resume, clear, compact)
SessionEndSession endsNoNoCleanup, logging

Workflow

Step 1: Determine Hook Requirements

Ask the user:

  1. What should trigger the hook? (which event from table above)
  2. What should the hook do? (the action to take)
  3. Should it block/modify behavior? (for events that support blocking)

Step 2: Determine Installation Scope

Ask where to install the hook:

ScopePathUse Case
Project (shared).claude/settings.jsonTeam-shared hooks, committed to git
Project (local).claude/settings.local.jsonPersonal project hooks, not committed
User global~/.claude/settings.jsonPersonal hooks for all projects
User profile~/.claude-<profile>/settings.jsonProfile-specific hooks

For user-level hooks, ask which profile or if using default ~/.claude/.

Step 3: Create the Hook

Configuration Format

json
{
  "hooks": {
    "EventName": [
      {
        "matcher": "ToolPattern",
        "hooks": [
          {
            "type": "command",
            "command": "path/to/script.py",
            "timeout": 60
          }
        ]
      }
    ]
  }
}

Matcher Patterns

  • Exact match: "Write" - matches only Write tool
  • Wildcard: "*" or "" - matches all tools
  • Regex: "Edit|Write" - matches Edit OR Write
  • MCP tools: "mcp__server__tool" pattern

Events WITHOUT matcher support: UserPromptSubmit, Stop, SubagentStop, SessionEnd

Hook Script Template

Create a Python script that:

  1. Reads JSON from stdin
  2. Processes the input
  3. Outputs JSON for control (optional)
  4. Exits with appropriate code
python
#!/usr/bin/env python3
import json
import sys

try:
    input_data = json.load(sys.stdin)
except json.JSONDecodeError:
    sys.exit(0)

# Process input_data based on hook event
# Common fields: session_id, transcript_path, cwd, permission_mode, hook_event_name

# Exit codes:
#   0 = Success (allow)
#   2 = Block (stderr used as error message)
#   other = Non-blocking error

sys.exit(0)

Step 4: Hook Input/Output Reference

See references/hook-events.md for detailed input/output fields per event.

See references/examples.md for complete working examples.

Environment Variables

VariableAvailable InDescription
CLAUDE_PROJECT_DIRAll hooksProject root directory
CLAUDE_CODE_REMOTEAll hooks"true" if remote, empty if local
CLAUDE_ENV_FILESessionStart onlyFile to persist env vars

Security Considerations

  • Hooks run with your user credentials
  • Always validate and sanitize inputs
  • Quote shell variables: "$CLAUDE_PROJECT_DIR"
  • Block path traversal: reject paths with ..
  • Set reasonable timeouts (default 60s)
  • Never access .env, credentials, private keys