Skip to content

Agent SDK

The Agent SDK lets you control Claude Code programmatically from TypeScript or Python. You can spawn sessions, send prompts, stream results, and build custom orchestration that goes beyond what workflows and subagents can express. This lesson covers the SDK basics and when to reach for it.

Owl mascot

What you'll learn

  • The Agent SDK provides programmatic control over Claude Code sessions from TypeScript or Python
  • Use it when you need custom orchestration logic that workflows can't express, or when integrating Claude Code into an existing application
  • The SDK supports streaming, structured output, session management, and custom tool registration

The problem

Workflows handle fan-out and cross-checking. Subagents handle delegation. But sometimes you need Claude Code embedded in your own application, a custom code review pipeline, a chat interface, or an automation that calls Claude Code as one step in a larger process. The Agent SDK gives you that control.

Options & when to use each

ApproachGood forWhen to use it
WorkflowsFan-out, cross-checking, scaleWhen the task needs many agents and the orchestration pattern is fan-out-and-merge
SubagentsDelegation within a sessionWhen Claude should decide what to delegate
Agent SDKProgrammatic control, custom appsWhen you need to embed Claude Code in your own codebase

Build it

Step 1: Install the SDK

Install the @anthropic-ai/claude-code package from npm to gain access to the SDK. This package provides the TypeScript client needed to control sessions programmatically.

bash
npm install @anthropic-ai/claude-code

Step 2: Basic usage

Instantiate the ClaudeCode class with your Anthropic API key and target model. You can then invoke the prompt method to dispatch tasks with defined constraints like maximum turns and allowed tools.

typescript
import { ClaudeCode } from '@anthropic-ai/claude-code';

const claude = new ClaudeCode({
  apiKey: process.env.ANTHROPIC_API_KEY,
  model: 'claude-sonnet-4-6',
});

const result = await claude.prompt(
  'Review the auth module for security issues',
  { maxTurns: 10, allowedTools: ['Read', 'Grep'] }
);

console.log(result.response);

Step 3: Streaming output

When building interactive applications, use promptStream to receive chunks of the response as they are generated. This allows you to render the output in real-time or process it progressively.

typescript
const stream = await claude.promptStream(
  'Refactor the database layer',
  { maxTurns: 15 }
);

for await (const chunk of stream) {
  process.stdout.write(chunk);
}

Step 4: Session management

You can persist and retrieve ongoing sessions by their unique ID, enabling async workflows. Branching is also supported by forking an active session, which duplicates the context for parallel tasks.

typescript
// Resume a session
const session = await claude.resume(sessionId);
const result = await session.prompt('Continue from where you left off');

// Fork a session
const forked = await session.fork();

What goes wrong

MistakeHow you notice itThe fix
SDK version mismatch with CLISDK methods fail with unexpected errorsKeep the SDK and CLI versions in sync. Check claude --version and match the SDK version
Session timeoutLong-running sessions disconnectSessions last 5 hours. For longer tasks, break into multiple sessions with checkpointing
Permission errors in SDKTool calls get deniedSDK sessions inherit the same permission model. Configure permissionMode in the SDK options

Confirm it worked

Verify the installation and authentication by writing a minimal script that invokes a basic prompt. Execute the script locally to ensure the API key is valid and the client can establish a connection.

bash
# Create a minimal test script
cat > /tmp/test-sdk.js << 'EOF'
import { ClaudeCode } from '@anthropic-ai/claude-code';
const claude = new ClaudeCode({ apiKey: process.env.ANTHROPIC_API_KEY });
const result = await claude.prompt('Say hello', { maxTurns: 1 });
console.log(result.response);
EOF

# Run it
ANTHROPIC_API_KEY=your-key node /tmp/test-sdk.js

Next: Routines & Scheduled Tasks