深入理解 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 参数说明
|
|
|
|
|
|---|---|---|---|
|
|
|
|
/help 中 |
|
|
|
|
Read, Grep, Bash(git:*) |
|
|
|
|
|
|
|
|
|
[pr-number] [priority] |
|
|
|
|
|
完整 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'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 字段
|
|
|
|
|---|---|---|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
完整 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. 主 Agent 使用 Task 工具调用 Subagent -
2. Subagent 独立处理任务 -
3. 结果返回给主 Agent -
4. 主 Agent 整合结果
Skill 参数说明
除了 Command、Agent、Hooks,Claude Code 还支持 Skill(技能):
---name: Skill Namedescription: When to use this skillversion: 1.0.0---Skill instructions and guidance...
|
|
|
|
|
|---|---|---|---|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
四、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. PreToolUse – 工具执行前 -
2. PostToolUse – 工具执行后 -
3. Stop – Agent 停止前 -
4. SubagentStop – 子代理停止前 -
5. SessionStart – 会话开始 -
6. SessionEnd – 会话结束 -
7. UserPromptSubmit – 用户提交提示 -
8. PreCompact – 上下文压缩前 -
9. Notification – 通知事件
Hooks 配置
{ "PreToolUse": [ { "matcher": "Write|Edit", "hooks": [ { "type": "prompt", "prompt": "Validate file write safety. Check: system paths, credentials, path traversal. Return 'approve' or 'deny'." } ] } ], "Stop": [ { "matcher": "*", "hooks": [ { "type": "prompt", "prompt": "Verify task completion: tests run, build succeeded. Return 'approve' to stop or 'block' 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 '.tool_input.file_path')# 检查路径遍历if [[ "$file_path" == *".."* ]]; then echo '{"decision": "deny", "reason": "Path traversal detected"}' >&2 exit 2fi# 检查敏感文件if [[ "$file_path" == *".env"* ]]; then echo '{"decision": "deny", "reason": "Sensitive file"}' >&2 exit 2fiecho '{"decision": "approve"}'exit 0
Hooks 参数说明
|
|
|
|
|
|---|---|---|---|
|
|
|
|
Write|Edit、mcp__.*__delete.* |
|
|
|
|
command(执行脚本)或 prompt(LLM 判断) |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Hook 事件参数
|
|
|
|
|---|---|---|
|
|
|
$TOOL_INPUT |
|
|
|
$TOOL_INPUT
$TOOL_RESULT |
|
|
|
$LAST_ASSISTANT_MESSAGE |
|
|
|
$LAST_ASSISTANT_MESSAGE |
|
|
|
$USER_PROMPT |
|
|
|
$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 参数说明
|
|
|
|
|
|---|---|---|---|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Subagent 任务参数
|
|
|
|
|---|---|---|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
团队协作模式
-
1. 协调者模式:一个主 Agent 协调多个子 Agent -
2. 并行模式:多个 Agent 同时处理不同任务 -
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 参数说明
|
|
|
|
|
|---|---|---|---|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
总结
|
|
|
|
|---|---|---|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
掌握这些概念后,你就可以开始构建强大的 Claude Code 插件了!
夜雨聆风