Embed Claude Code in your own applications using the @anthropic-ai/claude-code package.
The Claude Code SDK lets you drive Claude Code programmatically from TypeScript or JavaScript. You can send prompts, stream responses, manage multi-turn sessions, and build tools that run in the same process.
Messages yielded by query() are a discriminated union keyed on type:
type
Description
user
A user turn (echoed back)
assistant
An assistant turn with content blocks
tool_use
Claude invoking a tool
tool_result
The result of a tool call
result
Final result message with usage stats
system
System-level metadata
for await (const msg of query({ prompt: 'Summarize this repo' })) { switch (msg.type) { case 'assistant': // msg.message.content is ContentBlock[] break case 'result': // msg.subtype is 'success' | 'error_max_turns' | ... // msg.usage contains token counts and cost break }}
Options
Pass an Options object to control behavior:
const stream = query({ prompt: 'Fix the type errors', options: { // Working directory cwd: '/path/to/project', // Max agent turns before stopping maxTurns: 10, // Model override model: 'claude-sonnet-4-6', // Custom system prompt systemPrompt: 'You are a TypeScript expert.', // Append to the default system prompt appendSystemPrompt: 'Always prefer const over let.', // Permission mode permissionMode: 'acceptEdits', // Allowed tools (restrict what Claude can use) allowedTools: ['Read', 'Bash', 'Edit'], // MCP server configurations mcpServers: { myServer: { type: 'stdio', command: 'node', args: ['./mcp-server.js'], }, }, },})
ModelUsage
The result message includes usage data:
if (msg.type === 'result') { const usage = msg.usage // { // inputTokens: number // outputTokens: number // cacheReadInputTokens: number // cacheCreationInputTokens: number // webSearchRequests: number // costUSD: number // contextWindow: number // maxOutputTokens: number // }}
// Send a message and stream the responsefor await (const message of session.query('What files are here?')) { console.log(message)}// Send a follow-up (same session context)for await (const message of session.query('Now edit the README')) { console.log(message)}
For single prompts without managing a session object:
import { unstable_v2_prompt } from '@anthropic-ai/claude-code'const result = await unstable_v2_prompt('What files are here?', { model: 'claude-sonnet-4-6', cwd: '/path/to/project',})// result is an SDKResultMessage