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.
git clone --depth 1 https://github.com/secondsky/claude-skills /tmp/claude-agent-sdk && cp -r /tmp/claude-agent-sdk/plugins/claude-agent-sdk/skills/claude-agent-sdk ~/.claude/skills/claude-agent-sdkSKILL.md
# Claude Agent SDK
**Status**: Production Ready
**Last Updated**: 2025-11-21
**Dependencies**: @anthropic-ai/claude-code, zod
**Latest Versions**: @anthropic-ai/claude-code@2.0.49+, zod@3.23.0+
---
## 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 modeRole-based access control (RBAC) with permissions and policies. Use for admin dashboards, enterprise access, multi-tenant apps, fine-grained authorization, or encountering permission hierarchies, role inheritance, policy conflicts.
100+ animated React components (Aceternity UI) for Next.js with Tailwind. Use for hero sections, parallax, 3D effects, or encountering animation, shadcn CLI integration errors.
shadcn/ui AI chat components for conversational interfaces. Use for streaming chat, tool/function displays, reasoning visualization, or encountering Next.js App Router setup, Tailwind v4 integration, AI SDK v5 migration errors.
Vercel AI SDK v5 for backend AI (text generation, structured output, tools, agents). Multi-provider. Use for server-side AI or encountering AI_APICallError, AI_NoObjectGeneratedError, streaming failures.
Vercel AI SDK v5 React hooks (useChat, useCompletion, useObject) for AI chat interfaces. Use for React/Next.js AI apps or encountering parse stream errors, no response, streaming issues.
Secure API authentication with JWT, OAuth 2.0, API keys. Use for authentication systems, third-party integrations, service-to-service communication, or encountering token management, security headers, auth flow errors.
Creates comprehensive API changelogs documenting breaking changes, deprecations, and migration strategies for API consumers. Use when managing API versions, communicating breaking changes, or creating upgrade guides.
Verifies API contracts between services using consumer-driven contracts, schema validation, and tools like Pact. Use when testing microservices communication, preventing breaking changes, or validating OpenAPI specifications.