Skip to content
Claudekit.ai

How to Build an AI Agent with Claude (Step by Step)

Build an AI agent with Claude: compare subagents, the Agent SDK, Managed Agents and the API tool loop, then run a Python agent with a custom tool and a budget.

By Claudekit Team Published Checked 9 min read

You can build a Claude agent four ways: a Claude Code subagent (no code), the Agent SDK (Python or TypeScript), Managed Agents (Anthropic hosts it), or your own tool loop on the Claude API. For most people the Agent SDK with an API key is the right start. It gives you the same tools and agent loop that run Claude Code, so a useful agent fits in about 50 lines of Python.

This guide is the hands-on part. If you want the concepts first, read Claude agents explained. Every command, option and price below was checked against Anthropic’s Agent SDK overview, quickstart, Python reference and pricing page on 25 Oct 2026.

Pick your route

RouteCode neededWho runs the loopYou pay withPick it when
Claude Code subagentNone, a Markdown fileClaude Code on your machineYour Claude plan or API keyThe agent helps you inside Claude Code
Agent SDKPython or TypeScriptYour process, your serverAPI key (per token)You want files, shell and web tools out of the box in your own app
Managed AgentsAPI callsAnthropic, in a managed sandboxAPI key (tokens plus session runtime)You want long-running agents without hosting a sandbox
API tool loopAny languageYour codeAPI key (per token)The agent only needs your own tools, with full control

Anthropic’s own advice in Building effective agents applies to all four: find the simplest solution that works, and add complexity only when it pays off. If a single prompt or a fixed two-step pipeline does the job, you don’t need an agent.

Build an agent with the Agent SDK

The example agent triages customer emails. It reads .txt files in a folder with Claude’s built-in read-only tools and calls one custom tool, log_followup, to append the emails that need a reply to a CSV file. It cannot run shell commands or edit files.

1. Set up the project

You need Python 3.10 or later (or Node.js 18+ for TypeScript) and an Anthropic account.

mkdir email-agent && cd email-agent
python3 -m venv .venv
source .venv/bin/activate
pip install claude-agent-sdk

The SDK bundles a native Claude Code binary, so most installs need no separate Claude Code install. With uv, run uv init && uv add claude-agent-sdk instead.

2. Set your API key

Create a key in the Claude Console and export it in the shell that runs the agent:

export ANTHROPIC_API_KEY=your-api-key

The SDK reads the key from the environment and does not load .env files on its own. If you keep the key in .env, load it yourself before the agent starts, and never commit the file. Our Claude API key guide covers creating and storing keys. Amazon Bedrock, Google Cloud, Microsoft Foundry and Claude Platform on AWS also work, through environment variables such as CLAUDE_CODE_USE_BEDROCK=1.

3. Write the agent

Save this as agent.py:

import asyncio
import csv
from datetime import date
from typing import Any

from claude_agent_sdk import (
    ClaudeAgentOptions,
    ClaudeSDKError,
    ResultMessage,
    create_sdk_mcp_server,
    query,
    tool,
)


@tool(
    "log_followup",
    "Record a customer email that needs a reply, with a one-line reason",
    {"file": str, "customer": str, "reason": str},
)
async def log_followup(args: dict[str, Any]) -> dict[str, Any]:
    with open("followups.csv", "a", newline="", encoding="utf-8") as f:
        csv.writer(f).writerow([date.today().isoformat(), args["file"], args["customer"], args["reason"]])
    return {"content": [{"type": "text", "text": f"Logged {args['file']}"}]}


inbox = create_sdk_mcp_server(name="inbox", version="1.0.0", tools=[log_followup])


async def main() -> None:
    options = ClaudeAgentOptions(
        system_prompt="You triage customer emails. Use only facts that appear in the files.",
        tools=["Read", "Glob", "Grep"],  # the only built-in tools Claude can see
        mcp_servers={"inbox": inbox},
        allowed_tools=["Read", "Glob", "Grep", "mcp__inbox__log_followup"],
        max_turns=30,
        max_budget_usd=0.50,
    )
    try:
        async for message in query(
            prompt="Read every .txt file in ./emails. Log each email that needs a reply.",
            options=options,
        ):
            if isinstance(message, ResultMessage):
                print(message.result or message.subtype)
                if message.total_cost_usd is not None:
                    print(f"Estimated cost: ${message.total_cost_usd:.4f}")
    except ClaudeSDKError as err:
        print(f"Agent stopped: {err}")


asyncio.run(main())

What each part does, per the Python SDK reference:

  • @tool and create_sdk_mcp_server turn a Python function into a tool that runs inside your process. Claude sees it as mcp__inbox__log_followup: mcp__, the key you gave the server in mcp_servers, then the tool name.
  • tools controls which built-in tools exist for this agent. Bash, Edit and Write are left out, so Claude never sees them.
  • allowed_tools pre-approves calls. SDK runs start in Manual mode, where any call that would need approval is denied, so list every tool the agent should use.
  • max_turns and max_budget_usd stop a runaway loop. The budget is checked against a client-side estimate that can overshoot slightly, so leave headroom.
  • ResultMessage arrives once at the end with the final text and total_cost_usd. When a run ends in an error, such as hitting the budget, the SDK raises an error after that message, which the except block catches.

4. Run it

Put two or three sample emails in ./emails/ as .txt files, then run:

python agent.py

You get a summary, an estimated cost, and a followups.csv with one row per email that needs a reply. To see each step, print AssistantMessage blocks as the official quickstart does.

5. Grow it carefully

  • Add tools one at a time. A real version might swap the CSV for your helpdesk API. Return "is_error": True in the tool result when a call fails, so Claude reads a useful message instead of a raw exception.
  • Give it more power only with limits. Adding "Bash" lets the agent run commands; pair it with deny rules or hooks first. The Agent SDK permissions docs list the evaluation order.
  • Pick the model on purpose. Set model="sonnet" or model="haiku" in the options. Smaller models cost less per token for narrow, repeated jobs.

Not working in Python or TypeScript? Run claude -p "your task" --output-format json as a subprocess from any language. Our headless mode guide covers the flags.

The no-code route: a Claude Code subagent

If the agent only helps you while you work, skip the SDK. A subagent is a Markdown file in .claude/agents/:

---
name: email-triage
description: Triage customer emails in ./emails and list the ones that need a reply
tools: Read, Glob, Grep
model: haiku
---
You triage customer emails. Read each file in ./emails, then list the ones that
need a reply with the customer name and a one-line reason. Use only facts in the files.

Ask Claude Code to “use the email-triage agent” and it runs in its own context window. The subagents guide covers every frontmatter field.

Managed Agents and the raw API loop

Managed Agents is a hosted agent harness on the Claude API. You define an agent (model, system prompt, tools, MCP servers, skills), an environment, and then start sessions; Anthropic runs the loop and the sandbox. It is in beta, every endpoint needs the managed-agents-2026-04-01 beta header (the official SDKs add it), and access is on by default for API accounts. It suits long-running or scheduled jobs. See the Managed Agents overview.

The API tool loop means calling the Messages API yourself, defining tools as JSON schemas, and running each tool call in your own code until Claude stops asking for tools. The client SDKs include a beta tool runner that drives that loop for you. Pick this when you need full control and no built-in file or shell tools.

What a Claude agent costs

Every route except a subagent on your own plan is billed per token at API prices. On 25 Oct 2026 the pricing page listed:

ModelInput per million tokensOutput per million tokens
Claude Sonnet 5.5$2$10
Claude Haiku 5.5 (prompts up to 100,000 tokens)$0.10$0.50
Claude Opus 5.5$4$20

Agents re-send their growing context on every step, so input tokens dominate. A run that reads 200,000 input tokens and writes 10,000 output tokens on Sonnet 5.5 costs $0.40 + $0.10 = $0.50 at list price, before prompt caching lowers the input share. Managed Agents adds $0.08 per session-hour while a session is running, and idle time is free.

The SDK’s total_cost_usd is an estimate computed on your machine. For real billing, use the Usage page in the Claude Console. To model your own numbers, try our API cost calculator. For build, hosting and maintenance costs beyond tokens, see our guide to AI agent development cost.

Can I use my Pro or Max subscription?

No, not for products you ship. Anthropic’s legal and compliance page says developers building products or services, including with the Agent SDK, should use API key authentication through the Claude Console or a supported cloud provider. Third-party developers may not offer claude.ai login or route requests through Free, Pro or Max credentials on behalf of their users.

The same page says advertised Pro and Max limits assume “ordinary, individual usage of Claude Code and the Agent SDK”. A personal script you run for yourself while signed in is ordinary use; an agent that serves customers or colleagues needs an API key.

Before you ship

  • Keep the tool list as short as the job allows, and keep Bash out unless you need it.
  • Set max_turns and max_budget_usd on every run.
  • Log total_cost_usd per run, so a cost jump shows up before the invoice does.
  • Do not call your product “Claude Code” or “Claude Code Agent”. The SDK’s branding rules allow names such as “YourAgent Powered by Claude”.

If you would rather not build and run it yourself, you can have one built for you.

Frequently asked questions

Can I build an AI agent with Claude for free?

Not on the API: the Agent SDK costs nothing to install, but every run is billed per token at Claude API rates. If you already pay for Pro or Max, a Claude Code subagent for your own work runs inside that plan's usage limits, which is the closest thing to free.

Can I use my Claude Pro or Max subscription for an Agent SDK agent?

Not for anything you ship to other people. Anthropic's docs say third-party developers may not offer claude.ai login or rate limits in their products, including Agent SDK agents, unless previously approved. Use a Claude Console API key or a supported cloud provider.

How much does a Claude agent cost to run?

Agent SDK runs are billed per token at the model's API price; on 25 Oct 2026 Claude Sonnet 5.5 was $2 per million input tokens and $10 per million output tokens. Managed Agents adds $0.08 per session-hour of running time on top of tokens.

Do I need Python to build a Claude agent?

No. The Agent SDK also ships for TypeScript, a Claude Code subagent is a Markdown file, and any other language can drive the same loop by running claude -p with --output-format json as a subprocess.

Get the weekly Claude digest

New skills, MCP servers, prompts and Claude updates — one short email a week. No spam, unsubscribe anytime.

The newsletter is launching soon. Follow the RSS feed in the meantime.