Claude Code: Agent SDK
Last updated: 2026-08-31
The Agent SDK turns Claude Code's capabilities into a programmable API — embed AI coding abilities in your applications, build custom AI workflows.
💡 Tip: The Agent SDK doesn't make Claude Code an API server; it provides an SDK to call Claude Code's Agent capabilities in your code — file read/write, code generation, test execution, etc.
📋 Prerequisites: Chapter 23 - Git Workflow and GitHub Actions
1. What You'll Learn
- Agent SDK positioning and architecture
- SDK installation and basic usage
- Core API overview
- Custom Agent building
- SDK vs CLI distinction
2. Agent SDK Architecture
(1) SDK vs CLI
| Dimension | CLI | SDK |
|---|---|---|
| Usage | Terminal command | Code invocation |
| Interaction | Human conversation | Programming interface |
| Customizability | Limited | Fully customizable |
| Integration | Pipeline/scripts | Deep embedding |
| Use case | Daily development | Building AI applications |
▶ Example 1: SDK Basic Usage
TYPESCRIPT
import { Agent } from "@anthropic-ai/claude-code-sdk";
const agent = new Agent({
apiKey: process.env.ANTHROPIC_API_KEY,
model: "claude-sonnet-4-20250514",
workingDir: "./my-project",
});
const result = await agent.run("Add user login with JWT authentication");
console.log(result.summary);
console.log(`Files modified: ${result.files.length}`);
console.log(`Tests passed: ${result.testsPassed}`);
3. Core API
(1) Agent Creation and Configuration
TYPESCRIPT
const agent = new Agent({
apiKey: "sk-ant-api03-xxxxx",
model: "claude-sonnet-4-20250514",
workingDir: "/path/to/project",
tools: ["Read", "Write", "Bash"],
maxTurns: 30,
style: "concise",
});
(2) Execute Tasks
TYPESCRIPT
// Basic execution
const result = await agent.run("Fix all TypeScript errors");
// Streaming execution
const stream = agent.runStream("Refactor auth module");
for await (const event of stream) {
console.log(event.type, event.data);
}
// With context
const result = await agent.run("Modify this function", {
files: ["src/auth/jwt.ts"],
context: "Use RS256 instead of HS256",
});
(3) Result Handling
TYPESCRIPT
interface AgentResult {
summary: string;
files: FileChange[];
commands: CommandResult[];
testsPassed: number;
testsFailed: number;
tokensUsed: number;
cost: number;
}
▶ Example 2: Custom Workflow
TYPESCRIPT
async function reviewAndFix(projectDir: string) {
const agent = new Agent({
apiKey: process.env.ANTHROPIC_API_KEY!,
workingDir: projectDir,
tools: ["Read", "Write", "Bash"],
});
// Step 1: Code review
const review = await agent.run(
"Review project code quality, list all issues to fix"
);
// Step 2: Auto-fix
if (review.summary.includes("issue")) {
const fix = await agent.run("Fix all listed quality issues, run tests");
console.log(`Tests: ${fix.testsPassed} passed, ${fix.testsFailed} failed`);
}
}
4. Custom Agent
(1) Custom Tools
TYPESCRIPT
const databaseQueryTool: Tool = {
name: "database_query",
description: "Execute a read-only SQL query",
parameters: {
sql: { type: "string", description: "SQL query (SELECT only)" },
},
execute: async ({ sql }) => {
if (!sql.trim().toUpperCase().startsWith("SELECT")) {
throw new Error("Only SELECT queries allowed");
}
const result = await db.query(sql);
return { rows: result.rows, count: result.rowCount };
},
};
const agent = new Agent({
apiKey: process.env.ANTHROPIC_API_KEY!,
tools: ["Read", "Write", databaseQueryTool],
});
(2) Event Listening
TYPESCRIPT
agent.on("file:write", (data) => {
console.log(`Modified: ${data.filePath}`);
auditLog.record(data);
});
agent.on("bash:execute", (data) => {
if (data.command.includes("DROP")) {
throw new Error("Dangerous command blocked");
}
});
▶ Example 3: Code Review Bot
TYPESCRIPT
class CodeReviewBot {
private agent: Agent;
constructor(apiKey: string) {
this.agent = new Agent({
apiKey,
model: "claude-sonnet-4-20250514",
tools: ["Read", "Bash"],
});
}
async reviewPR(repoDir: string, prDiff: string) {
this.agent.setWorkingDir(repoDir);
const result = await this.agent.run(
`Review PR changes:\n${prDiff}\n\nCheck security, performance, style, test coverage`
);
return { review: result.summary, score: this.calculateScore(result.summary) };
}
private calculateScore(text: string): number {
let score = 100;
if (text.includes("critical")) score -= 30;
if (text.includes("warning")) score -= 10;
return Math.max(0, score);
}
}
5. SDK vs CLI Collaboration
| Scenario | CLI | SDK |
|---|---|---|
| Daily development | ✅ | ❌ |
| CI/CD | ✅ (headless) | ✅ |
| Custom tools | ❌ | ✅ |
| Web app integration | ❌ | ✅ |
| Batch automation | ⚠️ (scripts) | ✅ |
❓ FAQ
Q Does SDK require separate CLI install?
A No. SDK is an independent npm package. Both share the same API Key.
Q Is the SDK API stable?
A Core API is stable, but details may change with versions. Lock version numbers, watch changelog.
Q Can SDK run in browser?
A No. Needs Node.js environment; involves filesystem and Shell operations.
Q Same pricing as CLI?
A Yes. Both call Anthropic API with same billing.
📖 Summary
- Agent SDK provides programming interface for Claude Code capabilities in code
- Core API: create Agent, execute tasks, handle results, event listening
- Custom tools, event hooks, complete workflow construction
- CLI for daily dev, SDK for custom apps and deep integration
- Both share API Key and billing
📝 Exercises
- Basic (⭐): Create an Agent with SDK, execute a simple task, print results.
- Intermediate (⭐⭐): Build an auto code review script with structured output.
- Advanced (⭐⭐⭐): Build a code review bot integrated with GitHub Webhook for auto PR review.