Claude Code 插件开发完全指南:从入门到精通官方 Plugin-Dev
Claude Code 插件开发完全指南:从入门到精通官方 Plugin-Dev
Claude Code 的强大之处不仅在于其 AI 能力,更在于其插件生态系统。通过插件,你可以扩展 Claude Code 的功能,集成外部工具,自动化工作流,并将专业知识打包成可复用的组件。
Anthropic 官方维护了一个 claude-plugins-official 仓库,其中包含了一个 plugin-dev 插件——它是插件的插件,专门用于帮助开发者学习如何构建高质量的 Claude Code 插件。
本文将:
- 解析什么是 Claude Code Plugin
- 深入 plugin-dev 官方插件的结构和设计
- 展示如何从零开始构建一个插件
- 分享最佳实践和高级技巧
- 提供实战案例和完整示例
什么是 Claude Code Plugin?
Plugin 的本质
Plugin 是一个自包含的目录,包含以下组件:
my-plugin/
├── .claude-plugin/
│ └── plugin.json # 插件清单(必需)
├── commands/ # Slash 命令
├── agents/ # 专业化子智能体
├── skills/ # 自动激活的知识模块
├── hooks/ # 事件处理器
│ ├── hooks.json
│ └── scripts/
├── .mcp.json # MCP 服务器集成
└── scripts/ # 共享脚本工具核心概念:
| 组件 | 用途 | 触发方式 |
|---|---|---|
| Skills | 注入项目知识、技术栈规范 | 自动检测或手动加载 |
| Agents | 专门的子智能体,并行处理任务 | 主 Agent 分派 |
| Commands | 快捷命令(如 /review) |
用户手动调用 |
| Hooks | 在特定事件时自动执行 | 事件触发(SessionStart、PreToolUse 等) |
| MCP | 集成外部工具和 API | 按 need 调用 |
Plugin vs 本地配置
| 特性 | 本地配置 (.claude/) |
Plugin |
|---|---|---|
| 可移植性 | 绑定到项目 | 可跨项目复用 |
| 分发 | Git 同步 | 可发布到市场 |
| 版本管理 | 随项目代码 | 独立版本控制 |
| 发现性 | 手动设置 | 市场搜索安装 |
| 更新 | 手动更新 | 自动更新 |
使用场景:
- 本地配置:项目特定的约定、团队规范
- Plugin:通用功能、可复用工具、公开分享
官方 plugin-dev 插件解析
plugin-dev 是什么?
plugin-dev 是一个教学插件,它展示了如何构建一个高质量的 Claude Code 插件。它包含:
- 完整的示例代码:Skills、Agents、Commands、Hooks
- 详细的文档:每个组件都有 SKILL.md 说明
- 最佳实践:官方推荐的目录结构和命名规范
- 参考实现:可以直接复制粘贴的模板
plugin-dev 目录结构
plugin-dev/
├── .claude-plugin/
│ └── plugin.json # 插件清单
├── commands/ # 示例命令
│ ├── create-plugin.md
│ ├── validate-manifest.md
│ └── test-skill.md
├── skills/ # 教学技能
│ ├── plugin-structure/
│ │ └── SKILL.md # 插件结构指南
│ ├── plugin-structure/
│ │ ├── examples/
│ │ │ ├── minimal-plugin.md
│ │ │ ├── standard-plugin.md
│ │ │ └── advanced-plugin.md
│ │ └── references/
│ │ ├── manifest-reference.md
│ │ └── plugin-anatomy.md
│ ├── command-development/
│ │ └── SKILL.md
│ ├── agent-development/
│ │ └── SKILL.md
│ ├── skill-development/
│ │ └── SKILL.md
│ └── hook-development/
│ └── SKILL.md
├── agents/ # 示例 Agents
│ ├── plugin-validator.md
│ └── code-reviewer.md
├── hooks/
│ ├── hooks.json
│ └── scripts/
│ └── validate.sh
└── .mcp.json # MCP 示例配置plugin.json 清单文件
.claude-plugin/plugin.json:
{
"name": "plugin-dev",
"version": "1.0.0",
"description": "Official plugin development guide and examples",
"author": {
"name": "Anthropic",
"email": "support@anthropic.com",
"url": "https://anthropic.com"
},
"homepage": "https://github.com/anthropics/claude-plugins-official",
"repository": {
"type": "git",
"url": "https://github.com/anthropics/claude-plugins-official.git"
},
"license": "MIT",
"keywords": [
"plugin",
"development",
"tutorial",
"examples"
],
"commands": [
"./commands"
],
"agents": [
"./agents"
],
"skills": [
"./skills"
],
"hooks": "./hooks/hooks.json",
"mcpServers": "./.mcp.json"
}关键字段说明:
name:插件唯一标识符(安装时使用)version:遵循语义化版本(SemVer)commands/agents/skills:组件路径,可以是目录或单个文件hooks:Hooks 配置文件路径mcpServers:MCP 服务器配置文件路径
从零开始:构建你的第一个 Plugin
步骤 1:初始化插件结构
# 创建插件目录
mkdir my-first-plugin
cd my-first-plugin
# 创建必要的目录
mkdir -p .claude-plugin commands agents skills hooks/scripts
# 创建 plugin.json
cat > .claude-plugin/plugin.json << 'EOF'
{
"name": "my-first-plugin",
"version": "0.1.0",
"description": "My first Claude Code plugin",
"author": {
"name": "Your Name"
},
"license": "MIT",
"commands": ["./commands"],
"skills": ["./skills"]
}
EOF步骤 2:创建第一个 Command
commands/hello.md:
---
description: Say hello and demonstrate plugin functionality
---
# Hello Command
This is a simple command that demonstrates how plugins work.
## What it does
- Prints a greeting
- Shows plugin metadata
- Displays current time
## Usage
Type `/hello` in the Claude Code REPL to invoke this command.步骤 3:创建第一个 Skill
skills/project-info/SKILL.md:
---
name: project-info
description: Load project-specific information and context
---
# Project Information
## Project Overview
This is a {{framework}} project using {{language}}.
## Key Technologies
- Frontend: {{frontend}}
- Backend: {{backend}}
- Database: {{database}}
## Development Rules
1. Follow {{style_guide}}
2. Write tests for all new features
3. Run linter before committing步骤 4:本地测试插件
# 在项目目录中创建本地配置
mkdir -p .claude
cat > .claude/settings.local.json << 'EOF'
{
"plugins": [
"../my-first-plugin"
]
}
EOF
# 启动 Claude Code
claude
# 在 Claude Code 中测试
> /hello
> Load project-info skill深入组件开发
1. Skills:可复用的知识模块
Skill 是 Plugin 的知识单元,用于封装:
- 技术栈信息:框架、库、工具的最佳实践
- 项目约定:代码风格、命名规范
- 领域知识:业务逻辑、行业规范
- 工作流程:开发流程、部署步骤
示例:React 最佳实践 Skill
skills/react-best-practices/SKILL.md:
---
name: react-best-practices
description: React development best practices and patterns
---
# React Best Practices
## Component Design
### Functional Components
✅ Prefer functional components with hooks:
```tsx
function UserProfile({ userId }) {
const [user, setUser] = useState(null);
// ...
}❌ Avoid class components:
class UserProfile extends Component {
// ...
}Hooks Guidelines
- Custom hooks for reusable logic:
useUserData,useFetch - Hook rules: Only call at top level, only from React functions
- Dependency arrays: Include all dependencies, no false positives
Performance
Memoization
- Use
useMemofor expensive computations - Use
useCallbackfor callbacks passed to optimized components - Avoid premature optimization
Code Splitting
- Use
React.lazy()for route-based splitting - Use dynamic imports for heavy components
Patterns
Container/Presenter
// Container: handles logic
function UserContainer() {
const user = useUserData();
return ;
}
// Presenter: handles UI
function UserPresentational({ user }) {
return {user.name};
}Custom Hooks
function useFetch(url) {
const [data, setData] = useState(null);
const [loading, setLoading] = useState(true);
useEffect(() => {
fetch(url)
.then(r => r.json())
.then(setData)
.finally(() => setLoading(false));
}, [url]);
return { data, loading };
}
### 2. Agents:专业化子智能体
Agent 是 Plugin 的**行动单元**,用于:
- **并行处理**:多个 Agent 同时工作
- **专业分工**:每个 Agent 擅长特定领域
- **异步协作**:通过 mailbox 通信
**示例:安全审查 Agent**
**`agents/security-auditor/SKILL.md`**:
```markdown
---
name: security-auditor
description: Reviews code for security vulnerabilities
---
# Security Auditor Agent
You are a security specialist. Review the provided code for:
## 1. Common Vulnerabilities
- SQL Injection
- XSS (Cross-Site Scripting)
- CSRF (Cross-Site Request Forgery)
- Authentication/Authorization issues
- Sensitive data exposure
## 2. Dependency Security
- Outdated packages with known CVEs
- Unnecessary dependencies
- License compliance
## 3. Best Practices
- Input validation
- Output encoding
- Parameterized queries
- Secure headers
- Principle of least privilege
## Output Format
For each file:
```markdown
## Security Review: {{filename}}
### Critical Issues
1. [Issue]
- Location: line {{line_number}}
- Severity: HIGH
- Fix: {{recommendation}}
### Medium Issues
...
### Summary
- Critical: X
- Medium: Y
- Low: Z
- Overall Score: N/10Review Process
- Read the code
- Identify vulnerabilities
- Check dependencies (run
npm audit) - Provide remediation steps
- Assign risk score
### 3. Commands:快捷操作界面
Command 是 Plugin 的**用户界面**,提供:
- **快捷操作**:一键执行复杂任务
- **工作流封装**:多步骤流程自动化
- **参数化命令**:接受用户输入
**示例:完整功能开发 Command**
**`commands/feature.md`**:
```markdown
---
description: Complete feature development workflow
---
# Feature Development
Develop a new feature from start to finish.
## Step 1: Planning
Ask the user:
1. What is the feature about?
2. What are the acceptance criteria?
3. Any technical constraints?
Create a task list:
```markdown
## Tasks
- [ ] Design API
- [ ] Implement backend
- [ ] Implement frontend
- [ ] Write tests
- [ ] Update docsStep 2: Implementation
Load relevant skills:
- project-conventions
- tech-stack
- api-patterns
Implement following the task list.
Step 3: Testing
- Generate unit tests
- Generate integration tests
- Run tests and fix failures
Step 4: Review
- Self-review the code
- Check for security issues
- Verify performance
Step 5: Documentation
- Generate JSDoc
- Update README
- Create changelog entry
User Input
{{feature_description}}
Context
- Current branch: {{git_branch}}
- Uncommitted changes: {{git_status}}
### 4. Hooks:事件驱动自动化
Hook 是 Plugin 的**自动化引擎**,在特定事件时触发:
**`hooks/hooks.json`**:
```json
{
"SessionStart": [
{
"matcher": "*",
"hooks": [
{
"type": "command",
"command": "${CLAUDE_PLUGIN_ROOT}/scripts/init-env.sh",
"timeout": 10
},
{
"type": "prompt",
"prompt": "Load project-context skill and review recent git history"
}
]
}
],
"PostToolUse": [
{
"matcher": "Write|Edit.*\\.tsx?$",
"hooks": [
{
"type": "command",
"command": "npx prettier --check $CLAUDE_FILE_PATH",
"timeout": 10
},
{
"type": "command",
"command": "npx eslint $CLAUDE_FILE_PATH",
"timeout": 15
}
]
}
],
"PreToolUse": [
{
"matcher": "bash.*rm -rf",
"hooks": [
{
"type": "prompt",
"prompt": "⚠️ DANGER: About to recursively delete. Confirm this is intentional."
}
]
}
]
}hooks/scripts/init-env.sh:
#!/bin/bash
# Initialize development environment
echo "🚀 Initializing development environment..."
# Check Node.js version
if command -v node &> /dev/null; then
echo "Node version: $(node --version)"
fi
# Check dependencies
if [ -f "package.json" ]; then
echo "📦 Installing dependencies..."
npm install --silent
fi
# Check database connection
if [ -n "$DATABASE_URL" ]; then
echo "🗄️ Database URL configured"
fi
# Run type check
echo "🔍 Running type check..."
npx tsc --noEmit || echo "⚠️ Type errors found"
echo "✅ Environment ready!"5. MCP:集成外部工具
MCP (Model Context Protocol) 让 Plugin 能调用外部工具和 API。
.mcp.json:
{
"mcpServers": {
"filesystem": {
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-filesystem", "/allowed/path"]
},
"github": {
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-github"]
},
"postgres": {
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-postgres", "postgresql://user:pass@localhost:5432/db"]
},
"brave-search": {
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-brave-search"]
}
}
}使用 MCP 工具:
> Search the web for latest React best practices
(Uses brave-search MCP server)
> List open PRs in our GitHub repo
(Uses github MCP server)
> Query the users table for inactive accounts
(Uses postgres MCP server)高级技巧
1. 条件 Hooks
根据上下文条件触发:
{
"PostToolUse": [
{
"matcher": "Write.*\\.tsx?$",
"condition": "{{git_branch}} == 'main'",
"hooks": [
{
"type": "prompt",
"prompt": "⚠️ Writing to main branch. Ensure this is intentional."
}
]
}
]
}2. 共享脚本和工具
scripts/utils.sh:
#!/bin/bash
# Shared utility functions
log_info() {
echo "ℹ️ $1"
}
log_success() {
echo "✅ $1"
}
log_error() {
echo "❌ $1"
}
check_file_exists() {
if [ ! -f "$1" ]; then
log_error "File not found: $1"
return 1
fi
return 0
}在 Hook 中使用:
{
"SessionStart": [
{
"hooks": [
{
"type": "command",
"command": "${CLAUDE_PLUGIN_ROOT}/scripts/utils.sh && check_file_exists package.json"
}
]
}
]
}3. 动态配置
scripts/load-config.sh:
#!/bin/bash
# Load project-specific configuration
if [ -f ".claude/config.json" ]; then
echo "📋 Loading project config..."
cat .claude/config.json
fi
if [ -f ".env" ]; then
echo "🔐 Environment variables detected"
grep -v "^#" .env | grep "=" | head -5
fi4. 多语言支持
如果你的插件支持多种编程语言,可以组织 Skills:
skills/
├── python/
│ ├── SKILL.md
│ └── references/
├── javascript/
│ ├── SKILL.md
│ └── references/
└── rust/
├── SKILL.md
└── references/plugin.json:
{
"skills": [
"./skills/python",
"./skills/javascript",
"./skills/rust"
]
}实战案例:构建企业级插件
场景:电商网站开发助手
插件结构:
ecommerce-helper/
├── .claude-plugin/
│ └── plugin.json
├── commands/
│ ├── feature.md # 新功能开发
│ ├── bugfix.md # Bug 修复工作流
│ └── deploy.md # 部署流程
├── agents/
│ ├── security-reviewer.md # 安全审查
│ ├── performance-tuner.md # 性能优化
│ └── test-generator.md # 测试生成
├── skills/
│ ├── tech-stack/ # 技术栈知识
│ ├── api-patterns/ # API 设计模式
│ └── business-rules/ # 业务规则
├── hooks/
│ ├── hooks.json
│ └── scripts/
│ ├── pre-commit.sh
│ └── post-merge.sh
└── .mcp.jsonplugin.json:
{
"name": "ecommerce-helper",
"version": "1.0.0",
"description": "Enterprise e-commerce development assistant",
"author": {
"name": "DevOps Team",
"email": "devops@company.com"
},
"keywords": [
"ecommerce",
"next.js",
"stripe",
"prisma"
],
"commands": ["./commands"],
"agents": ["./agents"],
"skills": ["./skills"],
"hooks": "./hooks/hooks.json",
"mcpServers": "./.mcp.json"
}hooks/hooks.json(质量门禁):
{
"PostToolUse": [
{
"matcher": "Write.*\\.tsx?$",
"hooks": [
{
"type": "command",
"command": "npm run lint",
"timeout": 30
},
{
"type": "command",
"command": "npm run test:related",
"timeout": 60
}
]
}
],
"Stop": [
{
"matcher": "*",
"hooks": [
{
"type": "prompt",
"prompt": "Run e-commerce specific checks: cart calculations, payment flow, inventory updates. Generate test report."
}
]
}
]
}发布你的 Plugin
1. 准备发布
检查清单:
- 所有组件都有文档
-
plugin.json完整且准确 - 测试所有 Commands
- 验证 Hooks 不会死锁
- 添加 README.md
- 添加 LICENSE 文件
2. 发布到 GitHub
# 初始化 Git 仓库
git init
git add .
git commit -m "Initial release: v1.0.0"
# 推送到 GitHub
git remote add origin git@github.com:username/ecommerce-helper.git
git push -u origin main
# 创建 Release
gh release create v1.0.0 --notes "First release of ecommerce-helper plugin"3. 提交到官方市场
目前 Anthropic 官方插件市场正在完善中。你可以:
- 在社区分享:在 Reddit、Discord、GitHub 分享你的插件
- 发布到 GitHub:使用
claude-plugintopic 标记 - 等待官方市场:关注 Anthropic 官方公告
4. 版本管理
遵循语义化版本(SemVer):
- MAJOR(1.0.0 → 2.0.0):破坏性变更
- MINOR(1.0.0 → 1.1.0):新功能,向后兼容
- PATCH(1.0.0 → 1.0.1):Bug 修复
最佳实践
✅ DO
- 保持专注:每个插件解决一个明确的问题
- 文档先行:每个组件都有清晰的说明
- 渐进增强:从最小可用插件开始
- 测试充分:在多种场景下测试
- 错误处理:Hooks 设置合理的 timeout
- 权限控制:限制插件能访问的路径
- 版本兼容:明确最低 Claude Code 版本要求
❌ DON'T
- 过度设计:不要为了炫技而添加复杂功能
- 硬编码路径:使用
${CLAUDE_PLUGIN_ROOT}变量 - 忽略性能:避免在 Hook 中执行耗时操作
- 假设环境:不要假设特定的工具或版本
- 破坏性变更:MINOR 版本不应破坏向后兼容性
- 忽略安全:验证用户输入,限制危险操作
- 混淆视听:保持命名清晰、一致
调试技巧
1. 本地测试
# 在项目目录中引用本地插件
cat > .claude/settings.local.json << 'EOF'
{
"plugins": [
{
"name": "my-plugin",
"source": "local",
"path": "/path/to/my-plugin"
}
]
}
EOF
# 启动 Claude Code 并查看日志
claude --debug2. 测试单个组件
# 测试 Command
> /my-command
# 测试 Skill
> Load my-skill
# 测试 Agent
> Ask my-agent to review this file3. 验证 Hooks
# 手动触发 Hook 脚本
./hooks/scripts/pre-commit.sh
# 检查输出
echo $? # 应该为 04. 查看插件状态
> /plugin list
> /plugin status my-plugin
> /plugin reload my-plugin资源与参考
官方资源
- Anthropic Claude Plugins Official - 官方插件目录
- Plugin Reference - Claude Code Docs - 完整插件参考
- MCP Specification - Model Context Protocol
- Complete Guide to Building Skills (PDF) - 官方 Skill 构建指南
教程与文章
- How to Build Claude Code Plugins - DataCamp - 完整教程
- Claude Agent Skills: Teaching AI to Wear Multiple Hats - Skills 深度解析
- Understanding Plugins, Agents, Skills - Reddit - 社区讨论
视频教程
社区
- r/ClaudeCode - Subreddit 社区
- Claude Code Discord - 官方 Discord
总结
Claude Code Plugin 是扩展 AI 编程助手能力的最佳方式。通过插件,你可以:
- 封装专业知识:Skills 存储团队规范和最佳实践
- 并行处理任务:Agents 协作完成复杂工作流
- 一键执行操作:Commands 提供快捷界面
- 自动化工作流:Hooks 在关键时刻触发
- 集成外部工具:MCP 连接无限可能
开始建议:
- 安装 plugin-dev:
/plugin install plugin-dev@claude-plugins-official - 学习示例:阅读 plugin-dev 的所有 Skills
- 复制模板:使用示例作为起点
- 小步迭代:从简单 Command 开始,逐步添加功能
- 社区分享:发布你的插件,获得反馈
记住:最好的插件是那些解决真实问题、文档清晰、易于使用的插件。
下一步行动
安装官方 plugin-dev:
/plugin install plugin-dev@claude-plugins-official探索插件结构:
> Load plugin-structure skill创建你的第一个插件:
> /create-plugin my-awesome-plugin测试并发布:
> /validate-plugin
Happy Plugin Development! 🚀
Sources: