
The Claude Code SDK extends Claude Code from an interactive coding assistant into a fully programmable agent runtime. If you've been using Claude Code interactively, the SDK opens up a fundamentally different set of possibilities — automated pipelines, custom UIs, multi-agent orchestration, and CI/CD integration.
What Is the Claude Code SDK?
The Claude Code SDK is a programmatic interface that lets you:
- Run Claude Code non-interactively from scripts and pipelines
- Control which files, directories, and tools are in context
- Parse structured output for downstream processing
- Chain Claude Code with other tools in automated workflows
- Build custom UIs on top of Claude Code's reasoning
Available as a Node.js package:
npm install @anthropic-ai/claude-code
Or invoke via CLI in non-interactive mode:
claude -p "Your prompt here" --output-format json
Core SDK Concepts
Non-Interactive Mode
The most basic SDK use case: run Claude Code with a prompt, get output, done.
# CLI non-interactive
claude -p "Review src/auth.ts for security vulnerabilities" \
--output-format json \
--max-turns 5
// SDK
const { query } = require('@anthropic-ai/claude-code');
const result = await query({
prompt: "Review src/auth.ts for security vulnerabilities",
options: {
maxTurns: 5,
outputFormat: 'json'
}
});
Tool Configuration
Control which tools Claude Code has access to in your SDK call:
const result = await query({
prompt: "Generate a test suite for src/utils.ts",
options: {
allowedTools: ['Read', 'Write', 'Bash'],
// Disable tools you don't need:
// disallowedTools: ['WebSearch', 'mcp__custom_tool']
}
});
Custom System Prompts
Override the default Claude Code system prompt for specialized behavior:
const result = await query({
prompt: "Refactor this module",
options: {
systemPrompt: `You are a TypeScript expert specializing in functional programming patterns.
Always prefer immutable data structures. Use Result types for error handling.
Never use any or unknown types.`,
}
});
Practical SDK Patterns
1. Automated Code Review in CI
// .github/workflows/code-review.js
const { query } = require('@anthropic-ai/claude-code');
const { execSync } = require('child_process');
const diff = execSync('git diff main...HEAD').toString();
const review = await query({
prompt: `Review this PR diff for: security issues, performance problems, and missing tests.
Output as JSON with keys: security[], performance[], testing[].
Diff:
${diff}`,
options: {
outputFormat: 'json',
allowedTools: ['Read'], // Read-only in CI
maxTurns: 3
}
});
console.log(JSON.parse(review.result));
2. Automated Documentation Generation
const fs = require('fs');
const { query } = require('@anthropic-ai/claude-code');
async function generateDocs(srcPath) {
const result = await query({
prompt: `Generate comprehensive JSDoc documentation for all exported functions in ${srcPath}.
Add parameter descriptions, return types, and usage examples.
Write the updated file with documentation added.`,
options: {
allowedTools: ['Read', 'Write'],
cwd: process.cwd()
}
});
return result;
}
3. Multi-Agent Pipeline with External Capabilities
This is where AnyCap integration becomes powerful. A pipeline where Claude Code handles code reasoning, and AnyCap handles media and publishing:
const { query } = require('@anthropic-ai/claude-code');
const { execSync } = require('child_process');
async function buildAndPublishDocs(repoPath) {
// Step 1: Claude Code generates documentation
const docsResult = await query({
prompt: "Generate a comprehensive README for this project with setup instructions, API reference, and examples",
options: {
cwd: repoPath,
allowedTools: ['Read', 'Write', 'Bash']
}
});
// Step 2: AnyCap generates a hero diagram
execSync(`anycap image generate \
--prompt "Technical architecture diagram for a developer tool, clean minimal style" \
--model nano-banana-2 \
-o ${repoPath}/docs/architecture.png`);
// Step 3: AnyCap publishes as a web page
const pageResult = execSync(`anycap page deploy ${repoPath}/docs/`).toString();
return { docs: docsResult, page: JSON.parse(pageResult) };
}
SDK Authentication
The SDK uses the same authentication as Claude Code. Set your API key:
export ANTHROPIC_API_KEY=your_key_here
Or for team environments, use environment-specific configuration:
const { query } = require('@anthropic-ai/claude-code');
// SDK picks up ANTHROPIC_API_KEY automatically
// Or pass explicitly:
process.env.ANTHROPIC_API_KEY = await getSecretFromVault('anthropic-api-key');
Output Formats
The SDK supports three output formats:
| Format | Use Case |
|---|---|
text |
Default, human-readable output |
json |
Programmatic processing — includes result, cost, session info |
stream-json |
Real-time output for UIs and dashboards |
// JSON output includes metadata
{
"result": "The function has a potential SQL injection vulnerability...",
"is_error": false,
"session_id": "sess_xxxx",
"cost_usd": 0.0043,
"num_turns": 2
}
Rate Limits and Cost Management in SDK Workflows
SDK-based automation can consume tokens faster than interactive use. Built-in guardrails:
const result = await query({
prompt: "...",
options: {
maxTurns: 5, // Limit reasoning iterations
timeoutMs: 30000, // Timeout for long-running tasks
}
});
// Always check cost in production
if (result.cost_usd > 0.10) {
logger.warn(`High cost session: $${result.cost_usd}`);
}
For capability-heavy tasks (image generation, video creation, web search), offload to AnyCap rather than letting Claude Code handle them in-context. This keeps SDK costs predictable and avoids hitting Claude's rate limits on non-reasoning tasks.
Getting Started
# Install the SDK
npm install @anthropic-ai/claude-code
# Install AnyCap for capability extension
curl -fsSL https://anycap.ai/install.sh | sh
# Add AnyCap skill to Claude Code
npx -y skills add anycap-ai/anycap -y