claude-agent-sdk
Anthropic Claude Agent SDK for autonomous agents and multi-step workflows. Use for subagents, tool orchestration, MCP servers, or encountering CLI not found, context length exceeded errors.
What this skill does
# Claude Agent SDK **Status**: Production Ready **Last Updated**: 2025-11-21 **Dependencies**: @anthropic-ai/claude-code, zod **Latest Versions**: @anthropic-ai/[email protected]+, [email protected]+ --- ## Quick Start (5 Minutes) ### 1. Install SDK ```bash bun add @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); } } ``` --- ## Secure Installation Agent SDK packages provide system-level capabilities — verify before installing to prevent unauthorized agent access. Follow supply chain security best practices: - **Block post-install scripts** — `npm config set ignore-scripts true` (or Bun: disabled by default) - **Cooldown period** — Wait 7 days for new package versions to be vetted by the community - **Audit before installing** — Run `socket package score npm <pkg>` or use `socket npm install <pkg>` to check packages Load the `dependency-upgrade` skill for full security configuration including Socket CLI integration, cooldown setup, lockfile validation, and CI enforcement. ## 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) --- ## When to Load References The skill includes comprehensive reference files for deep dives. Load these when needed: - **`references/query-api-reference.md`** - Load when configuring query() options, working with message types, understanding filesystem settings, or debugging API behavior - **`references/mcp-servers-guide.md`** - Load when creating custom tools, integrating external MCP servers, or debugging server connections - **`references/subagents-patterns.md`** - Load when designing multi-agent systems, orchestrating specialized agents, or optimizing agent workflows - **`references/session-management.md`** - Load when implementing persistent conversations, forking sessions, or managing long-running interactions - **`references/permissions-guide.md`** - Load when implementing custom permission logic, securing agent capabilities, or controlling tool access - **`references/top-errors.md`** - Load when encountering errors, debugging issues, or implementing error handling --- ## Core Query API The `query()` function is the primary interface for interacting with Claude Code CLI programmatically. It returns an AsyncGenerator that streams messages as the agent works. **For complete API details, options, and advanced patterns**: Load `references/query-api-reference.md` when working with advanced configurations, message streaming, or filesystem settings. ### Basic Usage ```typescript import { query } from "@anthropic-ai/claude-agent-sdk"; const response = query({ prompt: "Review this code for bugs", options: { model: "claude-sonnet-4-5", // or "haiku", "opus" workingDirectory: "/path/to/project", allowedTools: ["Read", "Grep", "Glob"], permissionMode: "default" } }); for await (const message of response) { // Process streaming messages } ``` ### 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 | --- ## Tool Integration (Built-in + Custom) Claude Code provides built-in tools (Read, Write, Edit, Bash, Grep, Glob, WebSearch, WebFetch, Task) that can be controlled via `allowedTools` and `disallowedTools` options. **For complete tool configuration, custom monitoring, and advanced patterns**: Load `references/query-api-reference.md` when implementing tool restrictions or monitoring. ### 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 } }); ``` **CRITICAL**: `allowedTools` = whitelist (only these tools), `disallowedTools` = blacklist (everything except these). If both specified, `allowedTools` wins. --- ## MCP Servers (Model Context Protocol) MCP servers extend agent capabilities with custom tools via `createSdkMcpServer()` (in-process) or external servers (stdio, HTTP, SSE). **For complete MCP server implementation guide**: Load `references/mcp-servers-guide.md` when creating custom tools or integrating MCP servers. **Quick Example**: Create server with `tool(name, description, zodSchema, handler)`, use with `mcpServers` option and `allowedTools: ["mcp__<server>__<tool>"]` --- ## Subagent Orchestration Specialized agents with focused expertise, custom tools, different models, and dedicated prompts for multi-agent workflows. **For complete subagent patterns and orchestration strategies**: Load `references/subagents-patterns.md` when designing multi-agent systems. **AgentDefinition**: Use `agents` option with objects containing `description`, `prompt`, `tools` (optional), `model` (optional) --- ## Session Management Sessions enable persistent conversations, context preservation, and alternative exploration paths (forking). **For complete session patterns and workflows**: Load `references/session-management.md` when implementing persistent conversations. **Usage**: Capture `session_id` from system init message, resume with `resume: sessionId` option, fork with `forkSession: true` --- ## Permission Control Control agent capabilities with permission modes: `"default"` (standard checks), `"acceptEdits"` (auto-approve edits), `"bypassPermissions"` (skip all checks - use with caution). **For complete permission patterns and security policies**: Load `references/permissions-guide.md` when implementing custom permission logic. **Custom Logic**: Use `canUseTool: async (toolName, input) => ({ behavior: "allow" | "deny" | "ask", message?: string })` callback --- ## Filesystem Settings Control which settings files load via `settingSources` array: `"user"` (~/.claude/settings.json), `"project"` (.claude/settings.json), `"local"` (.claude/settings.local.json). **For complete configuration and priority rules**: Load `references/query-api-reference.md` when configuring settings sources. **Default**: `[]` (no settings loaded). **Priority**: Programmatic > local > project > user --- ## Message Types & Streaming The SDK streams messages: `system` (init/completion), `assistant` (responses), `tool_call` (tool requests), `tool_result` (tool outputs), `error` (failures). **For complete message type reference and streaming patterns**: Load `references/query-api-reference.md` when implementing advanced message handling. **Usage**: Process
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.