claude-agent-sdk
This skill provides comprehensive knowledge for working with the Anthropic Claude Agent SDK. It should be used when building autonomous AI agents, creating multi-step reasoning workflows, orchestrating specialized subagents, integrating custom tools and MCP servers, or implementing production-ready agentic systems with Claude Code's capabilities. Use when building coding agents, SRE systems, security auditors, incident responders, code review bots, or any autonomous system that requires programmatic interaction with Claude Code CLI, persistent sessions, tool orchestration, and fine-grained permission control. Keywords: claude agent sdk, @anthropic-ai/claude-agent-sdk, query(), createSdkMcpServer, AgentDefinition, tool(), claude subagents, mcp servers, autonomous agents, agentic loops, session management, permissionMode, canUseTool, multi-agent orchestration, settingSources, CLI not found, context length exceeded
What this skill does
# Claude Agent SDK **Status**: Production Ready **Last Updated**: 2025-10-25 **Dependencies**: @anthropic-ai/claude-agent-sdk, zod **Latest Versions**: @anthropic-ai/[email protected]+, [email protected]+ --- ## Quick Start (5 Minutes) ### 1. Install SDK ```bash npm install @anthropic-ai/claude-agent-sdk zod ``` **Why these packages:** - `@anthropic-ai/claude-agent-sdk` - Main Agent SDK - `zod` - Type-safe schema validation for tools ### 2. Set API Key ```bash export ANTHROPIC_API_KEY="sk-ant-..." ``` **CRITICAL:** - API key required for all agent operations - Never commit API keys to version control - Use environment variables ### 3. Basic Query ```typescript import { query } from "@anthropic-ai/claude-agent-sdk"; const response = query({ prompt: "Analyze the codebase and suggest improvements", options: { model: "claude-sonnet-4-5", workingDirectory: process.cwd(), allowedTools: ["Read", "Grep", "Glob"] } }); for await (const message of response) { if (message.type === 'assistant') { console.log(message.content); } } ``` --- ## 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. [Filesystem Settings](#filesystem-settings) 8. [Message Types & Streaming](#message-types--streaming) 9. [Error Handling](#error-handling) 10. [Known Issues](#known-issues-prevention) --- ## Core Query API ### The `query()` Function The primary interface for interacting with Claude Code CLI programmatically. ```typescript import { query } from "@anthropic-ai/claude-agent-sdk"; const response = query({ prompt: string | AsyncIterable<SDKUserMessage>, options?: Options }); // Response is AsyncGenerator<SDKMessage, void> for await (const message of response) { // Process streaming messages } ``` ### Basic Options ```typescript const response = query({ prompt: "Review this code for bugs", options: { model: "claude-sonnet-4-5", // or "haiku", "opus" workingDirectory: "/path/to/project", systemPrompt: "You are a security-focused code reviewer.", allowedTools: ["Read", "Grep", "Glob"], disallowedTools: ["Write", "Edit", "Bash"], permissionMode: "default" // or "acceptEdits", "bypassPermissions" } }); ``` ### Model Selection | Model | ID | Best For | Speed | Capability | |-------|-----|----------|-------|------------| | **Haiku** | `"haiku"` | Fast tasks, monitoring | Fastest | Basic | | **Sonnet** | `"sonnet"` or `"claude-sonnet-4-5"` | Balanced | Medium | High | | **Opus** | `"opus"` | Complex reasoning | Slowest | Highest | | **Inherit** | `"inherit"` | Use parent model | - | - | **Default**: `"sonnet"` if not specified ### System Prompts ```typescript const response = query({ prompt: "Implement user authentication", options: { systemPrompt: `You are an expert backend developer. Follow these principles: - Always use TypeScript with strict types - Implement comprehensive error handling - Add detailed logging for debugging - Write unit tests for all functions - Follow OWASP security guidelines` } }); ``` **CRITICAL:** - System prompt sets agent behavior for entire session - Should be clear and specific - Can be 1-10k tokens (affects context window) ### Working Directory ```typescript const response = query({ prompt: "Refactor the user service", options: { workingDirectory: "/Users/dev/projects/my-app", // Agent operates within this directory // Relative paths resolved from here } }); ``` **Best Practices:** - Use absolute paths for clarity - Agent stays within this directory scope - Critical for multi-project environments --- ## Tool Integration (Built-in + Custom) ### Built-in Tools The SDK provides access to Claude Code's built-in tools: | Tool | Description | Use Case | |------|-------------|----------| | `Read` | Read file contents | Code analysis | | `Write` | Create new files | Generate code | | `Edit` | Modify existing files | Refactoring | | `Bash` | Execute shell commands | Run tests, git | | `Grep` | Search file contents | Find patterns | | `Glob` | Find files by pattern | File discovery | | `WebSearch` | Search the web | Research | | `WebFetch` | Fetch URL content | Documentation | | `Task` | Delegate to subagent | Orchestration | ### Allowing/Disallowing Tools ```typescript // Whitelist approach (recommended) const response = query({ prompt: "Analyze code but don't modify anything", options: { allowedTools: ["Read", "Grep", "Glob"] // ONLY these tools can be used } }); // Blacklist approach const response = query({ prompt: "Review and fix issues", options: { disallowedTools: ["Bash"] // Everything except Bash allowed } }); // Combination (allowedTools takes precedence) const response = query({ prompt: "Safe code review", options: { allowedTools: ["Read", "Grep", "Glob", "Edit"], disallowedTools: ["Edit"] // Edit still blocked (allowedTools overridden) } }); ``` **CRITICAL:** - `allowedTools` = whitelist (only these tools) - `disallowedTools` = blacklist (everything except these) - If both specified, `allowedTools` wins ### Custom Tool Execution Monitoring ```typescript const response = query({ prompt: "Implement feature X", options: { allowedTools: ["Read", "Write", "Edit", "Bash"] } }); for await (const message of response) { if (message.type === 'tool_call') { console.log(`Tool requested: ${message.tool_name}`); console.log(`Input:`, message.input); } else if (message.type === 'tool_result') { console.log(`Tool ${message.tool_name} completed`); } } ``` --- ## MCP Servers (Model Context Protocol) ### Overview MCP servers extend agent capabilities with custom tools. The SDK supports: - **In-process servers** (`createSdkMcpServer`) - Run in same process - **External servers** (stdio, HTTP, SSE) - Separate processes ### Creating In-Process MCP Servers ```typescript import { createSdkMcpServer, tool } from "@anthropic-ai/claude-agent-sdk"; import { z } from "zod"; const weatherServer = createSdkMcpServer({ name: "weather-service", version: "1.0.0", tools: [ tool( "get_weather", "Get current weather for a location", { location: z.string().describe("City name or coordinates"), units: z.enum(["celsius", "fahrenheit"]).default("celsius") }, async (args) => { // Tool implementation const response = await fetch( `https://api.weather.com/v1/current?location=${args.location}&units=${args.units}` ); const data = await response.json(); return { content: [{ type: "text", text: `Temperature: ${data.temp}° ${args.units} Conditions: ${data.conditions} Humidity: ${data.humidity}%` }] }; } ) ] }); // Use in query const response = query({ prompt: "What's the weather in San Francisco?", options: { mcpServers: { "weather-service": weatherServer }, allowedTools: ["mcp__weather-service__get_weather"] } }); ``` ### Tool Definition Pattern ```typescript tool( name: string, // Tool identifier description: string, // What the tool does inputSchema: ZodSchema, // Input validation handler: async (args) => Result // Implementation ) ``` **Input Schema Options:** ```typescript // Simple object schema { email: z.string().email(), limit: z.number().min(1).max(100).default(10), enabled: z.boolean().optional() } // Complex nested schema { user: z.object({ name: z.string(), age: z.number().min(0) }), filters: z.array(z.string()).optional() } // Enum types { status: z.enum(["pending", "active", "completed"]), p
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.