agent-development

📁 sjnims/plugin-dev 📅 1 day ago
1
总安装量
1
周安装量
#52245
全站排名
安装命令
npx skills add https://github.com/sjnims/plugin-dev --skill agent-development

Agent 安装分布

cline 1
trae 1
opencode 1
cursor 1
claude-code 1

Skill 文档

Agent Development for Claude Code Plugins

Overview

Agents are autonomous subprocesses that handle complex, multi-step tasks independently. Master agent structure, triggering conditions, and system prompt design to create powerful autonomous capabilities.

Key concepts:

  • Agents are FOR autonomous work, commands are FOR user-initiated actions
  • Markdown file format with YAML frontmatter
  • Triggering via description field with examples
  • System prompt defines agent behavior
  • Model and color customization

Important – Field Name Difference: Agents use tools to restrict tool access. Skills use allowed-tools for the same purpose. Don’t confuse these when switching between component types.

Note on Official Documentation: The color field documented in this skill is supported by Claude Code and is generated by the built-in /agents command, but it is not yet reflected in the official sub-agents documentation. See anthropics/claude-code#8501 for tracking. The plugins-reference.md may show an older agent format using a capabilities field; for Claude Code plugins, prefer the structure documented in this skill which uses tools for tool restrictions.

Quick Start

Minimal working agent (copy-paste ready):

---
name: my-reviewer
description: Use this agent when the user asks to review code. Examples:

<example>
Context: User wrote new code
user: "Review my changes"
assistant: "I'll use the my-reviewer agent to analyze the code."
<commentary>
Code review request triggers the agent.
</commentary>
</example>

model: inherit
color: blue
---

You are a code reviewer. Analyze code for issues and provide feedback.

**Process:**

1. Read the code
2. Identify issues
3. Provide recommendations

**Output:** Summary with file:line references for each finding.

For complete format with all options, see Agent File Structure.

When to Use Agents vs Commands vs Skills

Component Best For Triggering Example Use Case
Agents Autonomous multi-step tasks Proactive or description-matched Code review after implementation
Commands User-initiated actions Explicit /command invocation /deploy production
Skills Knowledge and guidance Model-invoked based on context Domain expertise for PDF processing

See also: For command development, load the command-development skill. For skill development, load the skill-development skill.

Choose Agents When

  • Task requires autonomous, multi-step execution
  • Proactive triggering after certain events is desired
  • Specialized subprocess with focused tools needed
  • Work should happen in the background or as a subagent

Choose Commands When

  • User should explicitly trigger the action
  • Task has clear start/end with specific inputs
  • Action should not happen automatically
  • Workflow requires user confirmation at each step

Choose Skills When

  • Providing knowledge or procedural guidance
  • Extending Claude’s domain expertise
  • No autonomous execution needed
  • Information should be available contextually on-demand

Agent File Structure

Complete Format

---
name: agent-identifier
description: Use this agent when [triggering conditions]. Examples:

<example>
Context: [Situation description]
user: "[User request]"
assistant: "[How assistant should respond and use this agent]"
<commentary>
[Why this agent should be triggered]
</commentary>
</example>

<example>
[Additional example...]
</example>

model: inherit
color: blue
tools: Read, Write, Grep
---

You are [agent role description]...

**Your Core Responsibilities:**

1. [Responsibility 1]
2. [Responsibility 2]

**Analysis Process:**
[Step-by-step workflow]

**Output Format:**
[What to return]

Frontmatter Fields

name (required)

Agent identifier used for namespacing and invocation.

Format: lowercase, numbers, hyphens only Length: 3-50 characters Pattern: Must start and end with alphanumeric

Good examples:

  • code-reviewer
  • test-generator
  • api-docs-writer
  • security-analyzer

Bad examples:

  • helper (too generic)
  • -agent- (starts/ends with hyphen)
  • my_agent (underscores not allowed)
  • ag (too short, < 3 chars)

description (required)

Defines when Claude should trigger this agent. This is the most critical field.

Must include:

  1. Triggering conditions (“Use this agent when…”)
  2. Multiple <example> blocks showing usage
  3. Context, user request, and assistant response in each example
  4. <commentary> explaining why agent triggers

Format:

Use this agent when [conditions]. Examples:

<example>
Context: [Scenario description]
user: "[What user says]"
assistant: "[How Claude should respond]"
<commentary>
[Why this agent is appropriate]
</commentary>
</example>

[More examples...]

Best practices:

  • Include 2-4 concrete examples
  • Show proactive and reactive triggering
  • Cover different phrasings of same intent
  • Explain reasoning in commentary
  • Be specific about when NOT to use the agent

model (required)

Which model the agent should use.

Options:

  • inherit – Use same model as parent (recommended)
  • sonnet – Claude Sonnet (balanced)
  • opus – Claude Opus (most capable, expensive)
  • haiku – Claude Haiku (fast, cheap)

When to choose:

  • haiku – Fast, simple tasks; quick analysis; cost-sensitive operations
  • sonnet – Balanced performance; most use cases (default recommendation)
  • opus – Complex reasoning; detailed analysis; highest capability needed

Recommendation: Use inherit (recommended default) unless the agent specifically needs:

  • haiku for fast, cost-sensitive operations
  • opus for complex reasoning requiring maximum capability

color (required)

Visual identifier for agent in UI.

Note: This field is supported by Claude Code but not yet in official documentation. See the Overview note for details.

Options: blue, cyan, green, yellow, magenta, red

Guidelines:

  • Choose distinct colors for different agents in same plugin
  • Use consistent colors for similar agent types
  • Blue/cyan: Analysis, review
  • Green: Success-oriented tasks
  • Yellow: Caution, validation
  • Red: Critical, security
  • Magenta: Creative, generation

tools (optional)

Restrict agent to specific tools.

Format: Comma-separated tool names

tools: Read, Write, Grep, Bash

Default: If omitted, agent has access to all tools

Best practice: Limit tools to minimum needed (principle of least privilege)

Common tool sets:

  • Read-only analysis: Read, Grep, Glob
  • Code generation: Read, Write, Grep
  • Testing: Read, Bash, Grep
  • Full access: Omit field entirely

Important: Agents use tools while Skills use allowed-tools. The field names differ between component types. For skill tool restrictions, see the skill-development skill.

disallowedTools (optional)

Denylist complement to tools. Block specific tools while allowing all others:

disallowedTools: Bash, Write

Format: Comma-separated tool names

Default: No tools blocked

Field Approach Use When
tools Allowlist Few tools needed, restrict to minimum
disallowedTools Denylist Most tools needed, block specific risks

Best practice: Prefer tools (allowlist) for tighter security. Use disallowedTools when an agent needs broad access but specific tools are dangerous.

Note: Use one or the other. If both are specified, behavior is undefined.

skills (optional)

Load specific skills into the agent’s context:

skills:
  - testing-patterns
  - security-audit
  - api-design

Use cases:

  • Give agent domain expertise via skills
  • Combine multiple skills for comprehensive workflows
  • Share knowledge between agents and skills

Skills must be from the same plugin. The skill’s SKILL.md content loads into the agent’s context.

permissionMode (optional)

Control how the agent handles permission requests:

permissionMode: acceptEdits

Values:

  • default – Standard permission model, prompts user for each action (implicit when omitted)
  • acceptEdits – Auto-accept file edit operations (Write, Edit, NotebookEdit)
  • dontAsk – Skip permission dialogs for all operations
  • bypassPermissions – Full bypass (requires trust)
  • plan – Planning mode, propose changes without executing
  • delegate – Coordination-only, restricted to team management tools (spawn, message, manage tasks)

Default: default (standard permission model, asks user)

Security note: Use restrictive modes (plan, acceptEdits) for untrusted agents. bypassPermissions should only be used for fully trusted agents. Use delegate for team lead agents that should coordinate work without implementing directly.

For complete permission mode details and permission rule syntax, see references/permission-modes-rules.md.

maxTurns (optional)

Limit the maximum number of agentic turns before the agent stops:

maxTurns: 50

Use cases:

  • Prevent runaway agents from consuming excessive resources
  • Set reasonable bounds for task complexity
  • Higher values (50-100) for complex multi-file tasks; lower values (10-20) for focused checks

If omitted, the agent runs until it completes or the user interrupts.

memory (optional)

Enable persistent memory across sessions:

memory: user

Scopes: user (~/.claude/agent-memory/), project (.claude/agent-memory/), local (.claude/agent-memory-local/)

When enabled, the agent’s first 200 lines of MEMORY.md are auto-injected into its system prompt. The agent can read/write its memory directory to learn across sessions. See references/advanced-agent-fields.md for details.

mcpServers (optional)

Scope MCP servers to this agent:

mcpServers:
  slack:

Reference an already-configured server by name, or provide inline config. Restricts which MCP servers the agent can access. See references/advanced-agent-fields.md for configuration examples.

hooks (optional)

Define lifecycle hooks scoped to this agent:

hooks:
  PreToolUse:
    - matcher: Bash
      hooks:
        - type: command
          command: "${CLAUDE_PLUGIN_ROOT}/scripts/validate-bash.sh"

Supports all hook events. Note: Stop hooks in agent frontmatter are auto-converted to SubagentStop at runtime. Hooks activate when the agent starts and deactivate when it finishes. See references/advanced-agent-fields.md for full details.

Fields NOT Available for Agents

Some frontmatter fields are specific to skills and do not apply to agents:

Skill-Only Field Purpose Why Not for Agents
context: fork Run skill in separate subagent context Agents already run as subprocesses by design
agent Specify agent type for forked context Only applies when context: fork is set
user-invocable Control slash menu visibility Agents aren’t invoked via slash commands
disable-model-invocation Block programmatic Skill tool usage Agents use Task tool, not Skill tool
allowed-tools Restrict tool access (skill syntax) Agents use tools field instead (different field name)

Key distinction: Skills provide knowledge and guidance that loads into context. Agents are autonomous subprocesses that execute independently. This architectural difference explains why context-forking options don’t apply to agents—they’re already isolated processes.

System Prompt Design

The markdown body becomes the agent’s system prompt. Write in second person, addressing the agent directly.

Key elements:

  • Role definition (“You are [role] specializing in [domain]”)
  • Core responsibilities (numbered list)
  • Process steps (concrete, actionable)
  • Quality standards (measurable criteria)
  • Output format (specific structure)
  • Edge cases (how to handle exceptions)

Best practices:

  • Write in second person (“You are…”, “You will…”)
  • Be specific, not vague
  • Keep under 10,000 characters
  • Include concrete steps, not generic instructions

For detailed templates and patterns (Analysis, Generation, Validation, Orchestration agents), see references/system-prompt-design.md.

Creating Agents

Method 1: AI-Assisted Generation

Use this prompt pattern (extracted from Claude Code):

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

Requirements:
1. Extract core intent and responsibilities
2. Design expert persona for the domain
3. Create comprehensive system prompt with:
   - Clear behavioral boundaries
   - Specific methodologies
   - Edge case handling
   - Output format
4. Create identifier (lowercase, hyphens, 3-50 chars)
5. Write description with triggering conditions
6. Include 2-3 <example> blocks showing when to use

Return JSON with:
{
  "identifier": "agent-name",
  "whenToUse": "Use this agent when... Examples: <example>...</example>",
  "systemPrompt": "You are..."
}

Then convert to agent file format with frontmatter.

See examples/agent-creation-prompt.md for complete template.

Method 2: Manual Creation

  1. Choose agent identifier (3-50 chars, lowercase, hyphens)
  2. Write description with examples
  3. Select model (usually inherit)
  4. Choose color for visual identification
  5. Define tools (if restricting access)
  6. Write system prompt with structure above
  7. Save as agents/agent-name.md

Validation Rules

Identifier Validation

✅ Valid: code-reviewer, test-gen, api-analyzer-v2
❌ Invalid: ag (too short), -start (starts with hyphen), my_agent (underscore)

Rules:

  • 3-50 characters
  • Lowercase letters, numbers, hyphens only
  • Must start and end with alphanumeric
  • No underscores, spaces, or special characters

Description Validation

Length: 10-5,000 characters Must include: Triggering conditions and examples Best: 200-1,000 characters with 2-4 examples

System Prompt Validation

Length: 20-10,000 characters Best: 500-3,000 characters Structure: Clear responsibilities, process, output format

Agent Organization

Plugin Agents Directory

plugin-name/
└── agents/
    ├── analyzer.md
    ├── reviewer.md
    └── generator.md

All .md files in agents/ are auto-discovered.

Agent precedence: --agents CLI flag > .claude/agents/ (project) > ~/.claude/agents/ (personal) > Plugin agents/ directory. Higher-priority agents with the same name shadow lower-priority ones. Use distinctive, namespaced names for plugin agents to avoid collisions.

Portable Paths

When referencing files within your plugin (scripts, references, etc.) from agent system prompts, use ${CLAUDE_PLUGIN_ROOT} for portable paths:

Run the validation script at `${CLAUDE_PLUGIN_ROOT}/scripts/validate.sh`

This variable resolves to the plugin’s installation directory at runtime, ensuring paths work regardless of where the plugin is installed.

Namespacing

Agents are namespaced automatically:

  • Single plugin: agent-name
  • With subdirectories: plugin:subdir:agent-name

Testing Agents

Test Triggering

Create test scenarios to verify agent triggers correctly:

  1. Write agent with specific triggering examples
  2. Use similar phrasing to examples in test
  3. Check Claude loads the agent
  4. Verify agent provides expected functionality

Load Agents at Session Start

Use the --agents CLI flag to pre-load specific agents:

# Load single agent
claude --agents code-reviewer

# Load multiple agents
claude --agents "code-reviewer,test-generator"

Use cases:

  • Testing agent behavior without triggering
  • Workflows requiring specific agents
  • Debugging agent system prompts

Test System Prompt

Ensure system prompt is complete:

  1. Give agent typical task
  2. Check it follows process steps
  3. Verify output format is correct
  4. Test edge cases mentioned in prompt
  5. Confirm quality standards are met

Quick Reference

Frontmatter Fields Summary

Field Required Format Example
name Yes lowercase-hyphens code-reviewer
description Yes Text + examples Use when… …
model Yes inherit/sonnet/opus/haiku inherit
color Yes Color name blue
tools No Comma-separated tool names Read, Grep
disallowedTools No Comma-separated tool names Bash, Write
skills No Array of skill names [testing, security]
permissionMode No Permission mode string acceptEdits
maxTurns No Number 50
memory No user/project/local user
mcpServers No Object or server names { “slack”: {} }
hooks No Hook event config { PreToolUse: […] }

Note: Agents use tools to restrict tool access. Skills use allowed-tools for the same purpose. The field names differ between component types.

Best Practices

DO:

  • ✅ Include 2-4 concrete examples in description
  • ✅ Write specific triggering conditions
  • ✅ Use inherit for model unless specific need
  • ✅ Choose appropriate tools (least privilege)
  • ✅ Write clear, structured system prompts
  • ✅ Test agent triggering thoroughly

DON’T:

  • ❌ Use generic descriptions without examples
  • ❌ Omit triggering conditions
  • ❌ Give all agents same color
  • ❌ Grant unnecessary tool access
  • ❌ Write vague system prompts
  • ❌ Skip testing

Execution Modes

Agents can run in foreground (blocking) or background (concurrent) mode:

  • Foreground (default): Blocks the main conversation until the agent completes
  • Background: Runs concurrently; permissions must be pre-approved at spawn time since the user can’t be prompted

Background agents that need an unapproved permission will fail. Plan tool restrictions accordingly.

MCP limitation: MCP tools are unavailable in background subagents. If your agent relies on MCP tools (from the plugin’s .mcp.json), it must run in foreground mode. Design agents that may run in background to use only built-in tools.

Resuming agents: Each Task invocation creates a fresh agent. To continue with full prior context, ask Claude to “resume that agent” — it will restore the previous transcript.

Restricting spawnable agents: Use Task(agent_type1, agent_type2) syntax in settings.json allow rules to control which agent types can be spawned. Omitting Task entirely prevents subagent spawning.

Built-in agent types: Explore (read-only, Haiku), Plan (read-only research), general-purpose (all tools), Bash (terminal commands), statusline-setup (Haiku), Claude Code Guide (Haiku).

Agent Teams (Experimental)

Agent teams enable multi-agent coordination where a team lead spawns and manages multiple independent Claude Code sessions as teammates. Requires CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS=1.

Teams provide shared task lists, inter-agent messaging, and parallel execution. Use permissionMode: delegate to restrict a lead to coordination-only tools.

This is an advanced feature — see the official agent teams documentation for details.

Additional Resources

Reference Files

For detailed guidance, consult:

  • references/advanced-agent-fields.md – Detailed docs for maxTurns, memory, mcpServers, hooks, execution modes, and agent teams
  • references/permission-modes-rules.md – Complete permission mode details and permission rule syntax for fine-grained access control
  • references/system-prompt-design.md – Four system prompt patterns (Analysis, Generation, Validation, Orchestration) with complete templates and common pitfalls
  • references/triggering-examples.md – Example block anatomy, four example types, template library, and debugging guide
  • references/agent-creation-system-prompt.md – The exact prompt used by Claude Code’s agent generation feature with usage patterns

Example Files

Working examples in examples/:

  • agent-creation-prompt.md – AI-assisted agent generation template
  • complete-agent-examples.md – Full agent examples for different use cases

Utility Scripts

Development tools in scripts/:

  • create-agent-skeleton.sh – Generate new agent file from template
  • validate-agent.sh – Validate agent file structure
  • test-agent-trigger.sh – Test if agent triggers correctly