AgentSkillsCN

hooks-reference

Claude Code钩子配置参考。在创建钩子、理解钩子事件(PreToolUse、PostToolUse、Stop、SessionStart等)、调试钩子行为,或实现自动化时,可选用此技能。

SKILL.md
--- frontmatter
name: hooks-reference
description: Claude Code hooks configuration reference. Use when creating hooks, understanding hook events (PreToolUse, PostToolUse, Stop, SessionStart, etc.), debugging hook behavior, or implementing automation.

Claude Code Hooks Reference

Hooks are user-defined shell commands that execute at various points in Claude Code's lifecycle, providing deterministic control over behavior.

Quick Reference: Hook Events

EventWhenInputCan Control
PreToolUseBefore tool runsTool name, inputsBlock/modify tool
PostToolUseAfter tool succeedsTool name, resultFeedback to Claude
PostToolUseFailureAfter tool failsTool name, errorError handling
PermissionRequestPermission dialog shownDetailsAllow/deny
UserPromptSubmitUser submits promptUser inputModify prompt
NotificationNotification sentMessageCustom notifications
StopClaude stopsReasonContinue/stop
SubagentStopSubagent completesResultSubagent behavior
PreCompactBefore compactionContextModify context
SessionStartSession beginsSession infoEnv setup
SessionEndSession endsStatsCleanup

Hook Configuration Location

code
~/.claude/settings.json          # User-level (all projects)
.claude/settings.json            # Project-level (team shared)
.claude/settings.local.json      # Project-local (gitignored)

Basic Hook Structure

json
{
  "hooks": {
    "PreToolUse": [
      {
        "matcher": "Bash",
        "hooks": [
          {
            "type": "command",
            "command": "your-script.sh"
          }
        ]
      }
    ]
  }
}

Matcher Patterns

PatternMatches
*All tools
BashBash tool only
Write|EditWrite or Edit tools
Read.*Read and any Read variants

Hook Types

Command Hook

json
{
  "type": "command",
  "command": "jq '.tool_input' >> /tmp/log.txt"
}

Prompt Hook

json
{
  "type": "prompt",
  "prompt": "Review the output: $ARGUMENTS"
}

Agent Hook

json
{
  "type": "agent",
  "prompt": "Verify the changes meet security requirements"
}

Control Flow via Exit Codes

Exit CodeEffect
0Success, continue
2Block (PreToolUse only)
Non-zeroError, continue with warning

Hook Output Format (stdout JSON)

json
{
  "continue": true,
  "decision": "approve",
  "reason": "Looks good",
  "suppressOutput": false
}

Common Patterns

Auto-format on file write

json
{
  "PostToolUse": [{
    "matcher": "Write|Edit",
    "hooks": [{
      "type": "command",
      "command": "jq -r '.tool_input.file_path' | xargs prettier --write"
    }]
  }]
}

Block sensitive file edits

json
{
  "PreToolUse": [{
    "matcher": "Write|Edit",
    "hooks": [{
      "type": "command",
      "command": "jq -e '.tool_input.file_path | test(\"\\\\.env|\\\\.git\")' && exit 2 || exit 0"
    }]
  }]
}

Log all Bash commands

json
{
  "PreToolUse": [{
    "matcher": "Bash",
    "hooks": [{
      "type": "command",
      "command": "jq -r '.tool_input.command' >> ~/.claude/bash-log.txt"
    }]
  }]
}

Environment Variables in Hooks

VariableValue
CLAUDE_PROJECT_DIRProject root directory
CLAUDE_PLUGIN_ROOTPlugin installation path

Debugging Hooks

bash
# View loaded hooks
/hooks

# Test hook manually with sample input
echo '{"tool_name":"Bash","tool_input":{"command":"ls"}}' | your-hook.sh

# Check exit code
echo $?

Security Considerations

  • Hooks run with your credentials
  • Validate all input before use
  • Don't log sensitive data
  • Use absolute paths for scripts
  • Test hooks in isolation first

For complete documentation including all event schemas, see: