Claude Plugins 完整架构指南


1. 概述

1.1 什么是 Claude Plugin?

Claude Plugin 是一种模块化扩展系统,允许开发者为 Claude Code 和 Cowork 添加自定义功能。它将以下功能打包成可重用的单元:

  • Skills (技能): AI 自动调用的专业知识
  • Commands (命令): 用户触发的斜杠命令
  • Agents (代理): 专门处理特定任务的子智能体
  • Hooks (钩子): 事件驱动的生命周期处理器
  • MCP Servers: 外部工具和数据源集成

1.2 适用场景

场景 说明 示例
团队工作流 标准化团队流程和最佳实践 PR 审查流程、部署检查清单
专业领域 特定技术栈的深度支持 Python/Django、React/Next.js
工具集成 连接外部服务和 API Jira、GitHub、数据库
质量保障 自动化代码检查和测试 安全扫描、性能分析
知识库 公司特定的编码标准 架构模式、API 规范

1.3 与其他概念的关系

MCP Protocol (开放标准)
    ↓ 实现
Connectors (单个工具集成)
    ↓ 可打包进
Plugins (多功能组合)
    ↓ 组成部分
Commands + Skills + Agents + Hooks + MCP Servers

2. 核心概念

2.1 五大组件

:dart: Skills (技能)

  • 触发方式: AI 自动调用(基于任务上下文匹配)
  • 用途: 为 Claude 提供专业知识领域
  • 示例: 前端设计技能、API 集成技能

:zap: Commands (命令)

  • 触发方式: 用户手动调用(斜杠命令)
  • 用途: 执行预定义的工作流
  • 示例: /deploy/test/code-review

:robot: Agents (代理)

  • 触发方式: 手动或自动
  • 用途: 执行专门的分析任务(可并行)
  • 示例: 安全审查代理、测试生成代理

:hook: Hooks (钩子)

  • 触发方式: 事件驱动
  • 用途: 在特定生命周期点执行逻辑
  • 示例: 代码保存前验证、会话启动时注入上下文

:electric_plug: MCP Servers

  • 触发方式: 工具调用
  • 用途: 连接外部服务和数据源
  • 示例: 数据库连接、API 调用、文件系统访问

2.2 命名空间机制

Plugin 使用命名空间防止冲突:

# 未安装插件时
/hello                    # 本地 .claude/ 目录中的命令

# 安装插件后
/my-plugin:hello          # 来自 my-plugin 的命令
/other-plugin:hello       # 来自 other-plugin 的同名命令

2.3 自动发现机制

Claude Code 会自动发现并加载符合标准结构的组件:

组件 发现规则
Commands commands/*.md
Skills skills/*/SKILL.md
Agents agents/*.md
Hooks hooks/hooks.json
MCP .mcp.json

3. 架构设计

3.1 系统架构图

┌─────────────────────────────────────────────────────────────┐
│                    Claude Code / Cowork                      │
└───────────────────────┬─────────────────────────────────────┘
                        │
        ┌───────────────┴───────────────┐
        │     Plugin System Core        │
        │  (加载、命名空间、生命周期)     │
        └───────────────┬───────────────┘
                        │
        ┌───────────────┼───────────────────────┐
        │               │                       │
   ┌────▼────┐   ┌─────▼─────┐         ┌──────▼──────┐
   │ Plugin A │   │  Plugin B │   ...   │  Plugin N   │
   └────┬────┘   └─────┬─────┘         └──────┬──────┘
        │              │                       │
   ┌────┴──────────────┴───────────────────────┴────┐
   │           Plugin Components                     │
   ├────────────┬────────────┬────────────┬─────────┤
   │ Skills     │ Commands   │ Agents     │ Hooks   │
   └────────────┴────────────┴────────────┴─────────┘
                        │
                ┌───────┴────────┐
                │   MCP Servers  │
                └────────────────┘
                        │
        ┌───────────────┼───────────────┐
        │               │               │
   ┌────▼────┐   ┌─────▼─────┐   ┌────▼────┐
   │Database │   │   API     │   │  Files  │
   └─────────┘   └───────────┘   └─────────┘

3.2 数据流

Skill 调用流程

用户提示
    ↓
Claude 分析任务上下文
    ↓
匹配 Skill description
    ↓
加载 SKILL.md 指令
    ↓
执行专业任务
    ↓
返回结果

Command 调用流程

用户输入 /command-name
    ↓
查找命名空间匹配
    ↓
加载 command.md
    ↓
替换 $ARGUMENTS
    ↓
执行命令逻辑
    ↓
返回结果

Hook 触发流程

生命周期事件触发 (如 PreToolUse)
    ↓
查找注册的 Hooks
    ↓
执行 matcher 匹配
    ↓
运行 hook 脚本
    ↓
继续/中断主流程

4. 目录结构详解

4.1 标准目录结构

my-awesome-plugin/
├── .claude-plugin/              # [必需] 插件元数据目录
│   └── plugin.json              # [必需] 插件清单文件
│
├── commands/                    # [可选] 斜杠命令
│   ├── deploy.md               # 单个命令文件
│   ├── test.md
│   └── code-review.md
│
├── agents/                      # [可选] 专业代理
│   ├── security-reviewer.md
│   ├── test-generator.md
│   └── architect.md
│
├── skills/                      # [可选] AI 技能
│   ├── api-testing/            # 技能目录
│   │   ├── SKILL.md           # [必需] 技能定义
│   │   ├── scripts/           # [可选] 辅助脚本
│   │   │   └── test-runner.py
│   │   └── references/        # [可选] 参考文档
│   │       └── api-spec.md
│   └── database-migrations/
│       ├── SKILL.md
│       └── examples/
│           └── migration-template.sql
│
├── hooks/                       # [可选] 生命周期钩子
│   ├── hooks.json              # Hook 配置
│   └── scripts/                # Hook 脚本
│       ├── validate.sh
│       └── check-style.sh
│
├── .mcp.json                    # [可选] MCP 服务器定义
│
├── scripts/                     # [可选] 共享脚本
│   ├── setup.sh
│   └── utils.js
│
├── README.md                    # [推荐] 使用文档
├── LICENSE                      # [推荐] 开源协议
└── .gitignore                  # [推荐] Git 忽略配置

4.2 关键规则

:x: 常见错误

my-plugin/
├── .claude-plugin/
│   ├── plugin.json
│   ├── commands/        # ❌ 错误!不能嵌套在 .claude-plugin/ 内
│   └── skills/          # ❌ 错误!

:white_check_mark: 正确做法

my-plugin/
├── .claude-plugin/
│   └── plugin.json      # ✅ 只有 manifest
├── commands/            # ✅ 在根目录
└── skills/              # ✅ 在根目录

4.3 最小化插件

最简单的插件只需要一个 manifest:

minimal-plugin/
└── .claude-plugin/
    └── plugin.json

这适用于仅需在市场中列出、不提供功能的占位符插件。


5. 核心组件深度解析

5.1 Skills (技能)

5.1.1 基本结构

<!-- skills/api-integration/SKILL.md -->

---
name: api-integration
description: Expert in making HTTP requests and handling API responses. Use when working with REST APIs, webhooks, or external services.
version: 1.0.0
---

# API Integration Skill

## When to Use
- Making HTTP requests (GET, POST, PUT, DELETE)
- Parsing JSON/XML responses
- Handling authentication (OAuth, API keys)
- Error handling and retries

## Best Practices
1. Always validate request parameters
2. Use appropriate HTTP methods
3. Handle rate limiting gracefully
4. Log requests for debugging

## Code Examples

### Basic GET Request
\`\`\`python
import requests

response = requests.get('https://api.example.com/data')
data = response.json()
\`\`\`

### POST with Authentication
\`\`\`python
headers = {'Authorization': f'Bearer {api_key}'}
response = requests.post(url, json=payload, headers=headers)
\`\`\`

5.1.2 Frontmatter 字段

字段 必需 说明
name :white_check_mark: 技能名称(kebab-case)
description :white_check_mark: 何时使用此技能(用于 AI 匹配)
version :x: 版本号

5.1.3 支持文件

Skills 可以包含辅助文件:

skills/
└── complex-skill/
    ├── SKILL.md              # 主文件
    ├── scripts/              # 可执行脚本
    │   └── analyzer.py
    ├── references/           # 参考文档
    │   ├── api-spec.yaml
    │   └── examples.md
    └── templates/            # 模板文件
        └── config.template.json

在 SKILL.md 中引用:

## Usage

Run the analyzer script:
\`\`\`bash
python ${CLAUDE_PLUGIN_ROOT}/skills/complex-skill/scripts/analyzer.py
\`\`\`

See [API specification](./references/api-spec.yaml) for details.

5.1.4 渐进式披露(Progressive Disclosure)

为减少 token 使用,将详细内容放在单独文件中:

<!-- SKILL.md -->
---
name: advanced-python
description: Python 3.12+ best practices, async patterns, type hints
---

# Advanced Python Skill

## Core Guidelines
- Use type hints everywhere
- Prefer async/await for I/O
- Follow PEP 8

For detailed patterns, see:
- [Async patterns](./references/async-patterns.md)
- [Type system guide](./references/typing-guide.md)

5.2 Commands (命令)

5.2.1 基本结构

<!-- commands/deploy.md -->

---
description: Deploy the application to production with safety checks
---

# Production Deployment

You are deploying the application. Follow these steps:

1. **Pre-deployment Checks**
   - Verify all tests pass: `npm test`
   - Check environment variables
   - Review CHANGELOG.md

2. **Deploy**
   - Build: `npm run build`
   - Deploy: `./scripts/deploy.sh production`

3. **Post-deployment**
   - Verify health endpoint: `/health`
   - Check logs for errors
   - Monitor metrics for 10 minutes

If any step fails, STOP and alert the team.

## Rollback Procedure
If issues detected:
\`\`\`bash
./scripts/rollback.sh
\`\`\`

5.2.2 参数传递

使用 $ARGUMENTS 占位符接收用户输入:

<!-- commands/greet.md -->

---
description: Greet a user by name
---

# Greeting Command

Greet the user named "$ARGUMENTS" warmly and ask how you can help them today.
Make the greeting personal and encouraging.

调用示例:

/my-plugin:greet Alice
# → "Hello Alice! Great to see you today! How can I help you?"

5.2.3 多参数处理

<!-- commands/create-feature.md -->

---
description: Create a new feature with name and description
---

# Feature Creation

Parse the arguments "$ARGUMENTS" as: [feature-name] [description]

Example: "user-auth Implement JWT authentication"

1. Create feature branch: `git checkout -b feature/$feature_name`
2. Generate boilerplate code for: $description
3. Create tests
4. Update documentation

5.3 Agents (代理)

5.3.1 基本结构

<!-- agents/security-reviewer.md -->

---
description: Security expert specializing in vulnerability detection
capabilities:
  - SQL injection detection
  - XSS vulnerability analysis
  - Authentication flaw identification
  - Secrets scanning
---

# Security Review Agent

You are a security expert reviewing code for vulnerabilities.

## Analysis Process

1. **Input Validation**
   - Check all user inputs are sanitized
   - Verify parameterized queries
   - Look for eval() or exec() usage

2. **Authentication & Authorization**
   - Verify JWT validation
   - Check permission checks
   - Review session management

3. **Data Protection**
   - Scan for hardcoded secrets
   - Check encryption usage
   - Verify HTTPS enforcement

## Output Format

Provide findings as:
- **Critical**: Immediate security risks
- **High**: Should be fixed soon
- **Medium**: Best practice violations
- **Low**: Nice-to-have improvements

For each finding, include:
- Location (file:line)
- Vulnerability type
- Recommended fix
- Code example

5.3.2 Frontmatter 字段

字段 必需 说明
description :white_check_mark: 代理角色和专长
capabilities :white_check_mark: 具体能力列表

5.3.3 并行代理模式

多个代理可以并行工作:

<!-- commands/comprehensive-review.md -->

---
description: Run comprehensive code review with multiple agents
---

# Comprehensive Review

Launch the following agents in parallel:

1. @security-reviewer - Check for vulnerabilities
2. @performance-analyzer - Identify bottlenecks  
3. @test-coverage-checker - Verify test completeness
4. @documentation-reviewer - Check docs quality

Synthesize all findings into a prioritized action list.

5.4 Hooks (钩子)

5.4.1 可用事件

事件 触发时机 用途
PreToolUse 工具调用前 验证、警告、阻止
PostToolUse 工具调用后 清理、记录
SessionStart 会话开始 注入上下文、初始化
SessionEnd 会话结束 保存状态、清理
UserPromptSubmit 用户提交提示 预处理、增强
PreCompact 上下文压缩前 保存重要信息
Stop 主流程停止 清理资源
SubagentStop 子代理停止 收集结果
Notification 系统通知 自定义处理

5.4.2 配置示例

// hooks/hooks.json
{
  "PreToolUse": [
    {
      "matcher": "Write|Edit|Delete",
      "hooks": [
        {
          "type": "command",
          "command": "bash ${CLAUDE_PLUGIN_ROOT}/hooks/scripts/validate.sh",
          "timeout": 30,
          "description": "Validate code before modification"
        }
      ]
    }
  ],
  "SessionStart": [
    {
      "hooks": [
        {
          "type": "command",
          "command": "node ${CLAUDE_PLUGIN_ROOT}/hooks/scripts/inject-context.js",
          "description": "Load project-specific context"
        }
      ]
    }
  ],
  "PostToolUse": [
    {
      "matcher": "file_write",
      "hooks": [
        {
          "type": "command",
          "command": "python ${CLAUDE_PLUGIN_ROOT}/hooks/scripts/format.py",
          "description": "Auto-format written files"
        }
      ]
    }
  ]
}

5.4.3 Hook 脚本示例

#!/bin/bash
# hooks/scripts/validate.sh

# Hook 脚本接收环境变量
echo "Validating action: $HOOK_EVENT"
echo "Tool: $TOOL_NAME"

# 执行验证
if ! ./scripts/lint.sh; then
    echo "ERROR: Linting failed"
    exit 1
fi

if ! ./scripts/test.sh; then
    echo "ERROR: Tests failed"
    exit 1
fi

echo "✅ Validation passed"
exit 0

5.4.4 Matcher 语法

{
  "matcher": "Write|Edit|Delete",        // 正则表达式匹配
  "matcher": "file_.*",                  // 匹配工具名模式
  "matcher": "",                         // 空字符串 = 总是匹配
}

5.5 MCP Servers

5.5.1 配置位置

MCP 服务器可以在两个位置配置:

方式 1: 独立文件 (推荐)

// .mcp.json (插件根目录)
{
  "my-database-server": {
    "command": "node",
    "args": ["${CLAUDE_PLUGIN_ROOT}/servers/db-server.js"],
    "env": {
      "DB_HOST": "localhost",
      "DB_PORT": "5432"
    }
  },
  "api-integration-server": {
    "command": "python",
    "args": ["${CLAUDE_PLUGIN_ROOT}/servers/api_server.py"],
    "env": {
      "API_KEY": "${API_KEY}"
    }
  }
}

方式 2: 内联在 manifest

// .claude-plugin/plugin.json
{
  "name": "my-plugin",
  "version": "1.0.0",
  "mcpServers": {
    "my-server": {
      "command": "${CLAUDE_PLUGIN_ROOT}/servers/server.sh",
      "args": ["--port", "8080"]
    }
  }
}

5.5.2 环境变量

MCP 服务器可以使用特殊环境变量:

变量 说明 示例
${CLAUDE_PLUGIN_ROOT} 插件安装路径 /Users/alice/.claude/plugins/...
${API_KEY} 用户配置的 API 密钥 从 Claude Code 设置中获取
自定义变量 在 env 中定义 "DEBUG": "true"

5.5.3 服务器实现示例

// servers/db-server.js
const { Server } = require('@modelcontextprotocol/sdk/server/index.js');
const { StdioServerTransport } = require('@modelcontextprotocol/sdk/server/stdio.js');
const { Pool } = require('pg');

const pool = new Pool({
  host: process.env.DB_HOST,
  port: process.env.DB_PORT,
  database: process.env.DB_NAME,
});

const server = new Server(
  {
    name: 'database-mcp-server',
    version: '1.0.0',
  },
  {
    capabilities: {
      tools: {},
    },
  }
);

// 定义工具
server.setRequestHandler('tools/list', async () => {
  return {
    tools: [
      {
        name: 'query_database',
        description: 'Execute a SQL query',
        inputSchema: {
          type: 'object',
          properties: {
            sql: { type: 'string' },
            params: { type: 'array' },
          },
          required: ['sql'],
        },
      },
    ],
  };
});

server.setRequestHandler('tools/call', async (request) => {
  const { name, arguments: args } = request.params;
  
  if (name === 'query_database') {
    const { sql, params = [] } = args;
    const result = await pool.query(sql, params);
    return {
      content: [
        {
          type: 'text',
          text: JSON.stringify(result.rows, null, 2),
        },
      ],
    };
  }
});

// 启动服务器
async function main() {
  const transport = new StdioServerTransport();
  await server.connect(transport);
  console.error('Database MCP server running');
}

main().catch(console.error);

6. Manifest 配置详解

6.1 plugin.json 完整 Schema

{
  "$schema": "https://anthropic.com/claude-code/plugin.schema.json",
  
  // ========== 必需字段 ==========
  "name": "my-awesome-plugin",
  "version": "1.0.0",
  "description": "A comprehensive plugin for modern development workflows",
  
  // ========== 作者信息 ==========
  "author": {
    "name": "Your Name",
    "email": "you@example.com",
    "url": "https://yourwebsite.com"
  },
  
  // ========== 可选元数据 ==========
  "displayName": "My Awesome Plugin",
  "category": "development",  // development, productivity, testing, etc.
  "keywords": ["workflow", "automation", "testing"],
  "license": "MIT",
  "homepage": "https://github.com/user/my-plugin",
  "repository": {
    "type": "git",
    "url": "https://github.com/user/my-plugin.git"
  },
  "bugs": {
    "url": "https://github.com/user/my-plugin/issues"
  },
  
  // ========== 组件路径配置 ==========
  "commandsDirectory": "./commands",      // 默认: commands/
  "agentsDirectory": "./agents",          // 默认: agents/
  "skillsDirectory": "./skills",          // 默认: skills/
  "hooksDirectory": "./hooks",            // 默认: hooks/
  
  // ========== MCP 服务器配置 ==========
  "mcpServers": {
    "my-server": {
      "command": "${CLAUDE_PLUGIN_ROOT}/servers/server.sh",
      "args": ["--port", "8080"],
      "env": {
        "API_KEY": "${API_KEY}",
        "DEBUG": "true"
      }
    }
  },
  
  // ========== 或者引用外部 MCP 配置 ==========
  "mcpServers": "./.mcp.json",  // 字符串路径
  
  // ========== Hooks 配置 ==========
  "hooks": "./hooks/hooks.json",  // 引用外部文件
  
  // ========== 或者内联 Hooks ==========
  "hooks": {
    "PreToolUse": [
      {
        "matcher": "Write",
        "hooks": [
          {
            "type": "command",
            "command": "bash ${CLAUDE_PLUGIN_ROOT}/scripts/validate.sh"
          }
        ]
      }
    ]
  },
  
  // ========== 依赖声明 ==========
  "dependencies": {
    "node": ">=18.0.0",
    "python": ">=3.10"
  },
  
  // ========== 配置 Schema ==========
  "configSchema": {
    "type": "object",
    "properties": {
      "apiEndpoint": {
        "type": "string",
        "description": "API endpoint URL"
      },
      "timeout": {
        "type": "number",
        "default": 5000
      }
    }
  }
}

6.2 字段说明

6.2.1 必需字段

字段 类型 说明
name string 插件唯一标识符(kebab-case),用于命名空间
version string 语义化版本号(semver)
description string 简短描述(显示在市场中)

6.2.2 作者字段

字段 类型 必需 说明
author.name string :white_check_mark: 作者名称
author.email string :x: 联系邮箱
author.url string :x: 个人网站

6.2.3 元数据字段

字段 类型 说明
displayName string 友好显示名称
category string 分类(用于市场筛选)
keywords string[] 搜索关键词
license string 开源协议
homepage string 项目主页
repository object 代码仓库信息

6.2.4 目录配置

默认情况下,组件自动从标准目录加载。可以自定义:

{
  "commandsDirectory": "./my-commands",
  "skillsDirectory": "./expertise",
  "agentsDirectory": "./bots"
}

6.2.5 MCP 服务器配置

内联对象方式:

{
  "mcpServers": {
    "server-name": {
      "command": "node",
      "args": ["server.js"],
      "env": { "KEY": "value" }
    }
  }
}

外部文件引用:

{
  "mcpServers": "./.mcp.json"
}

数组方式 (多个文件):

{
  "mcpServers": [
    "./.mcp.json",
    "./mcp-servers/production.json"
  ]
}

7. 开发指南

7.1 快速开始

步骤 1: 创建插件目录

mkdir my-first-plugin
cd my-first-plugin
mkdir -p .claude-plugin commands skills

步骤 2: 创建 Manifest

cat > .claude-plugin/plugin.json << 'EOF'
{
  "name": "my-first-plugin",
  "version": "1.0.0",
  "description": "My first Claude plugin",
  "author": {
    "name": "Your Name"
  }
}
EOF

步骤 3: 添加一个命令

cat > commands/hello.md << 'EOF'
---
description: Say hello to the user
---

# Hello Command

Greet the user warmly and introduce yourself as their AI assistant.
Ask how you can help them today.
EOF

步骤 4: 本地测试

# 使用 --plugin-dir 标志加载本地插件
claude --plugin-dir ./my-first-plugin

# 在 Claude Code 中测试
/my-first-plugin:hello

步骤 5: 迭代开发

修改文件后重启 Claude Code 以重新加载:

# 或使用调试模式查看详细日志
claude --debug --plugin-dir ./my-first-plugin

7.2 添加 Skill

mkdir -p skills/python-expert
cat > skills/python-expert/SKILL.md << 'EOF'
---
name: python-expert
description: Expert in Python 3.12+, async programming, and type hints. Use when writing or reviewing Python code.
---

# Python Expert Skill

## Best Practices
- Always use type hints
- Prefer async/await for I/O operations
- Follow PEP 8 style guide
- Use dataclasses or Pydantic for data models

## Code Examples

### Async HTTP Client
```python
import asyncio
import aiohttp
from typing import Dict, Any

async def fetch_data(url: str) -> Dict[str, Any]:
    async with aiohttp.ClientSession() as session:
        async with session.get(url) as response:
            return await response.json()

# Usage
data = asyncio.run(fetch_data("https://api.example.com/data"))

EOF

### 7.3 添加 Agent

```bash
cat > agents/test-generator.md << 'EOF'
---
description: Generates comprehensive unit tests for code
capabilities:
  - Unit test creation
  - Edge case identification
  - Mock setup
  - Test documentation
---

# Test Generator Agent

You are a testing expert. Generate comprehensive unit tests for the given code.

## Test Structure
1. **Arrange**: Set up test data and mocks
2. **Act**: Execute the code under test
3. **Assert**: Verify expected outcomes

## Coverage Goals
- Happy path scenarios
- Error handling
- Edge cases
- Boundary conditions

## Output Format
Provide tests using pytest framework with clear docstrings.
EOF

7.4 添加 Hook

mkdir -p hooks/scripts
cat > hooks/hooks.json << 'EOF'
{
  "PreToolUse": [
    {
      "matcher": "Write|Edit",
      "hooks": [
        {
          "type": "command",
          "command": "bash ${CLAUDE_PLUGIN_ROOT}/hooks/scripts/lint.sh",
          "timeout": 30
        }
      ]
    }
  ]
}
EOF

cat > hooks/scripts/lint.sh << 'EOF'
#!/bin/bash
echo "Running linter..."
# 添加你的 lint 逻辑
exit 0
EOF

chmod +x hooks/scripts/lint.sh

7.5 添加 MCP Server

mkdir -p servers
cat > .mcp.json << 'EOF'
{
  "file-search": {
    "command": "node",
    "args": ["${CLAUDE_PLUGIN_ROOT}/servers/file-search.js"],
    "env": {
      "SEARCH_PATH": "."
    }
  }
}
EOF

cat > servers/file-search.js << 'EOF'
// 简单的文件搜索 MCP 服务器示例
const { Server } = require('@modelcontextprotocol/sdk/server/index.js');
const { StdioServerTransport } = require('@modelcontextprotocol/sdk/server/stdio.js');
const fs = require('fs').promises;
const path = require('path');

const server = new Server(
  { name: 'file-search-server', version: '1.0.0' },
  { capabilities: { tools: {} } }
);

server.setRequestHandler('tools/list', async () => ({
  tools: [{
    name: 'search_files',
    description: 'Search for files by pattern',
    inputSchema: {
      type: 'object',
      properties: {
        pattern: { type: 'string' },
        directory: { type: 'string' }
      },
      required: ['pattern']
    }
  }]
}));

server.setRequestHandler('tools/call', async (request) => {
  if (request.params.name === 'search_files') {
    const { pattern, directory = '.' } = request.params.arguments;
    // 实现搜索逻辑...
    return {
      content: [{
        type: 'text',
        text: 'Search results...'
      }]
    };
  }
});

async function main() {
  const transport = new StdioServerTransport();
  await server.connect(transport);
}

main();
EOF

7.6 ${CLAUDE_PLUGIN_ROOT} 使用

关键规则: 所有插件内部路径引用必须使用 ${CLAUDE_PLUGIN_ROOT}

为什么需要?

插件安装位置不固定:

  • 市场安装: ~/.claude/plugins/cache/...
  • 本地开发: ./my-plugin
  • NPM 安装: node_modules/...

正确用法

// ✅ 正确 - MCP 配置
{
  "mcpServers": {
    "my-server": {
      "command": "node",
      "args": ["${CLAUDE_PLUGIN_ROOT}/servers/server.js"]
    }
  }
}
// ✅ 正确 - Hook 脚本
{
  "PreToolUse": [{
    "hooks": [{
      "command": "bash ${CLAUDE_PLUGIN_ROOT}/scripts/validate.sh"
    }]
  }]
}
<!-- ✅ 正确 - Command 中引用 -->
Run the setup script:
\`\`\`bash
bash ${CLAUDE_PLUGIN_ROOT}/scripts/setup.sh
\`\`\`

错误用法

// ❌ 错误 - 相对路径
{
  "command": "./servers/server.js"  // 会在错误的工作目录查找
}

// ❌ 错误 - 绝对路径
{
  "command": "/Users/alice/my-plugin/servers/server.js"  // 别人无法使用
}

在脚本中使用

#!/bin/bash
# hooks/scripts/my-script.sh

# ${CLAUDE_PLUGIN_ROOT} 在环境变量中可用
PLUGIN_ROOT="${CLAUDE_PLUGIN_ROOT}"

# 加载共享工具
source "${PLUGIN_ROOT}/lib/utils.sh"

# 读取配置
CONFIG_FILE="${PLUGIN_ROOT}/config/settings.json"

8. 最佳实践

8.1 设计原则

8.1.1 单一职责

每个插件应专注于一个明确的用途:

:white_check_mark: 好例子:

python-testing-plugin/
├── skills/pytest-expert/
├── commands/run-tests.md
└── agents/test-generator.md

:x: 避免:

everything-plugin/
├── skills/python/, javascript/, ruby/, go/
├── commands/test/, deploy/, database/, email/
└── ...  # 太多不相关功能

8.1.2 清晰的命名

组件 命名规范 示例
Plugin kebab-case, 描述性 react-testing-library
Skill kebab-case api-integration
Command kebab-case, 动词开头 deploy-production
Agent kebab-case, 角色名 security-reviewer

8.1.3 渐进增强

从简单开始,逐步添加功能:

Version 1.0.0: 基本命令
    ↓
Version 1.1.0: 添加 Skill
    ↓
Version 1.2.0: 添加 Agent
    ↓
Version 2.0.0: 添加 MCP 集成

8.2 性能优化

8.2.1 减少 Token 消耗

使用 Progressive Disclosure:

<!-- SKILL.md - 简洁主文件 -->
## Quick Reference
- Pattern A: Use case 1
- Pattern B: Use case 2

For detailed examples, see [examples.md](./examples.md)

条件加载:

{
  "skills": {
    "advanced-patterns": {
      "condition": "user.experience === 'expert'"
    }
  }
}

8.2.2 优化 Hook 执行

{
  "PreToolUse": [
    {
      "matcher": "file_write",  // 只匹配特定工具
      "hooks": [{
        "command": "quick-check.sh",
        "timeout": 5  // 设置超时
      }]
    }
  ]
}

8.2.3 MCP 服务器优化

// 使用连接池
const pool = new Pool({ max: 10 });

// 实现缓存
const cache = new Map();

server.setRequestHandler('tools/call', async (request) => {
  const cacheKey = JSON.stringify(request.params);
  
  if (cache.has(cacheKey)) {
    return cache.get(cacheKey);
  }
  
  const result = await expensiveOperation();
  cache.set(cacheKey, result);
  return result;
});

8.3 安全考虑

8.3.1 敏感信息处理

// ❌ 不要硬编码密钥
{
  "env": {
    "API_KEY": "sk-1234567890abcdef"
  }
}

// ✅ 使用环境变量引用
{
  "env": {
    "API_KEY": "${API_KEY}"
  }
}

8.3.2 输入验证

#!/bin/bash
# hooks/scripts/validate-input.sh

INPUT="$1"

# 验证输入格式
if [[ ! "$INPUT" =~ ^[a-zA-Z0-9_-]+$ ]]; then
    echo "ERROR: Invalid input format"
    exit 1
fi

8.3.3 权限最小化

{
  "mcpServers": {
    "database": {
      "env": {
        "DB_ROLE": "readonly"  // 只读权限
      }
    }
  }
}

8.4 文档编写

8.4.1 README 模板

# Plugin Name

> Brief description (one sentence)

## Features

- Feature 1
- Feature 2
- Feature 3

## Installation

\`\`\`bash
/plugin install my-plugin@marketplace
\`\`\`

## Quick Start

### Commands

- \`/my-plugin:command-name\` - Description

### Skills

The plugin provides these AI skills:
- **skill-name**: When to use it

### Configuration

\`\`\`json
{
  "apiKey": "your-key-here",
  "timeout": 5000
}
\`\`\`

## Examples

### Example 1: Basic Usage

\`\`\`
/my-plugin:deploy staging
\`\`\`

## Requirements

- Node.js >= 18.0.0
- Python >= 3.10

## Troubleshooting

### Issue 1
**Symptom**: Error message
**Solution**: How to fix

## License

MIT

8.4.2 Inline 文档

在每个组件中提供清晰说明:

<!-- commands/complex-workflow.md -->

---
description: Multi-step deployment workflow
---

# Complex Deployment Workflow

## What This Does
This command performs a safe production deployment with:
1. Pre-deployment checks
2. Blue-green deployment
3. Post-deployment verification
4. Automatic rollback on failure

## When to Use
- Deploying to production
- Need zero-downtime deployment
- Require automatic rollback

## Prerequisites
- All tests passing
- Approval from team lead
- Production database backed up

## Steps
...

8.5 版本管理

8.5.1 语义化版本

MAJOR.MINOR.PATCH

1.0.0 → 1.0.1  # Bug fix (patch)
1.0.1 → 1.1.0  # New feature (minor)
1.1.0 → 2.0.0  # Breaking change (major)

8.5.2 CHANGELOG.md

# Changelog

## [2.0.0] - 2026-02-01

### Breaking Changes
- Renamed command `/deploy` to `/deploy-app`
- Changed config schema for API keys

### Added
- New skill: `docker-compose-expert`
- MCP server for database queries

### Fixed
- Bug in rollback script

## [1.1.0] - 2026-01-15

### Added
- New command: `/health-check`

9. 调试与故障排查

9.1 调试工具

9.1.1 启用调试模式

# 查看详细日志
claude --debug

# 查看插件加载过程
claude --debug --plugin-dir ./my-plugin

# 查看特定组件
claude --debug 2>&1 | grep "loading plugin"

9.1.2 调试输出示例

[DEBUG] Loading plugin from: /Users/alice/.claude/plugins/my-plugin
[DEBUG] Reading manifest: .claude-plugin/plugin.json
[DEBUG] Found components:
  - Commands: 3 files
  - Skills: 2 directories
  - Agents: 1 file
  - Hooks: hooks.json
  - MCP: .mcp.json
[DEBUG] Registering namespace: my-plugin
[DEBUG] Loading MCP server: database-server

9.2 常见错误

9.2.1 Manifest 错误

错误: Plugin has an invalid manifest file

# 验证 JSON 语法
jq . .claude-plugin/plugin.json

# 检查必需字段
jq '.name, .version, .description' .claude-plugin/plugin.json

解决方案:

{
  "name": "my-plugin",        // ✅ 必需
  "version": "1.0.0",          // ✅ 必需
  "description": "My plugin"   // ✅ 必需
}

9.2.2 路径错误

错误: No commands found in plugin

检查点:

# 1. 目录结构正确吗?
tree -L 2 my-plugin/

# 应该看到:
# my-plugin/
# ├── .claude-plugin/
# │   └── plugin.json
# └── commands/          # ✅ 在根目录
#     └── hello.md

# ❌ 错误结构:
# my-plugin/
# └── .claude-plugin/
#     ├── plugin.json
#     └── commands/      # ❌ 嵌套在 .claude-plugin/ 内

解决方案: 移动组件到插件根目录

mv .claude-plugin/commands ./commands
mv .claude-plugin/skills ./skills

9.2.3 MCP 服务器无法启动

错误: MCP server 'my-server' failed to start

调试步骤:

# 1. 手动测试服务器
node servers/my-server.js

# 2. 检查路径
echo "${CLAUDE_PLUGIN_ROOT}/servers/my-server.js"

# 3. 验证依赖
npm list @modelcontextprotocol/sdk

常见原因:

  • 缺少依赖: npm install @modelcontextprotocol/sdk
  • 路径错误: 使用 ${CLAUDE_PLUGIN_ROOT}
  • 权限问题: chmod +x servers/my-server.js

9.2.4 Hook 未触发

检查清单:

// hooks/hooks.json
{
  "PreToolUse": [
    {
      "matcher": "Write",  // ✅ 检查 matcher 是否正确
      "hooks": [{
        "type": "command",
        "command": "bash ${CLAUDE_PLUGIN_ROOT}/hooks/scripts/validate.sh",  // ✅ 检查路径
        "timeout": 30  // ✅ 检查超时设置
      }]
    }
  ]
}
# 测试 hook 脚本
bash hooks/scripts/validate.sh

# 检查权限
chmod +x hooks/scripts/validate.sh

9.2.5 Skill 未自动加载

验证 frontmatter:

<!-- ✅ 正确 -->
---
name: my-skill
description: Clear description of when to use
---

<!-- ❌ 错误 - 缺少字段 -->
---
name: my-skill
---

验证目录结构:

skills/
└── my-skill/
    └── SKILL.md  # ✅ 必需

9.3 验证工具

9.3.1 Manifest 验证脚本

#!/bin/bash
# scripts/validate-manifest.sh

MANIFEST=".claude-plugin/plugin.json"

echo "Validating $MANIFEST..."

# 检查文件存在
if [ ! -f "$MANIFEST" ]; then
    echo "❌ Manifest file not found"
    exit 1
fi

# 检查 JSON 语法
if ! jq empty "$MANIFEST" 2>/dev/null; then
    echo "❌ Invalid JSON syntax"
    exit 1
fi

# 检查必需字段
REQUIRED_FIELDS=("name" "version" "description")
for field in "${REQUIRED_FIELDS[@]}"; do
    if ! jq -e ".$field" "$MANIFEST" > /dev/null; then
        echo "❌ Missing required field: $field"
        exit 1
    fi
done

echo "✅ Manifest is valid"

9.3.2 结构验证

#!/bin/bash
# scripts/validate-structure.sh

echo "Validating plugin structure..."

# 检查必需目录
if [ ! -d ".claude-plugin" ]; then
    echo "❌ Missing .claude-plugin/ directory"
    exit 1
fi

# 检查组件在正确位置
WRONG_LOCATIONS=(
    ".claude-plugin/commands"
    ".claude-plugin/skills"
    ".claude-plugin/agents"
)

for loc in "${WRONG_LOCATIONS[@]}"; do
    if [ -d "$loc" ]; then
        echo "❌ Wrong location: $loc"
        echo "   Components must be at plugin root, not inside .claude-plugin/"
        exit 1
    fi
done

echo "✅ Structure is valid"