Complete guide to the Claude Agent SDK for building custom AI agents.
From claude-code-expertnpx claudepluginhub markus41/claude --plugin claude-code-expertThis skill uses the workspace's default tool permissions.
Searches, retrieves, and installs Agent Skills from prompts.chat registry using MCP tools like search_skills and get_skill. Activates for finding skills, browsing catalogs, or extending Claude.
Searches prompts.chat for AI prompt templates by keyword or category, retrieves by ID with variable handling, and improves prompts via AI. Use for discovering or enhancing prompts.
Enables AI agents to execute x402 payments with per-task budgets, spending controls, and non-custodial wallets via MCP tools. Use when agents pay for APIs, services, or other agents.
Complete guide to the Claude Agent SDK for building custom AI agents.
The Claude Agent SDK allows you to programmatically spawn and control Claude Code sessions from TypeScript/JavaScript or Python applications.
npm install @anthropic-ai/claude-agent-sdk
# or
pnpm add @anthropic-ai/claude-agent-sdk
# Using uv (recommended)
uv init && uv add claude-agent-sdk
# Using pip
python3 -m venv .venv && source .venv/bin/activate
pip3 install claude-agent-sdk
Prerequisite: Claude Code CLI must be installed:
curl -fsSL https://claude.ai/install.sh | bash
Required env var: ANTHROPIC_API_KEY
import { claude } from "@anthropic-ai/claude-code-sdk";
// Simple query
const response = await claude("What files are in this directory?");
console.log(response.text);
// With options
const response = await claude("Refactor this function", {
model: "claude-sonnet-4-6",
maxTurns: 10,
cwd: "/path/to/project",
allowedTools: ["Read", "Write", "Edit", "Glob", "Grep"],
});
import asyncio
from claude_agent_sdk import query, ClaudeAgentOptions
async def main():
async for message in query(
prompt="Find and fix the bug in auth.py",
options=ClaudeAgentOptions(
allowed_tools=["Read", "Edit", "Bash"],
permission_mode="acceptEdits",
),
):
print(message)
asyncio.run(main())
ClaudeAgentOptions(
allowed_tools=["Read", "Edit", "Bash"],
permission_mode="acceptEdits", # default, acceptEdits, dontAsk, bypassPermissions, plan
system_prompt="Custom prompt",
agents={"reviewer": AgentDefinition(
description="Expert code reviewer",
prompt="Analyze code quality.",
tools=["Read", "Glob", "Grep"],
)},
mcp_servers={"playwright": {...}},
)
import { query } from "@anthropic-ai/claude-agent-sdk";
// Stream responses
for await (const message of query({
prompt: "Explain this codebase",
options: {
allowedTools: ["Read", "Glob", "Grep"],
}
})) {
console.log(message);
}
interface TextEvent {
type: "text";
text: string;
}
interface ToolUseEvent {
type: "tool_use";
name: string;
input: Record<string, unknown>;
id: string;
}
interface ToolResultEvent {
type: "tool_result";
tool_use_id: string;
content: string;
is_error: boolean;
}
interface StopEvent {
type: "stop";
reason: "end_turn" | "max_turns" | "error";
}
interface ClaudeOptions {
// Model selection
model?: string; // Claude model to use
// Conversation control
maxTurns?: number; // Max agentic turns
systemPrompt?: string; // Override system prompt
appendSystemPrompt?: string; // Append to system prompt
// Working directory
cwd?: string; // Working directory for file operations
// Permissions
allowedTools?: string[]; // Allowed tools list
disallowedTools?: string[]; // Denied tools list
permissionMode?: "default" | "plan" | "bypassPermissions";
// Session management
sessionId?: string; // Resume existing session
continue?: boolean; // Continue last session
// MCP
mcpConfig?: string; // Path to MCP config file
// Environment
env?: Record<string, string>; // Additional env vars
// Input
inputFormat?: "text" | "stream-json";
// Abort
abortSignal?: AbortSignal; // Cancel the request
}
When using the Agent tool within Claude Code, these sub-agent types are available:
| Type | Purpose | Tools Available |
|---|---|---|
general-purpose | Multi-step tasks, code search | All tools |
Explore | Fast codebase exploration | Read-only tools |
Plan | Architecture & implementation planning | Read-only tools |
claude-code-guide | Claude Code feature questions | Read-only + web |
researcher | Deep research with web access | Read-only + web |
test-writer | Write comprehensive tests | All tools |
code-reviewer | Code review and quality | Read-only + Bash |
debugger | Debug errors and failures | All tools |
doc-writer | Documentation generation | Write tools |
security-reviewer | Security audit | Read-only + Bash |
regex-expert | Regular expression design | Read/Write tools |
prisma-specialist | Prisma ORM operations | All tools |
redis-specialist | Redis caching patterns | All tools |
graphql-specialist | GraphQL API design | All tools |
infrastructure-specialist | Distributed systems, k8s | All tools |
docker-ops | Docker build and registry | Read-only + Bash |
k8s-image-auditor | K8s deployment auditing | Read-only + Bash |
ansible-specialist | Ansible automation | All tools |
pulumi-specialist | Pulumi IaC | All tools |
coverage-analyzer | Test coverage analysis | All tools |
spec-validator | API spec validation | All tools |
rabbitmq-specialist | RabbitMQ messaging | All tools |
event-streaming-architect | CQRS/event sourcing | All tools |
kafka-specialist | Apache Kafka streaming | All tools |
plugin-manager | Claude Code plugin management | All tools |
statusline-setup | Claude Code status line config | Read + Edit |
When spawning agents, Claude should prefer to orchestrate — delegate work to specialist agents rather than doing it directly. Key principles:
SendMessage(to: agent_id) every 2 minrun_in_background: true for independent work you don't need immediatelyisolation: "worktree" for agents that write code to prevent conflictsName your agents for easy resumption:
Agent(name="builder-1", subagent_type="general-purpose", ...)
Agent(name="auditor-1", subagent_type="code-reviewer", ...)
# Later, resume:
SendMessage(to: "builder-1", message: "Fix the issues found in audit")
import { claude } from "@anthropic-ai/claude-code-sdk";
// Run multiple agents in parallel
const [security, performance, docs] = await Promise.all([
claude("Review security of auth module", {
allowedTools: ["Read", "Glob", "Grep"],
}),
claude("Profile and optimize the API routes", {
allowedTools: ["Read", "Glob", "Grep", "Bash"],
}),
claude("Generate API documentation", {
allowedTools: ["Read", "Glob", "Grep", "Write"],
}),
]);
// Step 1: Research
const research = await claude("Analyze the authentication system");
// Step 2: Plan based on research
const plan = await claude(`Based on this analysis: ${research.text}\n\nCreate an implementation plan`);
// Step 3: Implement based on plan
const impl = await claude(`Implement this plan: ${plan.text}`, {
allowedTools: ["Read", "Write", "Edit", "Bash"],
});
import { claude } from "@anthropic-ai/claude-code-sdk";
async function supervisedTask(task: string) {
// Worker does the task
const result = await claude(task, {
maxTurns: 20,
allowedTools: ["Read", "Write", "Edit", "Bash", "Glob", "Grep"],
});
// Reviewer checks the work
const review = await claude(
`Review this work for quality and correctness:\n\nTask: ${task}\n\nResult: ${result.text}`,
{
allowedTools: ["Read", "Glob", "Grep"],
}
);
return { result, review };
}
Inside Claude Code conversations, use the Agent tool:
Agent tool parameters:
- prompt: The task description
- subagent_type: Agent specialization (see table above)
- description: Short 3-5 word summary
- run_in_background: true/false for async execution
- isolation: "worktree" for isolated git worktree
- mode: "plan", "acceptEdits", "bypassPermissions", "default", "dontAsk"
- resume: Agent ID to resume previous agent
// Launch in background - get notified on completion
Agent(subagent_type="researcher", run_in_background=true, ...)
// Resume a completed agent
Agent(resume="agent-id-here", ...)
// Run agent in isolated git worktree
Agent(subagent_type="test-writer", isolation="worktree", ...)
// Agent gets its own copy of the repo
// Changes are on a separate branch
Create custom agent definitions in .claude/agents/:
---
name: my-specialist
description: Domain-specific expert
tools:
- Read
- Write
- Edit
- Bash
model: claude-sonnet-4-6
---
# My Specialist Agent
You are an expert in [domain]. When activated, you should:
1. Analyze the current context
2. Apply domain-specific knowledge
3. Provide actionable recommendations
## Guidelines
- Always check existing code before suggesting changes
- Follow project conventions
- Include tests for new functionality
Agent teams allow multiple Claude instances to collaborate on tasks.
# Enable agent teams
export CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS=1
# Start as teammate
claude --teammate-mode "task description"
# Set team name
export CLAUDE_CODE_TEAM_NAME="my-team"
# Require plan mode for teammates
export CLAUDE_CODE_PLAN_MODE_REQUIRED=1
// Coordinator spawns specialized teammates
const result = await claude("Coordinate the following tasks", {
agents: {
"frontend-dev": {
description: "Frontend specialist",
prompt: "You handle React components",
tools: ["Read", "Write", "Edit", "Bash"],
},
"backend-dev": {
description: "Backend specialist",
prompt: "You handle API routes",
tools: ["Read", "Write", "Edit", "Bash"],
},
},
});
# Create a cloud session
claude --remote "implement feature X"
# Resume a web session locally
claude --teleport
# Start remote control
/remote-control
import { claude } from "@anthropic-ai/claude-code-sdk";
try {
const response = await claude("risky operation", {
maxTurns: 5,
});
if (response.exitCode !== 0) {
console.error("Agent encountered an error");
}
} catch (error) {
if (error.name === "AbortError") {
console.log("Agent was cancelled");
} else {
console.error("Unexpected error:", error);
}
}
# GitHub Actions example
- name: Code Review with Claude
run: |
npx claude -p "Review the changes in this PR and report issues" \
--output-format json \
--max-turns 10 \
> review.json
env:
ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}