Building Agents on Claude¶
Part of: Build Workflows > Agents
Claude provides three approaches to building agents, each suited to different workflow patterns.
| Approach | Best for | Complexity |
|---|---|---|
| Subagents | Focused, single-responsibility tasks | Low — one .md file per agent, no code required |
| Agent teams | Multi-agent coordination with parallel execution | Medium — experimental feature, multiple agents collaborating |
| Agent SDK | Production applications and CI/CD automation | Higher — Python or TypeScript code, full programmatic control |
Subagents¶
A subagent is a Markdown file that defines an agent's role, instructions, and capabilities. Claude Code spawns it as a subprocess with its own context window, tools, and permissions.
Official docs: Claude Code Sub-agents
Where agent files live¶
| Location | Scope |
|---|---|
.claude/agents/ (in your project) | Available to anyone working in this project |
~/.claude/agents/ (in your home directory) | Available across all your projects |
Agent file structure¶
Each agent is a single .md file with YAML frontmatter for configuration and Markdown body for instructions:
---
name: research-analyst
description: Use this agent to research companies and summarize findings
model: sonnet
tools:
- WebSearch
- WebFetch
- Read
- Write
---
# Research Analyst
You are a research analyst who investigates companies and produces structured briefs.
## Process
1. Search for the company using web search
2. Visit the company website and key pages
3. Summarize findings in a structured format
## Output Format
Write findings to `outputs/[company-name]-research.md` with sections for:
- Company overview
- Key products/services
- Recent news
- Relevant insights
Frontmatter options¶
| Field | Required | Description |
|---|---|---|
name | No | Display name (defaults to filename) |
description | Yes | When to use this agent — Claude reads this to decide whether to activate it |
model | No | Which model to use (opus, sonnet, haiku) |
tools | No | Which tools the agent can access (e.g., Read, Write, WebSearch, Bash) |
permissionMode | No | How tool permissions are handled (default, acceptEdits, bypassPermissions) |
skills | No | Skills the agent can use (list of skill names) |
mcpServers | No | MCP servers the agent can connect to |
maxTurns | No | Maximum number of turns before the agent stops |
memory | No | Path to a persistent memory file the agent can read and update |
hooks | No | Shell commands triggered by agent lifecycle events |
Creating an agent¶
Two options:
- Use the
/agentscommand — Claude Code walks you through creating an agent interactively - Create the file manually — Write a
.mdfile in.claude/agents/following the structure above
How agents activate¶
When you describe a task in Claude Code, it checks agent descriptions to decide whether to delegate. You can also invoke an agent directly:
# Run from the command line
claude --agent research-analyst
# Or describe the task and let Claude choose the right agent
claude "Research Acme Corp and write a brief"
Agents can run in the foreground (you see their work in real-time) or in the background (they work independently while you continue).
Key capabilities¶
- Tool restrictions — limit which tools an agent can use, preventing unintended actions
- Skills — attach reusable skills that give the agent domain expertise
- MCP servers — connect to external services (databases, APIs, browsers) via the Model Context Protocol
- Persistent memory — give the agent a memory file it reads at startup and updates as it learns
- Hooks — trigger shell commands when the agent starts, stops, or encounters specific events
Mapping your Design blueprint¶
Your Design phase produced a platform-agnostic agent blueprint. Here's how each component maps to a Claude Code agent file:
| Design blueprint | Claude Code agent file |
|---|---|
| Name | Filename (e.g., research-analyst.md) and optional name frontmatter |
| Description | description frontmatter — write it so Claude knows when to activate this agent |
| Instructions | Markdown body — the agent's role, process, constraints, and output format |
| Model | model frontmatter (opus, sonnet, haiku) |
| Tools | tools frontmatter (list of tool names) + mcpServers for external connections |
| Context | skills frontmatter + reference files mentioned in the instructions |
| Goal | Captured in the description (activation trigger) and instructions (success criteria) |
Agent Teams¶
Agent teams let multiple Claude Code instances work together on complex tasks — a team lead coordinates while teammates handle specialized subtasks in parallel.
Official docs: Claude Code Agent Teams
Experimental feature
Agent teams require the CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS environment variable. The feature is under active development and behavior may change.
How teams work¶
A team lead (a Claude Code agent) can spawn teammates — independent Claude Code instances that each get their own context window and tools. The team lead coordinates work through a shared task list and inter-agent messaging.
Team Lead
├── Teammate A (e.g., research analyst)
├── Teammate B (e.g., writer)
└── Teammate C (e.g., editor)
Key capabilities¶
- Shared task list — the team lead creates tasks, teammates claim and complete them
- Inter-agent messaging — teammates can send messages to the team lead and to each other
- Parallel execution — teammates work simultaneously on independent tasks
- Plan approval — the team lead can present a plan for your approval before dispatching work
When to use teams vs. single agents¶
| Use single agents when... | Use agent teams when... |
|---|---|
| The task has one focus area | The task spans multiple expertise domains |
| Steps are sequential | Steps can run in parallel |
| One agent can handle everything | Different steps need different tools or knowledge |
| You want simple, predictable execution | You want to maximize throughput on complex tasks |
Good use cases for teams¶
- Parallel research — multiple teammates research different aspects simultaneously
- Competing approaches — teammates try different solutions, team lead picks the best
- Cross-layer coordination — frontend, backend, and testing teammates work on related changes
- Pipeline processing — research → write → edit with specialized teammates for each stage
Mapping your Design blueprint¶
For multi-agent workflows, the Design phase produced configurations for multiple agents. On Claude Code:
- Each specialist agent becomes a teammate definition
- The orchestrator becomes the team lead's instructions
- Handoff points map to task list entries and messaging patterns
- Human review gates map to plan approval checkpoints
Agent SDK¶
The Claude Agent SDK lets you build agents in Python or TypeScript with full programmatic control. It gives you the same tools, agent loop, and context management that power Claude Code — but as a library you can embed in your own applications.
Official docs: Agent SDK Overview
When to use the SDK vs. Markdown agents¶
| Use Markdown agents when... | Use the Agent SDK when... |
|---|---|
| You're working interactively in Claude Code | You're building a production application |
| You want no-code configuration | You need programmatic control over agent behavior |
| One-off or ad-hoc tasks | CI/CD pipelines and automation |
| You don't need custom logic between agent steps | You need hooks, callbacks, or custom orchestration |
Installation¶
Set your API key as an environment variable:
The SDK also supports Amazon Bedrock, Google Vertex AI, and Azure AI Foundry as alternative providers.
Basic example¶
import asyncio
from claude_agent_sdk import query, ClaudeAgentOptions
async def main():
async for message in query(
prompt="Find all TODO comments and create a summary",
options=ClaudeAgentOptions(allowed_tools=["Read", "Glob", "Grep"]),
):
if hasattr(message, "result"):
print(message.result)
asyncio.run(main())
The SDK handles the full agent loop — Claude autonomously reads files, runs commands, and produces results without you implementing tool execution.
Key capabilities¶
The SDK exposes the same capabilities as Claude Code's Markdown agents, plus programmatic features:
| Capability | Description |
|---|---|
| Built-in tools | Read, Write, Edit, Bash, Glob, Grep, WebSearch, WebFetch — no tool implementation needed |
| Subagents | Spawn specialized agents with their own tools and instructions |
| MCP servers | Connect to external systems (databases, browsers, APIs) via the Model Context Protocol |
| Hooks | Run callback functions at key points in the agent lifecycle (PreToolUse, PostToolUse, Stop, etc.) |
| Sessions | Maintain context across multiple exchanges — resume or fork conversations |
| Permissions | Control exactly which tools the agent can use, from read-only to full access |
| Skills and memory | Load project skills and CLAUDE.md instructions via settingSources |
Subagents in the SDK¶
Define custom subagents programmatically — useful when you need multiple specialized agents coordinating within your application:
import { query } from "@anthropic-ai/claude-agent-sdk";
for await (const message of query({
prompt: "Use the code-reviewer agent to review this codebase",
options: {
allowedTools: ["Read", "Glob", "Grep", "Task"],
agents: {
"code-reviewer": {
description: "Expert code reviewer for quality and security reviews.",
prompt: "Analyze code quality and suggest improvements.",
tools: ["Read", "Glob", "Grep"]
}
}
}
})) {
if ("result" in message) console.log(message.result);
}
import asyncio
from claude_agent_sdk import query, ClaudeAgentOptions, AgentDefinition
async def main():
async for message in query(
prompt="Use the code-reviewer agent to review this codebase",
options=ClaudeAgentOptions(
allowed_tools=["Read", "Glob", "Grep", "Task"],
agents={
"code-reviewer": AgentDefinition(
description="Expert code reviewer for quality and security reviews.",
prompt="Analyze code quality and suggest improvements.",
tools=["Read", "Glob", "Grep"],
)
},
),
):
if hasattr(message, "result"):
print(message.result)
asyncio.run(main())
Mapping your Design blueprint¶
Your Design phase produced a platform-agnostic agent blueprint. Here's how each component maps to the Agent SDK:
| Design blueprint | Agent SDK |
|---|---|
| Name | Key in the agents dictionary |
| Description | description field in the agent definition |
| Instructions | prompt field — the agent's role, process, constraints, and output format |
| Model | model option (opus, sonnet, haiku) |
| Tools | allowedTools list + mcpServers for external connections |
| Context | settingSources to load skills and CLAUDE.md, or inline in the prompt |
| Goal | Captured in the description (activation trigger) and prompt (success criteria) |
What's Next¶
- Agents overview — the platform-agnostic agent decision framework
- Design Your AI Workflow — produce the agent blueprint that feeds into these implementations
- Scheduling Subagents — run agents automatically on a schedule
- Agent SDK Quickstart — build a bug-fixing agent in minutes
- Agent SDK Example Agents — email assistant, research agent, and more