⚡ Quick Answer: Three Ways to Build Agents with Claude Code
1. Claude Agent SDK — Python or TypeScript. Full programmatic control. Free, you pay only for API tokens.
2. CLAUDE.md + Custom Commands — File-based configuration. No code required. Lives with your project.
3. Claude Managed Agents — Hosted infrastructure. $0.08/session-hour + tokens. Production-ready.
What Is Claude Code and Why Use It for Agents?
Claude Code is Anthropic's agentic coding tool — available as a terminal CLI, VS Code extension, JetBrains plugin, and desktop app. It reads your codebase, edits files, runs shell commands, and integrates with your development tools. Most people use it interactively. But the engine behind Claude Code — the Claude Agent SDK — is available as a library you can import into your own Python or TypeScript applications.
Anthropic renamed the Claude Code SDK to the Claude Agent SDK to reflect its broader scope. As Anthropic wrote in their engineering blog: "It has begun to power almost all of our major agent loops" — including deep research, video creation, and note-taking, not just coding. The SDK gives you what would otherwise take hundreds of lines of orchestration code: a built-in agent loop, tool execution, context management, MCP server connections, and subagent spawning.
The SDK is free and open source. You pay only for the API tokens your agent consumes — no license fees, no per-agent charges. As of April 2026, Claude Opus 4.7 requires Agent SDK v0.2.111 or later.
The Three Approaches Compared
| Approach | Best For | Code Required | Cost | Where It Runs |
| Agent SDK | Custom agent pipelines, CI/CD, automation | Yes (Python or TS) | API tokens only | Your infrastructure |
| CLAUDE.md Config | Project-level agents, team workflows | No | API tokens only | Your machine / Claude Code CLI |
| Managed Agents | Long-running, production, multi-hour tasks | Yes | $0.08/hr + tokens | Anthropic's cloud |
Approach 1 — The Claude Agent SDK
Install
The SDK is available for both Python and TypeScript.
# Python
pip install claude-code-sdk
# TypeScript / Node
npm install @anthropic-ai/claude-agent-sdk
You also need Claude Code installed and authenticated:
curl -fsSL https://claude.ai/install.sh | bash
# Then run: claude
# Follow the prompts to authenticate with your Anthropic account
Your First Agent — 10 Lines of Python
The core function is query(). Pass a prompt and options. The SDK handles the agent loop, tool execution, and context management automatically.
import asyncio
from claude_code_sdk import query, ClaudeCodeOptions
async def run_agent():
async for message in query(
prompt="Read the README.md file and write a summary of what this project does",
options=ClaudeCodeOptions(
max_turns=10,
model="claude-opus-4-7-20260416",
)
):
print(message)
asyncio.run(run_agent())
That single query() call gives the agent access to all built-in tools: Read, Write, Edit, Bash, Glob, Grep, WebSearch, WebFetch, and Agent (for spawning subagents). You do not configure these individually — they are included by default.
Built-In Tools You Get for Free
Every agent built on the SDK gets immediate access to these tools without any configuration:
- Read — Read any file including images, PDFs, and Jupyter notebooks
- Write — Create new files or overwrite existing ones
- Edit — Surgical string replacements (sends only the diff, not the full file)
- Bash — Execute shell commands with configurable timeouts
- Glob / Grep — Search files by pattern or content across a codebase
- WebSearch / WebFetch — Search the web and retrieve full page content
- Agent — Spawn subagents that work in parallel on separate subtasks
Restricting What the Agent Can Do
For production agents, you almost always want to restrict tool access. Pass an allowed_tools list to prevent the agent from running bash commands or writing files it should not touch:
from claude_code_sdk import query, ClaudeCodeOptions
async def security_audit():
async for message in query(
prompt="Review all Python files in /src for security vulnerabilities",
options=ClaudeCodeOptions(
system_prompt="You are a security auditor. Read files and report issues. Do not edit anything.",
allowed_tools=["Read", "Glob", "Grep"], # No Write, Edit, or Bash
max_turns=20,
model="claude-opus-4-7-20260416",
)
):
print(message)
Real Example — Code Review Agent
This is a production-shaped agent that analyses a codebase and returns structured feedback. It spawns three subagents in parallel: one for security, one for code quality, one for test coverage.
import asyncio
from claude_code_sdk import query, ClaudeCodeOptions
REVIEW_PROMPT = """
You have 3 tasks. Use the Agent tool to run them in parallel:
1. Spawn a subagent to audit all dependencies for security vulnerabilities
2. Spawn a subagent to run the test suite and report any failures
3. Spawn a subagent to check code quality metrics across /src
Wait for all three to complete, then write a combined report to review-output.md
"""
async def run_code_review():
async for message in query(
prompt=REVIEW_PROMPT,
options=ClaudeCodeOptions(
max_turns=30,
model="claude-opus-4-7-20260416",
)
):
print(message)
asyncio.run(run_code_review())
Connecting MCP Servers
The Model Context Protocol lets your agent connect to external services — Slack, GitHub, Google Drive, Jira, databases — without writing custom integration code. The SDK handles authentication and API calls automatically.
from claude_code_sdk import query, ClaudeCodeOptions
async def github_agent():
async for message in query(
prompt="Check all open PRs in the repo, review the code changes, and post a summary comment on each",
options=ClaudeCodeOptions(
mcp_servers={
"github": {
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-github"],
"env": {"GITHUB_TOKEN": "your-token-here"}
}
},
max_turns=25,
)
):
print(message)
Note: stdio-based MCP servers (those that shell out to npx or uvx) work with the local SDK. Managed Agents requires HTTP or SSE transport — a distinction that matters if you plan to move an agent to production later.
Approach 2 — CLAUDE.md and Custom Commands
If you do not want to write Python or TypeScript, Claude Code's file-based configuration system lets you define agents declaratively. This is configuration-as-code — the same mental model as a Dockerfile or GitHub Actions workflow.
CLAUDE.md — Your Agent's Persistent Memory
Create a CLAUDE.md file in your project root. Claude Code reads this at the start of every session. Use it to set coding standards, architecture decisions, preferred libraries, and review checklists. Claude also builds auto-memory as it works — saving learnings like build commands and debugging insights across sessions without you writing anything.
# CLAUDE.md
## Project Context
This is a Django REST API. Always use PostgreSQL. Never use SQLite.
## Code Standards
- All new endpoints must have tests in /tests/
- Use Black for formatting, run before every commit
- No print() statements in production code — use logging
## Build Commands
- Run tests: pytest tests/ -v
- Start dev server: python manage.py runserver
- Lint: black . && flake8 .
Custom Slash Commands
Create reusable workflows your team can share. Store them in .claude/commands/ as markdown files. Each file becomes a slash command in Claude Code.
# .claude/commands/review-pr.md
---
description: Review the current branch changes for bugs, security issues, and style
---
1. Run `git diff main` to see all changes
2. For each changed file, check for:
- Security vulnerabilities (SQL injection, XSS, exposed secrets)
- Logic errors or edge cases not handled
- Missing tests for new functionality
- Style issues that violate our standards in CLAUDE.md
3. Write a structured review to pr-review.md with: Critical Issues, Warnings, Suggestions
Your team runs this with /review-pr in any Claude Code session. No code required. Version-controlled alongside your source.
Agent Skills
Agent Skills are modular capabilities packaged as directories with a SKILL.md file. Claude discovers and uses them automatically based on task relevance. Skills let you define domain expertise — workflows, context, and best practices — that turn a general-purpose agent into a specialist.
# skills/database-migration/SKILL.md
---
name: database-migration
description: Use when creating or reviewing database migration files
triggers: [migration, alembic, schema change, database]
---
When creating a migration:
1. Always check existing migrations for conflicts first
2. Never use CASCADE DELETE without explicit confirmation
3. Add a rollback (downgrade) function for every upgrade
4. Test both upgrade and downgrade paths before committing
Approach 3 — Claude Managed Agents (Production)
Claude Managed Agents launched in public beta on April 8, 2026. It is Anthropic's hosted infrastructure for running long-horizon agents — you define the tasks, tools, and guardrails, and Anthropic handles sandboxed execution, session state, credential management, and error recovery.
All Anthropic API accounts have access by default — no waitlist. The SDK sets the required beta header (managed-agents-2026-04-01) automatically.
Pricing
- Standard Claude model token rates (same as the Messages API)
- $0.08 per session-hour of active runtime
- $10 per 1,000 web searches
- Runtime only accrues while the session is actively running — idle time does not count
A practical note from independent testing: cache write costs on first-time agent tool calls can dominate your bill early on. On a smoke-test "say hi" session, cache writes cost approximately 240x the runtime fee. Watch your token usage, not just the hourly rate.
Quickstart — Managed Agent in Python
pip install anthropic # version 0.97 or later required
from anthropic import Anthropic
client = Anthropic()
# Step 1: Create the agent (once — reuse the ID across sessions)
agent = client.beta.agents.create(
name="Support Ticket Analyst",
model="claude-sonnet-4-6",
system="""You are a support ticket analyst.
Read the tickets provided, identify common issues from the last 7 days,
and write a structured report to weekly-report.md.""",
tools=[{"type": "agent_toolset_20260401"}],
)
print(f"Agent created: {agent.id}")
# Step 2: Create an environment (cloud container)
environment = client.beta.environments.create(
name="analyst-env",
config={
"type": "cloud",
"networking": {"type": "unrestricted"},
}
)
# Step 3: Start a session
session = client.beta.sessions.create(
agent_id=agent.id,
environment_id=environment.id,
)
# Step 4: Send a task and stream results
for event in client.beta.sessions.stream(
session_id=session.id,
input="Analyse the support tickets in /data/tickets.json and write the weekly report."
):
print(event)
When to Use Managed Agents vs Agent SDK
| Scenario | Use |
| Multi-hour research or processing tasks | Managed Agents |
| Production agent your users interact with | Managed Agents |
| CI/CD pipeline or scheduled automation | Agent SDK |
| Local development and prototyping | Agent SDK |
| You need multi-model routing (GPT + Claude) | Agent SDK + your own orchestration |
| Full control over sandboxing and infrastructure | Agent SDK |
The common path Anthropic recommends: prototype with the Agent SDK locally, then migrate to Managed Agents for production.
Decision Framework — Which Approach Is Right for You?
If you have never written Python or TypeScript → Start with CLAUDE.md and custom commands. Define your agent's behaviour in markdown, no installation required beyond Claude Code itself.
If you are a developer building an automated pipeline → Use the Agent SDK. It gives you full control over tool access, system prompts, subagent coordination, and MCP server connections. Free — you only pay for tokens.
If you are shipping an agent that runs for hours and serves users → Use Managed Agents. Anthropic handles the infrastructure. You focus on what the agent does, not how it stays alive.
If you need agents to coordinate in parallel → Use the Agent SDK's Agent tool to spawn subagents, or apply for Managed Agents multi-agent research preview at claude.com/form/claude-managed-agents.
Honest Limitations
Claude Managed Agents: Claude-only — does not support GPT, Gemini, or other models. stdio-based MCP servers do not work; you need HTTP or SSE transport. OAuth connectors from claude.ai do not carry over — each MCP server must be re-registered with credentials stored in a Vault. Agents cannot be deleted via the SDK as of v0.97.
Agent SDK: Runs on your infrastructure, which means you manage sandboxing, memory, and error recovery for long-running tasks. For multi-hour production workloads, the overhead of self-managing this infrastructure is the main reason to migrate to Managed Agents.
CLAUDE.md approach: Skills and commands only work within Claude Code sessions — they are not exposed as APIs. If you need to trigger agent behaviour programmatically from another system, you need the SDK.
FAQ
What is the Claude Agent SDK?
The Claude Agent SDK is the library that powers Claude Code, made available for developers to build their own agents. It provides a built-in agent loop, 10+ tools (file operations, bash, web search), MCP server connections, and subagent spawning in Python and TypeScript. It was previously called the Claude Code SDK. Install it with pip install claude-code-sdk or npm install @anthropic-ai/claude-agent-sdk.
Do I need to know how to code to build agents with Claude Code?
No. The CLAUDE.md and custom commands approach requires no code — you write markdown files that Claude Code reads as instructions. For more complex automated agents that run without your input, Python or TypeScript knowledge is needed.
How much does it cost to build agents with Claude Code?
The Agent SDK itself is free and open source. You pay only for Claude API tokens at standard Anthropic rates. Claude Managed Agents adds $0.08 per session-hour of active runtime plus $10 per 1,000 web searches, on top of token costs.
What is the difference between Claude Code and the Claude Agent SDK?
Claude Code is the interactive tool — the CLI, the VS Code extension, the app you use to build software. The Claude Agent SDK is the same engine, packaged as a library you can import and call programmatically from your own applications. Claude Code uses the Agent SDK internally.
Can I use Claude agents with other AI models?
The Agent SDK is Claude-only for the agent itself, but you can route individual tool calls to other services via MCP servers. Claude Managed Agents does not support non-Claude models at all. For true multi-model agent orchestration (Claude + GPT-5.5 + Gemini), you need to build your own routing layer on top of the standard Anthropic Messages API.
How do I connect my Claude agent to external tools like Slack or GitHub?
Use MCP (Model Context Protocol) servers. The Agent SDK supports MCP connections via configuration — you specify the server command and credentials, and Claude handles authentication and API calls. Managed Agents requires HTTP or SSE transport MCP servers (not stdio). Pre-built MCP servers exist for GitHub, Slack, Google Drive, Jira, and dozens of other services.