Claude Code TypeScript SDK
The @anthropic-ai/claude-code TypeScript SDK is an “agentic coding tool” that provides both CLI and programmatic access to Claude Code, Anthropic’s AI assistant for coding tasks. It can understand your codebase, edit files, run terminal commands, and handle entire workflows.
Overview
Key Features
- Type-Safe API: Full TypeScript support with comprehensive type definitions
- Streaming Support: Real-time response streaming for better user experience
- Flexible Authentication: Multiple auth methods including API keys, OAuth, and cloud providers
- Tool Integration: Built-in support for file operations, bash commands, and custom tools
- Cost Tracking: Automatic usage and cost monitoring
- MCP Support: Model Context Protocol for extending Claude’s capabilities
Use Cases
- Code Generation: Generate functions, classes, and entire modules
- Code Review: Automated code analysis and suggestions
- Refactoring: Intelligent code transformation
- Documentation: Auto-generate documentation from code
- Testing: Create comprehensive test suites
- Migration: Assist with framework and language migrations
- Learning: Interactive coding tutorials and explanations
Installation and Setup
Prerequisites
- Node.js 18+ required (20+ recommended)
- TypeScript 4.9+ supported
- Built-in TypeScript declarations included
Installation Options
Global CLI Installation
npm install -g @anthropic-ai/claude-codeLocal SDK Installation
npm install @anthropic-ai/claude-code
npm install --save-dev @types/node typescriptAuthentication
Option A: Anthropic API Key (Recommended)
- Create an API key in the Anthropic Console
- Set environment variable:
export ANTHROPIC_API_KEY="your-api-key-here"
Option B: OAuth Token (for Pro/Max users)
claude setup-token
# This generates CLAUDE_CODE_OAUTH_TOKENOption C: Third-Party Providers
- Amazon Bedrock: Set
CLAUDE_CODE_USE_BEDROCK=1 - Google Vertex AI: Set
CLAUDE_CODE_USE_VERTEX=1
Basic Usage
Simple Example
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 function that calculates fibonacci numbers",
abortController: new AbortController()
})) {
messages.push(message);
// Handle different message types
switch (message.type) {
case 'assistant':
console.log("Claude:", message.data.message.content);
break;
case 'result':
console.log(`\nCompleted in ${message.data.total_time_ms}ms`);
console.log(`Cost: $${message.data.total_cost_usd}`);
break;
case 'system':
console.log("Available tools:", message.data.tools);
break;
}
}
}
main().catch(console.error);Understanding the Response Stream
The SDK returns an async iterable stream of messages:
- System Message: Sent first, contains initialization info and available tools
- User Message: Echoes your prompt
- Assistant Message: Claude’s responses (may be multiple)
- Result Message: Final message with cost and timing data
Core API
Query Function
The main interface is the query function that returns an async iterable:
import { query, type SDKMessage } from "@anthropic-ai/claude-code";
async function main() {
for await (const message of query({
prompt: "Your prompt here",
abortController: new AbortController(),
options: {
maxTurns: 3, // Max conversation turns
cwd: "/path/to/project", // Working directory
model: "claude-sonnet-4-20250514",
systemPrompt: "Custom system prompt",
allowedTools: ["Read", "Write", "Bash"],
permissionMode: "acceptEdits"
}
})) {
// Handle messages
}
}Message Types
The SDKMessage type is a discriminated union:
type SDKMessage =
| { type: "assistant"; data: { message: { role: 'assistant'; content: string; }; }; }
| { type: "user"; data: { message: { role: 'user'; content: string; }; }; }
| { type: "result"; data: { result: 'success' | 'error'; total_cost_usd?: number; total_time_ms?: number; }; }
| { type: "system"; data: { configuration: object; tools: string[]; model: string; }; };Advanced Features
Multi-turn Conversations
The SDK supports multi-turn conversations where Claude can iteratively work on complex tasks:
const response = query({
prompt: "Build a complete REST API with authentication",
abortController: new AbortController(),
options: {
maxTurns: 10, // Allow more turns for complex tasks
cwd: process.cwd(),
allowedTools: ["Read", "Write", "Edit", "Bash"]
}
});Tool Integration
Claude Code can use various tools:
- File Operations: Read, Write, Edit, MultiEdit
- Command Execution: Bash commands with timeout control
- Web Operations: WebSearch, WebFetch
- Custom Tools: Integration via Model Context Protocol (MCP)
Cost Management
Every operation includes automatic cost tracking:
- Total cost in USD via
total_cost_usd - API time via
duration_api_ms - Total execution time via
duration_ms - Number of conversation turns via
num_turns
Common Patterns
Working with AbortController
async function cancelableQuery() {
const controller = new AbortController();
// Cancel after 30 seconds
const timeout = setTimeout(() => controller.abort(), 30000);
try {
for await (const message of query({
prompt: "Analyze this large codebase",
abortController: controller
})) {
// Process messages
}
clearTimeout(timeout);
} catch (error) {
if (error.name === 'AbortError') {
console.log('Query was cancelled');
}
}
}Cost Tracking
async function trackCosts() {
const messages: SDKMessage[] = [];
for await (const message of query({
prompt: "Build a REST API with Express and TypeScript",
options: { maxTurns: 10 }
})) {
messages.push(message);
}
const result = messages.find(m => m.type === "result");
if (result) {
console.log(`Total cost: $${result.total_cost_usd}`);
console.log(`API time: ${result.duration_api_ms}ms`);
console.log(`Total time: ${result.duration_ms}ms`);
console.log(`Turns used: ${result.num_turns}`);
}
}Troubleshooting
Common Issues
Authentication Failed
# Check if API key is set
echo $ANTHROPIC_API_KEY
# Set it if missing
export ANTHROPIC_API_KEY="sk-ant-..."Permission Errors (npm)
# Fix with migrate-installer
claude migrate-installer
# Or configure npm to use user directory
mkdir ~/.npm-global
npm config set prefix ~/.npm-global
export PATH=~/.npm-global/bin:$PATHWindows/WSL Platform Errors
# Force Linux environment during installation
FORCE_NODE_ENV=linux npm install -g @anthropic-ai/claude-code
# Verify you're using Linux Node.js (not Windows Node.js)
which npm # Should show /usr/... not /mnt/c/...
which node # Should show /usr/... not /mnt/c/...Rate Limiting
try {
for await (const message of query({ prompt })) {
// Process messages
}
} catch (error) {
if (error.status === 429) {
console.log('Rate limited, retry after delay');
}
}Best Practices
Development Guidelines
- ✅ Always use TypeScript for type safety
- ✅ Implement proper error handling
- ✅ Use environment variables for API keys
- ✅ Follow rate limiting guidelines
- ✅ Test thoroughly with mock responses
Performance Tips
- Use streaming for long responses
- Implement request caching where appropriate
- Batch requests when possible
- Monitor API usage and costs
Security Considerations
- Never expose API keys in client-side code
- Validate and sanitize user inputs
- Use secure storage for credentials
- Implement proper access controls
SDK Documentation
Quick Links
- Complete SDK Guide - Comprehensive guide with examples
- Quick Start Guide - Get started in 5 minutes
- API Reference - Complete type definitions and methods
- Code Examples - Practical implementations
- Best Practices - Architecture and production tips
Additional Resources
- Streaming Patterns - Real-time response handling
- Error Handling - Robust error management
- Advanced Patterns - Complex scenarios
- Tool Integration - Extending with custom tools
Data Privacy and Security
- Claude Code collects usage feedback
- User feedback transcripts are stored for 30 days
- Feedback will not be used for model training
- The package is currently in beta phase
Limitations and Considerations
- Requires Node.js 18 or higher
- TypeScript 4.9 or higher recommended
- API key required for direct Anthropic usage
- Subject to rate limits based on your API plan
- Currently in beta, so APIs may change
Resources
Official Resources
- NPM Package (v1.0.56)
- Official Documentation
- GitHub Repository
- API Reference
- Anthropic Console
- GitHub Cookbook
Support Channels
- GitHub Issues: Report bugs and feature requests
- Community Forums: Search for similar issues in discussions
- Anthropic Support: Contact support for API-specific issues
Essential Commands
# Installation
npm install -g @anthropic-ai/claude-code
# Setup
claude setup-token # Generate OAuth token
export ANTHROPIC_API_KEY="..." # Set API key
# Debugging
claude doctor # Check installation
claude --verbose # Verbose output
claude --mcp-debug # MCP debugging
# Usage
claude --continue # Resume last conversation
claude --resume <session-id> # Resume specific sessionVersion Information
- Current Version: 1.0.56 (July 2025)
- Node.js Requirement: 18+ (20+ recommended)
- TypeScript Support: 4.9+ (5.0+ recommended)
- License: MIT
- Publisher: Anthropic
Tags: claude-code typescript sdk documentation guide
Verifications
Last verified: 2025-07-22
Sources
-
NPM Package Information: Verified from npm registry - Package version 1.0.56 is confirmed as the latest version (published 2 days ago as of July 22, 2025)
-
SDK Documentation: Verified from Anthropic’s official docs - Claude Code SDK is now generally available (GA) and accessible with both Pro and Max plans
-
TypeScript SDK Usage: Confirmed the TypeScript SDK is included in the main @anthropic-ai/claude-code package and provides the
queryfunction withSDKMessagetype support -
Installation Commands: Verified the global installation command and TypeScript SDK usage patterns are accurate
Why Verified
- Version Currency: Confirmed v1.0.56 is the latest version as of July 2025
- Feature Set: All listed features (type-safe API, streaming support, authentication methods, tool integration) are current
- Code Examples: The TypeScript examples using
queryfunction andSDKMessagetype match current SDK implementation - Installation Instructions: Both global CLI and local SDK installation methods are accurate
- Authentication Options: All three authentication methods (API key, OAuth token, cloud providers) are confirmed