Frameworks

Claude Agent SDK: Hello World, Tools and Limits

Checked 2026-10-31

Loading poll...

The Claude Agent SDK is Claude Code as a library. In Python or TypeScript you get the same built-in tools, agent loop, hooks, subagents, MCP and permissions that power Claude Code, and you call them from your own program. You pay for Claude API use; the SDK itself has no separate fee. Checked 31 October 2026.

At a glance

Claude Agent SDK

Vendor

Anthropic

Languages

Python (claude-agent-sdk), TypeScript (@anthropic-ai/claude-agent-sdk)

Requirements

Node.js 18.14+ or Python 3.10+, and an Anthropic account

What you get

Built-in tools, hooks, subagents, MCP, permissions, sessions, skills, plugins

Terms

Anthropic's Commercial Terms of Service, except components with their own LICENSE file

Repo activity

Python about 8,400 stars (MIT per GitHub), pushed 30 October 2026; TypeScript about 1,850 stars

Auth

API key, or Amazon Bedrock, Google Cloud, Microsoft Foundry, Claude Platform on AWS

Cost

Model usage on whatever provider you authenticate with; Sonnet 5.5 is $2 and $10 per million input and output tokens

What it is

The overview defines an agent as "an application that completes a task by planning its own steps and calling tools that read files, run commands, or edit code." The SDK "gives you the same tools, agent loop, and context management that power Claude Code, programmable in Python and TypeScript."

It does this by running the Claude Code binary underneath. The docs say both SDKs bundle a native Claude Code binary, so most installs need no separate Claude Code install. That has a consequence worth knowing: the SDK inherits Claude Code's behavior, including its skills, commands and memory loaded from .claude/ in your project and ~/.claude/.

Which Claude tool do you want?

Anthropic offers several ways to run an agent, and the overview has a table to separate them.

You want to

Use

Embed Claude Code's agent in your own Python or TypeScript app, in a process you operate

Agent SDK

Do interactive development or one-off tasks from a terminal

Claude Code CLI

Call the Claude API directly and write the tool loop yourself (or use the beta tool runner)

Client SDK

Have Anthropic host the agent, with sessions in a managed cloud sandbox or a self-hosted one

Managed Agents

If your language is not Python or TypeScript, the docs suggest running the CLI as a subprocess with -p and --output-format json.

Capabilities

Capability

What it does

Built-in tools

Read, write and edit files, run commands, search the web

Hooks

Run custom code at points in the agent lifecycle

Subagents

Spawn specialized agents for focused subtasks

MCP

Connect external tools and data through the Model Context Protocol

Permissions

Control which tools run automatically and which need approval

Sessions

Keep context across exchanges, resume or fork later

Skills, commands and memory

Load automatically from .claude/ and ~/.claude/, as in Claude Code

Plugins

Package skills, agents, hooks and MCP servers and load them by local path

For the user-facing side of the same features see subagents, skills and the MCP server list.

Install

# TypeScript (new project)
npm init -y
npm pkg set type=module
npm install @anthropic-ai/claude-agent-sdk
npm install --save-dev tsx

# Python with uv
uv init
uv add claude-agent-sdk

# Python with pip
python3 -m venv .venv
source .venv/bin/activate
pip install claude-agent-sdk

Two install gotchas from the docs:

  • If pip installs the Python source distribution instead of a platform wheel (the docs give ARM64 Windows as an example), no binary is bundled. Install Claude Code natively and the SDK will find it on your PATH.
  • The TypeScript SDK gets its binary through npm optional dependencies. An install that skips them, such as npm ci --omit=optional, gets no binary.

Authentication

Set your key in the environment of the process that runs your agent:

export ANTHROPIC_API_KEY=your-api-key

The SDK does not load .env files on its own, so load yours (for example with dotenv) before calling it. Other providers are switched on with environment variables:

Provider

Variable

Amazon Bedrock

CLAUDE_CODE_USE_BEDROCK=1 plus AWS credentials

Claude Platform on AWS

CLAUDE_CODE_USE_ANTHROPIC_AWS=1 and ANTHROPIC_AWS_WORKSPACE_ID

Google Cloud's Agent Platform

CLAUDE_CODE_USE_VERTEX=1 plus Google Cloud credentials

Microsoft Foundry

CLAUDE_CODE_USE_FOUNDRY=1 plus Azure credentials

One rule in the docs is easy to miss and matters for anyone building a product: "Unless previously approved, Anthropic does not allow third party developers to offer claude.ai login or rate limits for their products, including agents built on the Claude Agent SDK." Use API key authentication.

Hello world

The quickstart builds an agent that finds and fixes bugs. First a file with two bugs, utils.py:

def calculate_average(numbers):
    total = 0
    for num in numbers:
        total += num
    return total / len(numbers)


def get_user_name(user):
    return user["name"].upper()

Then the agent, in Python:

import asyncio
from claude_agent_sdk import query, ClaudeAgentOptions, AssistantMessage, ResultMessage


async def main():
    async for message in query(
        prompt="Review utils.py for bugs that would cause crashes. Fix any issues you find.",
        options=ClaudeAgentOptions(
            allowed_tools=["Read", "Edit", "Glob"],  # Auto-approve these tools
            permission_mode="acceptEdits",  # Auto-approve file edits
        ),
    ):
        if isinstance(message, AssistantMessage):
            for block in message.content:
                if hasattr(block, "text"):
                    print(block.text)
                elif hasattr(block, "name"):
                    print(f"Tool: {block.name}")
        elif isinstance(message, ResultMessage):
            print(f"Done: {message.subtype}")


asyncio.run(main())

And in TypeScript:

import { query } from "@anthropic-ai/claude-agent-sdk";

for await (const message of query({
  prompt: "Review utils.py for bugs that would cause crashes. Fix any issues you find.",
  options: {
    allowedTools: ["Read", "Edit", "Glob"],
    permissionMode: "acceptEdits"
  }
})) {
  if (message.type === "assistant" && message.message?.content) {
    for (const block of message.message.content) {
      if ("text" in block) console.log(block.text);
      else if ("name" in block) console.log(`Tool: ${block.name}`);
    }
  } else if (message.type === "result") {
    console.log(`Done: ${message.subtype}`);
  }
}

Run it with npx tsx agent.ts or uv run agent.py.

The three parts are query (the entry point, returning an async iterator you stream), prompt (what you want) and options (tools, permission mode and more). The loop keeps yielding messages as Claude thinks, calls tools and reads results, until the task is done.

Tools and permissions

The tools you allow define the agent:

Tools

What the agent can do

Read, Glob, Grep

Read-only analysis

Read, Edit, Glob

Analyze and modify code

Read, Edit, Bash, Glob, Grep

Full automation

Permission modes set how much human oversight you keep. The SDK evaluates the active mode with your allow and deny rules in a fixed order, which the permissions page describes. Start read-only, move to edit once you trust the prompt, and add Bash last.

Designing your first real agent

The quickstart fixes bugs in one file. A real agent needs three decisions made up front. These are our suggestions, built on the tool and permission tables above.

Decision

Safe starting point

When to widen

Tools

Read, Glob, Grep only

Add Edit once the read-only output is right; add Bash last

Permission mode

Ask for approval

acceptEdits for a tested prompt on a scratch branch

Where it runs

A throwaway folder or container

A CI job with a clean checkout and no production secrets

Examples of agents that fit this shape include a code reviewer that reads a diff and writes comments, a docs agent that compares code to its README, and a migration helper that edits files on a branch. Our guides on a code review agent, a docs agent and a QA agent cover the prompts.

The docs also note that the streaming loop is for live progress. For background jobs or CI pipelines where nobody watches, you can collect all messages at once instead of streaming. Either way, log the tool calls. When an agent does something odd, the tool list is the first place to look.

Subagents are the way to keep a large task tidy. Rather than giving one agent every tool, spawn a focused subagent for a subtask with only the tools it needs. That limits what a mistake can touch.

Give the agent your own tool

The built-in tools cover files and shell commands. For anything specific to your business, such as looking up an order or reading an internal API, you add a custom tool. The docs describe a tool as four parts: a name, a description, an input schema and a handler. You wrap tools in an in-process MCP server, which runs inside your application and not as a separate process, then pass it to query through mcp_servers.

This Python example follows the pattern in the custom tools documentation, with a local tool so it needs no extra libraries. It counts the words in a text file under a docs folder.

import asyncio
from pathlib import Path
from typing import Annotated, Any

from claude_agent_sdk import ClaudeAgentOptions, ResultMessage, create_sdk_mcp_server, query, tool

DOCS = Path("docs").resolve()


@tool(
    "count_words",
    "Count the words in one text file inside the docs folder",
    {"path": Annotated[str, "Relative path, for example guide.md"]},
)
async def count_words(args: dict[str, Any]) -> dict[str, Any]:
    target = (DOCS / args["path"]).resolve()
    if not target.is_relative_to(DOCS) or not target.is_file():
        return {"content": [{"type": "text", "text": "No such file in docs."}], "is_error": True}
    n = len(target.read_text(errors="replace").split())
    return {"content": [{"type": "text", "text": f"{args['path']}: {n} words"}]}


server = create_sdk_mcp_server(name="docs", version="1.0.0", tools=[count_words])


async def main() -> None:
    options = ClaudeAgentOptions(
        mcp_servers={"docs": server},
        allowed_tools=["mcp__docs__count_words"],
    )
    async for message in query(prompt="How long is guide.md?", options=options):
        if isinstance(message, ResultMessage):
            print(message.subtype)


asyncio.run(main())

Three points from the docs make this safe to copy. The tool name the model sees is mcp__{server_name}__{tool_name}, so the name in allowed_tools must use the key you gave the server in mcp_servers, here docs. A tool that is not in allowed_tools triggers a permission prompt, and in an unattended job there is nobody to answer it, so list what you intend to allow. And return errors as results with an error flag, instead of letting the handler raise, so the agent can recover. The path check is the same guard used in our how to build an AI agent guide, and for the same reason: the model chooses the arguments, so treat them as untrusted. A server can hold many tools, and a wildcard such as mcp__docs__* covers all of them.

The docs also describe tool annotations, optional hints such as whether a tool is read-only. Mark read-only tools as such, since a client can use the hint to decide how much to ask.

What an agent run costs

An SDK agent loops like Claude Code does, so cost scales with the number of turns and the size of the context, not with the length of your prompt. As an illustration of the arithmetic only, suppose one run makes ten model calls that together read 150,000 input tokens and write 8,000 output tokens. Those numbers are assumptions, and you should replace them with the token counts the SDK reports for your own runs.

Model

Price per million in / out

One run

20 runs a month

500 runs

5,000 runs

Haiku 5.5

$0.10 / $0.50

about $0.02

about $0.38

about $9.50

about $95

Sonnet 5.5

$2 / $10

about $0.38

about $7.60

about $190

about $1,900

Opus 5.5

$4 / $20

about $0.76

about $15

about $380

about $3,800

For Sonnet 5.5 the sum is 150,000 x $2 / 1,000,000 plus 8,000 x $10 / 1,000,000, which is $0.30 plus $0.08. Cache reads are billed at a fraction of the input price, and an agent that repeats the same system prompt and tool list benefits, so real bills are often lower. Batch processing is half price where it fits, but an interactive agent loop usually does not. The levers that matter most are the model you pick, the number of turns you allow, and how much each tool returns. Cap turns with the SDK's options, and keep file reads small. Check Claude API pricing for the current rates and the spend limit steps in how to build an AI agent.

Running it in production

A script on your laptop and a service for customers are different jobs. These rules separate them.

  1. Isolate the process. The SDK runs tools on the machine it is on, so an agent with Bash can do whatever that user can. Use a container with no production credentials, a read-only mount for source you only read, and a short-lived working folder.
  2. Authenticate with an API key or a cloud provider. The docs forbid offering claude.ai login or its rate limits to your users unless Anthropic approved it. Keep the key in a secret store and scope it to a workspace with its own spend limit.
  3. Cap everything. Set a turn limit, a time limit on the job, and a spend limit at the provider. A stuck agent should fail loudly after a known cost.
  4. Log tool calls. Record every tool name and input with the run id. When something odd happens, the log is how you find out why.
  5. Treat inputs as untrusted. A file, a web page or a ticket the agent reads can contain instructions. Give tools the smallest reach, and keep write and send actions behind approval.
  6. Pin versions. The SDK bundles a native binary and moves with Claude Code, so pin the package version in your lockfile and upgrade on purpose, with your tests run.
  7. Decide on sessions. Resume a session only when the task needs earlier context. A fresh session per job is cheaper and avoids carrying stale assumptions forward.
  8. Review output. Anything the agent changes goes through the same review as a human change, with the diff in front of a person.

Migrating from the older SDK or a hand-written loop

If you built on the earlier Claude Code SDK packages, the overview links a migration guide, and the first job is renaming the package and updating imports. If you have a hand-written loop on the Messages API, as in how to build an AI agent, the question is what you gain. You give up some control and gain tools you would otherwise write yourself: file editing, search, a shell, subagents and permissions. Move when you find yourself reimplementing those. Stay on the Client SDK for a chat feature, a classifier or a plain tool call, where the agent harness adds weight you do not need. A middle path is to keep your own loop and expose its tools over MCP, so you can try the SDK later without rewriting them.

Terms and branding

Use of the SDK is "governed by Anthropic's Commercial Terms of Service, including when you use it to power products and services that you make available to your own customers and end users," except for components with their own license. Do not assume the whole package is open source; check the LICENSE file in each repository and component. The TypeScript repository's LICENSE file reads "All rights reserved. Use is subject to Anthropic's Commercial Terms of Service", so only the Python package is MIT licensed, according to GitHub.

Branding rules for partners:

  • Allowed: "Claude Agent", "Claude" inside a menu already labeled "Agents", or "{YourAgentName} Powered by Claude".
  • Not permitted: "Claude Code" or "Claude Code Agent", and Claude Code-branded ASCII art or visuals.

Data handling

When you use the API, data handling follows Anthropic's commercial terms. Our Claude Code page summarizes the data-usage policy for the CLI, which says Anthropic does not train on code or prompts sent under commercial terms unless the customer opts in. Because the SDK runs tools on your machine, the larger risk is local: an agent with Bash can do whatever your user can. Run it in a container for anything unattended.

Limits

  • It is Claude-only. It runs Claude models through Anthropic or a cloud provider.
  • It depends on a Claude Code binary underneath, with the install gotchas above.
  • Auth restrictions apply to products you ship.
  • The package is aimed at agents that read files and run commands. For a plain chat or classification app, the Client SDK is simpler.

Questions people ask

Is this the old Claude Code SDK? The overview links a migration guide from the Claude Code SDK packages to the Agent SDK, so the name changed. If you see old tutorials, check the package name first.

Does it need Claude Code installed? Usually not. Both SDKs bundle a native binary. The exceptions are the install cases listed above.

Can I use MCP servers? Yes. MCP is one of the listed capabilities, and the docs have a page for it. The same servers you use in the CLI, such as GitHub MCP, are the natural first choice.

Where are the examples? Anthropic keeps a demos repository of example agents for local development, linked from the overview.

Who it suits

  • Developers who want Claude Code's behavior inside their own app, CI job or internal tool.
  • Teams building code-aware agents: reviewers, migrators, doc updaters.
  • Anyone who has already built workflow in .claude/ (skills, commands) and wants it to run headless.

It suits less well if you want a model-neutral framework; see LangGraph, CrewAI or the OpenAI Agents SDK.

Compared with the other frameworks

Core idea

Best for

Claude Agent SDK

Claude Code's tools and loop as a library

Coding and file agents on Claude

OpenAI Agents SDK

Small agents, tools, handoffs

OpenAI-first apps

LangGraph

State graphs

Long, stateful, multi-vendor flows

CrewAI

Role-based crews

Agent teams with roles

See AI agent frameworks for the whole field.

Our take

This comes from Anthropic's SDK documentation and the two repositories. We did not build an agent for this page.

The SDK's appeal is that the hard parts are already there. Tool use, permissions, sessions and subagents are the same ones people run daily in Claude Code, so an agent you prototype in the CLI can be moved to code with little translation. Its cost is the same coupling: Claude only, a bundled binary and terms you should read.

If you already use Claude Code and want a headless version, this is the natural step. If you want one framework that works across vendors, look elsewhere. Start with the bug-fixing quickstart in a scratch folder with read-only tools, then widen the permissions one step at a time.

Checklist

  • Install the package and confirm a binary is present
  • Set ANTHROPIC_API_KEY in the process environment
  • Run the quickstart with read-only tools
  • Choose a permission mode on purpose
  • Read the Commercial Terms and branding rules before shipping a product
  • Run unattended agents in a container

Questions

What is the Claude Agent SDK?

A library, in Python and TypeScript, that gives you the same tools, agent loop and context management that power Claude Code, so you can build your own agents.

How do I install it?

Python: pip install claude-agent-sdk or uv add claude-agent-sdk. TypeScript: npm install @anthropic-ai/claude-agent-sdk. Set ANTHROPIC_API_KEY.

Can I offer claude.ai login in my product?

Not without prior approval. Anthropic does not allow third-party developers to offer claude.ai login or rate limits for products built on the SDK; use API key authentication.

Can I call my agent Claude Code?

No. The branding rules say not to use Claude Code or Claude Code Agent as the name of your product.

Loading poll...

Sources

  1. code.claude.com/docs/en/agent-sdk/overview
  2. code.claude.com/docs/en/agent-sdk/quickstart
  3. github.com/anthropics/claude-agent-sdk-python
  4. github.com/anthropics/claude-agent-sdk-typescript
  5. code.claude.com/docs/en/agent-sdk/custom-tools

Part of the Wbcom Designs family

The all-in-one WordPress community stack

Also ours: wbcomdesigns.comvapvarun.combrndle.com