[ PROMPT_NODE_23882 ]
Agent SDK 设计模式
[ SKILL_DOCUMENTATION ]
# 智能体 SDK 模式 — TypeScript
## 基础智能体
typescript
import { query } from "@anthropic-ai/claude-agent-sdk";
async function main() {
for await (const message of query({
prompt: "解释此仓库的作用",
options: {
cwd: "/path/to/project",
allowedTools: ["Read", "Glob", "Grep"],
},
})) {
if ("result" in message) {
console.log(message.result);
}
}
}
main();
---
## 钩子 (Hooks)
### 工具使用后钩子
typescript
import { query, HookCallback } from "@anthropic-ai/claude-agent-sdk";
import { appendFileSync } from "fs";
const logFileChange: HookCallback = async (input) => {
const filePath = (input as any).tool_input?.file_path ?? "unknown";
appendFileSync(
"./audit.log",
`${new Date().toISOString()}: modified ${filePath}n`,
);
return {};
};
for await (const message of query({
prompt: "重构 utils.py 以提高可读性",
options: {
allowedTools: ["Read", "Edit", "Write"],
permissionMode: "acceptEdits",
hooks: {
PostToolUse: [{ matcher: "Edit|Write", hooks: [logFileChange] }],
},
},
})) {
if ("result" in message) console.log(message.result);
}
---
## 子智能体
typescript
import { query } from "@anthropic-ai/claude-agent-sdk";
for await (const message of query({
prompt: "使用代码审查智能体来审查此代码库",
options: {
allowedTools: ["Read", "Glob", "Grep", "Agent"],
agents: {
"code-reviewer": {
description: "用于质量和安全审查的专家代码审查员。",
prompt: "分析代码质量并提出改进建议。",
tools: ["Read", "Glob", "Grep"],
},
},
},
})) {
if ("result" in message) console.log(message.result);
}
---
## MCP 服务器集成
### 浏览器自动化 (Playwright)
typescript
for await (const message of query({
prompt: "打开 example.com 并描述你看到的内容",
options: {
mcpServers: {
playwright: { command: "npx", args: ["@playwright/mcp@latest"] },
},
},
})) {
if ("result" in message) console.log(message.result);
}
---
## 会话恢复
typescript
import { query } from "@anthropic-ai/claude-agent-sdk";
let sessionId: string | undefined;
// 第一次查询:捕获会话 ID
for await (const message of query({
prompt: "读取身份验证模块",
options: { allowedTools: ["Read", "Glob"] },
})) {
if (message.type === "system" && message.subtype === "init") {
session