第 15 章 · SDK 与编程式调用
本章目标:掌握 Claude Code SDK(
@anthropic-ai/claude-code)的 TypeScript API,学会以编程方式驱动 Claude 完成任务、处理流式输出,并构建自定义 Agent 应用。
15.1 SDK 概述
Claude Code 不只是一个终端工具——它提供完整的 SDK,让你把 Claude 的编码能力嵌入到自己的应用中:
bash
npm install @anthropic-ai/claude-codeSDK 的核心是 query() 函数,它启动一个 Claude Code 进程并返回异步迭代器。每个消息代表 Claude 的一次输出或工具调用结果。
15.2 基本用法:单次查询
typescript
import { query } from '@anthropic-ai/claude-code';
async function main() {
const result = await query({
prompt: '解释这段代码的作用: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();关键配置项:
prompt:发给 Claude 的指令;maxTurns:限制对话轮数,防止无限循环;cwd:工作目录;allowedTools:白名单限制可用工具。
15.3 流式输出与实时处理
SDK 支持流式接收 Claude 的响应,适合构建实时 UI:
typescript
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':
// 处理文本块
break;
case 'tool_use':
console.log(`🔧 调用工具: ${msg.name}`);
break;
case 'result':
console.log('✅ 完成');
break;
}
messages.push(msg);
}
return messages;
}15.4 构建自定义 Agent
将 Claude Code SDK 与自定义逻辑组合,可以构建领域专属的 AI Agent:
typescript
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: '你是一个专注于 TypeScript 项目的编码助手。回答简洁准确。',
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();本章小结
- SDK 通过
@anthropic-ai/claude-code包提供query()函数; - 支持
maxTurns、allowedTools、cwd等配置项精确控制行为; - 流式输出通过
for await...of迭代器逐条处理消息; - 可基于 SDK 构建自定义 Agent 循环。
🧪 随堂测验
点击你认为正确的选项。答错时会展示正确答案与原因解析。
1. Claude Code SDK 的核心函数是什么?
2. `maxTurns` 参数的作用是?
3. 如何让 SDK 只允许读取文件而不执行命令?
4. SDK 流式输出的正确遍历方式是?
🛠️ 动手实践
- 安装 SDK 并用
query()发送一条简单指令,打印完整响应。 - 使用
allowedTools: ['Read']限制工具集,观察 Claude 行为变化。 - 编写一个循环式 Agent,支持用户多轮输入。
掌握 SDK 后,进入第 16 章了解企业级配置管理。