<!-- title: Plugin全栈实战：三合一打包到发布 -->

# Claude Code Plugin全栈开发：从零构建到生态发布的完整实战

## 概述

Claude Code Plugin是2026年Anthropic推出的最高层级扩展机制——它将Skills（技能指令）、Hooks（生命周期钩子）、MCP Servers（工具服务）三大扩展能力打包成一个可分发、可版本化的独立单元。本教程面向已有Claude Code基础使用经验的开发者，带你从理解Plugin架构开始，逐步构建一个完整的代码质量守护Plugin，最终发布到团队Marketplace。

**学习目标**：掌握Plugin架构原理、手动创建完整Plugin项目、理解plugin.json清单配置、调试和测试Plugin、发布到Marketplace。

**适用人群**：已熟悉Claude Code基本操作和至少一种扩展方式（Skills/Hooks/MCP）的开发者。

## 前置条件

| 项目 | 要求 |
|------|------|
| Claude Code | >= 1.0.50（支持Plugin系统） |
| Node.js | >= 18.x |
| Git | 用于版本管理和分发 |
| 基础知识 | 理解JSON配置、Shell脚本、TypeScript基础 |

```bash
# 确认Claude Code版本
claude --version
# 应显示 1.0.50 或更高
```

---

## 一、为什么需要Plugin：三层扩展的统一封装

### 1.1 扩展能力的演进路线

Claude Code的扩展体系经历了三个阶段的演进：

```mermaid
graph TD
    A["阶段一：原子扩展<br/>Skills / Hooks / MCP"] --> B["阶段二：项目级配置<br/>settings.json + CLAUDE.md"]
    B --> C["阶段三：Plugin系统<br/>三合一打包分发"]

    A1["Skills: 指令模板<br/>轻量级，纯文本"] --> A
    A2["Hooks: 事件钩子<br/>确定性Shell/HTTP"] --> A
    A3["MCP: 工具服务<br/>运行时能力扩展"] --> A

    C --> C1["单一manifest<br/>plugin.json"]
    C --> C2["可版本化<br/>Git tag/release"]
    C --> C3["可分发<br/>Marketplace/Git"]
    C --> C4["可组合<br/>多Plugin共存"]

    style C fill:#4A90D9,color:#fff
    style C1 fill:#6AB0DE,color:#fff
    style C2 fill:#6AB0DE,color:#fff
    style C3 fill:#6AB0DE,color:#fff
    style C4 fill:#6AB0DE,color:#fff
```

在Plugin出现之前，扩展Claude Code意味着要手动配置三套独立系统：
- Skills写在 `.claude/skills/` 目录下
- Hooks配置在 `settings.json` 的 `hooks` 字段中
- MCP Servers需要在 `.mcp.json` 或 `settings.json` 中声明

这种方式在单项目中可以工作，但**无法跨项目复用、无法版本管理、无法团队共享**。Plugin系统将三者统一封装，解决了这些痛点。

### 1.2 Plugin vs 裸扩展：决策矩阵

| 维度 | 裸扩展（Skills/Hooks/MCP） | Plugin |
|------|---------------------------|--------|
| 分发方式 | 复制文件/JSON | Git仓库/Marketplace |
| 版本管理 | 无内置支持 | 语义化版本 |
| 组件耦合 | 独立配置，无关联 | 统一manifest，逻辑关联 |
| 安装方式 | 手动复制配置 | `claude plugin add` |
| 适用场景 | 个人项目快速定制 | 团队共享、社区分发 |
| 维护成本 | 高（散落多处） | 低（集中管理） |

**决策原则**：如果只是个人快速实验，直接用Skills或Hooks即可。如果需要团队复用、版本管理、或打算发布到社区，就应该打包成Plugin。

---

## 二、Plugin架构深度解析

### 2.1 目录结构

一个完整的Plugin项目遵循以下结构：

```
my-quality-plugin/
├── .claude-plugin/
│   └── plugin.json          # 核心清单文件（必须）
├── skills/
│   ├── review.md            # Skill：代码审查指令
│   └── fix-quality.md       # Skill：质量修复指令
├── hooks/
│   └── format-on-save.sh    # Hook脚本：自动格式化
├── agents/
│   └── reviewer.yaml        # Agent定义：审查Agent
├── mcp/
│   └── quality-server/      # MCP Server源码
│       ├── package.json
│       ├── tsconfig.json
│       └── src/
│           └── index.ts
├── commands/
│   └── quality-check.md     # 斜杠命令定义
├── CLAUDE.md                # Plugin级上下文指令
└── README.md                # 使用说明
```

**关键规则**：
1. `plugin.json` 必须位于 `.claude-plugin/` 目录下，这是Claude Code自动发现Plugin的入口
2. Skills、Hooks、Agents、Commands放在Plugin根目录的对应子目录中
3. MCP Server可以是内嵌的（源码在Plugin内），也可以是外引的（指向已有URL）

### 2.2 plugin.json 清单全解

`plugin.json` 是Plugin的核心清单，定义了Plugin的身份、组件和配置：

```json
{
  "name": "code-quality-guardian",
  "version": "1.2.0",
  "description": "Automated code quality enforcement with linting, formatting, and review",
  "author": "your-name",
  "license": "MIT",
  "repository": "https://github.com/your-org/code-quality-guardian",
  
  "components": {
    "skills": [
      { "path": "skills/review.md", "command": "review" },
      { "path": "skills/fix-quality.md", "command": "fix-quality" }
    ],
    "hooks": [
      {
        "event": "PostToolUse",
        "matcher": "Edit|Write",
        "command": "bash hooks/format-on-save.sh",
        "description": "Auto-format after file edits"
      }
    ],
    "agents": [
      { "path": "agents/reviewer.yaml", "name": "code-reviewer" }
    ],
    "mcpServers": {
      "quality-tools": {
        "command": "node",
        "args": ["mcp/quality-server/dist/index.js"],
        "description": "Code quality analysis tools"
      }
    },
    "commands": [
      { "path": "commands/quality-check.md", "name": "quality-check" }
    ]
  },
  
  "dependencies": {
    "node": ">=18.0.0"
  },
  
  "settings": {
    "permissions": {
      "allow": [
        "Bash(npx prettier --write *)",
        "Bash(npx eslint --fix *)"
      ]
    }
  }
}
```

**字段说明**：

| 字段 | 类型 | 必须 | 说明 |
|------|------|------|------|
| `name` | string | 是 | Plugin唯一标识，小写+连字符 |
| `version` | string | 是 | 语义化版本号（semver） |
| `description` | string | 是 | 一句话描述 |
| `author` | string | 否 | 作者信息 |
| `license` | string | 否 | 开源协议 |
| `repository` | string | 否 | Git仓库地址 |
| `components.skills` | array | 否 | Skill组件列表 |
| `components.hooks` | array | 否 | Hook定义列表 |
| `components.agents` | array | 否 | Agent定义列表 |
| `components.mcpServers` | object | 否 | MCP Server配置 |
| `components.commands` | array | 否 | 斜杠命令列表 |
| `settings` | object | 否 | 安装时注入的权限和配置 |

---

## 三、实战：构建代码质量守护Plugin

我们将构建一个名为 `code-quality-guardian` 的Plugin，它包含：
- **2个Skills**：代码审查和自动修复
- **1个Hook**：编辑后自动格式化
- **1个MCP Server**：代码复杂度分析工具
- **1个Agent**：专门的审查Agent

### 3.1 初始化项目

```bash
# 创建项目目录
mkdir code-quality-guardian && cd code-quality-guardian

# 初始化Git
git init

# 创建Plugin清单目录
mkdir -p .claude-plugin

# 创建组件目录
mkdir -p skills hooks agents mcp/quality-server/src commands
```

### 3.2 创建plugin.json清单

```bash
cat > .claude-plugin/plugin.json << 'MANIFEST'
{
  "name": "code-quality-guardian",
  "version": "1.0.0",
  "description": "Code quality enforcement: auto-format, lint, complexity analysis, and review",
  "author": "dev-team",
  "license": "MIT",
  "components": {
    "skills": [
      { "path": "skills/review.md", "command": "review" },
      { "path": "skills/fix-quality.md", "command": "fix-quality" }
    ],
    "hooks": [
      {
        "event": "PostToolUse",
        "matcher": "Edit|Write",
        "command": "bash hooks/format-on-save.sh",
        "description": "Auto-format edited files"
      },
      {
        "event": "PreToolUse",
        "matcher": "Bash",
        "command": "bash hooks/block-destructive.sh",
        "description": "Block destructive shell commands"
      }
    ],
    "agents": [
      { "path": "agents/reviewer.yaml", "name": "code-reviewer" }
    ],
    "mcpServers": {
      "complexity-analyzer": {
        "command": "node",
        "args": ["mcp/quality-server/dist/index.js"],
        "description": "Code complexity and quality analysis"
      }
    },
    "commands": [
      { "path": "commands/quality-check.md", "name": "quality-check" }
    ]
  },
  "settings": {
    "permissions": {
      "allow": [
        "Bash(npx prettier --write *)",
        "Bash(npx eslint --fix *)",
        "Bash(node mcp/quality-server/dist/index.js *)"
      ]
    }
  }
}
MANIFEST
```

### 3.3 编写Skills

**skills/review.md** — 代码审查Skill：

```markdown
---
name: review
description: Perform a comprehensive code quality review
---

You are a senior code reviewer. Analyze the current codebase or specified files for:

1. **Code Smells**: Long functions, deep nesting, duplicate logic
2. **Security Issues**: SQL injection, XSS, hardcoded secrets
3. **Performance**: N+1 queries, unnecessary re-renders, memory leaks
4. **Type Safety**: Missing type annotations, `any` types, unsafe casts
5. **Test Coverage**: Untested edge cases, missing assertions

For each finding:
- Rate severity: 🔴 Critical / 🟡 Warning / 🔵 Info
- Show the exact file and line
- Suggest a concrete fix with code

Output a summary with:
- Total findings by severity
- Top 3 priority fixes
- Overall quality score (0-100)
```

**skills/fix-quality.md** — 自动修复Skill：

```markdown
---
name: fix-quality
description: Automatically fix code quality issues
---

You are an automated code quality fixer. Based on the issues identified:

1. Read the files that need fixing
2. Apply fixes in priority order:
   - 🔴 Critical security issues first
   - 🟡 Warnings next
   - 🔵 Info items last
3. For each fix:
   - Use the Edit tool to make changes
   - Add a brief comment explaining the fix
4. After all fixes, run the project's test suite
5. Report: files changed, fixes applied, test results

Rules:
- Never change business logic, only quality improvements
- Preserve existing comments unless they're misleading
- Run tests after every 3 file changes
- If a fix breaks tests, revert immediately and report
```

### 3.4 编写Hooks

**hooks/format-on-save.sh** — PostToolUse Hook，文件编辑后自动格式化：

```bash
#!/usr/bin/env bash
# format-on-save.sh - PostToolUse Hook for auto-formatting
# Reads JSON from stdin, formats the edited file

set -euo pipefail

# 读取Hook输入（JSON格式）
INPUT=$(cat)
FILE_PATH=$(echo "$INPUT" | jq -r '.tool_input.file_path // empty')

# 如果没有文件路径，退出
[[ -z "$FILE_PATH" ]] && exit 0

# 根据文件扩展名选择格式化工具
case "$FILE_PATH" in
  *.ts|*.tsx|*.js|*.jsx|*.json|*.css|*.md)
    # 检查prettier是否可用
    if command -v npx &>/dev/null; then
      npx --yes prettier --write "$FILE_PATH" 2>/dev/null || true
    fi
    ;;
  *.py)
    if command -v black &>/dev/null; then
      black "$FILE_PATH" 2>/dev/null || true
    fi
    ;;
  *.go)
    if command -v gofmt &>/dev/null; then
      gofmt -w "$FILE_PATH" 2>/dev/null || true
    fi
    ;;
esac

# 返回JSON输出（可选：包含格式化结果）
echo "{\"status\": \"formatted\", \"file\": \"$FILE_PATH\"}"
```

**hooks/block-destructive.sh** — PreToolUse Hook，拦截危险命令：

```bash
#!/usr/bin/env bash
# block-destructive.sh - PreToolUse Hook to block dangerous commands

set -euo pipefail

INPUT=$(cat)
COMMAND=$(echo "$INPUT" | jq -r '.tool_input.command // empty')

# 危险命令模式
DANGEROUS_PATTERNS=(
  "rm -rf /"
  "rm -rf ~"
  "rm -rf *"
  "git push --force"
  "git reset --hard"
  "DROP TABLE"
  ":(){:|:&};:"
  "dd if=/dev/zero"
  "mkfs"
  "> /dev/sda"
)

for pattern in "${DANGEROUS_PATTERNS[@]}"; do
  if echo "$COMMAND" | grep -qi "$pattern"; then
    # 输出拒绝消息到stderr（退出码2 = 阻止操作）
    echo "{\"decision\": \"block\", \"reason\": \"Blocked dangerous command: $pattern\"}" >&2
    exit 2
  fi
done

# 允许操作
exit 0
```

### 3.5 编写MCP Server

**mcp/quality-server/package.json**：

```json
{
  "name": "complexity-analyzer",
  "version": "1.0.0",
  "type": "module",
  "main": "dist/index.js",
  "scripts": {
    "build": "tsc",
    "dev": "tsc --watch"
  },
  "dependencies": {
    "@modelcontextprotocol/sdk": "^1.12.0"
  },
  "devDependencies": {
    "@types/node": "^22.0.0",
    "typescript": "^5.7.0"
  }
}
```

**mcp/quality-server/src/index.ts** — 代码复杂度分析MCP Server：

```typescript
#!/usr/bin/env node
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
import { z } from "zod";
import fs from "fs/promises";
import path from "path";

const server = new McpServer({
  name: "complexity-analyzer",
  version: "1.0.0",
});

// Tool 1: 分析文件复杂度
server.tool(
  "analyze-complexity",
  "Analyze cyclomatic complexity of a source file",
  { filePath: z.string().describe("Absolute path to the source file") },
  async ({ filePath }) => {
    const content = await fs.readFile(filePath, "utf-8");
    const lines = content.split("\n");
    
    // 计算基础指标
    const totalLines = lines.length;
    const codeLines = lines.filter(
      (l) => l.trim() && !l.trim().startsWith("//") && !l.trim().startsWith("*")
    ).length;
    const commentLines = totalLines - codeLines;
    
    // 简化的圈复杂度计算（基于分支关键词）
    const branchKeywords = ["if", "else if", "for", "while", "case", "catch", "&&", "||", "?"];
    let complexity = 1;
    for (const line of codeLines) {
      for (const keyword of branchKeywords) {
        if (line.includes(keyword)) complexity++;
      }
    }
    
    // 函数数量和最大函数长度
    const funcMatches = content.match(/(function\s+\w+|const\s+\w+\s*=\s*(?:async\s+)?\(|=>)/g);
    const funcCount = funcMatches ? funcMatches.length : 0;
    
    const rating = complexity <= 10 ? "LOW" : complexity <= 20 ? "MEDIUM" : "HIGH";
    
    return {
      content: [
        {
          type: "text" as const,
          text: JSON.stringify({
            file: filePath,
            metrics: {
              totalLines,
              codeLines,
              commentLines,
              cyclomaticComplexity: complexity,
              complexityRating: rating,
              estimatedFunctions: funcCount,
              commentRatio: (commentLines / totalLines * 100).toFixed(1) + "%",
            },
            recommendation: complexity > 20
              ? "Consider breaking this file into smaller modules"
              : complexity > 10
                ? "Some functions may benefit from extraction"
                : "Good complexity level",
          }, null, 2),
        },
      ],
    };
  }
);

// Tool 2: 项目级质量报告
server.tool(
  "quality-report",
  "Generate a quality report for all source files in a directory",
  {
    dirPath: z.string().describe("Directory to scan"),
    extensions: z.string().default(".ts,.tsx,.js,.jsx").describe("File extensions to include"),
  },
  async ({ dirPath, extensions }) => {
    const exts = extensions.split(",").map((e) => e.trim());
    const files: string[] = [];
    
    async function walk(dir: string) {
      const entries = await fs.readdir(dir, { withFileTypes: true });
      for (const entry of entries) {
        const fullPath = path.join(dir, entry.name);
        if (entry.isDirectory() && !entry.name.startsWith(".") && entry.name !== "node_modules") {
          await walk(fullPath);
        } else if (entry.isFile() && exts.some((ext) => entry.name.endsWith(ext))) {
          files.push(fullPath);
        }
      }
    }
    
    await walk(dirPath);
    
    const totalFiles = files.length;
    let totalLines = 0;
    let highComplexity = 0;
    
    for (const file of files.slice(0, 100)) {
      const content = await fs.readFile(file, "utf-8");
      totalLines += content.split("\n").length;
      const branchCount = (content.match(/\b(if|else if|for|while|case|catch)\b/g) || []).length;
      if (branchCount > 20) highComplexity++;
    }
    
    return {
      content: [
        {
          type: "text" as const,
          text: JSON.stringify({
            directory: dirPath,
            summary: {
              filesScanned: totalFiles,
              totalLinesOfCode: totalLines,
              highComplexityFiles: highComplexity,
              avgLinesPerFile: totalFiles > 0 ? Math.round(totalLines / totalFiles) : 0,
              healthScore: Math.max(0, 100 - highComplexity * 10),
            },
          }, null, 2),
        },
      ],
    };
  }
);

// 启动Server
const transport = new StdioServerTransport();
await server.connect(transport);
```

编译MCP Server：

```bash
cd mcp/quality-server

# 安装依赖
npm install

# 创建tsconfig.json
cat > tsconfig.json << 'TSCONFIG'
{
  "compilerOptions": {
    "target": "ES2022",
    "module": "Node16",
    "moduleResolution": "Node16",
    "outDir": "./dist",
    "rootDir": "./src",
    "strict": true,
    "esModuleInterop": true,
    "declaration": true
  },
  "include": ["src/**/*"]
}
TSCONFIG

# 编译
npx tsc

# 验证编译产物
ls dist/index.js
```

### 3.6 编写Agent定义

**agents/reviewer.yaml** — 代码审查Agent：

```yaml
name: code-reviewer
description: "Specialized agent for deep code review with quality enforcement"
model: claude-sonnet-4-6
tools:
  - Read
  - Grep
  - Glob
  - Bash
  - Task

instructions: |
  You are a code quality reviewer agent. Your job is to:
  
  1. Scan the specified files or directories
  2. Use the complexity-analyzer MCP tools to get metrics
  3. Read the actual code and identify specific issues
  4. Generate a structured review report
  
  Output format:
  ## Review Summary
  - Files reviewed: N
  - Issues found: N (🔴 Critical: N, 🟡 Warning: N, 🔵 Info: N)
  - Quality score: N/100
  
  ## Issues
  For each issue:
  - **File**: path/to/file:line
  - **Severity**: 🔴/🟡/🔵
  - **Category**: Security/Performance/Maintainability/Testing
  - **Description**: What's wrong
  - **Suggestion**: How to fix (with code snippet)
  
  ## Top Priority Fixes
  List the 3 most impactful fixes to make.
```

### 3.7 编写斜杠命令

**commands/quality-check.md**：

```markdown
---
name: quality-check
description: Run a full quality check on the codebase
---

Run a comprehensive code quality check:

1. Use the `quality-report` MCP tool to scan the current directory
2. For any files with HIGH complexity, use `analyze-complexity` for details
3. Apply the `/review` skill to the top 3 most complex files
4. Generate a summary with:
   - Overall health score
   - Top issues by severity
   - Suggested next actions
5. Save the report to `quality-report.md`
```

### 3.8 添加Plugin级CLAUDE.md

```markdown
# Code Quality Guardian Plugin

This plugin enforces code quality standards.

## Available Commands
- `/review` — Run a code quality review
- `/fix-quality` — Auto-fix quality issues  
- `/quality-check` — Full quality check with report

## MCP Tools
- `analyze-complexity` — Analyze single file complexity
- `quality-report` — Generate project-level quality report

## Auto-formatting
Files are automatically formatted after edits (PostToolUse hook).
Dangerous commands are blocked before execution (PreToolUse hook).

## Quality Standards
- Max cyclomatic complexity: 10 per function
- Min comment ratio: 10%
- All files must pass linting
```

---

## 四、Plugin测试与调试

### 4.1 本地安装测试

```bash
# 在Plugin项目根目录
cd code-quality-guardian

# 方式1：通过Git URL安装（推荐，模拟真实安装流程）
claude plugin add https://github.com/your-org/code-quality-guardian

# 方式2：通过本地路径安装（开发调试用）
claude plugin add ./path/to/code-quality-guardian

# 验证安装
claude plugin list
# 应显示：
# code-quality-guardian  1.0.0  Code quality enforcement...

# 查看已注册的Skills
claude /review --help
claude /fix-quality --help
claude /quality-check --help
```

### 4.2 验证Hook触发

```bash
# 在安装了Plugin的项目中启动Claude Code
claude

# 测试PostToolUse Hook：让Claude编辑一个文件
# 输入: "Edit src/utils.ts and add a formatDate function"
# 预期：文件编辑后自动触发格式化

# 测试PreToolUse Hook：尝试运行危险命令
# 输入: "Run rm -rf /tmp/test"
# 预期：命令被阻止，显示"Blocked dangerous command"
```

### 4.3 验证MCP Server

```bash
# 检查MCP Server是否正确注册
claude /mcp
# 应显示 complexity-analyzer server，状态为 connected

# 手动测试MCP工具
# 在Claude Code中输入:
# "Use the analyze-complexity tool on src/main.ts"
# 预期：返回文件的复杂度指标JSON
```

### 4.4 调试技巧

**Hook调试**：Hooks的stdout/stderr会显示在Claude Code的日志中。

```bash
# 查看Claude Code日志
cat ~/.claude/logs/*.log | grep "hook"

# 在Hook脚本中添加调试输出
echo "DEBUG: file=$FILE_PATH" >&2
```

**MCP Server调试**：使用MCP Inspector独立测试。

```bash
# 安装MCP Inspector
npx @modelcontextprotocol/inspector node mcp/quality-server/dist/index.js

# 在浏览器中打开Inspector UI
# 可以手动调用每个工具并查看响应
```

**常见问题排查**：

| 问题 | 原因 | 解决方案 |
|------|------|----------|
| Plugin不显示 | plugin.json路径错误 | 确认在 `.claude-plugin/` 目录 |
| Hook不触发 | matcher正则不匹配 | 检查event名称和matcher语法 |
| MCP Server连接失败 | 编译产物不存在 | 先 `npm run build` |
| Skill未注册 | path字段错误 | 确认文件相对于Plugin根的路径 |
| 权限被拒 | settings.permissions缺失 | 添加对应的allow规则 |

---

## 五、发布与分发

### 5.1 准备发布

```bash
# 1. 确保所有组件就绪
git add -A
git commit -m "feat: code-quality-guardian v1.0.0"

# 2. 打版本标签
git tag v1.0.0
git push origin main --tags

# 3. 确保package.json有正确的repository字段
# 4. README.md包含安装说明
```

**README.md模板**：

```markdown
# Code Quality Guardian

Auto-format, lint, complexity analysis, and code review for Claude Code.

## Install

claude plugin add https://github.com/your-org/code-quality-guardian

## Commands
| Command | Description |
|---------|-------------|
| `/review` | Code quality review |
| `/fix-quality` | Auto-fix issues |
| `/quality-check` | Full quality report |

## MCP Tools
- `analyze-complexity` — Per-file complexity metrics
- `quality-report` — Project-wide quality scan

## Hooks
- Auto-format on file edit (Prettier/Black/gofmt)
- Block dangerous shell commands
```

### 5.2 发布到Marketplace

Claude Code支持两种分发渠道：

**方式一：官方Plugin Directory**

```bash
# 提交到Anthropic官方目录（需要审核）
# Fork https://github.com/anthropics/claude-code-plugins
# 添加你的Plugin信息到registry.json
# 提交PR
```

**方式二：自建Marketplace**

任何静态JSON文件都可以作为Marketplace：

```json
// marketplace.json
{
  "name": "Team Plugin Hub",
  "plugins": [
    {
      "name": "code-quality-guardian",
      "version": "1.0.0",
      "description": "Code quality enforcement",
      "repository": "https://github.com/your-org/code-quality-guardian",
      "tags": ["quality", "linting", "review"]
    }
  ]
}
```

团队内部分发：

```bash
# 将marketplace.json托管到内部服务器
# 团队成员配置Marketplace源
claude config set pluginMarketplaces '["https://internal.example.com/marketplace.json"]'

# 然后直接从Marketplace安装
claude plugin add code-quality-guardian
```

### 5.3 版本更新流程

```bash
# 修改代码后更新版本号
# 在plugin.json中: "version": "1.1.0"

git commit -am "feat: add Python complexity analysis"
git tag v1.1.0
git push origin main --tags

# 已安装的用户更新
claude plugin update code-quality-guardian
```

---

## 六、完整工作流程

```mermaid
flowchart TB
    subgraph 开发阶段["开发阶段"]
        A[创建项目结构] --> B[编写plugin.json]
        B --> C[实现Skills]
        C --> D[实现Hooks]
        D --> E[实现MCP Server]
        E --> F[定义Agents]
        F --> G[编写Commands]
    end

    subgraph 测试阶段["测试阶段"]
        G --> H[本地安装Plugin]
        H --> I[验证Skills注册]
        I --> J[触发Hook测试]
        J --> K[MCP Inspector测试]
        K --> L[端到端集成测试]
    end

    subgraph 发布阶段["发布阶段"]
        L --> M[Git tag版本]
        M --> N{分发渠道}
        N --> O[官方Directory]
        N --> P[自建Marketplace]
        N --> Q[私有Git仓库]
    end

    subgraph 使用阶段["使用阶段"]
        O --> R[claude plugin add]
        P --> R
        Q --> R
        R --> S[团队协作开发]
    end

    style 开发阶段 fill:#E8F5E9
    style 测试阶段 fill:#E3F2FD
    style 发布阶段 fill:#FFF3E0
    style 使用阶段 fill:#F3E5F5
```

---

## 七、进阶模式

### 7.1 Plugin组合：多Plugin协同

多个Plugin可以同时安装并协同工作。例如：

- `code-quality-guardian` — 质量守护
- `security-scanner` — 安全扫描
- `test-generator` — 测试生成

Claude Code会合并所有已安装Plugin的Skills、Hooks和MCP工具。如果存在命名冲突，后安装的Plugin优先级更高。

### 7.2 条件式Hook：基于项目类型触发

```bash
#!/usr/bin/env bash
# hooks/smart-format.sh - 根据项目类型选择格式化工具

INPUT=$(cat)
FILE_PATH=$(echo "$INPUT" | jq -r '.tool_input.file_path // empty')
[[ -z "$FILE_PATH" ]] && exit 0

# 检测项目根目录
PROJECT_ROOT=$(git rev-parse --show-toplevel 2>/dev/null || echo ".")

# TypeScript/JavaScript项目
if [[ -f "$PROJECT_ROOT/tsconfig.json" ]] || [[ -f "$PROJECT_ROOT/package.json" ]]; then
  case "$FILE_PATH" in
    *.ts|*.tsx|*.js|*.jsx)
      npx --yes prettier --write "$FILE_PATH" 2>/dev/null || true
      npx --yes eslint --fix "$FILE_PATH" 2>/dev/null || true
      ;;
  esac
# Python项目
elif [[ -f "$PROJECT_ROOT/pyproject.toml" ]] || [[ -f "$PROJECT_ROOT/setup.py" ]]; then
  case "$FILE_PATH" in
    *.py)
      command -v black &>/dev/null && black "$FILE_PATH" 2>/dev/null || true
      command -v isort &>/dev/null && isort "$FILE_PATH" 2>/dev/null || true
      ;;
  esac
fi
```

### 7.3 Plugin内部MCP通信

Plugin内的MCP Server可以通过环境变量获取Plugin元数据：

```typescript
// MCP Server内部可以读取Plugin上下文
const pluginName = process.env.CLAUDE_PLUGIN_NAME;
const pluginVersion = process.env.CLAUDE_PLUGIN_VERSION;
const projectRoot = process.env.CLAUDE_PROJECT_ROOT;

// 基于项目上下文提供更智能的分析
server.tool(
  "smart-analyze",
  "Context-aware code analysis",
  { target: z.string().describe("File or directory to analyze") },
  async ({ target }) => {
    const fullPath = path.join(projectRoot || ".", target);
    // ... 基于完整项目上下文的分析逻辑
  }
);
```

---

## 八、训练营适用性评估

| 训练营类型 | 适用性 | 教学时长 | 说明 |
|-----------|--------|---------|------|
| Claude Code进阶训练营 | ★★★★★ | 4-5小时 | 核心进阶内容 |
| AI工程化训练营 | ★★★★☆ | 3-4小时 | 侧重Plugin架构和分发 |
| DevOps自动化训练营 | ★★★★☆ | 3小时 | 侧重Hooks和MCP集成 |
| 团队协作训练营 | ★★★☆☆ | 2-3小时 | 侧重Marketplace和分发 |
| AI零基础训练营 | ★★☆☆☆ | 不推荐 | 需要先完成基础教程 |

**推荐教学路径**：
1. 理论讲解（45分钟）：Plugin架构、三层扩展对比、plugin.json规范
2. 跟练环节（90分钟）：从零构建code-quality-guardian
3. 调试实践（45分钟）：Hook调试、MCP Inspector使用
4. 发布实战（30分钟）：Git tag、Marketplace发布
5. 综合练习（60分钟）：学员独立构建一个自定义Plugin

---

## 参考来源

1. [Plugins reference - Claude Code Docs](https://code.claude.com/docs/en/plugins-reference) — Anthropic官方Plugin系统技术参考，包含完整的plugin.json schema和CLI命令
2. [Create plugins - Claude Code Docs](https://code.claude.com/docs/en/plugins) — Anthropic官方Plugin创建指南，涵盖组件定义和目录结构
3. [Create and distribute a plugin marketplace - Claude Code Docs](https://code.claude.com/docs/en/plugin-marketplaces) — Marketplace搭建与分发完整文档
4. [Building My First Claude Code Plugin - alexop.dev](https://alexop.dev/posts/building-my-first-claude-code-plugin/) — 开发者实战经验，包含踩坑记录和最佳实践
5. [How to Build Claude Code Plugins - DataCamp](https://www.datacamp.com/tutorial/how-to-build-claude-code-plugins) — 系统化Plugin开发教程，从Skills到发布全流程

> [!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 等场景全覆盖。

![51学通信知识星球海报-扫码加入](https://wiki.500nian.com/images/zhixingqiu_qrcode.png)
