Claude Agent SDK: install, first agent, sign-in and billing
Claude Code as a Python or TypeScript library: install, a first agent, API key or Claude plan billing, permissions, MCP, subagents, and how it differs.
The Claude Agent SDK is Claude Code as a library: Anthropic’s Python and TypeScript packages that run the Claude Code binary for you and hand your code its agent loop, built-in tools (read, edit, shell, web search), permissions, hooks, subagents, MCP servers and sessions. Install it with pip install claude-agent-sdk (Python 3.10+) or npm install @anthropic-ai/claude-agent-sdk (Node 18.14+); the binary comes bundled. Set ANTHROPIC_API_KEY and call query() with a prompt and options. With a key you pay API token rates. On your own machine, signed in with your own Claude plan, Anthropic says as of its October 7, 2026 update that the SDK and claude -p “still draw from your subscription limits”; a product you ship to others has to use API keys. It differs from Claude Code in being driven from your code rather than a terminal, and from Managed Agents in running in a process you operate rather than on Anthropic’s infrastructure.
What it is, and where it sits among Anthropic’s tools
Anthropic’s Agent SDK overview describes it as giving you “the same tools, agent loop, and context management that power Claude Code, programmable in Python and TypeScript.” When your code calls query(), the SDK starts a claude process and talks to it over stdio, so Claude reads files, runs commands and edits code itself rather than asking you to implement each tool. The four options Anthropic sets side by side:
| Tool | Who runs the agent | What you get |
|---|---|---|
Agent SDK | A process you operate | Claude Code’s loop, tools, permissions, sessions and hooks, called from Python or TypeScript |
Claude Code CLI | You, in a terminal | The interactive tool; also scriptable with claude -p |
Client SDK (the anthropic package) | Your code | Direct Claude API calls; you write the tool loop yourself |
Managed Agents | Anthropic | A hosted agent harness, configured through the Claude API, with sessions in Anthropic’s cloud sandbox or one you host |
For any other language, Anthropic’s advice is to run the CLI as a subprocess with -p and --output-format json. What Managed Agents costs and what it keeps between sessions is in the Claude Managed Agents guide.
As of November 22, 2026 the current releases are TypeScript 0.3.330 and Python 0.2.187, both published November 20. The TypeScript release notes end “Updated to parity with Claude Code v2.1.330”: the SDK pins the binary it bundles, so updating the package is how you update the Claude Code underneath it. The SDK was called the Claude Code SDK until Anthropic renamed it; the old packages were @anthropic-ai/claude-code and claude-code-sdk, and Python’s ClaudeCodeOptions became ClaudeAgentOptions, per the migration guide.
Install it and run a first agent
From Anthropic’s quickstart, in an empty project folder. Python, with a virtual environment:
python3 -m venv .venv
source .venv/bin/activate
pip install claude-agent-sdkCopied(or uv init then uv add claude-agent-sdk). TypeScript:
npm init -y
npm pkg set type=module
npm install @anthropic-ai/claude-agent-sdk
npm install --save-dev tsxCopiedBoth packages bundle a native Claude Code binary, so there is nothing else to install in most cases. Two exceptions: an npm install that skips optional dependencies (npm ci --omit=optional) gets no binary, and a pip install that falls back to the source distribution, as on ARM64 Windows, has none either. For those, install Claude Code natively; the Python SDK finds it on your PATH, and the TypeScript SDK takes its path in pathToClaudeCodeExecutable.
Then the key, from the Claude Console, in the shell that will run the agent. The SDK does not read .env files on its own:
export ANTHROPIC_API_KEY=your-api-keyCopiedThe quickstart’s agent reviews a file called utils.py for crashing bugs and fixes them. Its Python version, saved as agent.py:
import asyncio
from claude_agent_sdk import query, ClaudeAgentOptions, AssistantMessage, ResultMessage
async def main():
# Agentic loop: streams messages as Claude works
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
),
):
# Print human-readable output
if isinstance(message, AssistantMessage):
for block in message.content:
if hasattr(block, "text"):
print(block.text) # Claude's reasoning
elif hasattr(block, "name"):
print(f"Tool: {block.name}") # Tool being called
elif isinstance(message, ResultMessage):
print(f"Done: {message.subtype}") # Final result
asyncio.run(main())CopiedThe same agent in TypeScript, as agent.ts:
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}`);
}
}CopiedRun it with python agent.py (or uv run agent.py) or npx tsx agent.ts. It prints Claude’s reasoning and each tool call, and ends with Done: success. query() returns an async stream of messages: Claude’s text, tool calls, tool results, and a final result message that carries the outcome and the session’s cost. An authentication error such as Not logged in or Invalid API key usually means the key is not set in the shell that runs the agent.
Signing in, and who pays
The SDK authenticates the way Claude Code does, because it is Claude Code underneath. Anthropic’s authentication page says ANTHROPIC_API_KEY, ANTHROPIC_AUTH_TOKEN and apiKeyHelper “apply to the CLI and the surfaces that wrap it, including the VS Code extension, the Agent SDK, and GitHub Actions,” and its precedence list puts a cloud provider first, then those variables, then CLAUDE_CODE_OAUTH_TOKEN, with the plan sign-in from /login last. So a key in the environment wins over a plan sign-in on the same machine.
- An API key: billed per token to the key’s Console organization. Since October 7, 2026, Max, Ultra and Team plans include monthly API credits, and Anthropic’s support article says they cover the Agent SDK run with an API key from the Console organization linked to the plan. The amounts per plan are in the guide to your Claude subscription in other agents.
- A cloud provider:
CLAUDE_CODE_USE_BEDROCK=1for Amazon Bedrock,CLAUDE_CODE_USE_VERTEX=1for Google Cloud’s Agent Platform,CLAUDE_CODE_USE_FOUNDRY=1for Microsoft Foundry, each with that provider’s own credentials, billed by the provider. - Your Claude plan: the SDK uses whatever login the Claude Code on that machine has, or a
CLAUDE_CODE_OAUTH_TOKENmade withclaude setup-token(one year, Pro, Max, Ultra, Team or Enterprise, model requests only). How to make and store that token is in the claude setup-token guide.
On billing a plan, Anthropic’s help article Use the Claude Agent SDK with your Claude plan says in its update of October 7, 2026 that “when you’re signed in with your Claude plan, the Claude Agent SDK and claude -p still draw from your subscription limits.” An earlier update, of June 15, 2026, says a previously announced change to how Agent SDK usage is billed has been paused, and that “Claude Agent SDK, claude -p, and third-party app usage still draw from your subscription limits.” The word “still” is doing work in both: the arrangement is current, not promised. That usage comes out of the same five-hour and weekly limits as your interactive sessions, explained in which Claude plans include Claude Code.
What a plan sign-in is not for is a product other people use. The overview and the quickstart both carry the same note: “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.” They point builders at API keys or the cloud providers, and the SDK as a whole is governed by Anthropic’s Commercial Terms of Service. A shipped product also may not call itself “Claude Code” or “Claude Code Agent”; Anthropic allows “Claude Agent”, or your agent’s own name followed by “Powered by Claude”.
To cap what one run spends, pass max_budget_usd (TypeScript maxBudgetUsd); there is no limit by default, and subagents’ requests count toward it. The hosting page is blunt about where the money goes: “Anthropic token cost typically dominates container infrastructure cost by an order of magnitude or more.”
Tools and permissions
The agent has Claude Code’s built-in tools: Read, Write, Edit, Glob, Grep, Bash, WebSearch, WebFetch, Agent and the rest. Three options decide what it can do, and the difference between them is the thing most first agents get wrong:
toolslimits which built-ins exist for Claude at all;tools=[]leaves only your MCP tools.allowed_toolspre-approves the tools it lists. It does not restrict: an unlisted tool is still available, and a call to it that needs approval goes on to the permission mode. Scoped entries work, such asBash(npm test *).disallowed_toolswith a bare name such as"Bash"removes the tool; with a pattern such asBash(rm *)it denies matching calls in every mode, includingbypassPermissions.
Per the permissions page, each call is checked in order: hooks, deny rules, ask rules, the permission mode, allow rules, then your canUseTool callback. The modes:
default: no automatic approvals. Since Claude Code 2.1.302 an SDK app starts here unless you set a mode, and a call that needs approval is denied unless an allow rule, a hook or your callback approves it.dontAsk: anything that would prompt is denied without calling your callback. With an exactallowed_toolslist, this is the lockdown for an agent nobody watches.acceptEdits: file edits and filesystem commands such asmkdir,mvandrminside the working directories run without asking. It does not approve MCP tools.plan: Claude explores and plans; edits go to your callback.auto: a classifier model approves or blocks shell commands and network requests, where auto mode is available.bypassPermissions: everything runs except a short list of actions no mode approves, andallowed_toolsdoes not narrow it. Claude Code refuses to start in this mode as root or undersudooutside a recognised sandbox. Subagents inherit it.
The locked-down pairing from Anthropic’s page:
const options = {
allowedTools: ["Read", "Glob", "Grep"],
permissionMode: "dontAsk"
};CopiedThe same choices for Claude Code’s own flags, and what each costs you in safety, are in running Claude Code and Codex without permission prompts.
MCP servers and your own tools
MCP servers go in mcp_servers (TypeScript mcpServers): a command for a local stdio server, a URL with "type": "http" or "sse" for a remote one. A .mcp.json at the project root is also loaded by default. Their tools are named mcp__<server>__<tool>, and the MCP page is plain that they “require explicit permission before Claude can use them”, so list them in allowed_tools, with a wildcard for a whole server. Anthropic’s example connects to its own documentation server:
options = ClaudeAgentOptions(
mcp_servers={
"claude-code-docs": {
"type": "http",
"url": "https://code.claude.com/docs/mcp",
}
},
allowed_tools=["mcp__claude-code-docs__*"],
)CopiedThe SDK never opens a browser for a server’s OAuth sign-in: a server that needs one reports needs-auth and the run carries on without its tools, so pass a token in headers or sign in once from an interactive Claude Code session on the same machine. Check each server’s status in the first system message of the stream before trusting a result.
Your own functions become tools without a separate server: decorate an async function with @tool (TypeScript tool() with a Zod schema), wrap it with create_sdk_mcp_server (createSdkMcpServer), and pass that in mcp_servers. It runs inside your process, and its tools are named and approved like any MCP tool. The custom tools page has the full pattern.
Subagents
Claude can hand a subtask to a subagent with its own context, prompt and tool set, and only its final message comes back. Define them in the agents option, each with a description (when to use it), a prompt, and optionally tools, model, maxTurns, effort and others; put Agent in allowed_tools. Files in .claude/agents/ load too, and the built-in general-purpose subagent is there even if you define none. From the subagents page, trimmed to one agent:
options=ClaudeAgentOptions(
allowed_tools=["Read", "Grep", "Glob", "Agent"],
agents={
"code-reviewer": AgentDefinition(
description="Expert code review specialist. Use for quality, security, and maintainability reviews.",
prompt="You are a code review specialist...",
tools=["Read", "Grep", "Glob"],
model="sonnet",
),
},
)CopiedOne prompt can grow into a tree of agents, so the limits matter: by default subagents nest three layers deep and up to 20 run at once (CLAUDE_CODE_MAX_SUBAGENT_SPAWN_DEPTH, CLAUDE_CODE_MAX_CONCURRENT_SUBAGENTS, set through the env option), and spend has no cap until you set max_budget_usd. In TypeScript, env replaces the whole environment, so spread process.env into it; Python merges it. How subagents behave in Claude Code itself is in the Claude Code subagents guide.
How it differs from Claude Code itself
It reads the same files. With no setting_sources option, an SDK agent loads user, project and local settings exactly as the CLI does: CLAUDE.md, rules, skills, slash commands, subagents, hooks and settings.json permission rules from ~/.claude/ and the working directory. That is convenient on your own machine and a leak in a shared one.
It does not use the same system prompt. Unless you set one, the SDK uses a minimal prompt that, per the system prompts page, “omits the rest of the claude_code preset’s content, including its security and safety instructions. This differs from claude -p, which uses the Claude Code system prompt by default.” To get Claude Code’s behaviour, ask for the preset, optionally with your own instructions on the end:
system_prompt={
"type": "preset",
"preset": "claude_code",
"append": "Always include detailed docstrings and type hints in Python code.",
}CopiedThere is also no terminal: nobody answers a prompt unless your code does, which is why the permission settings above decide whether a run does anything at all. If what you want is Claude Code running unattended on a server rather than a program of your own, a timer and claude -p is less code, and running Claude Code headless on a schedule covers it.
Running it on a server
From the hosting page: “One agent session maps to one subprocess,” each with its own shell, working directory and transcript under ~/.claude/projects/, so a session can be resumed by its ID for as long as that disk lasts. Anthropic’s starting size is 1 GiB of RAM, 5 GiB of disk and one CPU per agent, growing with session length, and the only network it needs is outbound HTTPS to api.anthropic.com (or your cloud provider’s endpoint) plus whatever its MCP servers and tools reach. A session has no timeout of its own: bound it with max_turns and the budget cap.
Several agents on one machine for different people need isolating from each other and from the host’s own Claude Code setup: pass setting_sources=[], set CLAUDE_CODE_DISABLE_AUTO_MEMORY=1 (auto memory loads regardless of setting sources), give each its own CLAUDE_CONFIG_DIR and its own cwd. The global ~/.claude.json and any managed policy are read whatever you pass.