claude-agent-sdk

jezweb/claude-skills · updated Apr 8, 2026

MDX-style export adds YAML metadata + attribution linking explainx.ai and this canonical listing URL.

$npx skills add https://github.com/jezweb/claude-skills --skill claude-agent-sdk
0 commentsdiscussion
summary

$22

skill.md

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:

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:

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
  2. Tool Integration
  3. MCP Servers
  4. Subagent Orchestration
  5. Session Management
  6. Permission Control
  7. Sandbox Settings
  8. File Checkpointing
  9. Filesystem Settings
  10. Query Object Methods
  11. Message Types & Streaming
  12. Error Handling
  13. Known Issues

Core Query API

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 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:

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:

// 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:

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:

// 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' 
how to use claude-agent-sdk

How to use claude-agent-sdk on Cursor

AI-first code editor with Composer

1

Prerequisites

Before installing skills in Cursor, ensure your development environment meets these requirements:

  • Cursor installed and configured on your development machine
  • Node.js version 16.0+ with npm package manager (verify with node --version)
  • Active project directory or workspace where you want to add claude-agent-sdk
2

Execute installation command

Execute the skills CLI command in your project's root directory to begin installation:

$npx skills add https://github.com/jezweb/claude-skills --skill claude-agent-sdk

The skills CLI fetches claude-agent-sdk from GitHub repository jezweb/claude-skills and configures it for Cursor.

3

Select Cursor when prompted

The CLI will show a list of available agents. Use arrow keys to navigate and space to select Cursor:

◆ Which agents do you want to install to?
│ ── Universal (.agents/skills) ── always included ────
│ • Amp
│ • Antigravity
│ • Cline
│ • Codex
│ ●Cursor(selected)
│ • Cursor
│ • Windsurf
4

Verify installation

Confirm successful installation by checking the skill directory location:

.cursor/skills/claude-agent-sdk

Reload or restart Cursor to activate claude-agent-sdk. Access the skill through slash commands (e.g., /claude-agent-sdk) or your agent's skill management interface.

Security & Verification Notice

We perform automated surface-level scans (Gen AI Scanner, Socket, Snyk) during installation. These checks detect common vulnerabilities but do not guarantee complete security. Always review skill source code and verify the publisher's reputation before production use.

Skills execute code in your development environment. Always verify the publisher's identity, review recent commits, and test in isolated environments before production deployment.

List & Monetize Your Skill

Submit your Claude Code skill and start earning

GET_STARTED →

Use Cases

Task Automation & Efficiency

Automate repetitive workflows and reduce manual effort

Example

Generate reports, summarize documents, draft communications

Save 3-5 hours per week on routine tasks

Knowledge Enhancement

Learn new skills, understand complex topics, get expert guidance

Example

Explain concepts, provide examples, suggest learning resources

Accelerate learning and skill development by 2x

Quality Improvement

Enhance output quality through reviews, suggestions, and refinements

Example

Review drafts, suggest improvements, catch errors

Improve work quality by 30-40% with less effort

Implementation Guide

Prerequisites

  • Claude Desktop or compatible AI client with skill support
  • Clear understanding of task or problem to solve
  • Willingness to iterate and refine outputs

Time Estimate

15-45 minutes depending on use case complexity

Installation Steps

  1. 1.Install skill using provided installation command
  2. 2.Test with simple use case relevant to your work
  3. 3.Evaluate output quality and relevance
  4. 4.Iterate on prompts to improve results
  5. 5.Integrate into regular workflow if valuable

Common Pitfalls

  • Expecting perfect results without iteration
  • Not providing enough context in prompts
  • Using skill for tasks outside its intended scope
  • Accepting outputs without review and validation

Best Practices

✓ Do

  • +Start with clear, specific prompts
  • +Provide relevant context and constraints
  • +Review and refine all outputs before using
  • +Iterate to improve output quality
  • +Document successful prompt patterns

✗ Don't

  • Don't use without understanding skill limitations
  • Don't skip validation of outputs
  • Don't share sensitive information in prompts
  • Don't expect skill to replace human judgment

💡 Pro Tips

  • Be specific about desired format and style
  • Ask for multiple options to choose from
  • Request explanations to understand reasoning
  • Combine AI efficiency with human expertise

When to Use This

✓ Use When

Use when skill capabilities match your task, clear ROI on time saved, and you can validate outputs. Best for repetitive tasks, learning, and quality improvement.

✗ Avoid When

Avoid when task requires deep expertise you can't validate, involves sensitive decisions, or when learning process is more valuable than speed of completion.

Learning Path

  1. 1Familiarize yourself with skill capabilities and limitations
  2. 2Start with low-risk, non-critical tasks
  3. 3Progress to more complex and valuable use cases
  4. 4Build expertise through regular use and experimentation

Discussion

Product Hunt–style comments (not star reviews)
  • No comments yet — start the thread.
general reviews

Ratings

4.856 reviews
  • Omar Verma· Dec 24, 2024

    Registry listing for claude-agent-sdk matched our evaluation — installs cleanly and behaves as described in the markdown.

  • Sofia Gill· Dec 24, 2024

    Useful defaults in claude-agent-sdk — fewer surprises than typical one-off scripts, and it plays nicely with `npx skills` flows.

  • Shikha Mishra· Dec 12, 2024

    claude-agent-sdk fits our agent workflows well — practical, well scoped, and easy to wire into existing repos.

  • Noor Huang· Dec 12, 2024

    I recommend claude-agent-sdk for anyone iterating fast on agent tooling; clear intent and a small, reviewable surface area.

  • Ren Menon· Nov 23, 2024

    claude-agent-sdk has been reliable in day-to-day use. Documentation quality is above average for community skills.

  • Aditi Bhatia· Nov 15, 2024

    Useful defaults in claude-agent-sdk — fewer surprises than typical one-off scripts, and it plays nicely with `npx skills` flows.

  • Nia Ramirez· Nov 15, 2024

    Registry listing for claude-agent-sdk matched our evaluation — installs cleanly and behaves as described in the markdown.

  • Yash Thakker· Nov 3, 2024

    claude-agent-sdk is among the better-maintained entries we tried; worth keeping pinned for repeat workflows.

  • Soo Thompson· Nov 3, 2024

    claude-agent-sdk reduced setup friction for our internal harness; good balance of opinion and flexibility.

  • Dhruvi Jain· Oct 22, 2024

    Keeps context tight: claude-agent-sdk is the kind of skill you can hand to a new teammate without a long onboarding doc.

showing 1-10 of 56

1 / 6