π€ Claude Agent SDK (TypeScript/JavaScript) Cheatsheet
Important: The Claude Code SDK has been renamed to Claude Agent SDK. Package:
@anthropic-ai/claude-agent-sdk
π¦ Installation & Setup
npm install @anthropic-ai/claude-agent-sdk# Set your API key
export ANTHROPIC_API_KEY=your-api-keyπ Core Functions
query() - Primary Agent Function
Creates an async generator that streams messages from Claude.
import { query } from '@anthropic-ai/claude-agent-sdk';
// Basic usage
for await (const message of query({
prompt: 'Find and fix bugs in auth.py',
options: {
allowedTools: ['Read', 'Edit', 'Bash'],
},
})) {
console.log(message);
}tool() - Create Type-Safe MCP Tools
Define custom tools for MCP servers.
import { tool } from '@anthropic-ai/claude-agent-sdk';
import { z } from 'zod';
const myTool = tool(
'my_tool',
'Description of what the tool does',
z.object({
param1: z.string(),
param2: z.number(),
}),
async (args, extra) => {
return { content: [{ type: 'text', text: 'Result' }] };
},
);createSdkMcpServer() - Create In-Process MCP Server
Create MCP servers that run in your application process.
import { createSdkMcpServer } from '@anthropic-ai/claude-agent-sdk';
const mcpServer = createSdkMcpServer({
name: 'my-server',
version: '1.0.0',
tools: [myTool],
});βοΈ Configuration Options
interface Options {
// Core
abortController?: AbortController;
additionalDirectories?: string[];
cwd?: string;
// Tools & Permissions
allowedTools?: string[];
disallowedTools?: string[];
canUseTool?: CanUseTool;
permissionMode?: PermissionMode;
allowDangerouslySkipPermissions?: boolean;
// Model & Budget
model?: string;
fallbackModel?: string;
maxBudgetUsd?: number;
maxThinkingTokens?: number;
// Settings Sources (filesystem-based config)
settingSources?: SettingSource[]; // 'user' | 'project' | 'local'
// System Prompt
systemPrompt?: string | { type: 'preset'; preset: 'claude_code'; append?: string };
// MCP & Plugins
mcpServers?: Record<string, McpServerConfig>;
plugins?: SdkPluginConfig[];
// Subagents
agents?: Record<string, AgentDefinition>;
// Hooks
hooks?: Partial<Record<HookEvent, HookCallbackMatcher[]>>;
// Advanced
betas?: SdkBeta[];
continue?: boolean;
enableFileCheckpointing?: boolean;
env?: Record<string, string>;
executable?: 'bun' | 'deno' | 'node';
forkSession?: boolean;
includePartialMessages?: boolean;
maxTurns?: number;
outputFormat?: { type: 'json_schema'; schema: JSONSchema };
resume?: string;
resumeSessionAt?: string;
sandbox?: SandboxSettings;
stderr?: (data: string) => void;
strictMcpConfig?: boolean;
tools?: string[] | { type: 'preset'; preset: 'claude_code' };
}π― Permission Modes
type PermissionMode =
| 'default' // Standard permission behavior
| 'acceptEdits' // Auto-accept file edits
| 'bypassPermissions' // Bypass all permission checks
| 'plan'; // Planning mode - no executionExample:
const result = await query({
prompt: 'Review this PR',
options: {
permissionMode: 'acceptEdits', // Auto-approve edits
allowedTools: ['Read', 'Edit', 'Grep'],
},
});π Setting Sources (Filesystem Config)
type SettingSource = 'user' | 'project' | 'local';// Load all settings (legacy behavior)
settingSources: ['user', 'project', 'local'];
// Load only project settings (for CI)
settingSources: ['project'];
// No settings (default - isolated)
settingSources: []; // or omit entirelySetting Locations:
user:~/.claude/settings.jsonproject:.claude/settings.json(version controlled)local:.claude/settings.local.json(gitignored)
Note: SettingSources includes 'project' to load CLAUDE.md files!
π§ Built-in Tools
| Tool Name | Description |
|---|---|
Read |
Read files (text, images, PDFs, Jupyter notebooks) |
Write |
Write/overwrite files |
Edit |
Perform exact string replacements in files |
Bash |
Execute bash commands |
BashOutput |
Retrieve output from background shells |
Glob |
Fast file pattern matching |
Grep |
Powerful regex-based file search |
WebSearch |
Search the web |
WebFetch |
Fetch and analyze web content |
Task |
Launch subagent for complex tasks |
AskUserQuestion |
Ask clarifying questions |
NotebookEdit |
Edit Jupyter notebook cells |
TodoWrite |
Create/manage task lists |
ExitPlanMode |
Exit planning mode |
πͺ Hooks System
type HookEvent =
| 'PreToolUse' // Before tool execution
| 'PostToolUse' // After successful tool use
| 'PostToolUseFailure' // After tool error
| 'Notification' // Display notification
| 'UserPromptSubmit' // Before prompt submission
| 'SessionStart' // When session starts
| 'SessionEnd' // When session ends
| 'Stop' // When execution stops
| 'SubagentStart' // Before subagent launch
| 'SubagentStop' // After subagent completes
| 'PreCompact' // Before context compaction
| 'PermissionRequest'; // Before permission checkExample:
const result = await query({
prompt: 'Build the project',
options: {
hooks: {
PreToolUse: [
{
hooks: [
async (input, toolUseId, { signal }) => {
console.log(`Tool ${input.tool_name} called`);
return { continue: true };
},
],
},
],
},
},
});π MCP Server Configuration
type McpServerConfig =
| McpStdioServerConfig // Command-based MCP server
| McpSSEServerConfig // SSE-based MCP server
| McpHttpServerConfig // HTTP-based MCP server
| McpSdkServerConfigWithInstance; // In-process MCP server
// Example: stdio MCP server
const stdioConfig = {
type: 'stdio' as const,
command: 'node',
args: ['server.js'],
env: { MY_VAR: 'value' },
};
// Example: SSE MCP server
const sseConfig = {
type: 'sse' as const,
url: 'https://api.example.com/mcp',
headers: { Authorization: 'Bearer token' },
};ποΈ Subagents
type AgentDefinition = {
description: string; // When to use this agent
tools?: string[]; // Allowed tools (inherits all if omitted)
prompt: string; // System prompt
model?: 'sonnet' | 'opus' | 'haiku' | 'inherit';
};Example:
const result = await query({
prompt: 'Review the security of this code',
options: {
agents: {
'security-reviewer': {
description: 'Use for security audits and code review',
prompt: 'You are a security expert. Identify vulnerabilities...',
tools: ['Read', 'Grep', 'Bash'],
},
},
},
});πͺ Sandbox Settings
type SandboxSettings = {
enabled?: boolean; // Enable sandbox mode
autoAllowBashIfSandboxed?: boolean; // Auto-approve sandboxed bash
excludedCommands?: string[]; // Commands that bypass sandbox
allowUnsandboxedCommands?: boolean; // Model can request unsandboxed
network?: NetworkSandboxSettings; // Network restrictions
ignoreViolations?: SandboxIgnoreViolations; // Violations to ignore
enableWeakerNestedSandbox?: boolean; // Enable weaker nested sandbox
};Example:
const result = await query({
prompt: 'Run tests in sandbox',
options: {
sandbox: {
enabled: true,
autoAllowBashIfSandboxed: true,
excludedCommands: ['docker'],
network: {
allowLocalBinding: true,
allowUnixSockets: ['/var/run/docker.sock'],
},
},
},
});π Message Types
type SDKMessage =
| SDKAssistantMessage // Claude's response
| SDKUserMessage // User input
| SDKUserMessageReplay // Replayed user message
| SDKResultMessage // Final result
| SDKSystemMessage // System init
| SDKPartialAssistantMessage // Streaming partial
| SDKCompactBoundaryMessage; // Context compactionResult Message Structure:
type SDKResultMessage = {
type: 'result';
subtype: 'success' | 'error_*';
uuid: string;
session_id: string;
duration_ms: number;
is_error: boolean;
num_turns: number;
result: string;
total_cost_usd: number;
usage: NonNullableUsage;
modelUsage: Record<string, ModelUsage>;
permission_denials: SDKPermissionDenial[];
structured_output?: unknown;
};π Migration from Claude Code SDK
# 1. Uninstall old package
npm uninstall @anthropic-ai/claude-code
# 2. Install new package
npm install @anthropic-ai/claude-agent-sdk// OLD import
import { query, tool, createSdkMcpServer } from '@anthropic-ai/claude-code';
// NEW import
import { query, tool, createSdkMcpServer } from '@anthropic-ai/claude-agent-sdk';Breaking Changes
- System prompt no longer defaults to Claude Code's prompt
// OLD: Used Claude Code system prompt by default
const result = query({ prompt: 'Hello' });
// NEW: Empty system prompt by default
const result = query({
prompt: 'Hello',
options: {
systemPrompt: { type: 'preset', preset: 'claude_code' },
},
});- Settings no longer loaded by default
// OLD: Loaded all settings automatically
const result = query({ prompt: 'Hello' });
// NEW: No settings by default
const result = query({
prompt: 'Hello',
options: {
settingSources: ['user', 'project', 'local'],
},
});π― Common Patterns
File Checkpointing
const result = await query({
prompt: 'Make changes to files',
options: {
enableFileCheckpointing: true,
},
});
// Later, if needed:
result.rewindFiles(userMessageUuid);Structured Output
const result = await query({
prompt: 'Analyze and return JSON',
options: {
outputFormat: {
type: 'json_schema',
schema: {
type: 'object',
properties: {
summary: { type: 'string' },
issues: { type: 'array' },
},
},
},
},
});Budget Control
const result = await query({
prompt: 'Process large codebase',
options: {
maxBudgetUsd: 5.0, // Maximum $5 spend
},
});π Query Interface Methods
interface Query extends AsyncGenerator<SDKMessage, void> {
interrupt(): Promise<void>;
rewindFiles(userMessageUuid: string): Promise<void>;
setPermissionMode(mode: PermissionMode): Promise<void>;
setModel(model?: string): Promise<void>;
setMaxThinkingTokens(maxThinkingTokens: number | null): Promise<void>;
supportedCommands(): Promise<SlashCommand[]>;
supportedModels(): Promise<ModelInfo[]>;
mcpServerStatus(): Promise<McpServerStatus[]>;
accountInfo(): Promise<AccountInfo>;
}π Quick Reference
| Task | Code |
|---|---|
| Install | npm install @anthropic-ai/claude-agent-sdk |
| Basic Query | query({ prompt: "..." }) |
| With Tools | query({ prompt: "...", options: { allowedTools: ['Read', 'Edit'] } }) |
| With Custom System Prompt | query({ options: { systemPrompt: "You are..." } }) |
| Load Project Settings | query({ options: { settingSources: ['project'] } }) |
| Enable Sandbox | query({ options: { sandbox: { enabled: true } } }) |
| Add Hooks | query({ options: { hooks: { 'PreToolUse': [...] } } }) |
| Create Tool | tool(name, description, schema, handler) |
| Create MCP Server | createSdkMcpServer({ name, tools }) |
π Links
- Agent SDK Overview
- TypeScript API Reference
- Migration Guide
- Anthropic TypeScript SDK
- Claude Code CLI
π‘ Pro Tip: The Claude Agent SDK is powerful for building autonomous agents that can read files, run commands, search the web, and edit code - all with built-in tool execution!