概述:2026年5月,Anthropic正式推出Claude Code Plugin Marketplace——一个面向全球开发者的插件生态平台。本教程将带你从零理解插件系统的完整架构,手把手构建一个可发布的生产级插件,并完成从本地测试到Marketplace上架的全流程。适合有Claude Code基础使用经验、希望将个人工作流封装为可分发产品的开发者。
前置条件:
- Claude Code ≥ 1.0.50(claude --version 检查)
- Node.js ≥ 18.x
- Git 基本操作能力
- 了解 Claude Code Skills 基础概念
- 一个 GitHub 账号(用于插件仓库托管)
Claude Code在2026年形成了一套清晰的扩展架构。理解这三层体系,是选择正确开发路径的前提。
graph TB
subgraph "Claude Code 扩展三层架构"
A[用户需求] --> B{选择扩展方式}
B -->|纯指令封装| C[Skill<br/>单文件 Markdown]
B -->|组合能力+Hooks| D[Plugin<br/>目录 + manifest]
B -->|外部工具调用| E[MCP Server<br/>独立进程]
C --> F[轻量<br/>无配置<br/>即时加载]
D --> G[中量<br/>manifest.json<br/>Skills+Hooks+Commands]
E --> H[重量<br/>独立服务<br/>跨语言支持]
D --> I[可包含多个 Skills]
D --> J[可挂载 Hooks]
D --> K[可注册 Commands]
D --> L[可捆绑 MCP Server]
end
style D fill:#4A90D9,color:#fff
style C fill:#7ED321,color:#fff
style E fill:#F5A623,color:#fff
| 维度 | Skill | Plugin | MCP Server |
|---|---|---|---|
| 格式 | 单个 .md 文件 |
目录 + plugin.json |
独立进程(Node/Python) |
| 加载方式 | 按需加载到上下文 | manifest 注册后自动发现 | stdio/SSE 连接 |
| 核心能力 | 注入指令和知识 | Skills + Hooks + Commands + MCP | 外部工具调用 |
| Token成本 | 低(按需注入) | 中(manifest固定 + skills按需) | 高(工具描述常驻) |
| 分发方式 | 文件/URL | Marketplace/私有Git | npm/pip/源码 |
| 适用场景 | 工作流模板 | 完整扩展包 | 数据库/API集成 |
何时选择Plugin而非Skill? 当你需要以下任意能力时,就是构建Plugin的信号:
/my-command)一个标准Claude Code插件的目录结构如下:
my-plugin/
├── .claude-plugin/
│ └── plugin.json # 必须:插件清单文件
├── skills/
│ ├── code-review.md # 可选:Skill 文件
│ └── refactor.md # 可选:另一个 Skill
├── hooks/
│ └── pre-commit.sh # 可选:Hook 脚本
├── agents/
│ └── reviewer.md # 可选:Agent 定义
├── commands/
│ └── review.md # 可选:自定义命令
├── mcp-servers/
│ └── my-server/ # 可选:捆绑的 MCP Server
│ ├── package.json
│ └── index.js
├── README.md # 必须:文档
└── LICENSE # 推荐:开源协议
plugin.json 清单文件全解析plugin.json 是插件的灵魂,位于 .claude-plugin/ 目录下:
{
"name": "code-quality-toolkit",
"version": "1.0.0",
"description": "A comprehensive code quality toolkit with review, lint, and refactor skills",
"author": {
"name": "Your Name",
"url": "https://github.com/yourusername"
},
"repository": "https://github.com/yourusername/code-quality-toolkit",
"license": "MIT",
"keywords": ["code-review", "quality", "refactor", "lint"],
"categories": ["development", "code-quality"],
"skills": [
{
"name": "code-review",
"path": "skills/code-review.md",
"triggers": ["review code", "code review", "check code quality"]
},
{
"name": "refactor",
"path": "skills/refactor.md",
"triggers": ["refactor", "improve code structure"]
}
],
"hooks": {
"PreToolUse": [
{
"matcher": "Write|Edit",
"command": "hooks/pre-commit.sh",
"description": "Run quality checks before file edits"
}
]
},
"commands": [
{
"name": "review",
"description": "Run a comprehensive code review on the current file",
"path": "commands/review.md"
}
],
"compatibility": {
"claudeCodeVersion": ">=1.0.50"
}
}
关键字段说明:
name:插件唯一标识符,使用小写kebab-case,全局唯一skills[].triggers:自然语言触发器,Claude根据用户意图匹配hooks.PreToolUse[].matcher:正则匹配工具名,决定何时触发Hookcommands[].name:注册为 /name 斜杠命令compatibility:声明最低兼容版本,避免版本冲突本节构建一个完整的、可发布的插件——code-patrol。它提供三个核心能力:代码审查、复杂度分析、自动重构建议。
# 创建项目目录
mkdir code-patrol && cd code-patrol
# 初始化插件清单
mkdir -p .claude-plugin skills commands hooks
# 创建核心文件
touch .claude-plugin/plugin.json
touch skills/quality-review.md
touch skills/complexity-analysis.md
touch commands/patrol.md
touch hooks/pre-edit-check.sh
创建 skills/quality-review.md:
---
name: quality-review
description: Perform a comprehensive code quality review following SOLID principles and clean code practices
triggers:
- review code
- code quality
- check quality
---
# Code Quality Review Skill
You are a senior code reviewer performing a thorough quality audit.
## Review Process
1. **Architecture Check**: Verify SOLID principle compliance
2. **Naming Convention**: Check variable, function, class naming clarity
3. **Error Handling**: Verify exception handling completeness
4. **Security Scan**: Flag potential OWASP Top 10 vulnerabilities
5. **Performance**: Identify N+1 queries, memory leaks, unnecessary loops
6. **Test Coverage**: Check if changed code has corresponding tests
## Output Format
For each finding, output:
| # | Category | Severity | File:Line | Description | Suggestion |
|---|----------|----------|-----------|-------------|------------|
| 1 | Security | HIGH | auth.js:42 | SQL injection risk | Use parameterized queries |
Severity levels: CRITICAL > HIGH > MEDIUM > LOW > INFO
## Rules
- NEVER suggest changes that modify external API contracts
- ALWAYS check for test coverage before suggesting refactors
- PRIORITIZE security findings over style issues
- Use the project's existing linting configuration as baseline
创建 skills/complexity-analysis.md:
---
name: complexity-analysis
description: Analyze code complexity metrics including cyclomatic complexity, cognitive complexity, and coupling
triggers:
- analyze complexity
- complexity check
- code complexity
---
# Code Complexity Analysis Skill
You are a code complexity analyst. Evaluate the codebase using industry-standard metrics.
## Metrics to Calculate
1. **Cyclomatic Complexity** (per function)
- Simple: 1-5 (no action needed)
- Moderate: 6-10 (consider simplification)
- Complex: 11-20 (should simplify)
- Untenable: 21+ (must simplify)
2. **Cognitive Complexity** (human readability score)
- Counts nesting, recursion, breaks in linear flow
3. **Coupling Analysis**
- Afferent coupling (Ca): how many depend on this module
- Efferent coupling (Ce): how many this module depends on
- Instability = Ce / (Ca + Ce)
4. **Lines of Code Distribution**
- Identify files exceeding 300 lines (refactoring threshold)
## Output Format
📊 Complexity Report ──────────────────── Total Functions: X Avg Cyclomatic: X.X High Risk Functions: [list] Recommended Refactors: [list with priority]
创建 commands/patrol.md:
---
name: patrol
description: Run a full code quality patrol on specified files or the entire project
---
# /patrol Command
Execute a complete code quality patrol:
1. First, use Glob to discover all source files in the project
2. For each file, apply the quality-review skill
3. Then apply the complexity-analysis skill
4. Aggregate findings into a single report
5. Prioritize by severity: CRITICAL and HIGH first
6. Suggest a refactoring plan with ordered steps
## Arguments
- If user specifies files/dirs: patrol only those targets
- If no arguments: patrol the entire project (exclude node_modules, .git, dist)
## Output
End with an executive summary:
- Total issues found (by severity)
- Top 3 recommended actions
- Estimated effort for each action
创建 hooks/pre-edit-check.sh:
#!/bin/bash
# Pre-edit quality gate hook
# Runs before any Write or Edit tool call
FILE_PATH="$1"
TOOL_NAME="$2"
# Only check source code files
case "$FILE_PATH" in
*.js|*.ts|*.jsx|*.tsx|*.py|*.go|*.rs|*.java)
;;
*)
exit 0 # Skip non-code files
;;
esac
# Check file size (warn if > 500 lines)
if [ -f "$FILE_PATH" ]; then
LINES=$(wc -l < "$FILE_PATH")
if [ "$LINES" -gt 500 ]; then
echo "⚠️ Warning: $FILE_PATH has $LINES lines. Consider splitting."
fi
fi
# Check for TODO/FIXME/HACK markers
if [ -f "$FILE_PATH" ]; then
MARKERS=$(grep -c -E '(TODO|FIXME|HACK|XXX):' "$FILE_PATH" 2>/dev/null || echo "0")
if [ "$MARKERS" -gt 0 ]; then
echo "ℹ️ Note: $FILE_PATH contains $MARKERS TODO/FIXME markers"
fi
fi
exit 0
赋予执行权限:
chmod +x hooks/pre-edit-check.sh
plugin.json 清单将所有组件组装到 .claude-plugin/plugin.json:
{
"name": "code-patrol",
"version": "1.0.0",
"description": "Code quality patrol toolkit: automated review, complexity analysis, and pre-edit safety gates",
"author": {
"name": "Your Name",
"url": "https://github.com/yourusername"
},
"repository": "https://github.com/yourusername/code-patrol",
"license": "MIT",
"keywords": ["code-quality", "review", "complexity", "patrol", "clean-code"],
"categories": ["development", "code-quality", "testing"],
"skills": [
{
"name": "quality-review",
"path": "skills/quality-review.md",
"triggers": ["review code", "code quality", "check quality", "quality check"]
},
{
"name": "complexity-analysis",
"path": "skills/complexity-analysis.md",
"triggers": ["analyze complexity", "complexity check", "code complexity"]
}
],
"hooks": {
"PreToolUse": [
{
"matcher": "Write|Edit",
"command": "hooks/pre-edit-check.sh",
"description": "Warn about large files and TODO markers before edits"
}
]
},
"commands": [
{
"name": "patrol",
"description": "Run a full code quality patrol on the project",
"path": "commands/patrol.md"
}
],
"compatibility": {
"claudeCodeVersion": ">=1.0.50"
}
}
有三种本地安装方式:
方式一:直接路径安装(开发推荐)
claude plugin add /path/to/code-patrol
方式二:Git仓库安装
# 先推送到 GitHub
cd code-patrol
git init && git add . && git commit -m "Initial plugin"
git remote add origin https://github.com/yourusername/code-patrol.git
git push -u origin main
# 然后安装
claude plugin add https://github.com/yourusername/code-patrol
方式三:在 settings.json 中配置
{
"plugins": {
"local": [
"/path/to/code-patrol"
]
}
}
# 查看已安装插件列表
claude plugin list
# 预期输出
# code-patrol v1.0.0 - Code quality patrol toolkit...
# Skills: quality-review, complexity-analysis
# Commands: /patrol
# Hooks: PreToolUse (Write|Edit)
启动Claude Code交互会话后,按以下顺序测试:
graph LR
A[安装插件] --> B[验证 Skill 加载]
B --> C["测试触发词<br/>'review code'"]
C --> D["测试命令<br/>/patrol"]
D --> E[测试 Hook]
E --> F[编辑一个 .js 文件]
F --> G{Hook 触发?}
G -->|✅| H[看到文件大小警告]
G -->|❌| I[检查 Hook 路径和权限]
H --> J[测试完成 ✅]
测试场景一:Skill触发
在Claude Code中输入:
> 请对我的 src/auth.js 做一次 code quality check
Claude应该自动加载 quality-review skill,并按照模板格式输出审查结果。
测试场景二:自定义命令
> /patrol src/
Claude应该执行 patrol.md 中定义的完整巡检流程。
测试场景三:Hook触发
> 请修改 src/utils.js 的第50行
在Claude执行 Write 或 Edit 工具前,应该看到Hook输出的文件行数警告或TODO标记提示。
| 检查项 | 要求 | 状态 |
|---|---|---|
plugin.json 格式正确 |
JSON Schema 验证通过 | ☐ |
| 每个 Skill 有完整 frontmatter | name + description + triggers | ☐ |
| Hook 脚本有执行权限 | chmod +x |
☐ |
| README.md 存在且内容完整 | 安装说明 + 使用示例 | ☐ |
| LICENSE 文件存在 | OSI 批准的开源协议 | ☐ |
| 无硬编码路径或密钥 | 全部使用相对路径 | ☐ |
| 最低版本声明正确 | compatibility.claudeCodeVersion |
☐ |
| 插件名称唯一 | 在 Marketplace 中搜索确认 | ☐ |
第一步:Fork官方仓库
# Fork anthropics/claude-plugins-official
gh repo fork anthropics/claude-plugins-official --clone
cd claude-plugins-official
第二步:添加插件注册信息
在 plugins/registry.json 中添加条目:
{
"name": "code-patrol",
"repository": "https://github.com/yourusername/code-patrol",
"version": "1.0.0",
"description": "Code quality patrol toolkit",
"author": "yourusername",
"categories": ["development", "code-quality"],
"installCommand": "claude plugin add https://github.com/yourusername/code-patrol"
}
第三步:创建Pull Request
git checkout -b add-code-patrol-plugin
git add plugins/registry.json
git commit -m "Add code-patrol plugin to registry"
git push origin add-code-patrol-plugin
gh pr create \
--title "Add plugin: code-patrol" \
--body "Code quality patrol toolkit with review, complexity analysis, and pre-edit safety gates."
第四步:审核流程
Anthropic团队会进行以下审核:
sequenceDiagram
participant Dev as 开发者
participant GH as GitHub PR
participant Bot as 自动化审查
participant Review as Anthropic审核员
Dev->>GH: 提交 PR
GH->>Bot: 触发 CI 检查
Bot->>Bot: JSON Schema 验证
Bot->>Bot: Skill 内容扫描
Bot->>Bot: 安全检查(无恶意Hook)
Bot-->>GH: ✅ 检查通过 / ❌ 报告问题
GH->>Review: 人工审核队列
Review->>Review: 功能测试
Review->>Review: 代码质量评估
Review-->>GH: 合并 PR
GH-->>Dev: 插件上架 ✅
如果插件不适合公开(如公司内部工具),可以搭建私有Marketplace:
# 创建团队插件仓库
mkdir team-plugins && cd team-plugins
git init
# 添加插件索引
cat > registry.json << 'EOF'
{
"name": "team-internal-plugins",
"plugins": [
{
"name": "code-patrol",
"repository": "[email protected]:tools/code-patrol.git",
"version": "1.0.0"
}
]
}
EOF
# 团队成员添加私有源
claude plugin source add https://github.yourcompany.com/tools/team-plugins
Plugin的Hook系统支持13种生命周期事件。以下是 code-patrol 可扩展的Hook配置:
{
"hooks": {
"PreToolUse": [
{
"matcher": "Write|Edit",
"command": "hooks/pre-edit-check.sh",
"description": "Pre-edit quality gate"
},
{
"matcher": "Bash",
"command": "hooks/command-audit.sh",
"description": "Audit dangerous commands"
}
],
"PostToolUse": [
{
"matcher": "Write|Edit",
"command": "hooks/post-edit-lint.sh",
"description": "Auto-lint after edits"
}
],
"Notification": [
{
"matcher": ".*",
"command": "hooks/notify-team.sh",
"description": "Notify team channel on important events"
}
],
"Stop": [
{
"matcher": ".*",
"command": "hooks/summary-report.sh",
"description": "Generate session summary on stop"
}
]
}
}
Hook事件优先级与执行顺序:
SessionStart — 会话开始时(适合加载项目配置)PreToolUse — 工具调用前(适合权限控制、预处理)PostToolUse — 工具调用后(适合自动格式化、日志)Notification — 通知触发时(适合集成Slack/飞书)Stop — 会话结束时(适合生成报告、清理)SubagentStop — 子代理完成时(适合结果汇总)规则一:触发词要具体且多元
# ❌ 不好的触发词
triggers:
- code
- review
# ✅ 好的触发词
triggers:
- review code quality
- check code for issues
- audit code standards
- 质量审查
- 代码检查
规则二:Skill内容要有约束边界
# ❌ 过于宽泛
You are a helpful code assistant...
# ✅ 有明确边界
You are a code quality reviewer. You ONLY review code.
You do NOT write new code or fix bugs.
Your output format is STRICTLY a markdown table.
规则三:避免Token浪费
Skill内容会被注入到上下文中,控制长度:
code-patrol/
├── v1.0.0 → 初始版本:quality-review + complexity-analysis
├── v1.1.0 → 新增:security-scan skill
├── v1.2.0 → 新增:/patrol-fast 命令
└── v2.0.0 → 破坏性变更:plugin.json schema 升级
在 plugin.json 中维护版本号,并使用语义化版本控制(SemVer):
# 开启插件调试日志
export CLAUDE_CODE_DEBUG=plugins
# 查看Skill加载详情
claude --debug-skill quality-review
# 验证plugin.json格式
npx -y ajv validate -s plugin-schema.json -d .claude-plugin/plugin.json
# 测试单个Hook
echo "test.js Write" | bash hooks/pre-edit-check.sh
从构思到上架的全流程:
flowchart TB
subgraph "阶段一:设计"
A[确定插件目标] --> B[选择包含的组件<br/>Skills/Hooks/Commands/MCP]
B --> C[规划目录结构]
end
subgraph "阶段二:开发"
C --> D[编写 plugin.json]
D --> E[编写 Skill 文件]
E --> F[编写 Hook 脚本]
F --> G[编写 Command 定义]
end
subgraph "阶段三:测试"
G --> H[本地路径安装]
H --> I[逐项功能测试]
I --> J{测试通过?}
J -->|否| K[修复问题]
K --> H
J -->|是| L[准备发布]
end
subgraph "阶段四:发布"
L --> M[创建 GitHub 仓库]
M --> N{公开 or 私有?}
N -->|公开| O[Fork 官方仓库]
O --> P[提交 PR 到 Registry]
P --> Q[审核通过 → 上架]
N -->|私有| R[部署私有 Marketplace]
R --> S[团队内分发]
end
style A fill:#4A90D9,color:#fff
style Q fill:#7ED321,color:#fff
style S fill:#7ED321,color:#fff
原因:触发词不匹配或Skill未正确注册。
# 检查插件状态
claude plugin info code-patrol
# 确认Skill已加载(查看输出中的 skills 列表)
claude plugin list --verbose
解决:确保 plugin.json 中 skills[].path 是相对于插件根目录的正确路径。
原因:脚本缺少执行权限或路径错误。
# 检查权限
ls -la hooks/pre-edit-check.sh
# 应显示 -rwxr-xr-x
# 修复权限
chmod +x hooks/pre-edit-check.sh
常见CI检查失败原因:
plugin.json 不符合JSON Schemarm -rf)当两个插件注册了相同的 /command 或Hook匹配器时:
# 查看冲突
claude plugin list --conflicts
# 解决方案:在 plugin.json 中限定作用域
{
"commands": [{
"name": "patrol",
"scope": "project", // 仅在包含特定文件时激活
"activator": "package.json"
}]
}
训练营适用性评估:
| 训练营类型 | 适用性 | 预计时长 | 备注 |
|---|---|---|---|
| Claude Code 进阶训练营 | ★★★★★ | 3小时 | 核心模块,含动手实验 |
| AI 工具生态开发者训练营 | ★★★★★ | 4小时 | 含完整的构建→测试→发布流程 |
| 企业DevOps自动化训练营 | ★★★★☆ | 2小时 | 侧重Hook和私有Marketplace |
| Claude Code 入门训练营 | ★★★☆☆ | 1.5小时 | 精简版,仅覆盖安装和使用已有插件 |
| 全栈开发者训练营 | ★★★★☆ | 2.5小时 | 侧重实战案例和代码质量场景 |
前置知识要求:需先掌握Claude Code基础操作(安装、对话、文件编辑)和Skill的基本概念。建议作为2-3天训练营的第二或第三天内容,在学员熟悉Claude Code基础后进行。
[!tip] 51学通信知识星球 星主:爱卫生(微信:gprshome201101)——公众号「51学通信」创办者,19 年通信行业运维与讲师经验,著有《GPRS网络信令实例详解》《EPC原理与实践》《5G核心网原理与实践》三本纸质书(各大电商平台有售)。 星球定位:深耕 5G 核心网、IMS、NFV/AI、云原生等 ICT 领域,主打运维岗位与信令分析。 当前规模:5200 篇主题 / 990 个回答,198 元/年。 加入福利:加入星球后请加爱卫生微信,拉您进知识星球年度陪伴与答疑群——不限量回复您的各种问题,另有群内分享。 AI 加持:51学通信知识星球已作为 skill 接入 WorkBuddy,使用 deepseek-4-flash 在海量星球帖子中精准找贴、找视频、找 FAQ 和案例,做总结、找文档和 PPT 等场景全覆盖。
