# How to Write Specialized Agents in Claude Code Plugins: A Complete Guide

> Learn to write specialized agents in Claude Code plugins. This guide helps you define autonomous subprocesses using Markdown and YAML for seamless user intent matching.

- Repository: [Anthropic/claude-code](https://github.com/anthropics/claude-code)
- Tags: how-to-guide
- Published: 2026-04-02

---

**Specialized agents in Claude Code plugins are autonomous subprocesses defined by Markdown files in an `agents/` directory, containing YAML front-matter with trigger examples and a second-person system prompt that executes when matched to user intent.**

You can extend Claude Code's capabilities by creating specialized agents that handle specific workflows autonomously. According to the `anthropics/claude-code` repository, these agents are single Markdown files placed in a plugin's `agents/` directory that Claude discovers and invokes automatically when user utterances match their defined trigger patterns.

## What Are Specialized Agents?

Specialized agents are **dedicated subprocesses** that run with their own system prompts, models, and tool permissions. Unlike simple commands, they maintain context throughout a sub-conversation and return structured results to the parent conversation. They follow the principle of least privilege, allowing you to restrict which tools an autonomous process can access.

## Directory Structure and Discovery

Claude Code scans for specialized agents recursively within each plugin's `agents/` folder. Any file ending in `.md` within this directory tree is treated as a potential agent definition.

```

plugins/
└── your-plugin/
    └── agents/
        ├── code-reviewer.md
        ├── security-audit.md
        └── nested/
            └── documentation-agent.md

```

The discovery mechanism loads these files at plugin initialization and registers them for trigger matching.

## Anatomy of a Specialized Agent File

Every agent definition consists of two mandatory sections: YAML front-matter and a Markdown body containing the system prompt.

### Front-Matter Configuration

The front-matter (enclosed by `---`) declares the agent's metadata and trigger conditions:

```yaml
---
name: code-reviewer
description: Use this agent when you need to review code for adherence to project guidelines. Examples:

<example>
Context: The user has just implemented a new authentication feature.
user: "I've added the new authentication feature. Can you check if everything looks good?"
assistant: "I'll use the Task tool to launch the code-reviewer agent."
<commentary>
User finished a feature and asks for validation → trigger code-reviewer.
</commentary>
</example>

model: opus
color: green
tools: ["Read", "Grep", "Edit"]
---

```

**Key front-matter fields:**

- **`name`**: Lower-case identifier using hyphens only, 3-50 characters, must start and end with alphanumeric (e.g., `security-scanner`, `api-validator`)
- **`description`**: Must start with "Use this agent when..." and contain 2-4 `<example>` blocks showing user/assistant/commentary dialogues that trigger the agent
- **`model`**: Specify `inherit`, `sonnet` (analysis), `opus` (heavy reasoning), or `haiku` (quick tasks)
- **`color`**: UI indicator chosen from `blue`, `cyan`, `green`, `yellow`, `magenta`, or `red`
- **`tools`**: Optional array restricting tool access (omit to allow all tools)

### System Prompt Body

Following the front-matter, write the system prompt in **second-person** ("You are...") that defines:

- Role description and expertise
- Numbered core responsibilities
- Step-by-step methodology
- Quality standards and edge-case handling
- Expected output format

Example from [`plugins/pr-review-toolkit/agents/code-reviewer.md`](https://github.com/anthropics/claude-code/blob/main/plugins/pr-review-toolkit/agents/code-reviewer.md):

```markdown
You are an expert code reviewer specializing in modern software development across multiple languages and frameworks.

Your Core Responsibilities:
1. Analyze code changes for bugs, security vulnerabilities, and performance issues.
2. Verify adherence to project-specific style guides and conventions.
3. Suggest concrete improvements with line-specific references.

Methodology:
- First, read the relevant files using the Read tool.
- Identify critical issues before minor style concerns.
- Provide confidence scores (High/Medium/Low) for each finding.

Edge Cases:
- If no issues are found, explicitly state "No issues detected."
- If the codebase lacks sufficient context, request specific files.

Output Format:
Return a structured markdown report with sections for Critical, Warning, and Suggestions.

```

## Agent Lifecycle and Execution Flow

According to the implementation in `anthropics/claude-code`, specialized agents follow a five-stage lifecycle:

1. **Discovery**: Claude scans `agents/` directories recursively for `.md` files at plugin load time
2. **Trigger Matching**: User utterances are compared against `<example>` blocks in each agent's description; semantic similarity determines eligibility
3. **Invocation**: The assistant launches the agent via the **Task** tool: `Task("agent-name")`
4. **Execution**: The agent runs with its specified model and tool restrictions, maintaining isolated context
5. **Integration**: Results return to the parent conversation in the format defined by the agent's system prompt

## Creating Your First Specialized Agent

Here's a minimal template based on [`plugins/plugin-dev/agents/agent-creator.md`](https://github.com/anthropics/claude-code/blob/main/plugins/plugin-dev/agents/agent-creator.md):

```markdown
---
name: json-inspector
description: Use this agent when you need to analyze JSON file structure without reading the full content. Examples:

<example>
Context: User is navigating a large configuration file.
user: "What are the top-level keys in package.json?"
assistant: "I'll inspect the structure for you."
<commentary>
User needs structural metadata, not values → trigger json-inspector.
</commentary>
</example>

model: haiku
color: cyan
tools: ["Read"]
---
You are a JSON structure analyzer. Your sole purpose is extracting top-level keys from JSON files.

Your Core Responsibilities:
1. Read the file path provided by the user.
2. Parse only the first level of JSON keys.
3. Return results in the specified JSON format.

Methodology:
- Use the Read tool to access the file.
- Validate JSON syntax before parsing.
- Never return nested key values unless explicitly requested.

Output Format:

```json
{
  "file": "<filename>",
  "top_level_keys": ["key1", "key2", "key3"],
  "key_count": 3
}

```

Edge Cases:
- If the file is not valid JSON, return `{"error": "Invalid JSON", "details": "<message>"}`
- If the file does not exist, suggest creating it with a scaffold

```

Save this as [`plugins/your-plugin/agents/json-inspector.md`](https://github.com/anthropics/claude-code/blob/main/plugins/your-plugin/agents/json-inspector.md).

## Orchestrating Multiple Agents

Commands can invoke specialized agents using the Task tool. From [`plugins/pr-review-toolkit/commands/review-pr.md`](https://github.com/anthropics/claude-code/blob/main/plugins/pr-review-toolkit/commands/review-pr.md):

```markdown
---
name: review-pr
description: Run a comprehensive pull request review using multiple specialized agents.
model: sonnet
color: blue
tools: ["Task"]
---
You are a coordinator orchestrating specialized agents on the current PR:

1. **Task("code-reviewer")** – analyzes style and bugs
2. **Task("comment-analyzer")** – evaluates existing review comments  
3. **Task("type-design-analyzer")** – validates TypeScript decisions
4. **Task("code-simplifier")** – suggests refactoring

Collect outputs, de-duplicate findings, and present a unified summary to the user.

```

## Validation and Schema Compliance

Before deploying, validate your agent against the schema using the provided script:

```bash
./plugins/plugin-dev/skills/agent-development/scripts/validate-agent.sh \
  plugins/your-plugin/agents/your-agent.md

```

This script checks for:
- Valid front-matter syntax and required fields
- Proper naming conventions (lowercase, hyphens, length constraints)
- Presence of `<example>` blocks in descriptions
- Valid model and color selections
- Non-empty system prompt body

## Summary

- **Specialized agents** are Markdown files in `plugins/<name>/agents/` that extend Claude Code with autonomous capabilities
- Each agent requires **YAML front-matter** with `name`, `description` containing trigger examples, `model`, and `color`
- The **system prompt** must use second-person perspective and define responsibilities, methodology, and output format
- Use the **`tools`** array to enforce least-privilege access control
- Agents are invoked via the **Task** tool and follow a discovery → matching → execution → integration lifecycle
- Validate agents using [`scripts/validate-agent.sh`](https://github.com/anthropics/claude-code/blob/main/scripts/validate-agent.sh) before deployment

## Frequently Asked Questions

### What is the difference between a specialized agent and a regular command?

A **command** is a single-turn interaction that processes input and returns output immediately, while a **specialized agent** maintains a sub-conversation with its own system prompt and can perform multi-step autonomous work. Agents are better suited for complex workflows like comprehensive code reviews or security audits that require multiple tool calls and contextual reasoning. According to the source code, commands live in `commands/` directories while agents reside in `agents/` directories.

### How does Claude decide which agent to trigger?

Claude evaluates the `description` field of each agent against the user's utterance using semantic matching against the `<example>` blocks. If the user's request closely matches any example scenario (or a paraphrase thereof), the agent becomes eligible for invocation. The assistant can then explicitly launch it via `Task("agent-name")`. You must include 2-4 diverse `<example>` blocks in the front-matter to ensure reliable trigger detection.

### Can I restrict which tools an agent can use?

Yes, include an optional `tools` array in the front-matter to implement the principle of least privilege. For example, `tools: ["Read", "Grep"]` limits the agent to only reading files and searching code, preventing it from making edits or executing bash commands. If you omit the `tools` field, the agent inherits access to all available tools. This restriction is enforced during the agent's execution phase.

### What models are supported for specialized agents?

You can specify `inherit` (uses the parent's model), `sonnet` (recommended for most analysis tasks), `opus` (for heavy reasoning and complex architectural decisions), or `haiku` (for quick, lightweight operations). According to the schema in [`plugins/plugin-dev/skills/agent-development/SKILL.md`](https://github.com/anthropics/claude-code/blob/main/plugins/plugin-dev/skills/agent-development/SKILL.md), `inherit` is the default and recommended unless the agent requires specific capabilities offered by a particular model tier.