返回顶部
c

claude-agent-sdkClaude代理SDK

|

作者: admin | 来源: ClawHub
源自
ClawHub
版本
V 0.1.0
安全检测
已通过
1,796
下载量
免费
免费
0
收藏
概述
安装方式
版本历史

claude-agent-sdk

Claude Agent SDK - 结构化输出与错误预防指南

包名: @anthropic-ai/claude-agent-sdk@0.2.12
重大变更: v0.1.45 - 结构化输出 (2025年11月), v0.1.0 - 无默认系统提示, 需要settingSources



v0.1.45+ 新特性 (2025年11月)

主要功能:

1. 结构化输出 (v0.1.45, 2025年11月14日)

  • - JSON schema 验证 - 确保响应与精确的 schema 匹配
  • outputFormat 参数 - 使用 JSON schema 或 Zod 定义输出结构
  • 访问验证结果 - 通过 message.structured_output
  • 需要 Beta 头: structured-outputs-2025-11-13
  • 类型安全 - 使用 Zod schema 实现完整的 TypeScript 类型推断

示例:
typescript
import { query } from @anthropic-ai/claude-agent-sdk;
import { z } from zod;
import { zodToJsonSchema } from zod-to-json-schema;

const schema = z.object({
summary: z.string(),
sentiment: z.enum([positive, neutral, negative]),
confidence: z.number().min(0).max(1)
});

const response = query({
prompt: 分析这段代码审查反馈,
options: {
model: claude-sonnet-4-5,
outputFormat: {
type: json_schema,
json_schema: {
name: AnalysisResult,
strict: true,
schema: zodToJsonSchema(schema)
}
}
}
});

for await (const message of response) {
if (message.type === result && message.structured_output) {
// 保证与 schema 匹配
const validated = schema.parse(message.structured_output);
console.log(情感分析: ${validated.sentiment});
}
}

Zod 兼容性 (v0.1.71+): SDK 支持 Zod v3.24.1+ 和 Zod v4.0.0+ 作为对等依赖。两种版本都使用 import { z } from zod 导入。

2. 插件系统 (v0.1.27)

  • - plugins 数组 - 加载本地插件路径
  • 自定义插件支持 - 扩展代理能力

3. 钩子系统 (v0.1.0+)

全部 12 个钩子事件:

钩子触发时机使用场景
PreToolUse工具执行前验证、修改或阻止工具调用
PostToolUse
工具执行后 | 记录结果、触发副作用 |
| Notification | 代理通知 | 显示状态更新 |
| UserPromptSubmit | 收到用户提示 | 预处理或验证输入 |
| SubagentStart | 子代理生成 | 跟踪委派、记录上下文 |
| SubagentStop | 子代理完成 | 汇总结果、清理 |
| PreCompact | 上下文压缩前 | 在截断前保存状态 |
| PermissionRequest | 需要权限 | 自定义审批流程 |
| Stop | 代理停止 | 清理、最终日志记录 |
| SessionStart | 会话开始 | 初始化状态 |
| SessionEnd | 会话结束 | 持久化状态、清理 |
| Error | 发生错误 | 自定义错误处理 |

钩子配置:
typescript
const response = query({
prompt: ...,
options: {
hooks: {
PreToolUse: async (input) => {
console.log(工具: ${input.toolName});
return { allow: true }; // 或 { allow: false, message: ... }
},
PostToolUse: async (input) => {
await logToolUsage(input.toolName, input.result);
}
}
}
});

4. 其他选项

  • - fallbackModel - 失败时自动切换模型
  • maxThinkingTokens - 控制扩展思考预算
  • strictMcpConfig - 严格的 MCP 配置验证
  • continue - 使用新提示继续(与 resume 不同)
  • permissionMode: plan - 用于规划工作流的新权限模式

📚 文档: https://platform.claude.com/docs/en/agent-sdk/structured-outputs



Claude Agent SDK 完整参考

目录

  1. 1. 核心查询 API
  2. 工具集成
  3. MCP 服务器
  4. 子代理编排
  5. 会话管理
  6. 权限控制
  7. 沙箱设置
  8. 文件检查点
  9. 文件系统设置
  10. 查询对象方法
  11. 消息类型与流式处理
  12. 错误处理
  13. 已知问题

核心查询 API

关键签名:
typescript
query(prompt: string | AsyncIterable, options?: Options)
-> AsyncGenerator

关键选项:

  • - outputFormat - 结构化 JSON schema 验证 (v0.1.45+)
  • settingSources - 文件系统设置加载 (user|project|local)
  • canUseTool - 自定义权限逻辑回调
  • agents - 编程式子代理定义
  • mcpServers - MCP 服务器配置
  • permissionMode - default|acceptEdits|bypassPermissions|plan
  • betas - 启用 Beta 功能(例如 1M 上下文窗口)
  • sandbox - 安全执行的沙箱设置
  • enableFileCheckpointing - 启用文件状态快照
  • systemPrompt - 系统提示(字符串或预设对象)

扩展上下文 (1M Token)

启用 100 万 token 上下文窗口:

typescript
const response = query({
prompt: 分析这个大型代码库,
options: {
betas: [context-1m-2025-08-07], // 启用 1M 上下文
model: claude-sonnet-4-5
}
});

系统提示配置

systemPrompt 的两种形式:

typescript
// 1. 简单字符串
systemPrompt: 你是一个有用的编程助手。

// 2. 带可选追加的预设(保留 Claude Code 默认值)
systemPrompt: {
type: preset,
preset: claude_code,
append: \n\n额外上下文: 关注安全性。
}

使用预设形式 当你想保留 Claude Code 的默认行为并添加自定义内容时。



工具集成 (内置 + 自定义)

工具控制:

  • - allowedTools - 白名单(优先)
  • disallowedTools - 黑名单
  • canUseTool - 自定义权限回调(见权限控制部分)

内置工具: Read, Write, Edit, Bash, Grep, Glob, WebSearch, WebFetch, Task, NotebookEdit, BashOutput, KillBash, ListMcpResources, ReadMcpResource, AskUserQuestion

AskUserQuestion 工具 (v0.1.71+)

在代理执行期间启用用户交互:

typescript
const response = query({
prompt: 审查并重构代码库,
options: {
allowedTools: [Read, Write, Edit, AskUserQuestion]
}
});

// 代理现在可以提出澄清问题
// 问题在消息流中显示为 tool_call,名称为 AskUserQuestion

使用场景:

  • - 在任务执行中澄清模糊需求
  • 在破坏性操作前获取用户批准
  • 呈现选项并获取选择

工具配置 (v0.1.57+)

工具配置的三种形式:

typescript
// 1. 精确允许列表(字符串数组)
tools: [Read, Write, Grep]

// 2. 禁用所有工具(空数组)
tools: []

// 3. 带默认值的预设(对象形式)
tools: { type: preset, preset: claude_code }

注意: allowedTools 和 disallowedTools 仍然可用,但 tools 提供了更多灵活性。



MCP 服务器 (模型上下文协议)

服务器类型:

  • - 进程内 - 使用 tool() 定义的 createS

标签

skill ai

通过对话安装

该技能支持在以下平台通过对话安装:

OpenClaw WorkBuddy QClaw Kimi Claude

方式一:安装 SkillHub 和技能

帮我安装 SkillHub 和 claude-agent-sdk-1776376051 技能

方式二:设置 SkillHub 为优先技能安装源

设置 SkillHub 为我的优先技能安装源,然后帮我安装 claude-agent-sdk-1776376051 技能

通过命令行安装

skillhub install claude-agent-sdk-1776376051

下载

⬇ 下载 claude-agent-sdk v0.1.0(免费)

文件大小: 53.29 KB | 发布时间: 2026-4-17 15:19

v0.1.0 最新 2026-4-17 15:19
claude-agent-sdk v0.1.0

- Initial release of Claude Agent SDK for building autonomous AI agents.
- Supports structured JSON output with schema validation.
- Introduces plugins system for extensibility.
- Hooks system enables event-driven workflows.
- Prevents 14 documented errors related to coding, SRE, security, and troubleshooting.

Archiver·手机版·闲社网·闲社论坛·羊毛社区· 多链控股集团有限公司 · 苏ICP备2025199260号-1

Powered by Discuz! X5.0   © 2024-2025 闲社网·线报更新论坛·羊毛分享社区·http://xianshe.com

p2p_official_large
返回顶部