How to Build Your First Claude Code Agent (Step-by-Step)
You've read about Claude Code agents. Now let's build one. This tutorial takes you from zero to a working autonomous agent in about 15 minutes — no prior experience required, just an Anthropic account and a terminal.
What we're building: A simple file-analysis agent that reads a directory, summarizes what it finds, and writes a report — fully autonomous, no human input during the run. Simple enough to understand, useful enough to actually run.
0 Prerequisites
Before starting, you need:
- Node.js 18+ installed (
node --versionto check) - An Anthropic account with API access at console.anthropic.com
- An API key — create one in the Anthropic console under API Keys
- A terminal (macOS Terminal, Windows WSL, Linux — all work)
Cost estimate: A 15-minute tutorial session with Claude Haiku will cost approximately €0.01–0.05. The Anthropic free tier is enough to complete this tutorial.
1 Install Claude Code
Claude Code is an npm package. Install it globally:
npm install -g @anthropic-ai/claude-code
Verify the installation:
claude --version
# Should output something like: 1.x.x
Now set your API key. Claude Code reads it from the environment:
# macOS/Linux
export ANTHROPIC_API_KEY="sk-ant-your-key-here"
# Or add to ~/.bashrc / ~/.zshrc to persist it
echo 'export ANTHROPIC_API_KEY="sk-ant-your-key-here"' >> ~/.bashrc
Windows users: Use WSL (Windows Subsystem for Linux) or set the environment variable via System Properties → Advanced → Environment Variables.
2 Your First Session
Create a test directory to work in:
mkdir ~/claude-agent-test
cd ~/claude-agent-test
# Create some test files for the agent to analyze
echo "Project Alpha: Build authentication system" > project-a.txt
echo "Project Beta: Migrate database to PostgreSQL" > project-b.txt
echo "Project Gamma: Design new UI dashboard" > project-c.txt
Start Claude Code interactively:
claude
You'll see the Claude Code prompt. Try a simple task:
> List the files in this directory and summarize what each one is about
Claude reads the directory, opens each file, and gives you a summary. It used the LS and Read tools automatically. This is an agent running one iteration.
Exit with Ctrl+C or type /exit. That was your first agent session. Now let's make it autonomous.
3 Write Your CLAUDE.md
The CLAUDE.md file is what separates a chat session from an actual agent. It defines the agent's role, task, constraints, and output format — loaded automatically every time Claude Code starts in that directory.
Create the file:
nano ~/claude-agent-test/CLAUDE.md
Paste this content:
# Project Analyst Agent
## Role
You are a project analysis agent. Your job is to analyze all .txt files
in this directory and produce a structured summary report.
## Task (run this automatically on every session start)
1. Read all .txt files in the current directory
2. Extract: project name, objective, any mentioned risks or blockers
3. Write a report to analysis-report.md with:
- Executive summary (2-3 sentences)
- Per-project table: | Project | Objective | Status | Notes |
- Priority recommendation: which project to tackle first and why
## Constraints
- ONLY read .txt files — do not modify them
- Write output ONLY to analysis-report.md
- If analysis-report.md already exists, overwrite it with the latest analysis
- Do not ask for confirmation — complete the full task autonomously
## Done criteria
The task is complete when analysis-report.md exists and contains all three sections.
Print "ANALYSIS COMPLETE" when done.
Save and exit (Ctrl+X, Y, Enter in nano).
Why this CLAUDE.md structure works
| Element | What it does | Without it |
|---|---|---|
| Role | Gives the agent an identity and scope | Agent tries to do everything |
| Task with numbered steps | Unambiguous execution order | Agent improvises, skips steps |
| Constraints | Prevents unintended side effects | Agent might edit source files |
| Done criteria | Agent knows when to stop | Agent keeps "improving" indefinitely |
4 Run the Agent Autonomously
Now run the agent in non-interactive mode — no human input required:
claude -p "Execute the task defined in CLAUDE.md" --allowedTools Read,Write,LS,Bash
The -p flag means "run this prompt and exit". The --allowedTools flag limits what the agent can touch (security best practice — only give it what it needs).
After it finishes, check the output:
cat analysis-report.md
A structured Markdown report with an executive summary and a table showing all three projects. The agent read the files, extracted the information, and wrote the report — without you touching the keyboard during execution.
Adding automation (the production pattern)
To run this on a schedule, add a cron job:
# Run the analysis agent every hour
crontab -e
# Add this line:
0 * * * * cd ~/claude-agent-test && claude -p "Execute the task in CLAUDE.md" --allowedTools Read,Write,LS >> ~/agent.log 2>&1
That's it. You now have an agent that runs autonomously on a schedule, reads files, and produces structured output — the same core pattern used in production multi-agent systems.
Common first-agent mistakes (and how to avoid them)
1. Vague task descriptions
❌ Bad: "Analyze the projects"
✓ Good: "Read each .txt file, extract project name and objective, write a table to analysis-report.md"
The more specific the task, the more consistent the output. Claude Code is good at following precise instructions — leverage that.
2. No done criteria
Without a clear "done" state, agents either stop too early or keep iterating. Always define what "finished" looks like. The line Print "ANALYSIS COMPLETE" when done in the example above also makes it easy to verify success in logs.
3. Giving the agent too many tools
The --allowedTools flag matters. An agent with Bash access can run any shell command. An agent that only needs to read and write files should only have Read,Write,LS. Principle of least privilege applies directly here.
4. Not checking the output
The agent reporting "ANALYSIS COMPLETE" is not proof the report is correct. Read the actual output file the first few times. Claude Code agents have a known failure mode: they confirm completion when only the happy path was tested. Your verification is the real QA gate.
What to Build Next
Once you understand the basic pattern — CLAUDE.md defines role + task + constraints, -p runs it non-interactively, cron automates it — you can scale to more complex systems:
- Multi-agent: Agent A produces output that Agent B reads as input. Chain them with a coordinator agent that calls each in sequence.
- Persistent memory: Agents write state to a shared file or database. Next run reads previous state and continues from there.
- Hierarchical systems: A "manager" agent spawns worker agents for subtasks. Each worker runs with its own CLAUDE.md and limited toolset.
- Event-triggered: n8n or a webhook triggers a Claude Code agent when something happens (new email, form submission, file upload).
Real production example: The company we run with 20+ agents uses exactly this pattern — each agent has a CLAUDE.md, runs via -p, writes reports that manager agents read, and escalates via Telegram when something needs human input. The complexity isn't in the tools, it's in the CLAUDE.md design.
The CLAUDE.md patterns that matter most
After running agents in production for months, these three CLAUDE.md patterns have the most impact:
Pattern 1: Explicit escalation rules
## Escalation triggers (STOP and alert human if any apply)
- Task requires spending more than €10
- Task requires deleting files
- Output would be sent to external parties
- Error occurs more than twice on the same step
Pattern 2: Checkpoint after each major step
## Execution
1. Read source files → write summary to .work/step1-summary.md
2. Analyze summaries → write findings to .work/step2-findings.md
3. Generate final report from findings → write to report.md
# Each step writes intermediate output — if agent crashes, restart from last checkpoint
Pattern 3: Verify, don't just report
## Done criteria
- analysis-report.md exists: YES
- File contains all three sections (verify with grep): YES
- Print actual first 5 lines of report as proof of completion
# Never say "done" without verifying the output file actually contains content
For a full breakdown of CLAUDE.md patterns used in production, see: The Complete CLAUDE.md Guide.
Want the production-ready templates?
The free 7-day trial includes the exact CLAUDE.md files, multi-agent architecture, and failure-mode documentation from our production system — not examples built for a course.
Start Free Trial →