Chapter 15 · SDK and Programmatic Invocation
Chapter goals: Master the TypeScript API of the Claude Code SDK (
@anthropic-ai/claude-code), learn to驱动 Claude programmatically tocomplete tasks, handle streaming output, and build custom Agent applications.
15.1 SDK Overview
Claude Code is not just a terminal tool — it provides a complete SDK让 you embed Claude's coding capabilities into your own applications:
npm install @anthropic-ai/claude-codeThe core of the SDK is the query() function, which spawns a Claude Code process and returns an async iterator. Each message represents one of Claude's outputs or a tool call result.
15.2 Basic Usage: Single Query
import { query } from '@anthropic-ai/claude-code';
async function main() {
const result = await query({
prompt: 'Explain what this code does: const x = arr.filter(Boolean).map(Number)',
options: {
maxTurns: 3,
cwd: '/path/to/project',
allowedTools: ['Read', 'Grep'],
},
});
for await (const message of result) {
if (message.type === 'assistant') {
for (const block of message.subtype) {
if (block.type === 'text') {
console.log(block.text);
}
}
}
}
}
main();Key configuration items:
prompt: the instruction sent to Claude;maxTurns: limit对话 rounds to prevent infinite loops;cwd: working directory;allowedTools: whitelist restricting available tools.
15.3 Streaming Output and Real-time Processing
The SDK supports streaming接收 Claude's responses, suitable for building real-time UIs:
import { query, type SDKMessage } from '@anthropic-ai/claude-code';
async function streamResponse(prompt: string) {
const messages: SDKMessage[] = [];
const result = query({
prompt,
options: { maxTurns: 5, outputFormat: 'stream-json' },
});
for await (const msg of result) {
switch (msg.type) {
case 'assistant':
// Process text blocks
break;
case 'tool_use':
console.log(`🔧 Called tool: ${msg.name}`);
break;
case 'result':
console.log('✅ Done');
break;
}
messages.push(msg);
}
return messages;
}15.4 Building a Custom Agent
Combining the Claude Code SDK with custom logic allows building domain-specific AI Agents:
import { query } from '@anthropic-ai/claude-code';
import * as readline from 'readline';
const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
async function agentLoop() {
while (true) {
const input = await new Promise<string>(r => rl.question('> ', r));
if (input === 'exit') break;
const result = query({
prompt: input,
options: {
maxTurns: 10,
systemPrompt: 'You are an coding assistant focused on TypeScript projects. Answer concisely and accurately.',
allowedTools: ['Read', 'Write', 'Edit', 'Bash', 'Grep', 'Glob'],
},
});
for await (const msg of result) {
if (msg.type === 'assistant') {
for (const block of msg.subtype) {
if (block.type === 'text') process.stdout.write(block.text);
}
}
}
console.log();
}
rl.close();
}
agentLoop();Chapter Summary
- The SDK provides the
query()function via the@anthropic-ai/claude-codepackage; - Supports precise control via
maxTurns,allowedTools,cwd, and其他 configuration items; - Streaming output is逐条 processed via the
for await...ofiterator; - Custom Agent loops can be built基于 the SDK.
🧪 随堂测验
点击你认为正确的选项。答错时会展示正确答案与原因解析。
1. What is the core function of the Claude Code SDK?
2. What is the purpose of the `maxTurns` parameter?
3. How do you让 the SDK only allow reading files without executing commands?
4. What is the correct way to traverse the SDK's streaming output?
🛠️ Hands-on Practice
- Install the SDK and send a simple指令 with
query(); print the完整 response. - Use
allowedTools: ['Read']to limit the工具集; observe changes in Claude's behavior. - Write a loop式 Agent supporting multi-turn user input.
After mastering the SDK, proceed to Chapter 16 to learn about enterprise configuration management.