Build an Agent with Claude Code
Claude Code is Anthropic's official CLI that turns Claude into an autonomous agent capable of reading files, executing commands, writing code, and reasoning about results — all from your terminal. This isn't a chatbot with tool access: it's a complete agentic execution environment where Claude acts, observes, and adjusts without you having to guide it step by step.
This guide explains how to build an agent with Claude Code from scratch: architecture, available tools, design patterns, and common mistakes. It applies whether you're prototyping solo or building a production system.
What Claude Code Actually Does
Before writing a single line, it's worth understanding what sets Claude Code apart from calling the Claude API directly.
| Capability | Standard API | Claude Code |
|---|---|---|
| Read system files | ✗ | ✓ |
| Execute shell commands | ✗ | ✓ |
| Navigate directories | ✗ | ✓ |
| Built-in agentic loop | ✗ | ✓ |
| Zero-config tool use | ✗ | ✓ |
Claude Code includes a set of predefined tools the model can invoke autonomously:
Read/Write/Edit— file reading and writingBash— terminal command executionGlob/Grep— filesystem searchWebFetch— web content retrievalTodoWrite/TodoRead— internal agent task management
The result: Claude can receive an instruction like "Refactor all endpoints in this API to use async/await" and execute it completely without human intervention.
Installation and Initial Setup
Requirements
- Node.js 18 or higher
- An Anthropic API key (environment variable
ANTHROPIC_API_KEY) - Write permissions in the working directory
npm install -g @anthropic-ai/claude-code
export ANTHROPIC_API_KEY="sk-ant-..."
claude
Running claude with no arguments opens interactive mode. Running claude -p "instruction" executes a non-interactive task — ideal for CI/CD pipelines.
Key Configuration Files
Claude Code reads two special files on startup:
CLAUDE.mdin the project root: persistent instructions, code conventions, system architecture. Everything Claude needs to know before it starts acting.~/.claude/CLAUDE.md: global user preferences (code style, response language, preferred tools).
Spending 20 minutes on a solid CLAUDE.md saves hours of corrections down the line.
Architecture of a Claude Code Agent
An agent built on Claude Code follows a Perception → Reasoning → Action → Observation loop:
User / System
│
▼
[Instruction]
│
▼
Claude (LLM) ──── reasons ────► selects tool
│ │
│◄─────── observes result ─────┘
│
Task complete?
├── No → next action
└── Yes → delivers result
This loop repeats automatically until Claude determines the task is finished or that it needs user input. The key is that the model decides when to ask — not at every step.
Proven Design Patterns
1. Single-Task Agent with a Specialized CLAUDE.md
The simplest and most reliable pattern. You define a CLAUDE.md with very specific context and point Claude Code at a well-scoped task.
# CLAUDE.md — Database Migration Agent
## Role
You are an agent specialized in PostgreSQL migrations.
## Rules
- Never execute DROP without confirming with the user
- Always generate the rollback script before the main script
- Use explicit transactions in all migrations
## Project Context
- ORM: Prisma 5.x
- DB: PostgreSQL 15
- Naming convention: snake_case
2. Multi-Step Agent with Sub-Agents
For complex tasks, Claude Code can orchestrate multiple instances of itself using the claude command inside a Bash or Python script. Each sub-agent has a specialized CLAUDE.md and a limited scope.
import subprocess
def run_subagent(prompt: str, working_dir: str) -> str:
result = subprocess.run(
["claude", "-p", prompt, "--output-format", "json"],
cwd=working_dir,
capture_output=True,
text=True
)
return result.stdout
# Agent 1: analysis
analysis = run_subagent("Analyze this codebase and identify code smells", "./src")
# Agent 2: refactoring based on the analysis
run_subagent(f"Refactor based on this analysis: {analysis}", "./src")
3. Agent with Custom Tools via MCP
Claude Code supports the Model Context Protocol (MCP), which lets you connect external tools: databases, internal APIs, ticketing systems, metrics dashboards.
# Add an MCP server to the project
claude mcp add my-internal-api -- python3 ./mcp_server.py
# Claude can now use the tools exposed by that server
With MCP, the agent can query your database, open tickets in Jira, read metrics from Datadog, or run queries in BigQuery — all within the same agentic loop.
Permission Control and Security
An autonomous agent with Bash access is powerful and potentially dangerous. Claude Code includes a granular permissions system:
Approval Modes
default: Claude asks for confirmation before executing commands that modify the system--allowedTools "Bash(git *),Read,Write": restricts access to specific tools only--dangerously-skip-permissions: disables confirmations (for isolated environments/CI only)
Security Best Practices
- Run Claude Code inside Docker containers in production
- Use
.claude/settings.jsonto define allowlists for permitted Bash commands - Never expose the API key in logs or in
CLAUDE.md - Restrict network access if the agent only needs to work with local files
// .claude/settings.json
{
"permissions": {
"allow": [
"Bash(npm run *)",
"Bash(git *)",
"Read",
"Write"
],
"deny": [
"Bash(rm -rf *)",
"Bash(curl *)"
]
}
}
Real-World Use Cases and Metrics
These are patterns that work in real projects — not theory:
Automated Code Review
An agent configured to review PRs can analyze a 500-line diff, run the tests, identify potential regressions, and write structured comments in under 3 minutes. The same manual process takes between 30 and 90 minutes.
Unit Test Generation
With a CLAUDE.md that defines the testing framework and project conventions, Claude Code can generate test suites with 80%+ coverage for untested modules. Not perfect, but functional and correctly structured.
Dependency Migration
Upgrading a project from React 17 to React 18 — including rendering API changes, Suspense handling, and TypeScript type updates — Claude Code completes this in a single session for projects up to ~50,000 lines of code.
Security Audits
Connected via MCP to static analysis tools, an agent can scan the codebase, prioritize vulnerabilities by severity, and generate the corresponding patches in the same session.
Common Mistakes When Building Claude Code Agents
1. Empty or Generic CLAUDE.md
Without project context, Claude falls back to defaults that may not match your conventions. A well-written 50-line CLAUDE.md has more impact than hours of prompting.
2. Tasks That Are Too Broad
"Refactor the entire application" leads to long loops, inconsistencies, and results that are hard to review. Better: "Refactor the authentication module to follow the Repository pattern."
3. Not Verifying Intermediate Results
Claude Code can make mistakes that compound over time. For long tasks, inserting verification checkpoints — either human or automated via validation scripts — reduces the cost of correction.
4. Ignoring Token Usage
A long agentic loop can easily consume between 50,000 and 500,000 tokens. Use --output-format json to monitor usage and set maximum budgets for non-critical tasks.
From Prototype to Production System
Building an agent that works on your machine is step one. Taking it to production requires:
- Orchestration: how agents are triggered (webhook, cron, queue event)
- Observability: structured logs for each agent action, duration, tokens used
- Error handling: what happens when the agent fails mid-task
- CLAUDE.md version control: treating agent instructions as code
These are exactly the problems that a team with AI systems architecture experience is built to solve. Building the agent is the easy part; integrating it robustly with your existing systems is where the real work is.
Next Steps
Building an agent with Claude Code is approachable. Building one that is reliable, auditable, and delivers measurable value in production is an engineering problem that combines systems design, LLM knowledge, and operational experience.
If you want to go deeper into how Catalizadora designs and deploys custom AI agents — with full code ownership and no recurring licenses — check out our approach at /manifiesto.