How to Build AI Agents with Claude Code
From single agent to multi-agent teams. Learn how to design, connect, and scale autonomous AI agents that write code, review PRs, and ship features.
What Is an AI Agent?
An AI agent is more than a chatbot. While a chatbot responds to prompts one at a time, an agent operates autonomously: it reads context, makes decisions, executes multi-step tasks, and produces structured output without waiting for human input at every step.
In Claude Code, an agent is a configured instance with an identity (via CLAUDE.md), a set of tools (file editing, bash, search), and a defined goal. It can spawn sub-agents, read files, write code, and coordinate with other agents to complete complex work.
Chatbot
- - Responds to one prompt at a time
- - No persistent state between turns
- - Cannot use tools or edit files
- - Human drives every step
AI Agent
- - Executes multi-step plans autonomously
- - Reads and writes persistent memory
- - Uses tools: file edit, bash, search, git
- - Human sets the goal, agent does the work
Single Agent Setup
Every agent starts with a CLAUDE.md file that defines its identity, rules, and guardrails. This is the agent's operating system — it loads automatically when Claude Code starts.
# CLAUDE.md — Agent Identity File ## Identity You are a Senior TypeScript Developer. ## Rules - Always use strict TypeScript — never `any`. - Write server components by default. - Keep components under 150 lines. ## Guardrails - Never install new dependencies without confirmation. - Never push to main without tests passing. - Never hardcode secrets in source code.
The CLAUDE.md file is the single most important lever for agent behavior. A well-written identity file eliminates 80% of prompt engineering by encoding your standards once.
Specialist Agents
Instead of one generalist agent, assign focused roles. Each specialist has a narrow scope, which means higher quality output and fewer conflicting decisions.
| Role | Focus | Output |
|---|---|---|
| Coder | Writes, refactors, and implements features based on specs | Code files, diffs, pull requests |
| Reviewer | Audits code for bugs, security issues, and style violations | Review comments, severity ratings, fix suggestions |
| Tester | Generates test cases, runs suites, checks coverage | Test files, coverage reports, pass/fail results |
| Researcher | Searches docs, reads codebases, gathers context before work begins | Context summaries, API references, dependency maps |
Agent Communication
Agents communicate through structured handoff files. When Agent A finishes work, it writes a JSON handoff that Agent B reads as input. No message queues needed.
// .claude/handoff/coder-to-reviewer.json
{
"from": "coder",
"to": "reviewer",
"task": "review-feature-auth",
"files_changed": ["src/lib/auth.ts", "src/app/api/login/route.ts"],
"context": "Added JWT refresh token rotation",
"confidence": 0.85,
"needs": ["security_check", "type_safety_check"]
}Shared context schemas ensure agents speak the same language. Define your handoff format once, and every agent in the team can produce and consume it.
Task Routing
An orchestrator agent receives incoming tasks and routes them to the right specialist. Routing uses pattern matching on the task description, confidence scores, and fallback chains.
Pattern Matching
Keywords like “write”, “implement”, “build” route to Coder. Keywords like “review”, “audit”, “check” route to Reviewer.
Confidence Scores
Each agent returns a confidence score (0-1). If below 0.7, the task is escalated or routed to a different specialist.
Fallback Chains
If the primary agent fails, the orchestrator tries the next agent in the chain. Example: Coder → Senior Coder → Architect.
Parallel Execution
When tasks are independent, run agents in parallel. A code review that takes one agent 90 seconds can finish in 30 seconds with three agents running simultaneously — security reviewer, logic reviewer, and test coverage checker each working on their own slice. Use the Agent tool in background mode to spawn concurrent workers.
Agent Memory
Agents that learn are agents that improve. Per-agent memory files store patterns, mistakes, and preferences that persist across sessions.
// .claude/agent-memory/reviewer.json
{
"agent": "reviewer",
"learned_patterns": [
"This codebase uses Zod for runtime validation — flag raw JSON.parse",
"Auth routes must check JWT expiry before processing",
"Database queries must use parameterized statements"
],
"common_issues": ["missing error boundaries", "unhandled promise rejections"],
"sessions_completed": 47
}The Agent Tool in Claude Code
Claude Code has a built-in Agent tool that lets you spawn sub-agents directly from a conversation. Each sub-agent gets its own context window, can use all available tools, and reports results back to the parent. Use background mode when you want multiple agents running simultaneously without blocking each other.
Inline Sub-Agent
Spawned for a focused task (e.g., “search the codebase for all usages of getDb”). Runs synchronously and returns results to the parent conversation.
Background Agent
Spawned for longer tasks (e.g., “refactor auth module”). Runs asynchronously. Parent continues working while the background agent completes independently.
Production Patterns
Error Recovery
Wrap each agent call in a retry loop with exponential backoff. If an agent fails three times, escalate to a fallback agent or alert the orchestrator.
Circuit Breakers
Track agent failure rates. If an agent fails more than 50% of recent calls, disable it temporarily and route tasks to alternatives.
Health Checks
Before assigning work, verify each agent can respond. A simple ping-pong prompt confirms the agent is available and the context window is not exhausted.
Idempotent Tasks
Design agent tasks so they can be safely retried. Agents should check existing state before creating new artifacts to avoid duplicates.
Get Pre-Built Agent Teams
AI Brain Pro ($97) includes ready-to-deploy agent configurations — coder, reviewer, tester, and researcher — with memory, handoff schemas, and orchestration pre-wired. One-time purchase. No subscription.
Get AI Brain Pro — $97