Use the Claude Code SDK (Agent SDK) to build custom AI coding agents, automate development workflows, and embed Claude Code in your applications programmatically.
Updated Feb 202610 min readAdvanced
What is the Claude Code SDK?
The Claude Code SDK (also known as the Agent SDK) lets you use Claude Code programmatically from TypeScript or JavaScript. Instead of running claude in a terminal interactively, you call it from your code:
example.ts
import { claude } from "@anthropic-ai/claude-code";
const result = await claude({
prompt: "Find all TODO comments in this project and create issues for them",
options: {
maxTurns: 20,
model: "claude-sonnet-4-6",
},
});
console.log(result.text);
The SDK gives your application the same powers as the Claude Code CLI: file editing, code search, bash execution, git operations, and multi-turn reasoning. But now you control the workflow programmatically.
SDK vs Anthropic API vs CLI
Feature
Anthropic API
Claude Code CLI
Claude Code SDK
Interface
HTTP / Python / TS
Terminal (interactive)
TypeScript / JavaScript
File editing
Manual (you build it)
Built-in
Built-in
Bash execution
Manual
Built-in
Built-in
Code search
Manual
Built-in (Glob, Grep)
Built-in
Git integration
Manual
Built-in
Built-in
Multi-turn
Manual loop
Automatic
Automatic
Subagents
Not available
Built-in (Task tool)
Built-in
Embeddable
Yes
CLI only
Yes
Best for
Chat apps, general AI
Interactive coding
Automated agents, CI/CD
When to use the SDK vs CLI
Use the CLI for interactive development (you're coding alongside Claude). Use the SDK when you want Claude to work autonomously — in scripts, CI/CD, bots, or custom tools.
Quick Start
Installation
$ npm install @anthropic-ai/claude-code
Basic Usage
agent.ts
import { claude } from "@anthropic-ai/claude-code";
// Simple one-shot task
const result = await claude({
prompt: "Add error handling to all API endpoints in src/api/",
options: {
maxTurns: 30,
model: "claude-sonnet-4-6",
allowedTools: ["Read", "Edit", "Write", "Glob", "Grep", "Bash"],
},
});
// result.text - Claude's final response
// result.cost - total token cost
// result.turns - number of turns taken
Streaming Responses
stream.ts
import { claude } from "@anthropic-ai/claude-code";
const stream = claude.stream({
prompt: "Refactor the user authentication module",
options: { maxTurns: 20 },
});
for await (const event of stream) {
if (event.type === "text") {
process.stdout.write(event.text);
} else if (event.type === "tool_use") {
console.log(`\n[Using tool: ${event.name}]`);
}
}
Core API
claude() Function
API Signature
const result = await claude({
// Required
prompt: string, // The task for Claude
// Optional
options: {
model?: string, // "claude-sonnet-4-6" (default), "claude-opus-4-6", etc.
maxTurns?: number, // Max agentic turns (default: 50)
systemPrompt?: string, // Additional system instructions
allowedTools?: string[], // Tools Claude can use
deniedTools?: string[], // Tools to block
workingDirectory?: string, // Project directory
env?: Record<string, string>, // Environment variables
timeout?: number, // Max execution time in ms
},
// Callbacks
onText?: (text: string) => void,
onToolUse?: (tool: string, input: any) => void,
onToolResult?: (tool: string, result: any) => void,
});
Result Object
Result structure
{
text: string, // Claude's final text response
turns: number, // Number of agentic turns
cost: {
inputTokens: number,
outputTokens: number,
totalCost: number, // USD
},
toolUses: Array<{
tool: string,
input: any,
result: any,
}>,
}
Available Tools
The SDK provides the same tools as the CLI:
Tool
Description
Use For
Read
Read files from the filesystem
Understanding code, reading configs
Edit
Make precise edits to existing files
Bug fixes, refactoring, adding features
Write
Create new files
New components, configs, tests
Glob
Find files by pattern
Discovering project structure
Grep
Search file contents
Finding usages, patterns, TODOs
Bash
Execute shell commands
Git, npm, tests, builds
Task
Launch subagent tasks
Parallel work, specialized agents
Restricting tools
// Read-only agent (can analyze but not modify)
const result = await claude({
prompt: "Review this codebase for security issues",
options: {
allowedTools: ["Read", "Glob", "Grep"],
// No Edit, Write, or Bash = read-only
},
});
// Specific bash commands only
const result = await claude({
prompt: "Run the test suite and fix any failures",
options: {
allowedTools: ["Read", "Edit", "Glob", "Grep", "Bash"],
deniedTools: ["Bash(rm *)", "Bash(git push*)"],
},
});
Building Custom Agents
Code Review Agent
agents/reviewer.ts
import { claude } from "@anthropic-ai/claude-code";
export async function reviewPR(prDiff: string) {
const result = await claude({
prompt: `Review this pull request diff for bugs, security issues,
and code quality problems. Be concise and actionable.
Only report significant issues, not style nits.
Diff:
${prDiff}`,
options: {
model: "claude-sonnet-4-6",
maxTurns: 10,
allowedTools: ["Read", "Glob", "Grep"], // Read-only
systemPrompt: `You are a senior code reviewer. Focus on:
1. Bugs and logic errors
2. Security vulnerabilities (OWASP Top 10)
3. Performance issues (N+1 queries, memory leaks)
4. Missing error handling`,
},
});
return result.text;
}
Migration Agent
agents/migrator.ts
import { claude } from "@anthropic-ai/claude-code";
export async function migrateToTypeScript(directory: string) {
const result = await claude({
prompt: `Migrate all JavaScript files in this project to TypeScript.
For each .js file:
1. Rename to .ts or .tsx
2. Add type annotations
3. Fix any type errors
4. Update imports
Run tsc --noEmit after each file to verify no errors.`,
options: {
maxTurns: 100,
model: "claude-sonnet-4-6",
workingDirectory: directory,
},
});
return {
summary: result.text,
filesChanged: result.toolUses
.filter(t => t.tool === "Edit" || t.tool === "Write")
.length,
cost: result.cost.totalCost,
};
}
Test Generator Agent
agents/test-writer.ts
import { claude } from "@anthropic-ai/claude-code";
export async function generateTests(sourceFile: string) {
const result = await claude({
prompt: `Read ${sourceFile} and write comprehensive tests for it.
Use the existing test framework (check package.json).
Include edge cases, error paths, and happy paths.
Run the tests to verify they pass.`,
options: {
maxTurns: 30,
systemPrompt: `You are a testing expert. Write thorough,
maintainable tests. Use describe/it pattern.
Mock external dependencies. Test behavior, not implementation.`,
},
});
return result.text;
}
Multi-Agent Systems
Build systems where multiple Claude agents collaborate:
multi-agent.ts
import { claude } from "@anthropic-ai/claude-code";
async function developFeature(issueDescription: string) {
// Agent 1: Plan the implementation
const plan = await claude({
prompt: `Read the codebase and create a detailed plan
for implementing: ${issueDescription}
List the files to create/modify and the approach.`,
options: {
maxTurns: 15,
allowedTools: ["Read", "Glob", "Grep"], // Read-only
},
});
// Agent 2: Implement the plan
const implementation = await claude({
prompt: `Implement this plan:
${plan.text}
Write clean, tested code following project conventions.`,
options: {
maxTurns: 50,
model: "claude-sonnet-4-6",
},
});
// Agent 3: Review the implementation
const review = await claude({
prompt: `Review all changes made by the previous agent.
Check for bugs, missing edge cases, and test coverage.
Fix any issues you find.`,
options: {
maxTurns: 20,
},
});
return {
plan: plan.text,
implementation: implementation.text,
review: review.text,
totalCost: plan.cost.totalCost
+ implementation.cost.totalCost
+ review.cost.totalCost,
};
}
Specialized agents are more effective
Rather than one agent doing everything, split work into focused agents: planner, implementer, reviewer, tester. Each can use a different model (Opus for planning, Sonnet for implementation, Haiku for simple checks).
Use Cases & Examples
🤖
CI/CD Bot
Auto-review PRs, fix CI failures, and generate changelogs
Auto-generate API docs, READMEs, architecture diagrams
🛠
Internal Tools
Custom CLI tools, Slack bots, internal portals with AI
Deployment & Production
Environment Variables
.env
ANTHROPIC_API_KEY=sk-ant-api03-...
ANTHROPIC_MAX_SPEND=50 # Monthly budget cap in USD
Error Handling
production.ts
import { claude } from "@anthropic-ai/claude-code";
try {
const result = await claude({
prompt: task,
options: {
maxTurns: 30,
timeout: 300000, // 5 minute timeout
},
});
if (result.cost.totalCost > 5.0) {
console.warn(`High cost session: $${result.cost.totalCost}`);
}
return result;
} catch (error) {
if (error.code === "rate_limit") {
// Retry with exponential backoff
await sleep(5000);
return retry(task);
}
if (error.code === "max_turns_exceeded") {
// Task was too complex
return { error: "Task exceeded turn limit" };
}
throw error;
}
Docker Deployment
Dockerfile
FROM node:22-slim
WORKDIR /app
COPY package*.json ./
RUN npm ci
COPY . .
RUN npm run build
ENV NODE_ENV=production
CMD ["node", "dist/agent.js"]
See the Docker Guide for detailed container setup including sandboxing and resource limits.
Frequently Asked Questions
How much does the SDK cost to use?
The SDK itself is free. You pay for Claude model usage via the Anthropic API (per-token pricing). A typical agent run costs $0.05-$2.00 depending on complexity. See the Pricing Guide for detailed cost breakdowns.
Can I use the SDK with Python?
The SDK is TypeScript/JavaScript native. For Python, you can either: (1) Use subprocess to call the claude CLI with --output-format json, or (2) Use the Anthropic Python SDK (anthropic package) and build your own tool loop. The official Python SDK for Claude Code agents is under development.
Is the SDK the same as the Anthropic SDK?
No. The Anthropic SDK (@anthropic-ai/sdk) is a thin client for the Messages API — raw model access. The Claude Code SDK (@anthropic-ai/claude-code) includes the full agentic framework with file editing, code search, bash execution, and multi-turn orchestration.
Can I run the SDK in the browser?
No. The SDK requires Node.js because it accesses the filesystem, executes bash commands, and manages subprocesses. It's designed for server-side, CLI, and CI/CD environments.
How do I test my custom agents?
Create test repositories with known issues, run your agents against them, and verify the outputs. Use maxTurns: 5 and model: "claude-haiku-4-5" for cheap, fast test runs. Compare results against expected outputs.