乐于分享
好东西不私藏

深入理解 Claude Code 插件开发:Command、Agent、Swarm、Subagent、Hooks、Team

深入理解 Claude Code 插件开发:Command、Agent、Swarm、Subagent、Hooks、Team

Claude Code 是 Anthropic 推出的 AI 编程助手,其强大的插件系统允许开发者扩展功能。本文将详细介绍 Command、Agent、Swarm、Subagent、Hooks、Team 等核心概念,帮助你快速掌握 Claude Code 插件开发。

一、Command(命令)

什么是 Command?

Command 是以斜杠 / 开头的指令,是用户主动触发的操作。例如 /review、/test 等。

Command 文件结构

.claude/commands/├── review.md           # /review 命令├── test.md             # /test 命令└── deploy.md           # /deploy 命令

基本示例

---description: Review code for security issuesallowed-tools: Read, Grep, Bash(git:*)model: sonnet---Review this code for security vulnerabilities including:- SQL injection- XSS attacks- Authentication bypass- Insecure data handlingProvide specific line numbers and severity ratings.

动态参数

---description: Fix issue by numberargument-hint: [issue-number]---Fix issue #$ARGUMENTS following our coding standards and best practices.

使用方式:/fix-issue 123

文件引用

---description: Review specific fileargument-hint: [file-path]---Review @$1 for:- Code quality- Best practices- Potential bugs

使用方式:/review-file src/api/users.ts

Command 参数说明

参数
类型
必填
说明
description
string
命令描述,显示在 /help 中
allowed-tools
string/array
允许使用的工具,如 Read, Grep, Bash(git:*)
model
string
指定模型(sonnet/opus/haiku)
argument-hint
string
参数提示,如 [pr-number] [priority]
disable-model-invocation
boolean
是否禁止程序化调用命令

完整 Command 示例

---description: Deploy application to environmentargument-hint: [environment] [version]allowed-tools: Bash(npm:*), Readmodel: sonnet---Deploy application to $1 environment using version $2.Run pre-deployment checks first.

二、Agent(代理)

什么是 Agent?

Agent 是自主运行的子进程,可以独立处理复杂的多步骤任务。与 Command 不同,Agent 是由 Claude 根据上下文自动触发的。

Agent 文件结构

---name: code-reviewerdescription: Use this agent when user asks to review code for bugs, security issues, or quality problems. Examples:<example>Context: User submitted a pull requestuser: "Can you review this PR?"assistant: "I&#x27;ll use the code-reviewer agent to perform a thorough review."<commentary>This is a classic code review scenario where the agent should trigger.</commentary></example>model: sonnetcolor: redtools: ["Read", "Grep", "Glob"]---You are an expert code reviewer...## Core Responsibilities1. Review code for bugs2. Check security vulnerabilities3. Evaluate code quality

Frontmatter 字段

字段
必填
说明
name
Agent 标识符(3-50字符,小写连字符)
description
触发条件和使用示例
model
使用模型(inherit/sonnet/opus/haiku)
color
UI 颜色(blue/cyan/green/yellow/magenta/red)
tools
允许使用的工具列表

完整 Agent 示例

---name: code-reviewerdescription: Reviews code for bugs, logic errors, security vulnerabilities, code quality issues, and adherence to project conventionsmodel: sonnetcolor: redtools: Glob, Grep, Read, Bash---You are an expert code reviewer specializing in modern software development.## Core Review Responsibilities**Bug Detection**: Identify actual bugs that will impact functionality - logic errors, null/undefined handling, race conditions, security vulnerabilities.**Code Quality**: Evaluate significant issues like code duplication, missing critical error handling, accessibility problems.## Confidence ScoringRate each potential issue on a scale from 0-100, only report issues with confidence ≥ 80.## Output FormatFor each high-confidence issue, provide:- Clear description with confidence score- File path and line number- Concrete fix suggestion

三、Subagent(子代理)

什么是 Subagent?

Subagent 是通过 Claude Code 的 Task 工具调用的子代理,用于将复杂任务委托给专门的 Agent 处理。

使用方式

在命令或 Agent 中调用:

Initiate comprehensive review of @$1 using the code-reviewer agent.

Subagent 配置

---name: subagent-namedescription: Use this agent when...model: inherit  # 继承父级模型color: bluetools: ["Read", "Write", "Grep"]---Agent instructions...

工作流程

  1. 1. 主 Agent 使用 Task 工具调用 Subagent
  2. 2. Subagent 独立处理任务
  3. 3. 结果返回给主 Agent
  4. 4. 主 Agent 整合结果

Skill 参数说明

除了 Command、Agent、Hooks,Claude Code 还支持 Skill(技能):

---name: Skill Namedescription: When to use this skillversion: 1.0.0---Skill instructions and guidance...
参数
类型
必填
说明
name
string
技能名称
description
string
触发条件描述
version
string
版本号

四、Swarm(蜂群)

什么是 Swarm?

Swarm 是多 Agent 协作模式,多个 Agent 可以同时工作,共同完成复杂任务。

Swarm 配置

在 .claude/settings.json 中配置:

{  "agents": {    "team-name": {      "members": ["agent-1", "agent-2", "agent-3"],      "coordinator": "main-agent"    }  }}

多 Agent 协作示例

# Multi-Agent WorkflowPhase 1 - Static Analysis:Launch code-analyzer agent for code structure analysis.Phase 2 - Security Review:Launch security-agent for vulnerability scanning.Phase 3 - Performance Analysis:Launch performance-agent for optimization suggestions.Phase 4 - Report Generation:Combine all findings into comprehensive report.

五、Hooks(钩子)

什么是 Hooks?

Hooks 是事件驱动的自动化脚本,在特定事件发生时自动执行。

Hook 类型

  1. 1. PreToolUse – 工具执行前
  2. 2. PostToolUse – 工具执行后
  3. 3. Stop – Agent 停止前
  4. 4. SubagentStop – 子代理停止前
  5. 5. SessionStart – 会话开始
  6. 6. SessionEnd – 会话结束
  7. 7. UserPromptSubmit – 用户提交提示
  8. 8. PreCompact – 上下文压缩前
  9. 9. Notification – 通知事件

Hooks 配置

{  "PreToolUse": [    {      "matcher": "Write|Edit",      "hooks": [        {          "type": "prompt",          "prompt": "Validate file write safety. Check: system paths, credentials, path traversal. Return &#x27;approve&#x27; or &#x27;deny&#x27;."        }      ]    }  ],  "Stop": [    {      "matcher": "*",      "hooks": [        {          "type": "prompt",          "prompt": "Verify task completion: tests run, build succeeded. Return &#x27;approve&#x27; to stop or &#x27;block&#x27; with reason."        }      ]    }  ],  "SessionStart": [    {      "matcher": "*",      "hooks": [        {          "type": "command",          "command": "bash ${CLAUDE_PLUGIN_ROOT}/scripts/load-context.sh"        }      ]    }  ]}

Hook 输出格式

{  "continue":true,  "suppressOutput":false,  "systemMessage": "Message for Claude"}

实际示例:文件写入验证

#!/bin/bashset -euo pipefailinput=$(cat)file_path=$(echo "$input" | jq -r &#x27;.tool_input.file_path&#x27;)# 检查路径遍历if [[ "$file_path" == *".."* ]]; then  echo &#x27;{"decision": "deny", "reason": "Path traversal detected"}&#x27; >&2  exit 2fi# 检查敏感文件if [[ "$file_path" == *".env"* ]]; then  echo &#x27;{"decision": "deny", "reason": "Sensitive file"}&#x27; >&2  exit 2fiecho &#x27;{"decision": "approve"}&#x27;exit 0

Hooks 参数说明

参数
类型
必填
说明
matcher
string
匹配规则,支持正则表达式,如 Write|Editmcp__.*__delete.*
type
string
钩子类型:command(执行脚本)或 prompt(LLM 判断)
command
string
是(type=command)
要执行的 bash 命令路径
prompt
string
是(type=prompt)
LLM 执行的提示词
timeout
number
超时时间(秒),默认 command 60s,prompt 30s

Hook 事件参数

事件
触发时机
输入变量
PreToolUse
工具执行前
$TOOL_INPUT
PostToolUse
工具执行后
$TOOL_INPUT

$TOOL_RESULT
Stop
Agent 停止前
$LAST_ASSISTANT_MESSAGE
SubagentStop
子代理停止前
$LAST_ASSISTANT_MESSAGE
UserPromptSubmit
用户提交提示
$USER_PROMPT
SessionStart
会话开始
$CLAUDE_ENV_FILE

(可持久化环境变量)

Hook 输出参数

// PreToolUse/Stop 输出{  "hookSpecificOutput": {    "permissionDecision": "allow|deny|ask",    "updatedInput": {"field": "modified_value"}  },  "systemMessage": "Explanation for Claude"}// 命令钩子输出{  "continue":true,  "suppressOutput":false,  "systemMessage": "Message for Claude"}

六、Team(团队)

什么是 Team?

Team 是 Claude Code 的多 Agent 协作功能,可以创建专业化的 Agent 团队。

团队创建

使用 TeamCreate 工具创建团队:

创建团队 "code-review-team",包含以下角色:- code-architect: 架构分析- code-explorer: 代码探索- code-reviewer: 代码审查

Team 配置

{  "team_name": "development-team",  "description": "Full-stack development team",  "agent_type": "general-purpose"}

Team/Subagent 参数说明

参数
类型
必填
说明
team_name
string
团队名称
description
string
团队描述和职责
agent_type
string
Agent 类型(如 general-purpose)
members
array
团队成员列表
coordinator
string
协调者 Agent 名称

Subagent 任务参数

参数
类型
说明
name
string
子代理名称
description
string
任务描述
subagent_type
string
子代理类型
mode
string
权限模式(default/plan/auto/bypassPermissions)
isolation
string
隔离模式(如 worktree)

团队协作模式

  1. 1. 协调者模式:一个主 Agent 协调多个子 Agent
  2. 2. 并行模式:多个 Agent 同时处理不同任务
  3. 3. 流水线模式:Agent 按顺序处理任务

团队通信

Send message to team-lead: "Architecture review completed. Findings attached."# 团队成员可以相互发送消息协调工作

七、插件结构完整示例

my-plugin/├── .claude-plugin/│   └── plugin.json          # 插件清单├── commands/                 # 命令│   ├── review.md│   └── test.md├── agents/                   # 代理│   ├── code-reviewer.md│   └── test-generator.md├── skills/                   # 技能│   └── api-testing/│       └── SKILL.md├── hooks/                    # 钩子│   └── hooks.json├── scripts/                  # 脚本│   └── validate.sh└── .mcp.json                # MCP 服务器

plugin.json

{  "name": "my-plugin",  "version": "1.0.0",  "description": "Code review and testing plugin",  "commands": "./commands",  "agents": "./agents",  "hooks": "./hooks/hooks.json"}

plugin.json 参数说明

参数
类型
必填
说明
name
string
插件名称(kebab-case 格式)
version
string
版本号(语义化版本)
description
string
插件描述
author
object
作者信息(name/email/url)
commands
string/array
自定义命令目录路径
agents
string/array
自定义代理目录路径
hooks
string
自定义钩子配置文件路径
mcpServers
string
MCP 服务器配置路径
keywords
array
关键词,用于插件市场搜索

总结

概念
触发方式
用途
Command
用户手动 /cmd
用户发起的操作
Agent
自动触发
自动化任务处理
Subagent
Task 工具调用
委托处理子任务
Swarm
配置多 Agent
多 Agent 协作
Hooks
事件自动触发
自动化验证/响应
Team
TeamCreate
多 Agent 团队协作

掌握这些概念后,你就可以开始构建强大的 Claude Code 插件了!