⚡ Quick verdict
- What it is: Anthropic's official SDK (released September 2025) for building autonomous agents — the same agent harness that powers Claude Code, packaged as a Python/TypeScript library.
- Install:
pip install claude-agent-sdk(Python 3.10+) ornpm install @anthropic-ai/claude-agent-sdk(Node 18+) — the Claude Code binary ships bundled, no separate install needed. - Authenticate:
export ANTHROPIC_API_KEY=your-api-keyfrom the Claude Console; Bedrock, Vertex AI, and Azure options also exist. - Run: the canonical entry point is
query()— an async iterator that streams messages as the agent works.
We may earn a commission if you buy through our links, at no extra cost to you.
If Claude Code is the product, the Claude Agent SDK is the engine room opened up: Anthropic's official library for building production AI agents in Python or TypeScript. Instead of hand-rolling the agent loop — prompt, tool calls, results, repeat — the SDK gives you the same battle-tested loop Claude Code runs on: file operations, bash execution, web search, MCP tool integration, subagents, hooks, session management, and automatic context compaction, all programmable from your code.
This is a researched setup guide, not a live lab test. Every step below is verified against Anthropic's official Agent SDK documentation and quickstart (mirrored and cross-checked across current guides from September 2026 — sources at the bottom). API details move fast, so treat signatures as current-as-of-writing and check the official docs if something doesn't match. This guide is aimed at developers comfortable with a terminal; if you'd rather build agents visually, see our n8n agent setup or Make AI agents guides instead.
What you'll need
- Python 3.10+ or Node.js 18+ — check with
python3 --versionornode --version. - An Anthropic account and an API key from the Claude Console (platform.claude.com). Billing must be enabled on your API account — the SDK is bring-your-own-key.
- A project folder — the SDK runs from any directory and gets file access to that folder and its subdirectories by default.
Step 1: Create a project folder
Make a home for your first agent and move into it:
mkdir my-agent && cd my-agent
That's the entire project setup. Your agent will operate on files inside this directory, so keep anything you don't want the agent touching outside of it — file access is a feature, but it's also the sharpest edge in this guide.
Step 2: Install the SDK
Pick your language. The two SDKs are near-identical in capability, so use whichever your project already runs in.
Python — create and activate a virtual environment first (system Python on recent Debian/Ubuntu/macOS installs refuses bare pip install outside a venv), then install:
python3 -m venv .venv
source .venv/bin/activate
pip install claude-agent-sdk
Prefer uv? uv init && uv add claude-agent-sdk handles the venv automatically.
TypeScript — for a new project:
npm init -y && npm pkg set type=module
npm install @anthropic-ai/claude-agent-sdk
npm install --save-dev tsx
Setting "type": "module" lets your agent script use top-level await, and tsx runs TypeScript files directly. If your interpreter complains the package wasn't found on Python, check python3 --version — the SDK needs 3.10 or later, and an older interpreter is the most common install failure.
Step 3: Set your API key
Get a key from the Claude Console, then put it in your process environment:
export ANTHROPIC_API_KEY=your-api-key
Two things that trip people up: the SDK does not read .env files on its own — load them yourself with a library like dotenv before the first query() call. And never commit a key to git; a leaked Anthropic key spends your money. Running on a cloud provider instead? One environment variable each routes auth there: CLAUDE_CODE_USE_BEDROCK=1 for Amazon Bedrock, CLAUDE_CODE_USE_VERTEX=1 for Google Vertex AI, or CLAUDE_CODE_USE_FOUNDRY=1 for Microsoft Azure, plus that provider's usual credentials. If you're already logged into the claude CLI, the SDK can also pick up your keychain credentials — you may not need an API key at all.
Step 4: Run your first agent
The canonical entry point is query() — an async iterator that streams messages as the agent works. The SDK handles the tool loop internally: Claude reads files, runs commands, and edits code without you implementing tool dispatch.
Python — save this as agent.py:
import asyncio
from claude_agent_sdk import query, ClaudeAgentOptions
async def main():
async for message in query(
prompt="Find and fix the bug in auth.py",
options=ClaudeAgentOptions(allowed_tools=["Read", "Edit", "Bash"]),
):
print(message)
asyncio.run(main())
TypeScript — save this as agent.ts and run it with npx tsx agent.ts:
import { query } from "@anthropic-ai/claude-agent-sdk";
for await (const message of query({
prompt: "Find and fix the bug in auth.ts",
options: { allowedTools: ["Read", "Edit", "Bash"] }
})) {
console.log(message);
}
Messages stream as Claude works: tool calls, tool results, intermediate reasoning, and the final result. Run it, watch it think, and note how little code you wrote — the agent loop is the SDK's job, not yours.
Step 5: Lock down the agent's permissions
This is the step most tutorials rush past. Your agent has real power — file edits, shell commands — so allowed_tools is your seatbelt. Start with the smallest set that can do the job: ["Read"] for a research agent, add "Edit" and "Bash" only when the task needs them. You can also cap the loop with max_turns so a confused agent can't burn tokens forever:
options = ClaudeAgentOptions(
system_prompt="You are a careful code reviewer. Never delete files.",
max_turns=10,
allowed_tools=["Read"],
)
A system prompt with explicit boundaries plus tight tool permissions is the difference between a helpful agent and an expensive accident. Keep the agent's working directory scoped to your project folder, and treat permission settings as code you review, not defaults you accept.
Step 6: Give it a custom tool (optional, but this is the point)
Built-in tools cover files and shell; your tools are what make the agent yours. The SDK lets you define tools as plain functions and register them as an in-process MCP server — no subprocess overhead, with type safety in your own process. Conceptually:
# define a tool as a function, bundle it into an
# in-process MCP server, and pass it via the
# mcp_servers option with matching allowed_tools,
# e.g. allowed_tools=["mcp__myserver__*"]
Real examples wire browser automation, database queries, or internal APIs into the agent this way. The exact decorator and server-builder shapes evolve between releases, so copy the current pattern from the official custom-tools docs or the official Python repo rather than from memory — inventing signatures is how you get a broken agent.
What it costs
The SDK is free; the tokens aren't. There's no SDK license fee — you pay Anthropic's standard API rates for the input and output tokens your agent consumes (or your cloud provider's rates if you route through Bedrock/Vertex/Azure). A few practical notes:
| Cost factor | What to expect | How to control it |
|---|---|---|
| SDK license | $0 — free library | Nothing to do |
| API tokens | Billed per token at your Anthropic API plan rates | Use max_turns, tight allowed_tools, cheap models for iteration |
| Context compaction | Automatic — keeps long sessions alive | Monitor session length; long sessions cost more |
| Subagents & hooks | Extra token spend per spawned agent | Spawn subagents only when parallelism pays |
Budget a few dollars for testing. A single confused agent with broad permissions and no turn limit can spend more in an afternoon than a month of careful runs — the guardrails in Step 5 are also your cost controls.
Next steps
Once the first agent runs, the roadmap writes itself: subagents for parallel work with isolated contexts; hooks (PreToolUse and friends) to intercept and control the agent at lifecycle points; MCP servers for pre-built integrations like GitHub and Slack; session persistence and resume for long-running work; and scheduling via cron or GitHub Actions for autonomous runs. Anthropic maintains a demo agents repo with email-assistant and research-agent examples worth reading. If you need a hosted option without operating your own sandbox, look at Anthropic's Managed Agents (hosted REST API) — the SDK stays the right call for agents that work directly on your filesystem. And when your agents go to production, our LLM observability tools roundup covers tracing and monitoring them.
Frequently asked questions
Is the Claude Agent SDK free?
The SDK itself costs nothing — you download and run it free. What you pay for is Claude's API usage: tokens consumed while the agent works, billed at your Anthropic API plan rates. Budget a few dollars for testing; real workloads scale with token use.
Should I use the Python or TypeScript version?
Use the language your project already runs in. The two SDKs are near-identical: pip install claude-agent-sdk for Python 3.10+, npm install @anthropic-ai/claude-agent-sdk for Node 18+. Python suits data and scripting work; TypeScript suits web and Node backends.
Do I need Claude Code installed to use the SDK?
No. The TypeScript SDK bundles the Claude Code binary as an optional dependency, and the Python package bundles the CLI too. Only if you skip the bundled binary (e.g. npm ci --omit=optional) do you need a separate install and to point the SDK at it via pathToClaudeCodeExecutable or cli_path.
What is the difference between the Agent SDK and Managed Agents?
The Agent SDK is a library that runs the agent loop inside your own process, on your infrastructure, working on your files. Managed Agents is a hosted REST API: Anthropic runs the agent and the sandbox while your app sends events and streams back results. Use the SDK for local and filesystem agents; Managed Agents when you don't want to operate a sandbox.
Does the SDK read .env files?
No — the SDK reads ANTHROPIC_API_KEY from the process environment and does not load .env files on its own. Load them yourself with a library like dotenv before the first query() call, or export the variable in your shell.
Can I run SDK agents on a schedule?
Yes. The SDK is a library, so scheduling comes from your infrastructure: cron, systemd timers, GitHub Actions, or a task queue invoking your agent script. Session persistence and resume features let long-running agents keep state across runs.
Sources
- Anthropic Agent SDK quickstart (docs mirror) — install, auth, first query()
- Official Python SDK repo — installation, bundled CLI, query() usage
- Agent SDK overview (docs mirror) — context management, permissions, production essentials
- SDK vs Managed Agents comparison (docs mirror)
- Claude Agent SDK skill reference — auth priority, quickstart patterns
- Quickstart reference — prerequisites, venv setup, provider auth