Building AI Agents with Claude Code
Claude CodeCLITutorial
Learn to build, debug, and deploy AI agents using Anthropic's official CLI tool.
Building AI Agents with Claude Code
Overview
Claude Code is Anthropic's official CLI for building AI-powered applications. This tutorial shows you how to use Claude Code to build, debug, and deploy AI agents efficiently.
Prerequisites
- Node.js 18+ or Python 3.10+
- Anthropic API key
- Basic CLI familiarity
Installation
# Install Claude Code globally
npm install -g @anthropic-ai/claude-code
# Or with npx (no installation required)
npx @anthropic-ai/claude-code
# Configure your API key
export ANTHROPIC_API_KEY=sk-ant-...
Your First Agent Project
Initialize a Project
# Create a new project directory
mkdir my-agent-project
cd my-agent-project
# Initialize with Claude Code
claude-code init
# This creates:
# - .claude/ directory with project config
# - src/ directory for your agent code
# - README.md with project structure
Build a Simple Agent
# src/agent.py
from anthropic import Anthropic
client = Anthropic()
def create_agent(system_prompt: str):
"""Create an agent with custom system prompt."""
return {
'model': 'claude-3-5-sonnet-20241022',
'system': system_prompt,
'max_tokens': 4096
}
# Use with Claude Code
agent = create_agent('You are a helpful coding assistant.')
Using Claude Code for Development
Interactive Coding Sessions
# Start an interactive session
claude-code
# Claude Code will:
# 1. Understand your codebase
# 2. Help you write new code
# 3. Debug issues
# 4. Refactor existing code
Code Generation
# Generate code from a prompt
claude-code "Create a Python function to calculate Fibonacci numbers"
# Generate with specific file
claude-code --file src/utils.py "Add a memoization decorator"
Debugging
# Debug an error
claude-code "Fix this TypeError in src/main.py:42"
# Or let Claude Code find issues
claude-code --analyze
Building Multi-Agent Systems
Agent Communication Pattern
# src/multi_agent.py
from anthropic import Anthropic
class Agent:
def __init__(self, name: str, role: str):
self.name = name
self.role = role
self.client = Anthropic()
def think(self, task: str, context: str = None) -> str:
messages = []
if context:
messages.append({'role': 'user', 'content': context})
messages.append({'role': 'user', 'content': task})
response = self.client.messages.create(
model='claude-3-5-sonnet-20241022',
max_tokens=1024,
messages=messages,
system=f'You are {self.name}, a {self.role}.'
)
return response.content[0].text
# Create agent team
researcher = Agent('Researcher', 'expert researcher')
writer = Agent('Writer', 'technical writer')
reviewer = Agent('Reviewer', 'quality assurance')
# Orchestrate workflow
research = researcher.think('Research quantum computing basics')
draft = writer.think(f'Write about: {research}')
feedback = reviewer.think(f'Review this: {draft}')
Integrating with MCP
MCP Server Configuration
// claude_desktop_config.json
{
"mcpServers": {
"filesystem": {
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-filesystem", "/path/to/workspace"]
},
"github": {
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-github"]
}
}
}
Using MCP Tools in Agents
# src/mcp_agent.py
from mcp import ClientSession
import asyncio
async def use_mcp_tool(server_name: str, tool_name: str, arguments: dict):
"""Call an MCP tool from your agent."""
async with ClientSession(...) as session:
result = await session.call_tool(tool_name, arguments)
return result
# Example: Read a file via MCP
file_content = await use_mcp_tool(
'filesystem',
'read_file',
{'path': '/workspace/config.json'}
)
Best Practices
1. Clear System Prompts
# Good: Specific and actionable
system_prompt = '''
You are a senior Python developer.
Focus on:
- Clean, readable code
- Error handling
- Type hints
- Performance considerations
'''
# Bad: Vague
system_prompt = 'You are helpful.'
2. Iterative Development
# Start with small tasks
claude-code "Create a function signature"
claude-code "Add docstring"
claude-code "Implement the function body"
claude-code "Add unit tests"
3. Context Management
# Keep context concise
context = {
'project': 'AI Agent Builder',
'current_task': 'Implement agent memory',
'constraints': ['Python 3.10+', 'no external deps'],
'previous_attempts': ['SQLite approach failed due to concurrency']
}
Advanced Features
Code Review
# Review your code
claude-code --review src/
# Get specific feedback
claude-code "Review this function for security issues: src/auth.py"
Refactoring
# Refactor with Claude Code
claude-code --refactor src/legacy_code.py
# Or specify changes
claude-code "Convert this class to use dataclasses"
Testing
# Generate tests
claude-code "Write unit tests for src/utils.py"
# Run and fix tests
claude-code --test
Troubleshooting
Common Issues
API key not found:
export ANTHROPIC_API_KEY=sk-ant-...
# Or use .env file
Slow responses:
# Use faster model
export CLAUDE_MODEL=claude-3-haiku-20240307
Context too large:
# Summarize before sending
def summarize_context(codebase: str) -> str:
"""Create concise summary for context."""
# Extract key files and structure
...
Resources
- Claude Code Docs: https://docs.anthropic.com/en/docs/claude-code
- Anthropic API: https://docs.anthropic.com/
- MCP Documentation: https://modelcontextprotocol.io/
- GitHub: https://github.com/anthropics/claude-code
Last updated: May 2026
