Claude
Skills
Sign in
Back

agent-sdk-builder

Included with Lifetime
$97 forever

Build apps with the Claude Agent SDK (formerly Claude Code SDK). Covers programmatic agent loops, tool integration, subagent orchestration, prompt caching, and migration between Claude model versions. TRIGGER WHEN: code references claude-agent-sdk, user says "agent sdk", "build an agent", "programmatic claude", "claude code sdk", "sidecar", "run claude programmatically". DO NOT TRIGGER WHEN: user is using the Claude API client SDK (`anthropic`/`@anthropic-ai/sdk`) for direct chat completions, or doing general programming unrelated to agent orchestration.

Backend & APIs

What this skill does


# Claude Agent SDK

The Claude Agent SDK lets you run Claude Code programmatically -- build AI agents that read files, write code, execute commands, search the web, and orchestrate subagents, all from your application code.

**Key distinction**: The Agent SDK (`claude-agent-sdk`) runs the full Claude Code agent loop with built-in tools. The Anthropic Client SDK (`anthropic`) is for raw API calls. Use the Agent SDK when you need autonomous tool-using agents.

## Quick Reference

| | TypeScript | Python |
|---|---|---|
| **Package** | `@anthropic-ai/claude-agent-sdk` | `claude-agent-sdk` |
| **Install** | `npm install @anthropic-ai/claude-agent-sdk` | `pip install claude-agent-sdk` |
| **Auth** | `ANTHROPIC_API_KEY` env var | `ANTHROPIC_API_KEY` env var |
| **Core function** | `query()` | `query()` |
| **GitHub** | `anthropics/claude-agent-sdk-typescript` | `anthropics/claude-agent-sdk-python` |

The CLI package `@anthropic-ai/claude-code` is bundled inside the SDK -- no separate install needed.

---

## 1. Installation & Auth

```bash
# TypeScript
npm install @anthropic-ai/claude-agent-sdk

# Python
pip install claude-agent-sdk
# or with uv
uv add claude-agent-sdk
```

Authentication via environment variable:

```bash
export ANTHROPIC_API_KEY=sk-ant-...
```

Alternative providers:
- **Amazon Bedrock**: `CLAUDE_CODE_USE_BEDROCK=1` + AWS credentials
- **Google Vertex AI**: `CLAUDE_CODE_USE_VERTEX=1` + GCP credentials
- **Microsoft Azure**: `CLAUDE_CODE_USE_FOUNDRY=1` + Azure credentials

---

## 2. Core API -- `query()`

Both SDKs expose `query()` as the primary entry point. It returns an async iterator streaming `SDKMessage` objects. Claude handles the entire tool loop autonomously -- you do NOT implement tool execution.

### TypeScript

```typescript
import { query } from "@anthropic-ai/claude-agent-sdk";

for await (const message of query({
  prompt: "Find and fix the bug in auth.py",
  options: {
    allowedTools: ["Read", "Edit", "Bash"],
    maxTurns: 10,
  },
})) {
  if (message.type === "assistant" && message.content) {
    for (const block of message.content) {
      if (block.type === "text") process.stdout.write(block.text);
    }
  }
  if ("result" in message) {
    console.log("\nFinal:", message.result);
    console.log("Cost:", message.total_cost_usd);
  }
}
```

### Python

```python
import asyncio
from claude_agent_sdk import query, ClaudeAgentOptions

async def main():
    options = ClaudeAgentOptions(
        allowed_tools=["Read", "Edit", "Bash"],
        max_turns=10,
    )
    async for message in query(prompt="Find and fix the bug in auth.py", options=options):
        if hasattr(message, "result"):
            print(f"Final: {message.result}")
            print(f"Cost: ${message.total_cost_usd:.4f}")

asyncio.run(main())
```

---

## 3. Configuration Options

### Full Options Reference

| Option (TS / Py) | Type | Description |
|---|---|---|
| `allowedTools` / `allowed_tools` | `string[]` | Tools to auto-approve without user confirmation |
| `disallowedTools` / `disallowed_tools` | `string[]` | Tools to always deny |
| `permissionMode` / `permission_mode` | `string` | Permission strategy (see Permissions section) |
| `systemPrompt` / `system_prompt` | `string` | Custom system prompt or `"claude_code"` for default |
| `model` | `string` | Model ID (e.g., `"claude-sonnet-4-7"`, `"claude-opus-4-7"`, `"claude-haiku-4-5"`) -- short aliases resolve to the latest date-slugged release (e.g., `"claude-sonnet-4-5-20250929"`); pin a full slug for reproducibility |
| `maxTurns` / `max_turns` | `number` | Maximum agentic loop iterations |
| `maxBudgetUsd` / `max_budget_usd` | `number` | Spending cap in USD |
| `effort` | `string` | `"low"`, `"medium"`, `"high"`, `"max"` |
| `cwd` | `string` | Working directory for file operations |
| `mcpServers` / `mcp_servers` | `object` | MCP server configurations |
| `hooks` | `object` | Lifecycle hook callbacks |
| `agents` | `object` | Subagent definitions |
| `resume` | `string` | Session ID to resume |
| `continue` / `continue_conversation` | `boolean` | Continue most recent session |
| `forkSession` / `fork_session` | `string` | Fork from an existing session |
| `settingSources` / `setting_sources` | `string[]` | Load settings from `["user", "project", "local"]` |
| `plugins` | `string[]` | Local plugin directory paths |
| `sandbox` | `object` | Sandbox/isolation settings |
| `thinking` | `object` | Extended thinking: `"adaptive"`, `{type: "enabled", budget: N}`, `"disabled"` |
| `outputFormat` / `output_format` | `object` | JSON schema for structured output |
| `env` | `object` | Environment variables passed to agent |
| `canUseTool` / `can_use_tool` | `function` | Runtime permission callback |
| `includePartialMessages` / `include_partial_messages` | `boolean` | Enable token-level streaming |
| `spawnClaudeCodeProcess` | `function` | Custom process spawner (VMs, containers, remote) |
| `agentProgressSummaries` | `boolean` | Enable periodic AI-generated progress summaries for running subagents |
| `debug` / `debug` | `boolean` | Enable programmatic debug logging |
| `debugFile` / `debug_file` | `string` | File path for debug log output |

### Example -- Full Configuration

```typescript
import { query } from "@anthropic-ai/claude-agent-sdk";

for await (const msg of query({
  prompt: "Refactor the auth module to use JWT tokens",
  options: {
    model: "claude-sonnet-4-7",
    allowedTools: ["Read", "Write", "Edit", "Bash", "Glob", "Grep"],
    disallowedTools: ["WebSearch", "WebFetch"],
    permissionMode: "bypassPermissions",
    maxTurns: 25,
    maxBudgetUsd: 1.0,
    effort: "high",
    cwd: "/home/user/project",
    systemPrompt: "You are a senior backend engineer. Follow the project's coding standards.",
    thinking: "adaptive",
    env: { NODE_ENV: "development" },
  },
})) {
  // process messages
}
```

---

## 4. Built-in Tools

The agent has access to these tools by default:

| Tool | Purpose |
|---|---|
| `Read` | Read files from filesystem |
| `Write` | Create new files |
| `Edit` | Precise string replacements in existing files |
| `Bash` | Execute shell commands |
| `Glob` | Find files by pattern |
| `Grep` | Search file contents with regex |
| `WebSearch` | Search the web |
| `WebFetch` | Fetch and parse web pages |
| `Agent` | Spawn subagents (required for multi-agent) |
| `Skill` | Invoke skills from plugins |
| `AskUserQuestion` | Request user input |
| `TodoWrite` | Manage task lists |
| `ToolSearch` | Discover deferred tools |

Control which tools the agent can use:

```typescript
// Only allow read-only operations
options: {
  allowedTools: ["Read", "Glob", "Grep"],
  disallowedTools: ["Bash", "Write", "Edit"],
}
```

---

## 5. Custom Tools via MCP

Create custom tools using the SDK's MCP server helpers. Tools are defined with schemas and handlers, then exposed as in-process MCP servers.

### TypeScript

```typescript
import { tool, createSdkMcpServer, query } from "@anthropic-ai/claude-agent-sdk";
import { z } from "zod";

// Define tools
const getWeather = tool(
  "get_weather",
  "Get current weather for a city",
  { city: z.string(), units: z.enum(["celsius", "fahrenheit"]).default("celsius") },
  async ({ city, units }) => ({
    content: [{ type: "text", text: JSON.stringify({ city, temp: 22, units }) }],
  })
);

const searchDatabase = tool(
  "search_db",
  "Search the application database",
  { query: z.string(), limit: z.number().default(10) },
  async ({ query: q, limit }) => {
    const results = await db.search(q, limit);
    return { content: [{ type: "text", text: JSON.stringify(results) }] };
  }
);

// Create MCP server
const server = createSdkMcpServer({
  name: "app-tools",
  tools: [getWeather, searchDatabase],
});

// Use in query
for await (const msg of query({
  prompt: "What's the weather in Rome and find related travel posts?",
  options: {
    mcpServers: { app: server },
    allowedTools: ["mcp__app__get_weather", "mcp__app__search_db"],
  },
})) 

Related in Backend & APIs