- Key Takeaways
- What Is the Claude Code SDK?
- Claude Code SDK vs. Anthropic Client SDK: When to Use Which
- Install the Claude Agent SDK
- Step 1: Configure Authentication
- Step 2: Run Your First Agent Query
- Step 3: Control Permissions with allowedTools
- Step 4: Use Hooks for Lifecycle Control
- Step 5: Resume Work with Sessions
- Step 6: Delegate Tasks with Subagents
- Step 7: Connect External Systems via MCP
- Use Novita AI as the Model Backend
- Claude Code SDK in CI/CD Pipelines
- Troubleshooting
- FAQ
The Claude Code SDK — now officially named the Claude Agent SDK — is a Python and TypeScript library that lets you run Claude as an autonomous agent inside your own application. You give it a prompt, and it handles the rest: reading files, running commands, editing code, and iterating until the task is done. No tool loop to write, no streaming plumbing to manage.
This guide covers everything developers need to get started: installation, the core query() API, built-in tools, hooks, sessions, subagents, MCP integration, and how to use Novita AI’s LLM API as the model backend.
Key Takeaways
- The Claude Code SDK is now called the Claude Agent SDK (
claude-agent-sdkfor Python,@anthropic-ai/claude-agent-sdkfor TypeScript). - A single
query()function replaces the manual tool-execution loop you’d need with the Anthropic Client SDK. - Built-in tools cover file reading, editing, bash execution, web search, and more — no implementation required.
- Sessions let agents resume work across multiple calls with full context intact.
- Hooks let you validate, log, or block tool calls at specific lifecycle points.
- Novita AI’s Anthropic-compatible endpoint (
https://api.novita.ai/anthropic) lets you use high-quality open-weight models with the same SDK code.
What Is the Claude Code SDK?
The Claude Code SDK is a programmatic interface to Claude Code’s agent capabilities. It exposes the same tools, reasoning loop, and context management that the Claude Code CLI uses interactively — but as a library you import and call from your own code.
Anthropic renamed it to Claude Agent SDK starting with the 4.6 generation, but the original search term “claude code sdk” still accurately describes what it is: the SDK layer that sits on top of Claude Code and lets you automate agent tasks in software.
What it’s good for:
- Automated code review, refactoring, or test generation in CI/CD
- Agents that read and modify files, run scripts, or search the web on your behalf
- Multi-agent pipelines where a coordinator delegates subtasks to specialized workers
- Any workflow where you want Claude to take autonomous multi-step action, not just answer a prompt
What it’s not for: If you need direct control over every message, structured output from a single call, or streaming responses for a chat UI, the Anthropic Client SDK is more appropriate.
Claude Code SDK vs. Anthropic Client SDK: When to Use Which
Both SDKs build on Claude, but they solve different problems.
| Claude Agent SDK | Anthropic Client SDK | |
|---|---|---|
| Tool execution | Handled autonomously by Claude | You implement the tool loop |
| Interface | query() returns an async iterator | client.messages.create() returns a response object |
| Built-in tools | Read, Write, Edit, Bash, Grep, Glob, WebSearch, and more | None — you define and execute all tools |
| Sessions | Built-in — resume with a session ID | Manual — manage conversation history yourself |
| Best for | Agentic pipelines, CI/CD, file operations | Chat apps, structured output, fine-grained control |
If you want Claude to figure out which files to read and edit them autonomously: Agent SDK. If you want Claude to respond to a specific prompt and return a value you process: Client SDK.
Install the Claude Agent SDK
Python (requires Python 3.10+):
pip install claude-agent-sdk
TypeScript / Node.js:
npm install @anthropic-ai/claude-agent-sdk
The TypeScript package bundles a native Claude Code binary for your platform as an optional dependency. You do not need to install Claude Code separately.
To verify your Python version before installing:
python3 --version # macOS/Linux
py --version # Windows
If pip reports No matching distribution found for claude-agent-sdk, your Python interpreter is older than 3.10.
Step 1: Configure Authentication
Set your Anthropic API key as an environment variable:
export ANTHROPIC_API_KEY=your-api-key
The SDK also supports Amazon Bedrock, Google Vertex AI, and Azure AI Foundry for teams that route through cloud providers:
# Amazon Bedrock
export CLAUDE_CODE_USE_BEDROCK=1
# plus standard AWS credentials
# Google Vertex AI
export CLAUDE_CODE_USE_VERTEX=1
# plus GOOGLE_CLOUD_PROJECT and gcloud credentials
# Microsoft Azure AI Foundry
export CLAUDE_CODE_USE_FOUNDRY=1
# plus Azure credentials
Step 2: Run Your First Agent Query
The entire SDK surface is built around a single function: query(). It accepts a prompt and options, and returns an async iterator of message events.
import asyncio
from claude_agent_sdk import query, ClaudeAgentOptions
async def main():
async for message in query(
prompt="List all Python files in this directory",
options=ClaudeAgentOptions(allowed_tools=["Bash", "Glob"]),
):
if hasattr(message, "result"):
print(message.result)
asyncio.run(main())
import { query } from "@anthropic-ai/claude-agent-sdk";
for await (const message of query({
prompt: "List all Python files in this directory",
options: { allowedTools: ["Bash", "Glob"] }
})) {
if ("result" in message) console.log(message.result);
}
The iterator yields several message types. The two most useful:
ResultMessage(or messages with aresultfield) — the agent’s final responseSystemMessagewithsubtype === "init"— carries thesession_idfor resuming later
Step 3: Control Permissions with allowedTools
The SDK ships with pre-implemented tools. You declare which ones the agent can use; Claude handles execution.
| Tool | What it does |
|---|---|
| Read | Read any file in the working directory |
| Write | Create new files |
| Edit | Make targeted edits to existing files |
| Bash | Run shell commands, scripts, git operations |
| Glob | Find files by pattern (**/*.ts, src/**/*.py) |
| Grep | Search file contents with regex |
| WebSearch | Search the web for current information |
| WebFetch | Fetch and parse web page content |
| Monitor | Watch a background script and react to output lines |
| AskUserQuestion | Ask the user clarifying questions mid-task |
| Agent | Invoke a defined subagent |
The combination of Bash + Read + Edit is enough for most automated code tasks. Add WebSearch or WebFetch when the agent needs external data.
allowed_tools (Python) / allowedTools (TypeScript) pre-approves specific tools without prompting. Restricting the tool set also limits what the agent can do unintentionally — a useful guardrail for automated pipelines.
Read-only code review agent:
from claude_agent_sdk import query, ClaudeAgentOptions
async for message in query(
prompt="Review this codebase for security issues and code smell",
options=ClaudeAgentOptions(
allowed_tools=["Read", "Glob", "Grep"],
),
):
if hasattr(message, "result"):
print(message.result)
Full edit agent (pre-approves file writes):
options=ClaudeAgentOptions(
allowed_tools=["Read", "Write", "Edit", "Bash"],
permission_mode="acceptEdits",
)
permission_mode="acceptEdits" auto-approves file edits without an interactive prompt, which is required when running in CI.
Step 4: Use Hooks for Lifecycle Control
Hooks let you run custom code at defined points in the agent’s execution. You can log actions, validate inputs, block dangerous operations, or update external state.
Available hook events: PreToolUse, PostToolUse, PostToolUseFailure, UserPromptSubmit, Stop, SubagentStop, SubagentStart, PreCompact, Notification, PermissionRequest
This example writes an audit log every time the agent edits or creates a file:
import asyncio
from datetime import datetime
from claude_agent_sdk import query, ClaudeAgentOptions, HookMatcher
async def log_file_change(input_data, tool_use_id, context):
file_path = input_data.get("tool_input", {}).get("file_path", "unknown")
with open("./audit.log", "a") as f:
f.write(f"{datetime.now().isoformat()}: modified {file_path}\n")
return {}
async def main():
async for message in query(
prompt="Refactor auth.py to use dataclasses",
options=ClaudeAgentOptions(
permission_mode="acceptEdits",
hooks={
"PostToolUse": [
HookMatcher(matcher="Edit|Write", hooks=[log_file_change])
]
},
),
):
if hasattr(message, "result"):
print(message.result)
asyncio.run(main())
import { query, HookCallback } from "@anthropic-ai/claude-agent-sdk";
import { appendFile } from "fs/promises";
const logFileChange: HookCallback = async (input) => {
const filePath = (input as any).tool_input?.file_path ?? "unknown";
await appendFile("./audit.log", `${new Date().toISOString()}: modified ${filePath}\n`);
return {};
};
for await (const message of query({
prompt: "Refactor auth.ts to use interfaces",
options: {
permissionMode: "acceptEdits",
hooks: {
PostToolUse: [{ matcher: "Edit|Write", hooks: [logFileChange] }]
}
}
})) {
if ("result" in message) console.log(message.result);
}
A PreToolUse hook returning { block: true } will prevent the tool call entirely — useful for enforcing policies like “never delete files” in automated contexts.
Step 5: Resume Work with Sessions
Sessions preserve the agent’s full context — which files it read, what it found, the conversation history — across multiple query() calls. This lets you break a long task into steps or continue work that was interrupted.
To resume a session, capture the session_id from the SystemMessage init event, then pass it to resume:
import asyncio
from claude_agent_sdk import query, ClaudeAgentOptions, SystemMessage, ResultMessage
async def main():
session_id = None
# First query: read and analyze the codebase
async for message in query(
prompt="Read the authentication module and identify all external dependencies",
options=ClaudeAgentOptions(allowed_tools=["Read", "Glob", "Grep"]),
):
if isinstance(message, SystemMessage) and message.subtype == "init":
session_id = message.data["session_id"]
# Second query: continue with full context from the first
async for message in query(
prompt="Now check if any of those dependencies have known vulnerabilities",
options=ClaudeAgentOptions(
resume=session_id,
allowed_tools=["Read", "Bash", "WebSearch"],
),
):
if isinstance(message, ResultMessage):
print(message.result)
asyncio.run(main())
The second prompt uses “those dependencies” — a reference that only makes sense because the session carries context from the first call. Without resume, Claude would have no idea what you’re referring to.
Step 6: Delegate Tasks with Subagents
Subagents are specialized agents that your main agent can invoke via the Agent tool. The main agent coordinates; subagents do focused work. Results flow back to the main context.
import asyncio
from claude_agent_sdk import query, ClaudeAgentOptions, AgentDefinition
async def main():
async for message in query(
prompt="Review this codebase: use the security-auditor agent for auth files and the style-checker agent for everything else",
options=ClaudeAgentOptions(
allowed_tools=["Read", "Glob", "Grep", "Agent"],
agents={
"security-auditor": AgentDefinition(
description="Specialist in authentication and authorization security.",
prompt="Audit auth-related code for OWASP Top 10 vulnerabilities. Be specific about line numbers and risk severity.",
tools=["Read", "Glob", "Grep"],
),
"style-checker": AgentDefinition(
description="Code style and maintainability reviewer.",
prompt="Check code for naming conventions, complexity, and documentation gaps.",
tools=["Read", "Glob"],
),
},
),
):
if hasattr(message, "result"):
print(message.result)
asyncio.run(main())
Include "Agent" in allowed_tools to pre-approve subagent invocations. Messages from a subagent include a parent_tool_use_id field so you can trace which output came from which subagent.
Step 7: Connect External Systems via MCP
Model Context Protocol (MCP) lets you add external capabilities to the agent — databases, browsers, internal APIs — without writing custom tools. The agent treats MCP tools the same as built-in tools.
This example adds browser automation via the Playwright MCP server:
import asyncio
from claude_agent_sdk import query, ClaudeAgentOptions
async def main():
async for message in query(
prompt="Open https://example.com and describe the page structure",
options=ClaudeAgentOptions(
mcp_servers={
"playwright": {
"command": "npx",
"args": ["@playwright/mcp@latest"]
}
}
),
):
if hasattr(message, "result"):
print(message.result)
asyncio.run(main())
The mcp_servers option accepts any server that follows the MCP spec. The community MCP registry at github.com/modelcontextprotocol/servers lists hundreds of integrations including Postgres, Puppeteer, Slack, GitHub, and file system variants.
Use Novita AI as the Model Backend
The Claude Agent SDK defaults to Anthropic’s API, but you can point it at Novita AI’s Anthropic-compatible endpoint to use cost-effective open-weight models — with zero code changes.
Novita AI’s endpoint mirrors the Anthropic API format:
https://api.novita.ai/anthropic
Set these two environment variables before running your agent:
export ANTHROPIC_BASE_URL="https://api.novita.ai/anthropic"
export ANTHROPIC_API_KEY="your-novita-api-key"
Your existing query() calls work without modification. The SDK reads ANTHROPIC_BASE_URL automatically.
Novita AI hosts a range of models — including Kimi K2.5, GLM 5.2, MiniMax M2.1, and Qwen 3.5 — that are accessible through this endpoint. For teams building agent pipelines that run thousands of tasks, the per-token cost difference can be significant. See Novita AI LLM API for the current model catalog and pricing.
If you need to deploy your agent to isolated sandbox infrastructure — useful for agentic code execution where you don’t want the agent touching your host filesystem — Novita Agent Sandbox provides an E2B-compatible execution environment purpose-built for agents built on the Claude Agent SDK.
Claude Code SDK in CI/CD Pipelines
The SDK’s permission_mode="acceptEdits" and allowed_tools restrictions make it practical to run agents unattended in CI. A typical GitHub Actions pattern:
- name: Run automated code review
env:
ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
run: |
python review_agent.py
Where review_agent.py contains something like:
import asyncio
from claude_agent_sdk import query, ClaudeAgentOptions
async def main():
async for message in query(
prompt="Review all changed Python files in this PR for correctness and test coverage gaps. Output a JSON report.",
options=ClaudeAgentOptions(
allowed_tools=["Read", "Glob", "Grep", "Bash"],
permission_mode="acceptEdits",
),
):
if hasattr(message, "result"):
print(message.result)
asyncio.run(main())
For agents that write back to the repo (automated refactoring, doc generation), pair this with a PostToolUse hook that validates changes before they reach git.
Troubleshooting
No matching distribution found for claude-agent-sdk
Your Python version is below 3.10. Run python3 --version and upgrade if needed.
ANTHROPIC_API_KEY is not set
The SDK requires the environment variable. Export it in your shell or .env file before running.
TypeScript agent exits before completing
Make sure you await the full iterator loop. The SDK needs to process all message events before your process exits.
Agent uses unexpected tools
Use allowed_tools to restrict the tool set explicitly. If you don’t specify it, the agent has access to all built-in tools.
Subagent messages not appearing in output
Filter for messages where parent_tool_use_id is set to identify subagent output separately from the main agent.
Session not resuming correctly
Capture session_id from the SystemMessage with subtype === "init" at the start of the first query, not from a result message.
FAQ
What is the difference between the Claude Code SDK and the Anthropic SDK?
The Claude Agent SDK (formerly Claude Code SDK) gives you an autonomous agent that handles tool execution automatically. The Anthropic Client SDK gives you raw API access where you implement the tool loop yourself. Use the Agent SDK for agentic pipelines; use the Client SDK for direct model calls with precise control.
What Python version is required for the claude-agent-sdk?
Python 3.10 or later. The package will not install on Python 3.9 or older.
Do I need to install Claude Code CLI to use the TypeScript SDK?
No. The @anthropic-ai/claude-agent-sdk package bundles its own native Claude Code binary as an optional dependency.
Can the Claude Agent SDK use models other than Anthropic’s Claude?
By setting ANTHROPIC_BASE_URL to an Anthropic-compatible endpoint like https://api.novita.ai/anthropic, you can use any model that provider hosts — including open-weight models from Kimi, GLM, MiniMax, or Qwen.
How is the Agent SDK different from Claude Managed Agents?
Managed Agents is a hosted REST API where Anthropic runs the agent in their infrastructure. The Agent SDK is a library that runs the agent loop in your own process, on your own filesystem. The Agent SDK is better for local development and agents that need to access your private files or services.
Does the Claude Agent SDK support streaming output?
The query() function returns an async iterator that yields messages as the agent works. This gives you streaming-like behavior — you see intermediate results before the final answer.
Can I use the Agent SDK with Amazon Bedrock or Vertex AI?
Yes. Set CLAUDE_CODE_USE_BEDROCK=1 plus AWS credentials for Bedrock, or CLAUDE_CODE_USE_VERTEX=1 plus Google Cloud credentials for Vertex AI.
What anthropic claude agent sdk documentation should I read first?
The official docs are at code.claude.com/docs/en/agent-sdk/overview. Start with the quickstart, then read the sessions and hooks guides once you have a working agent.
Recommended Articles
- Claude Code CLI Documentation: Setup, Slash Commands, and LLM API Integration
- Vercel AI SDK: Complete Developer Guide for Building AI Applications
- How to Deploy and Host Claude Agent SDK with Novita Sandbox
Sources checked July 3, 2026: Claude Agent SDK docs, Novita AI LLM API
