[ PROMPT_NODE_23880 ]
Agent SDK 说明文档
[ SKILL_DOCUMENTATION ]
# 智能体 SDK — TypeScript
Claude 智能体 SDK 提供了一个更高级的接口,用于构建具有内置工具、安全功能和智能体能力的 AI 智能体。
## 安装
bash
npm install @anthropic-ai/claude-agent-sdk
---
## 快速入门
typescript
import { query } from "@anthropic-ai/claude-agent-sdk";
for await (const message of query({
prompt: "解释此代码库",
options: { allowedTools: ["Read", "Glob", "Grep"] },
})) {
if ("result" in message) {
console.log(message.result);
}
}
---
## 内置工具
| 工具 | 描述 |
| --------- | ------------------------------------ |
| Read | 读取工作区中的文件 |
| Write | 创建新文件 |
| Edit | 对现有文件进行精确编辑 |
| Bash | 执行 shell 命令 |
| Glob | 按模式查找文件 |
| Grep | 按内容搜索文件 |
| WebSearch | 在网络上搜索信息 |
| WebFetch | 获取并分析网页 |
| AskUserQuestion | 向用户提出澄清问题 |
| Agent | 衍生子智能体 |
---
## 权限系统
typescript
for await (const message of query({
prompt: "重构身份验证模块",
options: {
allowedTools: ["Read", "Edit", "Write"],
permissionMode: "acceptEdits",
},
})) {
if ("result" in message) console.log(message.result);
}
权限模式:
- `"default"`: 对危险操作进行提示
- `"plan"`: 仅规划,不执行
- `"acceptEdits"`: 自动接受文件编辑
- `"dontAsk"`: 不提示 — **拒绝**任何未预先批准的操作(非自动批准模式)
- `"bypassPermissions"`: 跳过所有提示(需要在选项中设置 `allowDangerouslySkipPermissions: true`)
---
## MCP(模型上下文协议)支持
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);
}
### 进程内 MCP 工具
您可以使用 `tool()` 和 `createSdkMcpServer` 定义在进程内运行的自定义工具:
typescript
import { query, tool, createSdkMcpServer } from "@anthropic-ai/claude-agent-sdk";
import { z } from "zod";
const myTool = tool("my-tool", "描述", { input: z.string() },