---
title: "Build an Agent with Claude Code: What Actually Works"
description: "Learn how to build a reliable Claude Code agent from scratch — architecture, tools, agentic loops, and real production patterns that deliver measurable results."
slug: "como-construir-un-agente-con-claude-code-en"
url: "https://catalizadora.ai/blog/como-construir-un-agente-con-claude-code-en"
cluster: "aprender-construir-agentes"
published_at: "2026-08-24T07:29:49.286239+00:00"
updated_at: "2026-08-24T07:29:58.418319+00:00"
read_minutes: "7"
lang: "en"
---
# Build an Agent with Claude Code: What Actually Works

> Learn how to build a reliable Claude Code agent from scratch — architecture, tools, agentic loops, and real production patterns that deliver measurable results.

# 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 writing
- `Bash` — terminal command execution
- `Glob` / `Grep` — filesystem search
- `WebFetch` — web content retrieval
- `TodoWrite` / `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

```bash
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.md`** in 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.

```md
# 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.

```python
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.

```bash
# 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.json` to 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

```json
// .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](/manifiesto).
## Preguntas frecuentes

### Is Claude Code the same as the Claude API?

No. The Claude API is a plain-text interface where you manage context and tools yourself. Claude Code is an agentic CLI that includes predefined tools (read/write files, execute Bash, search the filesystem) and an autonomous execution loop. Claude Code uses the Claude API internally, but adds the entire agent layer on top.

### How much does Claude Code cost to use?

Claude Code is billed by tokens consumed through your Anthropic API key, using the Claude Sonnet or Opus model depending on your configuration. There is no additional fixed cost for the CLI itself. A typical mid-complexity agentic loop consumes between 20,000 and 100,000 input and output tokens, which at current prices amounts to a few cents per task.

### Is it safe to give an AI agent Bash access?

With the right configuration, yes. Claude Code has a granular permissions system that lets you approve only specific commands (for example, only 'git *' and 'npm run *'). For production, the recommended approach is to run the agent in isolated containers and use command allowlists in the .claude/settings.json file.

### Can I connect Claude Code to my own APIs or databases?

Yes, through the Model Context Protocol (MCP). You can expose custom tools as MCP servers and Claude Code will use them automatically within the agentic loop. This lets you connect the agent to PostgreSQL, internal REST APIs, ticketing systems, metrics dashboards, or any data source you can wrap in an MCP server.

### What size codebase can Claude Code handle?

Claude Code uses selective search (Glob, Grep) to work with large repositories without loading everything into context. In practice, it works well with projects up to 500,000 lines of code, though performance depends on how well-scoped the task is. For very large projects, the recommended approach is to break work into subtasks with limited scope.

### How is this different from GitHub Copilot or Cursor?

Copilot and Cursor are developer assistance tools: they suggest code as you type. Claude Code is an autonomous agent that executes complete tasks without the developer at the keyboard. This is a paradigm shift — assistance vs. autonomous execution. Both approaches are complementary.


---

Source: https://catalizadora.ai/blog/como-construir-un-agente-con-claude-code-en
Author:  — AI Catalysts, LLC (catalizadora.ai)
