Build autonomous AI agents with Claude Agent SDK. Structured outputs guarantee JSON schema validation, with plugins system and hooks for event-driven workflows. Prevents 14 documented errors. Use when: building coding agents, SRE systems, security auditors, or troubleshooting CLI not found, structured output validation, session forking errors, MCP config issues, subagent cleanup.
数据来源:ClawHub。 在 ClawSkills 查看
选择你使用的 Agent
方法一:命令行安装(推荐)
推荐(无需提前安装 clawhub)
npx clawhub@latest --dir ~/.claude/skills install claude-agent-sdk或使用 clawhub CLI(需提前安装)
clawhub --dir ~/.claude/skills install claude-agent-sdk⚠️ 需要 Node.js 18+,没有 Node?请使用下方方法二直接下载 ZIP。 安装 Node.js →
方法二:手动下载安装(无需 Node)
下载 ZIP,解压后将文件夹放到以下路径,重启 Agent 即可:
安装路径
~/.claude/skills/claude-agent-sdk/💡解压后将文件夹放到上方路径,重启 Agent 即可生效
--- name: claude-agent-sdk description: | Build autonomous AI agents with Claude Agent SDK. Structured outputs guarantee JSON schema validation, with plugins system and hooks for event-driven workflows. Prevents 14 documented errors.
Use when: building coding agents, SRE systems, security auditors, or troubleshooting CLI not found, structured output validation, session forking errors, MCP config issues, subagent cleanup. user-invocable: true ---
Package: @anthropic-ai/[email protected] Breaking Changes: v0.1.45 - Structured outputs (Nov 2025), v0.1.0 - No default system prompt, settingSources required
---
Major Features:
outputFormat parameter - Define output structure with JSON schema or Zodmessage.structured_outputstructured-outputs-2025-11-13Example:
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: "Analyze this code review feedback",
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) {
// Guaranteed to match schema
const validated = schema.parse(message.structured_output);
console.log(`Sentiment: ${validated.sentiment}`);
}
}
Zod Compatibility (v0.1.71+): SDK supports both Zod v3.24.1+ and Zod v4.0.0+ as peer dependencies. Import remains import { z } from "zod" for either version.
plugins array - Load local plugin pathsAll 12 Hook Events:
| Hook | When Fired | Use Case | |------|------------|----------| | PreToolUse | Before tool execution | Validate, modify, or block tool calls | | PostToolUse | After tool execution | Log results, trigger side effects | | Notification | Agent notifications | Display status updates | | UserPromptSubmit | User prompt received | Pre-process or validate input | | SubagentStart | Subagent spawned | Track delegation, log context | | SubagentStop | Subagent completed | Aggregate results, cleanup | | PreCompact | Before context compaction | Save state before truncation | | PermissionRequest | Permission needed | Custom approval workflows | | Stop | Agent stopping | Cleanup, final logging | | SessionStart | Session begins | Initialize state | | SessionEnd | Session ends | Persist state, cleanup | | Error | Error occurred | Custom error handling |
Hook Configuration:
const response = query({
prompt: "...",
options: {
hooks: {
PreToolUse: async (input) => {
console.log(`Tool: ${input.toolName}`);
return { allow: true }; // or { allow: false, message: "..." }
},
PostToolUse: async (input) => {
await logToolUsage(input.toolName, input.result);
}
}
}
});
fallbackModel - Automatic model fallback on failuresmaxThinkingTokens - Control extended thinking budgetstrictMcpConfig - Strict MCP configuration validationcontinue - Resume with new prompt (differs from resume)permissionMode: 'plan' - New permission mode for planning workflows📚 Docs: https://platform.claude.com/docs/en/agent-sdk/structured-outputs
---
---
Key signature:
query(prompt: string | AsyncIterable<SDKUserMessage>, options?: Options)
-> AsyncGenerator<SDKMessage>
Critical Options:
outputFormat - Structured JSON schema validation (v0.1.45+)settingSources - Filesystem settings loading ('user'|'project'|'local')canUseTool - Custom permission logic callbackagents - Programmatic subagent definitionsmcpServers - MCP server configurationpermissionMode - 'default'|'acceptEdits'|'bypassPermissions'|'plan'betas - Enable beta features (e.g., 1M context window)sandbox - Sandbox settings for secure executionenableFileCheckpointing - Enable file state snapshotssystemPrompt - System prompt (string or preset object)Enable 1 million token context window:
const response = query({
prompt: "Analyze this large codebase",
options: {
betas: ['context-1m-2025-08-07'], // Enable 1M context
model: "claude-sonnet-4-5"
}
});
Two forms of systemPrompt:
// 1. Simple string
systemPrompt: "You are a helpful coding assistant."
// 2. Preset with optional append (preserves Claude Code defaults)
systemPrompt: {
type: 'preset',
preset: 'claude_code',
append: "\n\nAdditional context: Focus on security."
}
Use preset form when you want Claude Code's default behaviors plus custom additions.
---
Tool Control:
allowedTools - Whitelist (takes precedence)disallowedTools - BlacklistcanUseTool - Custom permission callback (see Permission Control section)Built-in Tools: Read, Write, Edit, Bash, Grep, Glob, WebSearch, WebFetch, Task, NotebookEdit, BashOutput, KillBash, ListMcpResources, ReadMcpResource, AskUserQuestion
Enable user interaction during agent execution:
const response = query({
prompt: "Review and refactor the codebase",
options: {
allowedTools: ["Read", "Write", "Edit", "AskUserQuestion"]
}
});
// Agent can now ask clarifying questions
// Questions appear in message stream as tool_call with name "AskUserQuestion"
Use cases:
Three forms of tool configuration:
// 1. Exact allowlist (string array)
tools: ["Read", "Write", "Grep"]
// 2. Disable all tools (empty array)
tools: []
// 3. Preset with defaults (object form)
tools: { type: 'preset', preset: 'claude_code' }
Note: allowedTools and disallowedTools still work but tools provides more flexibility.
---
Server Types:
createSdkMcpServer() with tool() definitionsTool Definition:
tool(name: string, description: string, zodSchema, handler)
Handler Return:
{ content: [{ type: "text", text: "..." }], isError?: boolean }
...
安装 Claude Agent Sdk 后,可以对 AI 说这些话来触发它
Help me get started with Claude Agent Sdk
Explains what Claude Agent Sdk does, walks through the setup, and runs a quick demo based on your current project
Use Claude Agent Sdk to build autonomous AI agents with Claude Agent SDK
Invokes Claude Agent Sdk with the right parameters and returns the result directly in the conversation
What can I do with Claude Agent Sdk in my developer & devops workflow?
Lists the top use cases for Claude Agent Sdk, with example commands for each scenario
将技能文件夹放到 ~/.claude/skills/claude-agent-sdk/ 目录(个人级,所有项目可用),或 .claude/skills/claude-agent-sdk/(项目级)。重启 AI 客户端后,用 /claude-agent-sdk 主动调用,或让 AI 根据上下文自动发现并使用。
Claude Agent Sdk 支持 Claude、Cursor、OpenClaw,可与这些 AI 平台无缝集成,扩展其能力。
Claude Agent Sdk 可免费安装使用。请查阅仓库了解许可证信息。
Build autonomous AI agents with Claude Agent SDK. Structured outputs guarantee JSON schema validation, with plugins system and hooks for event-driven workflows. Prevents 14 documented errors. Use when: building coding agents, SRE systems, security auditors, or troubleshooting CLI not found, structured output validation, session forking errors, MCP config issues, subagent cleanup.
Automate my developer & devops tasks using Claude Agent Sdk
Identifies repetitive steps in your workflow and sets up Claude Agent Sdk to handle them automatically
Claude Agent Sdk 属于「Developer & DevOps」分类,该分类的技能帮助 AI 智能体在此领域执行专业任务。