Claude Code API Reference
This comprehensive API reference documents all types, interfaces, and methods available in the @anthropic-ai/claude-code TypeScript SDK (v1.0.56).
Table of Contents
- Core API
- Message Types
- Query Parameters
- Built-in Tools
- Error Types
- Advanced Patterns
- MCP Integration
Core API
Main Query Function
import { query, type QueryParams, type SDKMessage } from "@anthropic-ai/claude-code";
async function* query(params: QueryParams): AsyncGenerator<SDKMessage>The query function is the primary interface for interacting with Claude Code. It returns an async generator that yields messages as they’re received.
Type Definitions
The SDK provides comprehensive TypeScript type definitions for all API interfaces and methods.
Installation
# Global CLI installation
npm install -g @anthropic-ai/claude-code
# Project SDK installation
npm install @anthropic-ai/claude-code
npm install --save-dev @types/node typescriptMessage Types
SDKMessage Union Type
type SDKMessage =
| AssistantMessage
| UserMessage
| ResultMessage
| SystemMessage;AssistantMessage
Claude’s responses containing generated content:
interface AssistantMessage {
type: 'assistant';
data: {
message: {
role: 'assistant';
content: string | ContentBlock[];
};
conversation_id?: string;
turn_number?: number;
};
}
// Content blocks for structured responses
type ContentBlock =
| TextBlock
| ToolUseBlock
| ToolResultBlock;
interface TextBlock {
type: 'text';
text: string;
}
interface ToolUseBlock {
type: 'tool_use';
id: string;
name: string;
input: Record<string, any>;
}
interface ToolResultBlock {
type: 'tool_result';
tool_use_id: string;
content: string;
is_error?: boolean;
}UserMessage
User prompts echoed back:
interface UserMessage {
type: 'user';
data: {
message: {
role: 'user';
content: string;
};
};
}ResultMessage
Operation results with metadata:
interface ResultMessage {
type: 'result';
data: {
result: 'success' | 'error';
error?: {
message: string;
code?: string;
details?: any;
};
total_cost_usd?: number;
total_time_ms?: number;
tokens_used?: {
input: number;
output: number;
total: number;
};
turn_count?: number;
stop_reason?: 'max_turns' | 'stop_sequence' | 'end_turn';
};
}SystemMessage
System initialization and configuration:
interface SystemMessage {
type: 'system';
data: {
subtype: 'init';
configuration: {
model: string;
max_turns: number;
permission_mode: string;
working_directory: string;
};
tools: string[];
capabilities: string[];
timestamp: string;
apiKeySource: string;
cwd: string;
session_id: string;
mcp_servers: {
name: string;
status: string;
}[];
permissionMode: 'default' | 'acceptEdits' | string;
};
}Query Parameters
QueryParams Interface
interface QueryParams {
// Required: The prompt to send to Claude
prompt: string;
// Required: Controller for cancelling operations (optional in some contexts)
abortController?: AbortController;
// Optional: Configuration options
options?: QueryOptions;
}QueryOptions Interface
interface QueryOptions {
// Maximum conversation turns (default: 3)
maxTurns?: number;
// Working directory for file operations
workingDirectory?: string;
cwd?: string; // Alias for workingDirectory
// Model to use
model?: string;
// Custom system prompt
systemPrompt?: string;
// Permission mode for file operations
permissionMode?: 'strict' | 'cautious' | 'relaxed' | 'default' | 'acceptEdits';
// Resume from previous messages
resumeFrom?: SDKMessage[];
// Session ID for tracking
sessionId?: string;
// Allowed tools (e.g., ["Read", "Write", "Bash"])
allowedTools?: string[];
}Available Models
claude-sonnet-4-20250514- Default, balanced modelclaude-haiku-4-20250514- Faster, lightweight modelclaude-opus-4-20250514- Most capable model
Permission Modes
- strict: Requires explicit confirmation for all operations
- cautious: Asks for confirmation on potentially destructive operations (default)
- relaxed: Minimal confirmations, suitable for trusted environments
Built-in Tools
Claude Code has access to various tools when executing queries:
File Operations
Read- Read file contentsWrite- Write to filesEdit- Edit existing filesMultiEdit- Multiple edits in one operationNotebookRead- Read Jupyter notebooksNotebookEdit- Edit Jupyter notebooks
Command Execution
Bash- Execute bash commands with timeout control
Web Operations
WebSearch- Search the webWebFetch- Fetch and process web content
Other Tools
TodoWrite- Manage task listsGlob- File pattern matchingGrep- Search file contentsLS- List directory contents
File Operations Tool (str_replace_editor_tool)
View Command
interface ViewCommand {
command: 'view';
path: string;
view_range?: [number, number]; // Optional line range
}Create Command
interface CreateCommand {
command: 'create';
path: string;
file_text: string;
}String Replace Command
interface StrReplaceCommand {
command: 'str_replace';
path: string;
old_str: string;
new_str: string;
}Bash Command Tool
interface BashToolUse {
type: 'tool_use';
id: string;
name: 'bash';
input: {
command: string;
};
}Error Types
The SDK may throw various error types from the Anthropic SDK:
import { Anthropic } from "@anthropic-ai/sdk";
// Error types
Anthropics.APIError // Base error class
Anthropics.AuthenticationError // 401 - Invalid API key
Anthropics.PermissionDeniedError // 403 - Insufficient permissions
Anthropics.NotFoundError // 404 - Resource not found
Anthropics.RateLimitError // 429 - Rate limited
Anthropics.BadRequestError // 400 - Invalid request
Anthropics.InternalServerError // 500 - Server error
Anthropics.APIConnectionError // Network issues
Anthropics.APIConnectionTimeoutError // TimeoutError Handling Example
try {
for await (const message of query(params)) {
// Process messages
}
} catch (error) {
if (error instanceof Anthropic.RateLimitError) {
const retryAfter = error.headers?.['retry-after'];
console.log(`Rate limited. Retry after ${retryAfter} seconds`);
} else if (error instanceof Anthropic.AuthenticationError) {
console.log('Invalid API key');
} else if (error instanceof Anthropic.APIConnectionTimeoutError) {
console.log(`Request timed out after ${error.timeout}ms`);
} else {
throw error;
}
}Advanced Patterns
Session Management
class ClaudeSession {
private messages: SDKMessage[] = [];
private sessionId: string;
constructor() {
this.sessionId = crypto.randomUUID();
}
async query(prompt: string) {
const abortController = new AbortController();
for await (const message of query({
prompt,
abortController,
options: {
sessionId: this.sessionId,
resumeFrom: this.messages
}
})) {
this.messages.push(message);
yield message;
}
}
getHistory(): SDKMessage[] {
return [...this.messages];
}
clear(): void {
this.messages = [];
}
}Tool Use Detection
function extractToolUses(messages: SDKMessage[]): ToolUseBlock[] {
const toolUses: ToolUseBlock[] = [];
for (const message of messages) {
if (message.type === 'assistant') {
const content = message.data.message.content;
if (Array.isArray(content)) {
for (const block of content) {
if (block.type === 'tool_use') {
toolUses.push(block);
}
}
}
}
}
return toolUses;
}Streaming with Progress Tracking
async function executeWithProgress(prompt: string) {
const abortController = new AbortController();
let turnCount = 0;
let totalTokens = 0;
for await (const message of query({ prompt, abortController })) {
switch (message.type) {
case 'assistant':
turnCount++;
console.log(`Turn ${turnCount}:`, message.data.message.content);
break;
case 'result':
if (message.data.tokens_used) {
totalTokens = message.data.tokens_used.total;
}
break;
}
}
return { turnCount, totalTokens };
}Error Handling with Retries
async function safeQuery(prompt: string) {
const maxRetries = 3;
let attempt = 0;
while (attempt < maxRetries) {
try {
const messages: SDKMessage[] = [];
for await (const message of query({
prompt,
abortController: new AbortController()
})) {
messages.push(message);
}
return messages;
} catch (error) {
attempt++;
if (error instanceof RateLimitError) {
const retryAfter = error.headers.get('retry-after');
const delay = retryAfter ? parseInt(retryAfter) * 1000 : 60000;
console.log(`Rate limited. Waiting ${delay}ms...`);
await new Promise(resolve => setTimeout(resolve, delay));
} else if (error instanceof APIConnectionTimeoutError) {
console.log(`Timeout. Retrying (${attempt}/${maxRetries})...`);
} else {
throw error; // Re-throw non-retryable errors
}
}
}
throw new Error(`Failed after ${maxRetries} attempts`);
}MCP Integration
Creating an MCP Server
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
import { z } from "zod";
const server = new McpServer({
name: "my-tools-server",
version: "1.0.0",
description: "Custom tools for Claude"
});
// Define a custom tool
server.tool(
"custom-tool",
{
description: "Tool description",
inputSchema: z.object({
param1: z.string().describe("Parameter description"),
param2: z.number().optional()
})
},
async ({ param1, param2 }) => {
// Tool implementation
return {
content: [{
type: "text",
text: "Result"
}]
};
}
);
// Start the server
const transport = new StdioServerTransport();
await server.connect(transport);MCP Resources
// Provide data that Claude can access
server.resource(
"config://app",
async () => {
const config = await loadAppConfiguration();
return {
contents: [{
uri: "config://app",
mimeType: "application/json",
text: JSON.stringify(config, null, 2)
}]
};
}
);MCP Prompts
// Define reusable prompt templates
server.prompt(
"code-review",
{
description: "Perform a code review",
inputSchema: z.object({
files: z.array(z.string()),
focus: z.enum(['security', 'performance', 'style', 'all'])
})
},
({ files, focus }) => ({
messages: [{
role: "user",
content: {
type: "text",
text: `Review ${files.join(', ')} focusing on ${focus}`
}
}]
})
);Authentication Methods
Environment Variable (Recommended)
export ANTHROPIC_API_KEY="your-api-key-here"OAuth Token (for Pro/Max users)
claude setup-token
# This generates CLAUDE_CODE_OAUTH_TOKENThird-Party Providers
- Amazon Bedrock: Set
CLAUDE_CODE_USE_BEDROCK=1 - Google Vertex AI: Set
CLAUDE_CODE_USE_VERTEX=1
Configuration File
The SDK looks for configuration in these locations (in order):
- Environment variables
~/.config/claude-code/settings.json.claude/settings.json(project-specific)
settings.json Format
{
"api_key": "sk-ant-...",
"model": "claude-sonnet-4-20250514",
"max_turns": 5,
"permission_mode": "acceptEdits",
"bash_default_timeout_ms": 30000,
"bash_max_timeout_ms": 300000
}Quick Start
import { query, type SDKMessage } from "@anthropic-ai/claude-code";
async function main() {
const messages: SDKMessage[] = [];
for await (const message of query({
prompt: "Write a TypeScript hello world function",
abortController: new AbortController(),
options: {
maxTurns: 3,
model: "claude-sonnet-4-20250514"
}
})) {
messages.push(message);
if (message.type === 'assistant') {
console.log(message.data.message.content);
}
}
}
main().catch(console.error);Environment Variables
Authentication
ANTHROPIC_API_KEY- Your Anthropic API keyCLAUDE_CODE_OAUTH_TOKEN- OAuth token (fromclaude setup-token)CLAUDE_CODE_USE_BEDROCK- Use Amazon Bedrock (set to “1”)CLAUDE_CODE_USE_VERTEX- Use Google Vertex AI (set to “1”)
Configuration
CLAUDE_CONFIG_DIR- Custom config directoryBASH_DEFAULT_TIMEOUT_MS- Default timeout for bash commandsBASH_MAX_TIMEOUT_MS- Maximum timeout for bash commandsCLAUDE_BASH_MAINTAIN_PROJECT_WORKING_DIR- Maintain working directoryDISABLE_INTERLEAVED_THINKING- Disable interleaved thinking mode
Type Guards for Message Handling
function isAssistantMessage(msg: SDKMessage): msg is AssistantMessage {
return msg.type === 'assistant';
}
function isResultMessage(msg: SDKMessage): msg is ResultMessage {
return msg.type === 'result';
}
function isSystemMessage(msg: SDKMessage): msg is SystemMessage {
return msg.type === 'system';
}
// Usage
for await (const message of query(params)) {
if (isAssistantMessage(message)) {
console.log("Assistant:", message.data.message);
} else if (isResultMessage(message)) {
console.log("Cost:", message.data.total_cost_usd);
} else if (isSystemMessage(message)) {
console.log("Tools:", message.data.tools);
}
}Best Practices
- Always provide an AbortController for cancellable operations
- Handle all error types appropriately
- Monitor costs via the result message
- Use TypeScript for full type safety
- Set appropriate timeouts for long-running operations
See Also
- TypeScript SDK Documentation - Complete SDK documentation
- Quick Start - Get started quickly
- SDK Examples - Practical code examples
- Hooks Documentation - Integration with Claude Code hooks