Skip to content
Complete Guide to Claude Agent SDK

Complete Guide to Claude Agent SDK

January 8, 2025·Claude CN Community·Tutorial·Claude Agent SDK, AI Agent, TypeScript, Development Tools

If you’ve used Claude Code, you’ll notice AI Agents can actually get work done: reading files, executing commands, editing code, breaking down task steps. It doesn’t just help you write code—it acts like a thoughtful engineer who can take ownership of problems and solve them incrementally.

Claude Agent SDK is the same engine powering Claude Code, now available for developers. You can use it to build your own Agents to solve any problems you want.

This is the infrastructure behind Claude Code, provided as a library. You get the complete agent loop, built-in tools, context management, and more—essentially eliminating everything you’d need to build yourself.

This guide will build a code review Agent from scratch. When complete, you’ll have a tool that can analyze codebases, find bugs and security issues, and return structured feedback.

More importantly, you’ll understand how the SDK works, enabling you to build anything you actually need.

What We’re Building

Our code review Agent will:

  1. Analyze code for bugs and security issues
  2. Autonomously read files and search code
  3. Provide structured, actionable feedback
  4. Track work progress

Tech Stack

  • Runtime - Claude Code CLI
  • SDK - @anthropic-ai/claude-agent-sdk
  • Language - TypeScript
  • Model - Claude Opus 4.5

Core Capabilities from the SDK

If you’ve built Agents with the raw API, you know the pattern: call the model, check if tools are needed, execute tools, feed results back, repeat until done. This gets tedious for anything complex.

The SDK handles this loop:

// Without SDK: you manage the loop
let response = await client.messages.create({...});
while (response.stop_reason === "tool_use") {
  const result = yourToolExecutor(response.tool_use);
  response = await client.messages.create({ tool_result: result, ... });
}

// With SDK: Claude manages it
for await (const message of query({ prompt: "Fix the bug in auth.py" })) {
  console.log(message); // Claude reads files, finds bugs, edits code
}

You also get these tools out of the box:

  • Read - Read any file in the working directory
  • Write - Create new files
  • Edit - Make precise edits to existing files
  • Bash - Run terminal commands
  • Glob - Find files by pattern
  • Grep - Search file content with regex
  • WebSearch - Search the web
  • WebFetch - Fetch and parse web pages

You don’t need to implement these yourself.

Prerequisites

  1. Install Node.js 18+
  2. Anthropic API key (get one here)

Getting Started

Step 1: Install Claude Code CLI

The Agent SDK uses Claude Code as its runtime:

npm install -g @anthropic-ai/claude-code

After installation, run claude in your terminal and follow the authentication prompts.

Step 2: Create Project

mkdir code-review-agent && cd code-review-agent
npm init -y
npm install @anthropic-ai/claude-agent-sdk
npm install -D typescript @types/node tsx

Step 3: Set API Key

export ANTHROPIC_API_KEY=your-api-key

Your First Agent

Create agent.ts:

import { query } from "@anthropic-ai/claude-agent-sdk";

async function main() {
  for await (const message of query({
    prompt: "What files are in this directory?",
    options: {
      model: "opus",
      allowedTools: ["Glob", "Read"],
      maxTurns: 250
    }
  })) {
    if (message.type === "assistant") {
      for (const block of message.message.content) {
        if ("text" in block) {
          console.log(block.text);
        }
      }
    }
    
    if (message.type === "result") {
      console.log("\nDone:", message.subtype);
    }
  }
}

main();

Run it:

npx tsx agent.ts

Claude will use the Glob tool to list files and tell you what it found.

Understanding Message Flow

The query() function returns an async generator that streams messages as Claude works. Here are the key message types:

for await (const message of query({ prompt: "..." })) {
  switch (message.type) {
    case "system":
      // Session initialization info
      if (message.subtype === "init") {
        console.log("Session ID:", message.session_id);
        console.log("Available tools:", message.tools);
      }
      break;
      
    case "assistant":
      // Claude's responses and tool calls
      for (const block of message.message.content) {
        if ("text" in block) {
          console.log("Claude:", block.text);
        } else if ("name" in block) {
          console.log("Tool call:", block.name);
        }
      }
      break;
      
    case "result":
      // Final result
      console.log("Status:", message.subtype); // "success" or error type
      console.log("Cost:", message.total_cost_usd);
      break;
  }
}

Building the Code Review Agent

Now let’s build something practical. Create review-agent.ts:

import { query } from "@anthropic-ai/claude-agent-sdk";

async function reviewCode(directory: string) {
  console.log(`\n🔍 Starting code review for: ${directory}\n`);
  
  for await (const message of query({
    prompt: `Review the code in ${directory} for:
1. Bugs and potential crashes
2. Security vulnerabilities  
3. Performance issues
4. Code quality improvements

Be specific about file names and line numbers.`,
    options: {
      model: "opus",
      allowedTools: ["Read", "Glob", "Grep"],
      permissionMode: "bypassPermissions", // Auto-approve read operations
      maxTurns: 250
    }
  })) {
    // Display Claude's analysis in real-time
    if (message.type === "assistant") {
      for (const block of message.message.content) {
        if ("text" in block) {
          console.log(block.text);
        } else if ("name" in block) {
          console.log(`\n📁 Using ${block.name}...`);
        }
      }
    }
    
    // Show completion status
    if (message.type === "result") {
      if (message.subtype === "success") {
        console.log(`\n✅ Review complete! Cost: $${message.total_cost_usd.toFixed(4)}`);
      } else {
        console.log(`\n❌ Review failed: ${message.subtype}`);
      }
    }
  }
}

// Review current directory
reviewCode(".");

Adding Structured Output

For programmatic use, you need structured data. The SDK supports JSON Schema output:

const reviewSchema = {
  type: "object",
  properties: {
    issues: {
      type: "array",
      items: {
        type: "object",
        properties: {
          severity: { type: "string", enum: ["low", "medium", "high", "critical"] },
          category: { type: "string", enum: ["bug", "security", "performance", "style"] },
          file: { type: "string" },
          line: { type: "number" },
          description: { type: "string" },
          suggestion: { type: "string" }
        },
        required: ["severity", "category", "file", "description"]
      }
    },
    summary: { type: "string" },
    overallScore: { type: "number" }
  },
  required: ["issues", "summary", "overallScore"]
};

async function reviewCodeStructured(directory: string) {
  for await (const message of query({
    prompt: `Review the code in ${directory}. Identify all issues.`,
    options: {
      model: "opus",
      allowedTools: ["Read", "Glob", "Grep"],
      permissionMode: "bypassPermissions",
      maxTurns: 250,
      outputFormat: {
        type: "json_schema",
        schema: reviewSchema
      }
    }
  })) {
    if (message.type === "result" && message.subtype === "success") {
      const review = message.structured_output;
      // Process structured results
      console.log(`\n📊 Code Review Results\n`);
      console.log(`Score: ${review.overallScore}/100`);
      // ... display issue list
    }
  }
}

Permission Handling

By default, the SDK requests approval before executing tools. You can customize this:

Permission Modes

options: {
  // Standard mode - prompt for approval
  permissionMode: "default",
  
  // Auto-approve file edits
  permissionMode: "acceptEdits",
  
  // No prompts (use cautiously)
  permissionMode: "bypassPermissions"
}

Custom Permission Handler

For fine-grained control, use canUseTool:

options: {
  canUseTool: async (toolName, input) => {
    // Allow all read operations
    if (["Read", "Glob", "Grep"].includes(toolName)) {
      return { behavior: "allow", updatedInput: input };
    }
    
    // Block writing specific files
    if (toolName === "Write" && input.file_path?.includes(".env")) {
      return { behavior: "deny", message: "Cannot modify .env files" };
    }
    
    return { behavior: "allow", updatedInput: input };
  }
}

Creating Sub-Agents

For complex tasks, you can create specialized sub-agents:

import { query, AgentDefinition } from "@anthropic-ai/claude-agent-sdk";

async function comprehensiveReview(directory: string) {
  for await (const message of query({
    prompt: `Perform a comprehensive code review of ${directory}. 
Use the security-reviewer for security issues and test-analyzer for test coverage.`,
    options: {
      model: "opus",
      allowedTools: ["Read", "Glob", "Grep", "Task"], // Task enables sub-agents
      permissionMode: "bypassPermissions",
      maxTurns: 250,
      agents: {
        "security-reviewer": {
          description: "Security specialist for vulnerability detection",
          prompt: `You are a security expert. Focus on:
- SQL injection, XSS, CSRF vulnerabilities
- Exposed credentials and secrets
- Insecure data handling
- Authentication/authorization issues`,
          tools: ["Read", "Grep", "Glob"],
          model: "sonnet"
        } as AgentDefinition
      }
    }
  })) {
    // Process messages
  }
}

Session Management

For multi-turn conversations, capture and resume sessions:

async function interactiveReview() {
  let sessionId: string | undefined;
  
  // Initial review
  for await (const message of query({
    prompt: "Review this codebase and identify the top 3 issues",
    options: {
      model: "opus",
      allowedTools: ["Read", "Glob", "Grep"],
      maxTurns: 250
    }
  })) {
    if (message.type === "system" && message.subtype === "init") {
      sessionId = message.session_id;
    }
  }
  
  // Follow-up using same session
  if (sessionId) {
    for await (const message of query({
      prompt: "Now show me how to fix the most critical issue",
      options: {
        resume: sessionId, // Continue conversation
        allowedTools: ["Read", "Glob", "Grep"],
        maxTurns: 250
      }
    })) {
      // Claude remembers previous context
    }
  }
}

Using Hooks

Hooks let you intercept and customize agent behavior:

import { HookCallback, PreToolUseHookInput } from "@anthropic-ai/claude-agent-sdk";

const auditLogger: HookCallback = async (input, toolUseId, { signal }) => {
  if (input.hook_event_name === "PreToolUse") {
    const preInput = input as PreToolUseHookInput;
    console.log(`[AUDIT] ${new Date().toISOString()} - ${preInput.tool_name}`);
  }
  return {}; // Allow operation
};

const blockDangerousCommands: HookCallback = async (input, toolUseId, { signal }) => {
  if (input.hook_event_name === "PreToolUse") {
    const preInput = input as PreToolUseHookInput;
    if (preInput.tool_name === "Bash") {
      const command = (preInput.tool_input as any).command || "";
      if (command.includes("rm -rf") || command.includes("sudo")) {
        return {
          hookSpecificOutput: {
            hookEventName: "PreToolUse",
            permissionDecision: "deny",
            permissionDecisionReason: "Dangerous command blocked"
          }
        };
      }
    }
  }
  return {};
};

Adding Custom Tools with MCP

Extend Claude with custom tools via Model Context Protocol:

import { tool, createSdkMcpServer } from "@anthropic-ai/claude-agent-sdk";
import { z } from "zod";

// Create custom tool
const customServer = createSdkMcpServer({
  name: "code-metrics",
  version: "1.0.0",
  tools: [
    tool(
      "analyze_complexity",
      "Calculate cyclomatic complexity for a file",
      {
        filePath: z.string().describe("Path to the file to analyze")
      },
      async (args) => {
        // Your complexity analysis logic
        const complexity = calculateComplexity(args.filePath);
        return {
          content: [{
            type: "text",
            text: `Cyclomatic complexity for ${args.filePath}: ${complexity}`
          }]
        };
      }
    )
  ]
});

// Use custom tool
for await (const message of query({
  prompt: generateMessages(),
  options: {
    model: "opus",
    mcpServers: {
      "code-metrics": customServer
    },
    allowedTools: ["Read", "mcp__code-metrics__analyze_complexity"],
    maxTurns: 250
  }
})) {
  // ...
}

Cost Tracking

Track API costs for billing:

for await (const message of query({ prompt: "..." })) {
  if (message.type === "result" && message.subtype === "success") {
    console.log("Total cost:", message.total_cost_usd);
    console.log("Token usage:", message.usage);
    
    // Breakdown by model (useful for sub-agents)
    for (const [model, usage] of Object.entries(message.modelUsage)) {
      console.log(`${model}: $${usage.costUSD.toFixed(4)}`);
    }
  }
}

Next Steps

The code review Agent covers core features: query(), allowedTools, structured output, sub-agents, and permission management.

To dive deeper:

More Features

Production Deployment

Complete Reference

References

This guide is based on SDK V1. V2 is currently in development and this guide will be updated once stable.