Claude Code 插件 Agent 的 AI 辅助生成:agent-creation-prompt 模板与实战指南

原创2026-09-30 15:33:18948 阅读
文章标签:AI 插件开发工具插件系统

Claude Code 插件 Agent 的 AI 辅助生成:agent-creation-prompt 模板与实战指南

导读

本文讲解 claude-plugins-official 仓库中 plugin-dev 插件所内置的「AI 辅助 Agent 生成模板」(agent-creation-prompt.md):只需用一句话描述你需要的 Agent 能力,就能让 Claude 依据官方 Agent 创建系统提示词,自动产出包含 identifier、whenToUse、systemPrompt 三要素的 JSON 配置,再转换为标准的 agents/<identifier>.md 文件。读完本文,你将掌握完整的四步生成流程、三个可复用的生产级示例(代码审查、测试生成、文档撰写)、让生成质量显著提升的提示词写法,以及用仓库自带脚本校验与迭代生成结果的方法,从而为你的 Claude Code 插件快速创建可靠、可自主触发的 Agent。

一、模板的定位:从一句话需求到标准 Agent 文件

在 plugin-dev 的 agent-development 技能中,创建 Agent 有两种方法:

  • Method 1:AI 辅助生成(AI-Assisted Generation)——使用本文讲解的模板,把需求描述喂给 Claude,由 Claude 生成完整配置;
  • Method 2:手动创建(Manual Creation)——人工按照 frontmatter 字段与系统提示词结构逐项编写。

该模板的完整说明位于 agent-creation-prompt.md,其配套的生成系统提示词位于 agent-creation-system-prompt.md。从源码结构看,这套模板与 plugin-dev 内置的 agent-creator Agent(agent-creator.md)共享同一套设计理念:提炼核心意图 → 设计专家人格 → 构建完整指令 → 优化性能 → 生成标识符 → 编写触发描述。

使用模板的核心前提是:在向 Claude 发送生成请求前,先加载(或让 Claude 加载)Agent 创建系统提示词。这样 Claude 才会按照规定的 JSON 结构和触发描述格式进行输出,而不是自由发挥。

二、四步使用流程:从描述到落地文件

Step 1:描述你的 Agent 需求

在动手之前,先想清楚四个问题:

  • What task should the agent handle?——Agent 具体要完成什么任务?
  • When should it be triggered?——它应该在什么时机被触发?
  • Should it be proactive or reactive?——是需要主动触发(Proactive,助手在完成任务后自主调用),还是被动触发(Reactive,用户显式请求时调用)?
  • What are the key responsibilities?——它的核心职责有哪些?

这四问对应的是 agent-creation-system-prompt.md 中「Extract Core Intent」的要求:识别根本目的、关键职责与成功标准,既要看显式需求,也要捕捉隐含需求。

Step 2:使用生成提示词

将以下内容发送给 Claude(确保 agent-creation-system-prompt 已加载):

Create an agent configuration based on this request: "[YOUR DESCRIPTION]"

Return ONLY the JSON object, no other text.

将 [YOUR DESCRIPTION] 替换为你在 Step 1 中整理好的需求描述。

「Return ONLY the JSON object」这条约束很重要:它要求 Claude 严格返回可解析的 JSON,避免混入解释性文字,方便后续直接提取字段。可参考 SKILL.md 中给出的完整生成提示模式(含 5 条 Requirements 说明),信息量更完整。

Step 3:Claude 返回 JSON

Claude 会返回包含三个字段的 JSON 对象:

{
  "identifier": "agent-name",
  "whenToUse": "Use this agent when... Typical triggers include [scenario 1], [scenario 2], and [scenario 3]. See \"When to invoke\" in the agent body for worked scenarios.",
  "systemPrompt": "You are...\n\n## When to invoke\n\n- **[Scenario A].** [Description]\n- **[Scenario B].** [Description]\n\n**Your Core Responsibilities:**..."
}

三个字段的格式约定(来自 agent-creation-system-prompt.md):

  • identifier:唯一、描述性的标识符,只允许小写字母、数字和连字符,通常是 2~4 个单词用连字符连接(如 code-reviewer、api-docs-writer、test-generator),要能清晰表达主功能、便于记忆输入,避免 helper、assistant 这类泛化词;
  • whenToUse:平铺散文(flat prose),单行书写。标准句式是 Use this agent when [conditions]. Typical triggers include [scenario 1], [scenario 2], and [scenario 3]. See "When to invoke" in the agent body for worked scenarios.;
  • systemPrompt:完整的 Agent 行为系统提示词,用第二人称("You are..."、"You will...")书写,开头必须包含一个 "When to invoke" 小节,用散文项目符号列出 2~4 个触发场景(每个场景以加粗的短场景名开头,后面跟对情境与应对动作的散文描述),随后是人格、职责、流程、输出格式与边界情况。

关于触发场景的写作,有一条关键红线(在 triggering-examples.md 中有专门强调):不要用带引号的用户原话(transcript 形状)开头,而应描述用户所处的"情境"。例如用 The user has just implemented a feature (often spanning several files) and asks whether everything looks good. Run a review of the recent diff and report findings.,而不是把 user: "Can you check if everything looks good?" 这种对话记录写进场景里。同时要尽量同时覆盖主动触发与被动触发两种场景。

Step 4:转换为 Agent 文件

创建 agents/[identifier].md,将 JSON 中的字段映射到 YAML frontmatter 与正文:

---
name: [identifier from JSON]
description: [whenToUse from JSON]
model: inherit
color: [choose: blue/cyan/green/yellow/magenta/red]
tools: ["Read", "Write", "Grep"]  # Optional: restrict tools
---

[systemPrompt from JSON]

各 frontmatter 字段的取值规则(详见 SKILL.md):

字段 必填 取值/格式 说明
name 是 小写字母、数字、连字符,3~50 字符,首尾必须为字母数字 Agent 标识符,用于命名空间与触发
description 是 平铺散文,以 "Use this agent when..." 开头 最关键字段,Agent 注册时会被加载进上下文供路由决策,必须包含触发条件、2~4 个典型场景的散文摘要、以及对正文 "When to invoke" 的指引
model 是 inherit / sonnet / opus / haiku 推荐 inherit(与父级同模型),除非有特定模型能力需求
color 是 blue / cyan / green / yellow / magenta / red UI 视觉标识;蓝/青=分析审查,绿=生成,黄=校验警告,红=安全关键,品红=创作重构
tools 否 工具名数组,如 ["Read", "Write", "Grep"] 省略则拥有全部工具;最佳实践是按最小权限原则只给必要工具

常见工具组合:只读分析用 ["Read", "Grep", "Glob"],代码生成用 ["Read", "Write", "Grep"],测试执行用 ["Read", "Bash", "Grep"],完全权限则省略该字段或写 ["*"]。

三、实战示例 1:代码审查 Agent(Code Review Agent)

你的请求(Your request):

I need an agent that reviews code changes for quality issues, security vulnerabilities, and adherence to best practices. It should be called after code is written and provide specific feedback.

Claude 生成的结果(Claude generates):

{
  "identifier": "code-quality-reviewer",
  "whenToUse": "Use this agent when the user has written code and needs quality review, or explicitly asks to review code changes. Typical triggers include proactive review after the assistant writes new code, and an explicit user request for review of recent changes. See \"When to invoke\" in the agent body for worked scenarios.",
  "systemPrompt": "You are an expert code quality reviewer specializing in identifying issues in software implementations.\n\n## When to invoke\n\n- **Proactive review after new code.** The assistant has just written or modified code (e.g. an authentication feature). Run a review for quality, security, and best practices before declaring the task done.\n- **Explicit review request.** The user asks for the recent changes to be reviewed for issues. Run a thorough review and report findings.\n\n**Your Core Responsibilities:**\n1. Analyze code changes for quality issues (readability, maintainability, performance)\n2. Identify security vulnerabilities (injection, XSS, authentication issues)\n3. Check adherence to project best practices and coding standards\n4. Provide actionable, specific feedback with line numbers\n\n**Review Process:**\n1. Read the code changes using available tools\n2. Analyze for:\n   - Code quality (duplication, complexity, clarity)\n   - Security (OWASP top 10, input validation)\n   - Best practices (error handling, logging, testing)\n   - Project-specific standards (from CLAUDE.md)\n3. Identify issues with severity (critical/major/minor)\n4. Provide specific recommendations with examples\n\n**Output Format:**\nProvide a structured review:\n1. Summary (2-3 sentences)\n2. Critical Issues (must fix)\n3. Major Issues (should fix)\n4. Minor Issues (nice to fix)\n5. Positive observations\n6. Overall assessment\n\nInclude file names and line numbers for all findings."
}

你创建的 Agent 文件(You create):

文件路径:agents/code-quality-reviewer.md

---
name: code-quality-reviewer
description: Use this agent when the user has written code and needs quality review, or explicitly asks to review code changes. Typical triggers include proactive review after the assistant writes new code, and an explicit user request for review of recent changes. See "When to invoke" in the agent body for worked scenarios.
model: inherit
color: blue
tools: ["Read", "Grep", "Glob"]
---

You are an expert code quality reviewer specializing in identifying issues in software implementations.

## When to invoke

- **Proactive review after new code.** The assistant has just written or modified code (e.g. an authentication feature). Run a review for quality, security, and best practices before declaring the task done.
- **Explicit review request.** The user asks for the recent changes to be reviewed for issues. Run a thorough review and report findings.

**Your Core Responsibilities:**
1. Analyze code changes for quality issues (readability, maintainability, performance)
2. Identify security vulnerabilities (injection, XSS, authentication issues)
3. Check adherence to project best practices and coding standards
4. Provide actionable, specific feedback with line numbers

**Review Process:**
1. Read the code changes using available tools
2. Analyze for:
   - Code quality (duplication, complexity, clarity)
   - Security (OWASP top 10, input validation)
   - Best practices (error handling, logging, testing)
   - Project-specific standards (from CLAUDE.md)
3. Identify issues with severity (critical/major/minor)
4. Provide specific recommendations with examples

**Output Format:**
Provide a structured review:
1. Summary (2-3 sentences)
2. Critical Issues (must fix)
3. Major Issues (should fix)
4. Minor Issues (nice to fix)
5. Positive observations
6. Overall assessment

Include file names and line numbers for all findings.

可以对照 complete-agent-examples.md 中 code-reviewer 的生产级完整版本:其审查流程细化为 Gather Context(用 Glob 找最近修改文件)、Read Code、质量分析(DRY、复杂度、错误处理、日志)、安全分析(注入、认证授权、输入校验、硬编码密钥)、最佳实践、按严重度分类、生成报告七个步骤,并补充了「问题过多时按类型分组、优先列出 Top 10」「无问题时的正向确认」「大变更集先聚焦最影响文件」等边界情况处理——这些正是从模板生成后可以继续打磨的方向。

四、实战示例 2:测试生成 Agent(Test Generation Agent)

你的请求:

Create an agent that generates unit tests for code. It should analyze existing code and create comprehensive test suites following project conventions.

Claude 生成的结果:

{
  "identifier": "test-generator",
  "whenToUse": "Use this agent when the user asks to generate tests, needs test coverage, or has written code that needs testing. Typical triggers include proactive test generation after the assistant writes new functions, and an explicit user request for tests on a specific module. See \"When to invoke\" in the agent body.",
  "systemPrompt": "You are an expert test engineer specializing in creating comprehensive unit tests.\n\n## When to invoke\n\n- **Proactive coverage after new code.** The assistant has just implemented new functions (e.g. user authentication functions) without tests. Generate a comprehensive test suite before declaring the task done.\n- **Explicit test request.** The user asks for tests on a specific surface. Generate the requested suite following project conventions.\n\n**Your Core Responsibilities:**\n1. Analyze code to understand behavior\n2. Generate test cases covering happy paths and edge cases\n3. Follow project testing conventions\n4. Ensure high code coverage\n\n**Test Generation Process:**\n1. Read target code\n2. Identify testable units (functions, classes, methods)\n3. Design test cases (inputs, expected outputs, edge cases)\n4. Generate tests following project patterns\n5. Add assertions and error cases\n\n**Output Format:**\nGenerate complete test files with:\n- Test suite structure\n- Setup/teardown if needed\n- Descriptive test names\n- Comprehensive assertions"
}

你创建的 Agent 文件: agents/test-generator.md,采用与上面示例相同的结构(frontmatter + systemPrompt)。

生产级版本(见 complete-agent-examples.md)为测试生成 Agent 选了 color: green(生成/成功导向)与 tools: ["Read", "Write", "Grep", "Bash"](需要执行测试),并在质量标准中补充了 DAMP 原则(Descriptive And Meaningful Phrases)、测试独立性(无共享状态)、避免过度 Mock、AAA(Arrange-Act-Assert)结构等约束——生成模板时可把这些要求写进你的需求描述中。

五、实战示例 3:文档撰写 Agent(Documentation Agent)

你的请求:

Build an agent that writes and updates API documentation. It should analyze code and generate clear, comprehensive docs.

结果: Agent 文件采用 api-docs-writer 标识符,description 为散文式触发描述(覆盖"新增 API 面后的主动文档生成"与"显式文档请求"两类场景),正文包含 "When to invoke" 小节。

文档类的生产级完整模板同样在 complete-agent-examples.md 中(docs-generator,color: cyan,tools: ["Read", "Write", "Grep", "Glob"]),其生成流程为:分析代码理解公开接口/参数/返回值/错误条件 → 识别既有文档模式(Markdown/JSDoc、风格、示例组织)→ 生成内容 → 按项目约定格式化 → 校验准确性与完整性。

六、让生成质量跃升的四个提示词技巧

模板提供了四类经过验证的提示词增强手段:

1. 需求描述要具体(Be Specific in Your Request)

模糊写法(Vague):

"I need an agent that helps with code"

具体写法(Specific):

"I need an agent that reviews pull requests for type safety issues in TypeScript, checking for proper type annotations, avoiding 'any', and ensuring correct generic usage"

2. 明确触发偏好(Include Triggering Preferences)

告诉 Claude Agent 应在何时激活,尤其要说明是否需要主动触发:

"Create an agent that generates tests. It should be triggered proactively after code is written, not just when explicitly requested."

3. 带上项目上下文(Mention Project Context)

生成结果会参考 CLAUDE.md 中的项目规范,因此在描述中带上技术栈与约定:

"Create a code review agent. This project uses React and TypeScript, so the agent should check for React best practices and TypeScript type safety."

4. 定义输出期望(Define Output Expectations)

明确输出的形式与粒度:

"Create an agent that analyzes performance. It should provide specific recommendations with file names and line numbers, plus estimated performance impact."

更深层的生成规则可参考 agent-creation-system-prompt.md 中的定制化建议:安全类 Agent 追加 OWASP Top 10 检查与输入净化校验;测试类 Agent 追加 AAA 模式与测试隔离;文档类 Agent 追加语言简洁性与项目文档标准要求。另外注意其作用域约定:审查类 Agent 默认审查"最近编写的代码"而非整个代码库,除非用户明确说明——这个假设建议直接写进需求描述。

七、生成后的校验:用 validate-agent.sh 把关

模板要求生成后必须校验(Validation After Generation):

# Validate structure
./scripts/validate-agent.sh agents/your-agent.md

# Check triggering works
# Test with realistic invocation phrasings

仓库实际提供了该校验脚本,位于 validate-agent.sh,其检查项与判定标准如下:

  • 文件结构:文件必须存在,且以 --- 开头、存在第二个 --- 闭合 frontmatter;
  • name 字段:必填;必须匹配 ^[a-zA-Z0-9][a-zA-Z0-9-]*[a-zA-Z0-9]$(首尾为字母数字,仅含字母、数字、连字符);长度 3~50 字符;helper、assistant、agent、tool 等泛化名称会触发警告;
  • description 字段:必填;建议 10~5000 字符;应包含 <example> 触发示例块;应以 "Use this agent when..." 开头(这些是警告级别,脚本并不会因此失败);
  • model 字段:必填;合法值为 inherit、sonnet、opus、haiku;
  • color 字段:必填;合法值为 blue、cyan、green、yellow、magenta、red;
  • tools 字段:可选,有值则回显;省略视为拥有全部工具;
  • 系统提示词:不能为空;最短 20 字符、超 10000 字符告警;应使用第二人称(You are / You will / Your);建议包含 responsibilities/process 与 output 格式定义。

脚本按 error_count 与 warning_count 汇总结果:无错误且无警告输出 All checks passed!;有警告无错误仍算通过(exit 0);有错误则失败(exit 1)。

八、迭代改进:生成只是起点

如果生成的 Agent 需要改进,按以下循环操作:

  1. 识别问题——找出缺失或错误的地方;
  2. 手动编辑 Agent 文件——聚焦四个优化点:
    • 改进 description: 与 "When to invoke" 中触发场景的命名(更贴切、覆盖更全);
    • 让系统提示词更具体;
    • 让流程步骤更清晰;
    • 定义更好的输出格式;
  3. 重新校验(再次运行 validate-agent.sh);
  4. 再次测试(用真实场景验证触发与行为)。

关于触发的调试,triggering-examples.md 给出了三类常见问题的定位思路:Agent 不触发——检查 description: 是否命名了正确的场景、正文场景是否覆盖用户实际措辞、是否有更具体的竞争 Agent 抢走了路由;触发过于频繁——场景过于泛化或缺少"何时不要用"的边界说明,可添加 Do not invoke when... 行;在错误场景触发——重写场景使其与 Agent 实际能力匹配。场景数量建议为:最少 2 个(通常一个显式 + 一个主动),推荐 3~4 个,最多不超过 5 个。

九、AI 辅助生成的优势与手动编辑的取舍

模板总结了 AI 辅助生成的四个核心优势:

  • Comprehensive(全面):Claude 会自动纳入边界情况与质量检查;
  • Consistent(一致):遵循经过验证的模式,不同 Agent 间风格统一;
  • Fast(快速):秒级产出,远快于手动撰写;
  • Complete(完整):提供完整的系统提示词结构,无需从零搭建。

但以下情况建议手动编辑生成结果:

  • 需要非常特定的项目模式(如特定框架约定);
  • 需要自定义工具组合;
  • 想要独特的人格或风格;
  • 需要与既有 Agent 集成;
  • 需要精确的触发条件。

最佳实践是:先用生成起步,再手动精修(Start with generation, then refine manually for best results)。

十、在 plugin-dev 生态中的完整衔接

这份模板并非孤立文件,而是 plugin-dev 插件开发工具包的一部分:

  • 核心技能入口:agent-development/SKILL.md——承载 Agent 文件结构、frontmatter 全字段、系统提示词设计、验证规则等完整知识;
  • 生成系统提示词:agent-creation-system-prompt.md——本文模板所依赖的底层生成提示词原文;
  • 触发最佳实践:triggering-examples.md——description: 与 "When to invoke" 的写法规范与调试指南;
  • 系统提示词设计模式:system-prompt-design.md——分析、生成、校验、编排四类 Agent 的提示词模板,以及篇幅建议(标准 Agent 约 1000~2000 词,避免超过 10000 词);
  • 生产级完整示例:complete-agent-examples.md——四个可直接改用的完整 Agent(审查、测试、文档、安全);
  • 自动化执行者:agent-creator.md——把上述流程封装成 Agent 本身(model: sonnet、color: magenta、tools: ["Write", "Read"]),用户说出需求后它会自动生成 Agent 文件并给出配置摘要与测试建议;
  • 端到端工作流:create-plugin.md 的 8 阶段插件创建流程中,Phase 5 组件实现阶段会加载 agent-development 技能并使用 agent-creator 生成 Agent,Phase 6 用 plugin-validator 与 validate-agent.sh 统一校验,Phase 7 用真实场景测试触发。

十一、总结

AI 辅助生成 Agent 的本质,是用一套经过官方沉淀的结构化系统提示词,把"编写高质量 Agent"这一复杂任务转化为"描述需求 + 校验落地"两步。核心要点可归结为:

  1. 描述要具体——任务、触发时机、主动/被动、职责四要素齐全,并带上项目上下文与输出期望;
  2. 严格遵循 JSON 三字段结构——identifier 命名规范、whenToUse 平铺散文、systemPrompt 内含 "When to invoke" 散文场景列表;
  3. 生成后必须校验与迭代——用 validate-agent.sh 把关结构,用真实措辞测试触发,针对不触发/过触发/错触发三类问题定向修复;
  4. 生成与手写互补——用生成的全面性与一致性做起点,用手动精修补足项目特定模式、工具组合与触发精度。

按照本模板产出的 Agent 文件放入插件的 agents/ 目录后即被自动发现,无需额外注册配置,可直接随插件分发使用。

登录后查看全文
claude-plugins-official