Token导航 LogoToken导航

Agent Skill · 开发

creating-claude-hooks(creating Claude hooks 命令行)

creating-claude-hooks 用于处理 GitHub 仓库、Issue、Pull Request 和代码协作信息,适合在 Codex、Claude、Cursor、Gemini CLI 中需要围绕仓库状态、代码变更或协作事项进行整理时使用。可结合来源仓库、安装命令和原始 README 继续核验具体用法。安装前建议确认权限范围、维护状态,以及是否会触发联网、命令执行或文件读写。

creating-claude-hooks 是开发类 Agent Skill,可用宿主为 Codex、Claude、Cursor、Gemini CLI,通过GitHub 仓库获取,权限为接触敏感数据;许可证信息还不明确,第三方扫描已通过,按安装量在开发类的 21,746 个 Skill 里排第 17,985。

总安装 367周安装 15GitHub Stars 106下载 119核验 2026-05-01

安装说明

本站只整理中文说明,不托管安装包,也不代用户安装。
GitHub
许可证
unknown

安装方式

通过对话安装

复制提示词发给支持本地命令或 Skills 的 AI 助手,先确认命令和权限,再让它执行。

请帮我安装这个 Agent Skill:creating-claude-hooks(creating Claude hooks 命令行)
来源仓库:https://github.com/pr-pm/prpm
仓库路径:skills/creating-claude-hooks
安装命令:
npx skills add https://github.com/pr-pm/prpm --skill creating-claude-hooks
安装前请先检查当前环境是否支持对应 CLI,并向我确认将要执行的命令、安装目录、联网范围和文件读写权限;确认后再执行。

命令行安装

复制命令到本机终端执行。该命令会通过 npx skills 从第三方来源获取 Skill;本站只展示命令,不托管安装包,也不自动执行。

skills.shnpx skills
npx skills add https://github.com/pr-pm/prpm --skill creating-claude-hooks

这个 Skill 是做什么的

开发类 Skill 面向写代码、改代码和排查问题,一般会读写仓库文件,部分还会执行构建或测试命令。

该技能指导创建 Claude Code Hook,用于响应特定事件并执行预处理或后处理逻辑。适用于代码提交前检查、文件变更监听或自动化工作流集成时。支持 JSON 配置与脚本执行,可定义 onPreToolUse、onPostToolUse 等事件。

安装方式:GitHub 仓库,使用 npx 命令添加;注意 hook 生命周期与 I/O 安全。creating-claude-hooks 属于开发类 Skill,可作为该场景下的辅助能力补充。

来源仓库内路径:skills/creating-claude-hooks

上手步骤

4 步
  1. 1

    确认自己的宿主工具

    公开资料标注支持 Codex、Claude、Cursor、Gemini CLI;先确认自己用的是其中之一,再按对应工具的 Skills 目录放置。

  2. 2

    拿到安装命令

    可以直接复制的命令是 npx skills add https://github.com/pr-pm/prpm --skill creating-claude-hooks;命令里的占位符换成自己的路径或密钥再执行。

  3. 3

    安装后重启宿主

    命令执行完要完全退出宿主工具再打开,让新装的 Skill 被重新扫描到,否则列表里可能看不到。

  4. 4

    按最小权限试用

    它需要接触敏感数据,先在测试目录或测试账号里跑,确认没问题再放到正式项目。

常见问题

6 条

creating-claude-hooks 怎么安装?

在终端执行 npx skills add https://github.com/pr-pm/prpm --skill creating-claude-hooks。装完完全退出宿主工具再打开,让它重新扫描本地 Skill。

creating-claude-hooks 支持哪些 AI 工具?

公开资料标注支持 Codex、Claude、Cursor、Gemini CLI。其他工具只要能读取本地 Skill 目录,一般也能手动放进去,但要自己确认触发方式是否一致。

creating-claude-hooks 需要什么权限?

权限级别是接触敏感数据。该 Skill 可能接触密钥、Token、环境变量或敏感配置,应进入高风险复核队列,默认不自动发布。

creating-claude-hooks 是免费的吗?

公开资料没有标注明确许可证,收费和商用限制都无法确认。正式使用前请到来源仓库核对授权说明。

creating-claude-hooks 用的人多吗?

公开数据是累计安装 367 次,近一周安装 15 次,下载 119 次,GitHub 106 星。这些数字来自第三方目录统计,只能当作热度参考,不代表质量或安全性。

creating-claude-hooks 安全吗?

第三方扫描结果为通过,但这只覆盖已知的静态检查项,不能替代自己读一遍源码和安装命令。

值得选的地方和要先想清楚的地方

值得选的地方

  • 同时适配 4 种工具,换客户端不用重新找替代品。
  • 第三方扫描已通过,常见的高风险行为没有命中。

先想清楚的地方

  • 需要接触敏感数据,装到常用环境前要先评估影响面。
  • 许可证没有明确标注,能不能商用、能不能再分发都不确定。
  • 第三方目录整理,版本更新和行为细节以来源仓库为准。

适不适合你

更适合

  • 已经在用 Codex,想直接扩展它能力的人。
  • 需要处理开发类任务、又不想每次都手写提示词的人。

不太适合

  • 环境里有大量密钥、凭证,不方便给第三方 Skill 读取的人。
  • 需要明确授权才能用到公司项目里的场景。
  • 需要厂商级技术支持和 SLA 的生产系统。

开发类 Skill 对比

6 个同类
Skill总安装GitHub 星权限许可证扫描
skill-vetter

技能审查员 · OpenClaw

8,779,018986操作浏览器MIT-0通过
ontology

本体论 · OpenClaw

6,636,960576只读MIT-0通过
entra-app-registration

内部应用程序注册 · Codex、Claude

6,631,872764接触敏感数据未明确通过
entra-app-registration

内部应用程序注册 · Codex、Claude

3,757,680201接触敏感数据未明确通过
nano-banana-pro

纳米香蕉专业版 · OpenClaw

3,526,898364接触敏感数据MIT-0有提醒
creating-claude-hooks

creating Claude hooks 命令行 · 本页

367106接触敏感数据未明确通过

按安装量取同分类前几名;数字来自第三方目录统计,只作热度参考,不代表质量结论。

SKILL.md 原文

Creating Claude Code Hooks

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.

When to Use This Skill

Activate this skill when:

  • User asks to create a new Claude Code hook
  • User wants to publish a hook as a PRPM package
  • User needs to understand hook format or events
  • User is troubleshooting hook execution
  • User asks about hook vs skill vs command differences

Quick Reference

Two Hook Configuration Methods

Method 1: JSON Configuration (Recommended)

  • Configure in .claude/settings.json, ~/.claude/settings.json, or plugin's hooks.json
  • Supports both command hooks and prompt hooks
  • More flexible, supports matchers and timeouts

Method 2: Executable Files (Legacy)

  • Place executables in .claude/hooks/<event-name>
  • Simpler but less configurable

Hook Types

TypeDescriptionSpeedUse Case
CommandRuns external scriptFast (ms)Formatting, logging, file checks
PromptUses LLM reasoningSlow (2-10s)Complex validation, security analysis

Available Events

EventWhen It FiresCan Block?Common Use Cases
PreToolUseBefore tool executionYes (exit 2)Validation, permission checks, input modification
PostToolUseAfter tool completesNoFormatting, logging, cleanup
UserPromptSubmitBefore user input processesYesPrompt validation, enhancement
SessionStartNew session beginsNoEnvironment setup, context loading
StopWhen assistant finishesNoCleanup, summary, verification
SubagentStopWhen subagent finishesNoSubagent result processing
PreCompactBefore context compactionNoSave important context
NotificationDuring alertsNoDesktop notifications, logging
PermissionRequestWhen permission neededYesCustom permission handling

Exit Codes

CodeMeaningBehavior
0SuccessContinue normally
2BlockStop operation (PreToolUse only)
1 or otherErrorLog error, continue

JSON Hook Configuration

Settings-Based Hooks

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."
      }]
    }]
  }
}

Plugin hooks.json

For PRPM packages, use hook.json:

{
  "hooks": {
    "PreToolUse": [{
      "matcher": "Write",
      "hooks": [{
        "type": "command",
        "command": "${CLAUDE_PLUGIN_ROOT}/scripts/validate.sh",
        "timeout": 5000
      }]
    }]
  }
}

Matcher Patterns

PatternMatches
"Write"Only Write tool
`"Write\Edit"`Write OR Edit tools
"Bash"Only Bash tool
"mcp__github__*"All GitHub MCP tools
"*"All tools (use sparingly)

Hook Options

{
  "type": "command",
  "command": "./my-hook.sh",
  "timeout": 5000,
  "once": true,
  "continue": true,
  "stopReason": "Message when blocked",
  "suppressOutput": false,
  "systemMessage": "Warning to show user"
}
OptionTypeDefaultDescription
timeoutnumber60000Max execution time in ms
oncebooleanfalseRun only once per session
continuebooleantrueContinue after hook completes
stopReasonstring-Message when continue=false
suppressOutputbooleanfalseHide stdout from transcript
systemMessagestring-Warning message to user

Command Hooks

Command hooks run external scripts. They're fast and deterministic.

Shell Script Hook

#!/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

TypeScript Hook

#!/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

Prompt hooks use LLM reasoning for complex validation. Use sparingly - they take 2-10 seconds.

Basic Prompt Hook

{
  "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."
      }]
    }]
  }
}

Prompt Hook with Schema Validation

{
  "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"]
        }
      }]
    }]
  }
}

When to Use Prompt Hooks

Good use cases:

  • Security analysis that requires understanding code context
  • Detecting logic errors or anti-patterns
  • Validating architectural decisions
  • Complex permission checks

Avoid for:

  • Simple pattern matching (use command hooks)
  • File extension checks
  • Path validation
  • Anything that can be done with regex

File-Based Hooks (Legacy)

Simpler approach - place executables directly in hooks directory.

File Location

Project hooks:

.claude/hooks/PreToolUse
.claude/hooks/PostToolUse
.claude/hooks/SessionStart

User-global hooks:

~/.claude/hooks/PreToolUse
~/.claude/hooks/Stop

Requirements

Every file-based hook MUST:

  1. Have a shebang line:
#!/bin/bash
#!/usr/bin/env node
#!/usr/bin/env python3
  1. Be executable:
chmod +x .claude/hooks/PreToolUse
  1. Handle JSON input from stdin
  2. Exit with appropriate code

JSON Input Structure

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-Specific Input Fields

ToolAvailable Fields
Writefile_path, content
Editfile_path, old_string, new_string
Readfile_path
Bashcommand
Globpattern, path
Greppattern, path

Environment Variables

Available in hook execution:

VariableDescription
CLAUDE_PROJECT_DIRProject root directory
CLAUDE_CURRENT_DIRCurrent working directory
CLAUDE_PLUGIN_ROOTHook installation directory
CLAUDE_ENV_FILEFile for persisting variables
SESSION_IDCurrent session identifier

Common Patterns

Pattern 1: Format on Save

{
  "hooks": {
    "PostToolUse": [{
      "matcher": "Write|Edit",
      "hooks": [{
        "type": "command",
        "command": "${CLAUDE_PLUGIN_ROOT}/scripts/format.sh",
        "timeout": 5000
      }]
    }]
  }
}

Pattern 2: Block Sensitive Files

{
  "hooks": {
    "PreToolUse": [{
      "matcher": "Write|Edit|Read",
      "hooks": [{
        "type": "command",
        "command": "${CLAUDE_PLUGIN_ROOT}/scripts/block-sensitive.sh"
      }]
    }]
  }
}

Pattern 3: Test Verification Before Stop

{
  "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."
      }]
    }]
  }
}

Pattern 4: Session Context Loading

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

Pattern 5: Multi-Stage Validation

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"
      }]
    }]
  }
}

Common Mistakes

MistakeProblemSolution
Not quoting variablesBreaks on spacesAlways use "$VAR"
Missing shebangWon't executeAdd #!/bin/bash
Not executablePermission deniedRun chmod +x hook-file
Logging to stdoutClutters transcriptUse stderr: echo "log" >&2
Wrong exit codeDoesn't block when neededUse exit 2 to block
No input validationSecurity riskAlways validate JSON fields
Slow operationsBlocks ClaudeRun in background or use PostToolUse
Absolute paths missingCan't find scriptsUse ${CLAUDE_PLUGIN_ROOT}
Using * matcherRuns on everythingBe specific: `Write\Edit`
Prompt hooks everywhereSlow experienceUse only for complex logic

Best Practices

1. Keep Hooks Fast

Target < 100ms for PreToolUse hooks:

  • Cache results where possible
  • Run heavy operations in background
  • Use specific matchers, not wildcards

2. Handle Errors Gracefully

# 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

3. Use Shebangs

Always start with shebang:

#!/bin/bash
#!/usr/bin/env node
#!/usr/bin/env python3

4. Secure Sensitive Files

BLOCKED=(".env" ".env.*" "*.pem" "*.key")
for pattern in "${BLOCKED[@]}"; do
  case "$FILE" in
    $pattern)
      echo "Blocked: $FILE is sensitive" >&2
      exit 2
      ;;
  esac
done

5. Quote All Variables

# WRONG - breaks on spaces
prettier --write $FILE

# RIGHT - handles spaces
prettier --write "$FILE"

6. Log for Debugging

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

Publishing as PRPM Package

Package Structure

my-hook/
├── prpm.json          # Package manifest
├── HOOK.md            # Hook documentation
└── hook-script.sh     # Hook executable

prpm.json

{
  "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"
}

HOOK.md Format

---
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
\`\`\`

Publishing Process

# 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

Security Requirements

Input Validation

# 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

Path Sanitization

# 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

User Confirmation

Claude Code automatically:

  • Requires confirmation before installing hooks
  • Shows hook source code to user
  • Warns about hook execution
  • Displays hook output in transcript

Hooks vs Skills vs Commands

FeatureHooksSkillsCommands
FormatExecutable codeMarkdownMarkdown
TriggerAutomatic (events)Automatic (context)Manual (/command)
LanguageAny executableN/AN/A
Use CaseAutomation, validationReference, patternsQuick tasks
SecurityRequires confirmationNo special permissionsInherits from session

Examples:

  • Hook: Auto-format files on save
  • Skill: Reference guide for testing patterns
  • Command: /review-pr quick code review

Related Resources

  • claude-hook-writer skill - Detailed hook development guidance
  • typescript-hook-writer skill - TypeScript-specific hook development
  • Claude Code Docs
  • Schema

Checklist for New Hooks

Before publishing:

  • Shebang line included
  • File is executable (chmod +x)
  • Validates all stdin input
  • Quotes all variables
  • Handles missing dependencies gracefully
  • Uses appropriate exit codes
  • Logs errors to stderr or file
  • Tests with edge cases (spaces, Unicode, missing fields)
  • Documents dependencies in HOOK.md
  • Includes installation instructions
  • Source code included in documentation
  • Clear description and tags in prpm.json
  • Version number is semantic

平台分布

Codex

34.24%
按下载量换算41

Claude

28.94%
按下载量换算34

Cursor

19.03%
按下载量换算23

Gemini CLI

8.22%
按下载量换算10

安全审计

Gen Agent Trust Hub

通过

Socket

通过

Snyk

通过

权限和风险

接触敏感数据

该 Skill 可能接触密钥、Token、环境变量或敏感配置,应进入高风险复核队列,默认不自动发布。

安装前确认

本站仅展示第三方公开信息,不托管安装包,不提供自动安装或运行环境。安装前应自行审查源码、依赖和命令行为。目前只有一个公开来源,建议同时核对源仓库。

继续浏览同类 Skills