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.
What this skill does
# Claude Agent SDK - Structured Outputs & Error Prevention Guide **Package**: @anthropic-ai/[email protected] **Breaking Changes**: v0.1.45 - Structured outputs (Nov 2025), v0.1.0 - No default system prompt, settingSources required --- ## What's New in v0.1.45+ (Nov 2025) **Major Features:** ### 1. Structured Outputs (v0.1.45, Nov 14, 2025) - **JSON schema validation** - Guarantees responses match exact schemas - **`outputFormat` parameter** - Define output structure with JSON schema or Zod - **Access validated results** - Via `message.structured_output` - **Beta header required**: `structured-outputs-2025-11-13` - **Type safety** - Full TypeScript inference with Zod schemas **Example:** ```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: "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. ### 2. Plugins System (v0.1.27) - **`plugins` array** - Load local plugin paths - **Custom plugin support** - Extend agent capabilities ### 3. Hooks System (v0.1.0+) **All 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:** ```typescript 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); } } } }); ``` ### 4. Additional Options - **`fallbackModel`** - Automatic model fallback on failures - **`maxThinkingTokens`** - Control extended thinking budget - **`strictMcpConfig`** - Strict MCP configuration validation - **`continue`** - 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 --- ## The Complete Claude Agent SDK Reference ## Table of Contents 1. [Core Query API](#core-query-api) 2. [Tool Integration](#tool-integration-built-in--custom) 3. [MCP Servers](#mcp-servers-model-context-protocol) 4. [Subagent Orchestration](#subagent-orchestration) 5. [Session Management](#session-management) 6. [Permission Control](#permission-control) 7. [Sandbox Settings](#sandbox-settings-security-critical) 8. [File Checkpointing](#file-checkpointing) 9. [Filesystem Settings](#filesystem-settings) 10. [Query Object Methods](#query-object-methods) 11. [Message Types & Streaming](#message-types--streaming) 12. [Error Handling](#error-handling) 13. [Known Issues](#known-issues-prevention) --- ## Core Query API **Key signature:** ```typescript 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 callback - `agents` - Programmatic subagent definitions - `mcpServers` - MCP server configuration - `permissionMode` - 'default'|'acceptEdits'|'bypassPermissions'|'plan' - `betas` - Enable beta features (e.g., 1M context window) - `sandbox` - Sandbox settings for secure execution - `enableFileCheckpointing` - Enable file state snapshots - `systemPrompt` - System prompt (string or preset object) ### Extended Context (1M Tokens) Enable 1 million token context window: ```typescript const response = query({ prompt: "Analyze this large codebase", options: { betas: ['context-1m-2025-08-07'], // Enable 1M context model: "claude-sonnet-4-5" } }); ``` ### System Prompt Configuration Two forms of systemPrompt: ```typescript // 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 Integration (Built-in + Custom) **Tool Control:** - `allowedTools` - Whitelist (takes precedence) - `disallowedTools` - Blacklist - `canUseTool` - 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 ### AskUserQuestion Tool (v0.1.71+) Enable user interaction during agent execution: ```typescript 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:** - Clarify ambiguous requirements mid-task - Get user approval before destructive operations - Present options and get selection ### Tools Configuration (v0.1.57+) **Three forms of tool configuration:** ```typescript // 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. --- ## MCP Servers (Model Context Protocol) **Server Types:** - **In-process** - `createSdkMcpServer()` with `tool()` definitions - **External** - stdio, HTTP, SSE transport **Tool Definition:** ```typescript tool(name: string, description: string, zodSchema, handler) ``` **Handler Return:** ```typescript { content: [{ type: "text", text: "..." }], isError?: boolean } ``` ### External MCP Servers (stdio) ```typescript const response = query({ prompt: "List files and analyze Git history", options: { mcpServers: { // Filesystem server "filesystem": { command: "npx", args: ["@modelcontextprotocol/server-filesystem"], env: { ALLOWED_PATHS: "/Users/developer/projects:/tmp" } }, // Git operations server "git": { command: "npx", args: ["@modelcontextprotocol/s
Related in Backend & APIs
jfrog
IncludedInteract with the JFrog Platform via the JFrog CLI and REST/GraphQL APIs. Use this skill when the user wants to manage Artifactory repositories, upload or download artifacts, manage builds, configure permissions, manage users and groups, work with access tokens, configure JFrog CLI servers, search artifacts, manage properties, set up replication, manage JFrog Projects, run security audits or scans, look up CVE details, query exposures scan results from JFrog Advanced Security, manage release bundles and lifecycle operations, aggregate or export platform data, or perform any JFrog Platform administration task. Also use when the user mentions jf, jfrog, artifactory, xray, distribution, evidence, apptrust, onemodel, graphql, workers, mission control, curation, advanced security, exposures, or any JFrog product name.
cupynumeric-migration-readiness
IncludedPre-migration readiness assessor for porting NumPy to cuPyNumeric. Use BEFORE substantial porting work begins when the user asks whether code will scale on GPU, whether they should migrate to cuPyNumeric, which NumPy patterns transfer cleanly, what must be refactored before porting, or mentions pre-port assessment, scaling analysis, or refactor planning. Inspect the user's source code, look up NumPy usage, cross-reference the cuPyNumeric API support manifest, and distinguish distributed-scaling-friendly patterns from blockers such as unsupported APIs, scalar synchronization, host round-trips, Python/object-heavy control flow, shape/data-dependent branching, and in-place mutation hazards. Produce a verdict of READY, LIGHT REFACTOR, SIGNIFICANT REFACTOR, or NOT RECOMMENDED, with concrete refactor pointers.
alibabacloud-data-agent-skill
IncludedInvoke Alibaba Cloud Apsara Data Agent for Analytics via CLI to perform natural language-driven data analysis on enterprise databases. Data Agent for Analytics is an intelligent data analysis agent developed by Alibaba Cloud Database team for enterprise users. It automatically completes requirement analysis, data understanding, analysis insights, and report generation based on natural language descriptions. This tool supports: discovering data resources (instances/databases/tables) managed in DMS, initiating query or deep analysis sessions, real-time progress tracking, and retrieving analysis conclusions and generated reports. Use this Skill when users need to query databases, analyze data trends, generate data reports, ask questions in natural language, or mention "Data Agent", "data analysis", "database query", "SQL analysis", "data insights".
token-optimizer
IncludedReduce OpenClaw token usage and API costs through smart model routing, heartbeat optimization, budget tracking, and native 2026.2.15 features (session pruning, bootstrap size limits, cache TTL alignment). Use when token costs are high, API rate limits are being hit, or hosting multiple agents at scale. The 4 executable scripts (context_optimizer, model_router, heartbeat_optimizer, token_tracker) are local-only โ no network requests, no subprocess calls, no system modifications. Reference files (PROVIDERS.md, config-patches.json) document optional multi-provider strategies that require external API keys and network access if you choose to use them. See SECURITY.md for full breakdown.
resend-cli
IncludedUse this skill when the task is specifically about operating Resend from an AI agent, terminal session, or CI job via the official resend CLI: installing/authenticating the CLI, sending/listing/updating/cancelling emails, batch sends, domains and DNS, webhooks and local listeners, inbound receiving, contacts, topics, segments, broadcasts, templates, API keys, profiles, or debugging Resend CLI/API failures. Trigger on mentions of Resend CLI, `resend`, `resend doctor`, `resend emails send`, `resend domains`, `resend webhooks listen`, `resend emails receiving`, or agent-friendly terminal automation.
alibabacloud-odps-maxframe-coding
IncludedUse this skill for MaxFrame SDK development and documentation navigation on Alibaba Cloud MaxCompute (ODPS). Helps answer MaxFrame API, concept, official example, and supported pandas API questions; create data processing programs; read/write MaxCompute tables; debug jobs (remote or local); and build custom DPE runtime images. Trigger when users mention MaxFrame, MaxCompute with MaxFrame, ODPS table processing, DPE runtime, MaxFrame docs/examples, DataFrame/Tensor operations, or GPU runtime setup. Works for both English and Chinese queries about Alibaba Cloud data processing with MaxFrame.