首页 › tutorials › Claude Code插件生态全实战

Claude Code插件生态全实战:发现、安装到自研发布

概述

本教程面向希望系统性掌握Claude Code插件生态的开发者。你将学会:浏览和安装官方/社区插件,理解插件五大扩展原语(Skills、Commands、Agents、Hooks、MCP Servers),从零构建一个功能完整的插件,并发布到Marketplace。适合已具备Claude Code基础使用经验、希望提升团队效率的开发者。

前置条件


一、插件生态全景:为什么需要插件

1.1 从手工配置到标准化分发

Claude Code的定制化能力经历了三个阶段的演进:

graph LR
    A["阶段一<br/>CLAUDE.md 手工指令"] --> B["阶段二<br/>Skills 单文件封装"]
    B --> C["阶段三<br/>Plugins 标准化分发"]

    style A fill:#e8f4f8
    style B fill:#b8d4e3
    style C fill:#4a90d9,color:#fff

2026年5月,Anthropic推出了官方插件目录,标志着插件生态正式进入成熟期。截至2026年5月底,官方目录收录了12个内部插件和40+个外部插件,社区市场已有6700+个Skills和2500+个Marketplace条目。

1.2 插件的五大扩展原语

一个插件可以包含以下五种扩展组件的任意组合:

原语 作用 触发方式 示例
Skills 提供领域知识和行为指南 自动匹配 或 /命令 frontend-design 自动指导UI开发
Commands 注册斜杠命令 用户输入 /command-name /commit 自动提交
Agents 定义专业化子Agent Task工具分发 5个并行Reviewer做代码审查
Hooks 事件驱动的Shell脚本 自动触发(SessionStart、PreToolUse等) 安全提醒、自动格式化
MCP Servers 连接外部工具和数据源 Claude主动调用 数据库查询、API集成
graph TB
    subgraph "Plugin Architecture"
        P["plugin.json<br/>元数据"]
        P --> SK["skills/<br/>知识 & 命令"]
        P --> CM["commands/<br/>斜杠命令 (legacy)"]
        P --> AG["agents/<br/>专业Agent"]
        P --> HK["hooks/<br/>事件钩子"]
        P --> MCP[".mcp.json<br/>外部工具"]
    end

    SK --> |"自动匹配"| CL["Claude 主循环"]
    CM --> |"/command"| CL
    AG --> |"Task dispatch"| CL
    HK --> |"事件触发"| CL
    MCP --> |"工具调用"| CL

    style P fill:#2d3748,color:#fff
    style CL fill:#4a90d9,color:#fff

二、插件发现与安装

2.1 使用 /plugin 命令浏览

启动Claude Code后,输入 /plugin 进入插件管理界面:

> /plugin

  Plugin Manager
  ────────────────────────────────────────
  1. Installed     (3 plugins)
  2. Discover      (browse official marketplace)
  3. Browse        (search all marketplaces)

三个标签页的功能:

2.2 从命令行安装

不需要进入交互界面,直接用命令安装:

# 从官方目录安装
claude plugin install commit-commands@claude-plugins-official

# 从自定义Marketplace安装
claude plugin install my-plugin@my-company-marketplace

# 从本地路径安装(开发模式)
claude plugin install ./path/to/my-plugin

2.3 通过配置文件声明

在项目的 .claude/settings.json 中声明式安装:

{
  "plugins": {
    "enabled": [
      "commit-commands@claude-plugins-official",
      "code-review@claude-plugins-official",
      "security-guidance@claude-plugins-official"
    ]
  }
}

这种方式适合团队项目——所有人克隆仓库后自动获得相同的插件配置。

2.4 验证安装

# 列出所有已安装插件
claude plugin list

# 查看特定插件详情
claude plugin details commit-commands

# 检查插件健康状态
/doctor

claude plugin details 会显示插件包含的所有组件和预估的每会话token成本。


三、实战:安装和使用官方插件

3.1 实战一:代码审查插件(code-review)

这是官方目录中最受欢迎的插件之一,它启动5个并行的Sonnet Agent进行多维审查:

claude plugin install code-review@claude-plugins-official

安装后,在Claude Code中直接使用:

> /code-review

它会自动检测当前分支的PR变更,然后启动5个专业Agent:

Agent 职责
CLAUDE.md Compliance 检查代码是否符合项目规范
Bug Detection 查找潜在的正确性bug
Historical Context 分析PR的历史背景和动机
PR History 检查过往类似PR的经验教训
Code Comments 审查注释质量和准确性

每个Agent给出置信度评分,低置信度的发现会被自动过滤,减少误报。

3.2 实战二:安全提醒插件(security-guidance)

claude plugin install security-guidance@claude-plugins-official

这个插件通过 PreToolUse Hook监控9种安全模式:

安装后无需任何操作——每次编辑文件时自动触发。

3.3 实战三:功能开发插件(feature-dev)

claude plugin install feature-dev@claude-plugins-official

使用方式:

> /feature-dev 添加用户导出CSV功能

它遵循7阶段结构化流程:

graph TD
    D["Phase 1<br/>需求发现"] --> E["Phase 2<br/>代码库探索"]
    E --> F["Phase 3<br/>澄清问题"]
    F --> G["Phase 4<br/>架构设计"]
    G --> H["Phase 5<br/>实现"]
    H --> I["Phase 6<br/>代码审查"]
    I --> J["Phase 7<br/>交付"]

    style D fill:#e2f0d9
    style G fill:#d9e2f3
    style H fill:#fde9d9
    style J fill:#d9d2e9

Phase 2和Phase 4会启动2-3个并行的探索/架构Agent,每个Agent聚焦不同视角。


四、插件标准结构详解

4.1 目录布局

my-plugin/
├── .claude-plugin/
│   └── plugin.json          # 必需:插件元数据
├── skills/                  # 推荐:Skills目录
│   ├── my-skill/
│   │   └── SKILL.md         # 自动匹配的Skill
│   └── my-command/
│       └── SKILL.md         # 用户触发的斜杠命令
├── agents/                  # 可选:Agent定义
│   └── my-agent.md
├── hooks/                   # 可选:事件钩子
│   └── session-start.sh
├── .mcp.json               # 可选:MCP服务器配置
└── README.md               # 推荐:文档

4.2 plugin.json 规范

{
  "name": "my-plugin",
  "description": "一句话描述插件功能",
  "version": "1.0.0",
  "author": {
    "name": "你的名字",
    "email": "[email protected]",
    "url": "https://github.com/yourname"
  },
  "homepage": "https://github.com/yourname/my-plugin",
  "repository": {
    "type": "git",
    "url": "https://github.com/yourname/my-plugin.git"
  },
  "license": "MIT",
  "keywords": ["git", "workflow", "automation"],
  "dependencies": {
    "other-plugin@marketplace-name": ">=1.0.0"
  }
}

dependencies字段支持语义化版本约束。插件被禁用时,如果其他启用的插件依赖它,claude plugin disable会拒绝并提示完整的禁用链。

4.3 Skills的两种形态

自动触发型(Claude根据任务上下文自动激活):

---
name: api-design-patterns
description: Use when designing REST or GraphQL APIs, including endpoint design, error handling, and versioning strategies
version: 1.0.0
---

用户触发型(注册为斜杠命令):

---
name: gen-api
description: Generate API endpoint boilerplate
argument-hint: <method> <path>
allowed-tools: [Read, Write, Edit, Glob, Grep]
---

关键区别:用户触发型有argument-hint字段,会出现在 /help 的命令列表中。

4.4 Agent定义

---
name: db-schema-analyzer
description: Analyzes database schema for normalization issues and optimization opportunities
tools: [Read, Glob, Grep, Task]
effort: high
model: sonnet
---

You are a database schema analysis specialist. Your job is to:

1. Read all migration files and schema definitions
2. Identify normalization violations (1NF, 2NF, 3NF)
3. Check for missing indexes on foreign keys
4. Suggest query optimization opportunities
5. Return a list of the 5-10 most important files for the main agent to review

Agent的关键frontmatter字段: - tools:允许使用的工具列表 - effort:推理深度(low/medium/high) - model:指定使用的模型(默认继承主会话)

4.5 Hook配置

Hook不放在文件中,而是在plugin.json的hooks字段声明:

{
  "name": "my-plugin",
  "description": "...",
  "hooks": {
    "SessionStart": [
      {
        "type": "command",
        "command": "echo '🚀 Session started at $(date)'"
      }
    ],
    "PreToolUse": [
      {
        "type": "command",
        "command": "scripts/check-security.sh",
        "matcher": "Edit|Write"
      }
    ]
  }
}

支持的Hook事件类型:

事件 触发时机 典型用途
SessionStart 会话启动时 注入上下文、环境检查
PreToolUse 工具调用前 安全审查、参数校验
PostToolUse 工具调用后 自动格式化、日志记录
Stop Agent完成时 结果校验、通知发送
SubagentStart 子Agent启动时 注入额外上下文

4.6 MCP Server配置

.mcp.json 放在插件根目录:

{
  "my-database": {
    "type": "stdio",
    "command": "npx",
    "args": ["-y", "my-db-mcp-server"],
    "env": {
      "DB_URL": "${DB_CONNECTION_STRING}"
    }
  },
  "my-api": {
    "type": "http",
    "url": "https://api.example.com/mcp",
    "headers": {
      "Authorization": "Bearer ${API_TOKEN}"
    }
  }
}

支持 stdio(本地进程)和 http(远程服务)两种传输方式。环境变量用 ${VAR_NAME} 语法引用,安装时会提示用户配置。


五、完整实战:构建一个 TypeScript 类型守卫插件

下面我们从零构建一个名为 ts-guardian 的插件,它提供: 1. 一个斜杠命令 /ts-guard —— 分析TypeScript项目的类型安全性 2. 一个自动Skill —— 在编写TypeScript代码时提供类型安全建议 3. 一个Agent —— 深度分析复杂类型问题 4. 一个Hook —— 提交前自动检查类型错误

5.1 创建项目结构

mkdir ts-guardian && cd ts-guardian
mkdir -p .claude-plugin skills/ts-guard skills/ts-type-safety agents hooks

5.2 编写 plugin.json

{
  "name": "ts-guardian",
  "description": "TypeScript type safety analysis with automated checking, expert guidance, and pre-commit validation",
  "version": "1.0.0",
  "author": {
    "name": "Your Name",
    "url": "https://github.com/yourname"
  },
  "homepage": "https://github.com/yourname/ts-guardian",
  "license": "MIT",
  "keywords": ["typescript", "type-safety", "static-analysis"],
  "hooks": {
    "PreToolUse": [
      {
        "type": "command",
        "command": "bash hooks/pre-edit-typecheck.sh",
        "matcher": "Edit|Write"
      }
    ]
  }
}

5.3 斜杠命令 Skill

创建 skills/ts-guard/SKILL.md:

---
name: ts-guard
description: Analyze TypeScript type safety across the project
argument-hint: [path or glob pattern]
allowed-tools: [Read, Glob, Grep, Bash, Task, TodoWrite]
---

# TypeScript Type Safety Analysis

Analyze the TypeScript project for type safety issues. Follow this systematic approach:

## Step 1: Project Scan

Run a comprehensive type check:

```bash
npx tsc --noEmit --strict 2>&1 | head -100

Also check for common type safety anti-patterns:

# Find 'as any' casts
grep -rn "as any" --include="*.ts" --include="*.tsx" $ARGUMENTS .

# Find non-null assertions (!)
grep -rn "!\." --include="*.ts" --include="*.tsx" $ARGUMENTS .

# Find @ts-ignore / @ts-expect-error
grep -rn "@ts-" --include="*.ts" --include="*.tsx" $ARGUMENTS .

Step 2: Categorize Findings

Organize issues into severity levels:

Step 3: Launch Deep Analysis Agent

For files with 3+ critical findings, launch the ts-type-deep-analyzer agent to trace type flow and identify root causes.

Step 4: Generate Report

Output a structured report:

## Type Safety Report

### Summary
- Total files scanned: X
- Critical issues: X
- Warnings: X
- Info: X

### Critical Issues
| File | Line | Issue | Suggestion |
|------|------|-------|------------|
| ... | ... | ... | ... |

### Recommended Fixes
[Prioritized list of changes]
### 5.4 自动触发 Skill

创建 `skills/ts-type-safety/SKILL.md`:

```yaml
---
name: ts-type-safety
description: Use when writing or editing TypeScript code, providing type safety guidance and best practices
version: 1.0.0
allowed-tools: [Read, Edit, Glob, Grep]
---

# TypeScript Type Safety Guidelines

When working with TypeScript code in this project, follow these principles:

## Strict Type Practices

1. **Never use `any`** - Use `unknown` for truly unknown types, then narrow with type guards
2. **Prefer interfaces over type aliases** for object shapes (better error messages and declaration merging)
3. **Use discriminated unions** for state machines and polymorphic data
4. **Enable strict mode** - Ensure `tsconfig.json` has `"strict": true`

## Common Patterns

### Instead of `as any`:
```typescript
// Bad
const data = response as any;

// Good
const data: unknown = response;
if (isValidResponse(data)) {
  // data is now properly typed
}

Instead of non-null assertion:

// Bad
const user = users.find(u => u.id === id)!;

// Good
const user = users.find(u => u.id === id);
if (!user) throw new Error(`User ${id} not found`);

Type Guard Patterns

When the deep analyzer identifies complex type issues, suggest creating reusable type guards:

function isString(value: unknown): value is string {
  return typeof value === 'string';
}

function hasProperty<T extends string>(
  obj: unknown, 
  prop: T
): obj is Record<T, unknown> {
  return typeof obj === 'object' && obj !== null && prop in obj;
}
### 5.5 专业 Agent

创建 `agents/ts-type-deep-analyzer.md`:

```yaml
---
name: ts-type-deep-analyzer
description: Deep analysis of complex TypeScript type issues, tracing type flow through the codebase
tools: [Read, Glob, Grep]
effort: high
model: sonnet
---

You are a TypeScript type system expert. Your task is to perform deep analysis of type safety issues in specific files.

## Analysis Process

1. **Read the target file completely** - understand the full type context
2. **Trace type origins** - find where problematic types are defined or inferred
3. **Check upstream dependencies** - what functions/APIs feed into this code?
4. **Identify root causes** - is the issue from missing generics, loose types, or type assertions?
5. **Return findings** with:
   - List of 5-10 most important related files
   - Root cause analysis for each issue
   - Concrete type-safe fix suggestions with code examples

## Focus Areas

- Generic type parameter inference failures
- Excess property checking bypass
- Covariance/contravariance issues in function types
- Conditional type complexity
- Template literal type patterns
- Module augmentation side effects

5.6 安全 Hook 脚本

创建 hooks/pre-edit-typecheck.sh:

#!/bin/bash
# Pre-edit type safety check
# Only runs for TypeScript files

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

# Only check TypeScript files
if [[ "$FILE_PATH" =~ \.(ts|tsx)$ ]]; then
    # Check if tsc is available
    if command -v npx &>/dev/null; then
        ERRORS=$(npx tsc --noEmit 2>&1 | tail -5)
        ERROR_COUNT=$(npx tsc --noEmit 2>&1 | grep -c "error TS" || echo "0")

        if [ "$ERROR_COUNT" -gt 0 ]; then
            echo "⚠️  TypeScript has $ERROR_COUNT errors. Recent:"
            echo "$ERRORS"
        fi
    fi
fi

# Exit 0 to allow the edit (this is advisory only)
exit 0
chmod +x hooks/pre-edit-typecheck.sh

5.7 最终目录结构

ts-guardian/
├── .claude-plugin/
│   └── plugin.json
├── skills/
│   ├── ts-guard/
│   │   └── SKILL.md          # /ts-guard 斜杠命令
│   └── ts-type-safety/
│       └── SKILL.md          # 自动触发的类型安全指南
├── agents/
│   └── ts-type-deep-analyzer.md  # 深度分析Agent
├── hooks/
│   └── pre-edit-typecheck.sh     # 编辑前检查脚本
└── README.md

5.8 本地测试

# 在测试项目中安装本地插件
cd ~/projects/my-ts-project
claude plugin install ~/path/to/ts-guardian

验证各组件:

> /help
# 应该看到 /ts-guard 命令

> /ts-guard src/
# 运行类型安全分析

> 创建一个 UserService 类
# ts-type-safety skill 应自动激活,提供类型安全指导

用 /doctor 检查插件加载状态:

> /doctor

  Plugin: ts-guardian
  ├── Status: ✅ loaded
  ├── Skills: 2 (ts-guard, ts-type-safety)
  ├── Agents: 1 (ts-type-deep-analyzer)
  ├── Hooks: 1 (PreToolUse → pre-edit-typecheck.sh)
  └── MCP Servers: 0

六、发布到Marketplace

6.1 提交到Anthropic官方目录

Anthropic的官方目录托管在 github.com/anthropics/claude-plugins-official。

内部插件(Anthropic团队开发):直接提交到 /plugins/ 目录。

外部插件(社区开发):通过插件目录提交表单申请,需要通过质量和安全审核。

6.2 创建私有Marketplace

企业团队可以创建自己的Marketplace,托管在内网Git仓库:

# 创建Marketplace仓库
mkdir my-company-plugins && cd my-company-plugins
git init

# 创建manifest文件
cat > manifest.json << 'MANIFEST'
{
  "name": "my-company-plugins",
  "description": "Internal plugins for My Company",
  "plugins": {
    "ts-guardian": {
      "ref": "main",
      "sha": "abc123...",
      "path": "plugins/ts-guardian"
    }
  }
}
MANIFEST

# 添加插件目录
mkdir -p plugins
# 将 ts-guardian 复制到 plugins/ts-guardian/

git add . && git commit -m "Initial marketplace"
git remote add origin [email protected]:mycompany/claude-plugins.git
git push -u origin main

团队成员添加Marketplace:

claude plugin marketplace add my-company-plugins \
  --source [email protected]:mycompany/claude-plugins.git

然后就能在 /plugin > Discover 中看到公司内部的插件了。

6.3 版本管理与依赖

在 plugin.json 中声明依赖:

{
  "dependencies": {
    "security-guidance@claude-plugins-official": ">=1.0.0"
  }
}

插件启用时,依赖会自动安装。禁用被依赖的插件时,会收到提示:

❌ Cannot disable "security-guidance": "ts-guardian" depends on it.
   Disable chain: disable ts-guardian first, then security-guidance.

6.4 插件提示(Plugin Hints)

如果你的CLI工具想推荐用户安装配套插件,可以在工具输出中包含提示:

💡 Tip: Install the ts-guardian plugin for automatic TypeScript type checking.
   Run: claude plugin install ts-guardian@claude-plugins-official

七、插件开发最佳实践

7.1 设计原则

原则 说明 反模式
单一职责 一个插件解决一类问题 一个插件塞入代码审查+部署+监控
渐进披露 Skill描述精确触发,避免过度激活 description写"Use when coding"
零配置优先 开箱即用,通过环境变量可选配置 必须手动编辑5个配置文件
可观测性 Hook输出清晰的状态信息 静默失败,用户不知道插件在运行
成本意识 避免在Hook中触发额外API调用 Hook中运行claude -p "分析这段代码"

7.2 Skill描述优化

Skill的 description 字段是触发匹配的关键。写出好的描述:

# 差 - 太泛
description: Use when working with TypeScript

# 好 - 精确
description: Use when writing or editing TypeScript code that involves type annotations, generics, type guards, or strict null checks

7.3 Agent设计模式

高效Agent的设计要点:

  1. 明确返回值格式:要求Agent返回"最重要的5-10个文件列表",便于主Agent接力
  2. 限制工具范围:只给Agent需要的工具,减少权限风险
  3. 选择合适的模型:简单探索用Haiku,深度分析用Sonnet
  4. 控制effort级别:避免所有Agent都用high effort导致token浪费

7.4 Hook性能注意事项

7.5 调试技巧

# 查看插件加载日志
/doctor

# 验证插件结构
claude plugin validate ./ts-guardian

# 查看插件详情和预估token成本
claude plugin details ts-guardian

# 检查特定Hook的触发情况
/permissions

claude plugin validate 会检查: - plugin.json 格式是否正确 - skills/ 路径指向目录还是文件(必须指向目录) - Hook脚本是否有执行权限 - .mcp.json 环境变量是否都有对应说明


八、插件生态工作流全景

flowchart TB
    subgraph "发现阶段"
        A["/plugin > Discover"] --> B["选择插件"]
        B --> C["查看详情<br/>组件清单 + token成本"]
    end

    subgraph "安装阶段"
        C --> D["claude plugin install"]
        D --> E["配置环境变量<br/>(如需要)"]
        E --> F["验证 /doctor"]
    end

    subgraph "使用阶段"
        F --> G{插件类型}
        G --> |"Command"| H["/command-name 触发"]
        G --> |"Skill"| I["Claude 自动匹配"]
        G --> |"Agent"| J["Task 工具分发"]
        G --> |"Hook"| K["事件自动触发"]
        G --> |"MCP"| L["Claude 主动调用"]
    end

    subgraph "管理阶段"
        H --> M["claude plugin list"]
        I --> M
        J --> M
        K --> M
        L --> M
        M --> N["update / disable / uninstall"]
    end

    style A fill:#4a90d9,color:#fff
    style D fill:#2d3748,color:#fff
    style G fill:#7c3aed,color:#fff
    style M fill:#059669,color:#fff

九、常见问题与解决方案

Q1:安装插件后 /help 看不到斜杠命令

原因:Skill的 name 字段与目录名不一致时,Tab补全和 /help 可能无法正确显示。

解决:确保Skill目录名与frontmatter的 name 字段一致:

skills/
└── ts-guard/          # 目录名
    └── SKILL.md       # name: ts-guard  ← 必须匹配

Q2:Hook脚本没有执行

排查步骤: 1. 确认脚本有执行权限:chmod +x hooks/*.sh 2. 检查 /doctor 是否报告Hook错误 3. 确认 matcher 字段匹配了正确的工具名 4. 检查脚本是否依赖不在PATH中的命令

Q3:插件token消耗过高

优化方案: 1. 精简Skill的Markdown内容——Claude每次激活都会读取 2. 减少Agent的 effort 级别 3. 使用 claude plugin details <name> 查看预估的per-invocation成本 4. 对不常用的插件使用 disable 而非 uninstall

Q4:插件间冲突

当两个插件注册了同名的斜杠命令时,后安装的会覆盖先安装的。使用 /plugin 查看优先级,或使用全名调用:

> /ts-guardian:ts-guard

Q5:企业环境离线安装

# 在有网络的机器上下载
git clone https://github.com/yourorg/claude-plugins.git /tmp/plugins

# 打包传输
tar czf plugins.tar.gz -C /tmp/plugins .

# 在离线机器上
tar xzf plugins.tar.gz -C ~/company-plugins
claude plugin marketplace add company --source ~/company-plugins
claude plugin install ts-guardian@company

十、延伸阅读

训练营适用性评估

维度 评估
适合训练营类型 企业内训、开发者工坊、AI工具集训
教学时长 基础篇(安装使用):1.5小时;进阶篇(开发发布):3小时
实操占比 70%实操 + 30%讲解
前置要求 Claude Code基础使用经验,Git操作能力
最大班额 20人(需要每人有独立开发环境)
考核方式 学员独立开发并发布一个功能完整的插件

参考来源

  1. Claude Code Official Plugins Directory — Anthropic官方插件目录,包含示例插件和贡献指南
  2. Claude Code Plugins README — 官方仓库中的插件开发说明和完整插件清单
  3. Claude Code Changelog v2.1.139-v2.1.150 — 插件系统演进历程,包含Agent View、Plugin Marketplace等特性
  4. Plugins Reference - Claude Code Docs — 完整的插件技术规范和schema定义
  5. 45 Claude Code Tips — 社区维护的进阶技巧,涵盖插件、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学通信知识星球海报-扫码加入