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


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


📝 Exercises

  1. Basic (⭐): Create an Agent with SDK, execute a simple task, print results.
  2. Intermediate (⭐⭐): Build an auto code review script with structured output.
  3. Advanced (⭐⭐⭐): Build a code review bot integrated with GitHub Webhook for auto PR review.
Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏