# What Is the Claude Agent SDK? The Library Behind Claude Code

> The Claude Agent SDK lets you embed Claude Code's agent loop, tools, and permissions directly into Python and TypeScript applications on your infrastructure.

Source: https://camnangai.com/en/engineering/what-is-the-claude-agent-sdk  
Published: 2026-11-17

The [**Claude Agent SDK**](https://code.claude.com/docs/en/agent-sdk/overview) is a standalone
  library for Python 3.10+ and Node.js 18.14+/TypeScript that embeds the native Claude Code
  execution binary directly into your application process.

Instead of managing custom API loops or shelling out to external processes, you use the SDK to
programmatically drive the agent loop, execute local tools, manage context, enforce permission
boundaries, and run subagents inside infrastructure you operate.


  By integrating the engine behind Claude Code into your code, you gain full programmatic control
  over agent behavior, tool execution, and operational spend.

You configure system prompts, tool allowlists, spend caps, and event hooks in code while the library
handles low-level process management, prompt caching, and session persistence.

![The Claude Agent SDK embeds the native Claude Code engine directly into application processes](https://camnangai.com/articles/claude-agent-sdk-la-gi/01-infographic-en.webp)

## What is the Claude Agent SDK?

The **Claude Agent SDK** allows you to programmatically embed Claude Code's core agent capabilities into Python and TypeScript applications. These capabilities include inspecting codebases, reading and editing files on disk, executing shell commands, searching the web, tracking multi-turn sessions, spawning specialized subagents, running lifecycle hooks, and connecting to external systems via Model Context Protocol (MCP) servers.

Package installation installs the native platform binaries automatically. In Python, you install `claude-agent-sdk`; in TypeScript, you install `@anthropic-ai/claude-agent-sdk`. Both packages bundle an executable binary for your operating system, eliminating the need to install the Claude Code CLI separately. The bundled executable is omitted only under specific conditions, such as when `pip` installs from a source distribution on unsupported platforms like ARM64 Windows, or when `npm` installs skip optional dependencies (for example, `npm ci --omit=optional`). In those cases, the SDK falls back to finding a system-installed executable on your system path or using a configured executable path option (`cli_path` in Python or `pathToClaudeCodeExecutable` in TypeScript).

![Two ways to leverage the same core engine: interactive terminal CLI versus programmatic in-process Agent SDK](https://camnangai.com/articles/claude-agent-sdk-la-gi/02-en.webp)

Authentication is configured via environment variables. The SDK defaults to using standard Anthropic API keys set in `ANTHROPIC_API_KEY`. It also supports cloud provider platforms via targeted environment flags: Amazon Bedrock via `CLAUDE_CODE_USE_BEDROCK=1`, Claude Platform on AWS via `CLAUDE_CODE_USE_ANTHROPIC_AWS=1` (with `ANTHROPIC_AWS_WORKSPACE_ID`), Google Cloud Vertex AI via `CLAUDE_CODE_USE_VERTEX=1`, and Microsoft Foundry via `CLAUDE_CODE_USE_FOUNDRY=1`. [Anthropic](https://www.anthropic.com) explicitly prohibits third-party developers from offering end-user claude.ai logins or sharing claude.ai rate limits inside products built with the SDK.

The SDK automatically integrates with local project environments. When configured with project setting sources, it pulls project-level and user-level skills, custom commands, memory, and runtime rules from local `.claude/` directories and the user's home directory (`~/.claude/`). This ensures that agents running in your execution environment inherit existing workspace configurations without manual prompt construction.

## How the in-process agent loop works

Every session executed by the SDK follows a structured five-stage cycle:

1. **Prompt reception and initialization:** The engine receives your prompt alongside tool schemas, system instructions, and optional session history. The stream yields an initial `SystemMessage` with subtype `"init"` containing session metadata.
2. **Evaluation & response block emission:** Model logic evaluates the context state and emits decisions. The SDK yields `AssistantMessage` objects containing text content or structured tool call requests.
3. **Tool execution and output feedback:** The underlying binary executes requested tools (such as reading disk paths or running shell scripts) or routes custom tools back to application code. Results feed back into the model context as a `UserMessage`.
4. **Cycle repetition:** Steps 2 and 3 repeat continuously as a loop. The agent processes outputs, re-evaluates progress, and executes subsequent steps.
5. **Final result delivery:** Once the model generates a response containing no tool requests, the execution loop completes, yielding a `ResultMessage` containing final text, token usage metrics, dollar spend, and session identifiers.

Turn mechanics differ between simple queries and complex workflows. A turn consists of a single pass where the model emits output and the engine executes any requested tools, feeding results back automatically. Single-turn questions finish after reading context once, whereas complex refactorings execute dozens of tool calls across sequential turns. Throughout this cycle, control remains inside the binary execution loop and does not return control to caller application code until intermediate steps yield stream events or complete execution.

The SDK stream yields five primary message types:

- `SystemMessage`: Emits lifecycle events identified by their `subtype` field, including `"init"` (session start), `"compact_boundary"` (post-compaction boundary), `"informational"` (status banners), and `"worker_shutting_down"` (process exit).
- `AssistantMessage`: Emits content blocks generated by the model, such as `TextBlock` for text or `ToolUseBlock` for tool requests.
- `UserMessage`: Emits tool result payloads fed back to the model or user input injected mid-loop.
- `StreamEvent`: Emits raw API streaming deltas (such as partial token chunks) when partial message streaming is enabled.
- `ResultMessage`: Emits the final output state, token consumption counts, total dollar spend, and session IDs.

![The 5-stage in-process agent execution cycle with automatic context compaction](https://camnangai.com/articles/claude-agent-sdk-la-gi/03-en.webp)

Context window management is handled automatically by the engine. As conversation history grows and approaches token boundaries, the SDK triggers automatic compaction. Compaction summarizes older conversation turns to reclaim context space while keeping recent exchanges intact, emitting a `compact_boundary` system message to mark the summary point. Rules stored in `CLAUDE.md` files survive compaction because the engine re-injects their contents into the prompt on every request. Developers can intercept compaction events using `PreCompact` hooks or manually trigger compaction by sending `/compact` as a prompt string.

## Comparing Agent SDK to the CLI, Client SDK, and Managed Agents

Anthropic provides four primary methods for building with Claude. Selection depends on where execution occurs, which capabilities come pre-packaged, and how application code interacts with the model loop.

| Tool / Method       | Host / Execution Location                            | Built-in Capabilities                                                                       | Ideal Use Case                                                                                   |
| :------------------ | :--------------------------------------------------- | :------------------------------------------------------------------------------------------ | :----------------------------------------------------------------------------------------------- |
| **Agent SDK**       | Local/Self-hosted infrastructure (In-process binary) | Built-in tools, permission engine, session storage, lifecycle hooks, MCP support, subagents | Programmatic background services, web app backends, autonomous local agents, custom CI pipelines |
| **Claude Code CLI** | Local developer workstation (Terminal process)       | Terminal UI, built-in tools, interactive prompts, local config loading                      | Daily interactive coding, manual terminal debugging, quick ad-hoc scripts                        |
| **Client SDK**      | Application process (Direct API calls)               | Raw API access, basic model completions, optional beta tool runner                          | Single-turn text generation, simple custom tools, architectures requiring custom loop logic      |
| **Managed Agents**  | Anthropic Cloud sandbox or self-hosted container     | Cloud agent harness, hosted sandboxes, remote state, REST control                           | Serverless architectures needing hosted sandboxes without managing local execution binaries      |

## Building your first agent in Python and TypeScript

To build an agent, install the dependency, define code containing an error, and invoke `query()`. The agent inspects the file, identifies edge cases, and applies fixes to disk autonomously.

Create a file named `utils.py` containing buggy code:

```python
def calculate_average(numbers):
    total = 0
    for num in numbers:
        total += num
    return total / len(numbers)


def get_user_name(user):
    return user["name"].upper()
```

The Python SDK implementation uses `async for` to consume the message stream, using `isinstance` checks against typed content blocks:

```python
import asyncio
from claude_agent_sdk import (
    query,
    ClaudeAgentOptions,
    AssistantMessage,
    ResultMessage,
    TextBlock,
    ToolUseBlock,
)


async def main():
    async for message in query(
        prompt="Review utils.py for bugs that cause crashes. Fix any issues you find.",
        options=ClaudeAgentOptions(
            allowed_tools=["Read", "Edit", "Glob"],
            permission_mode="acceptEdits",
        ),
    ):
        if isinstance(message, AssistantMessage):
            for block in message.content:
                if isinstance(block, TextBlock):
                    print(f"Reasoning: {block.text}")
                elif isinstance(block, ToolUseBlock):
                    print(f"Tool Call: {block.name}")
        elif isinstance(message, ResultMessage):
            print(f"Final Status: {message.subtype}")


if __name__ == "__main__":
    asyncio.run(main())
```

The TypeScript SDK implementation uses `for await...of` to iterate over stream messages:

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

async function main() {
  for await (const message of query({
    prompt: "Review utils.py for bugs that cause crashes. Fix any issues you find.",
    options: {
      allowedTools: ["Read", "Edit", "Glob"],
      permissionMode: "acceptEdits",
    },
  })) {
    if (message.type === "assistant" && message.message?.content) {
      for (const block of message.message.content) {
        if (block.type === "text") {
          console.log(`Reasoning: ${block.text}`);
        } else if (block.type === "tool_use") {
          console.log(`Tool Call: ${block.name}`);
        }
      }
    } else if (message.type === "result") {
      console.log(`Final Status: ${message.subtype}`);
    }
  }
}

main();
```

When executed, the SDK streams content blocks as processing occurs. Text blocks contain reasoning steps, while tool use blocks detail executed file operations. The loop automatically writes updated code back to `utils.py`, adding checks for empty lists and `None`/`null` input values. The execution concludes by emitting a `ResultMessage`. If execution terminates due to safety bounds rather than completion, the result's `subtype` field yields `error_max_turns` or `error_max_budget_usd`.

## Safety controls: Tool permissions, sandboxing, and cost tracking

Every tool request generated by the model passes through a strict 6-step Permission Evaluation Flow:

1. **Hooks:** `PreToolUse` hooks execute first. A hook can explicitly allow or deny the call.
2. **Deny rules:** Checks `disallowed_tools` (Python) or `disallowedTools` (TypeScript) and settings files. If a match occurs, execution is denied immediately without triggering callbacks.
3. **Ask rules:** Checks `settings.json` ask rules, tools requiring user interaction, connector tools requiring organization approval, or custom tools marked `always_ask`. Matching calls fall through to your `canUseTool` callback or are denied in `dontAsk` mode.
4. **Permission mode check:** Evaluates active system permission mode logic (`acceptEdits`, `plan`, `bypassPermissions`, etc.).
5. **Allow rules:** Checks `allowed_tools` / `allowedTools` and settings files. If matched, the tool call is approved automatically.
6. **`canUseTool` callback:** If no prior step resolves the decision, the SDK calls your runtime `canUseTool` callback. In `dontAsk` mode, this step is skipped and the call is denied.

When configuring settings declaratively, your options must specify `setting_sources=["project"]` (Python) or `settingSources: ["project"]` (TypeScript) to load `.claude/settings.json` allow and deny rules alongside explicit `allowed_tools` arrays. Single-shot `query()` calls include `"project"` by default.

System permission modes define global operational boundaries:

- `default`: Requires explicit approval for tool calls matching no allow rules, falling through to `canUseTool`.
- `dontAsk`: Hard-denies any tool request that would otherwise require prompt confirmation, skipping `canUseTool`.
- `acceptEdits`: Automatically approves file modifications (`Edit`, `Write`, `NotebookEdit`) and common shell file operations (`mkdir`, `touch`, `mv`, `cp`) within designated working directories.
- `plan`: Forces the model to explore and generate plans. File tool edits reach `canUseTool` even if allowed by rules. Shell commands and network requests route to auto-mode classifiers when available.
- `auto`: Employs a model-based classifier to evaluate shell commands and network calls, allowing or blocking requests dynamically.
- `bypassPermissions`: Auto-approves tool requests without prompting (except critical actions). On Unix systems, the engine refuses to launch in `bypassPermissions` mode under root or `sudo` unless running in a recognized sandbox container.

Scoped rules provide granular target matching. Path rules distinguish between working directory scope and root file paths: `Edit(/secrets/**)` matches a `secrets` directory relative to the active workspace, whereas `Edit(//secrets/**)` matches absolute disk paths under root `/secrets/`. Built-in safeguards block dangerous commands like `rm -rf ~` (critical paths). Listing a tool in `allowed_tools` auto-approves matching calls without hiding unlisted tools from Claude's context; unlisted tools remain available and fall through to permission evaluation.

![The 6-step tool permission evaluation flow and budget limits](https://camnangai.com/articles/claude-agent-sdk-la-gi/04-en.webp)

Cost and turn bounds prevent runaway execution loops:

```python
options = ClaudeAgentOptions(
    max_turns=20,
    max_budget_usd=1.50,
    effort="high",
)
```

`max_turns` caps total loop iterations, while `max_budget_usd` limits cumulative spending across main agents and spawned subagents. Spend is evaluated _after_ model responses return token counts from the API. Because budget evaluations occur post-response, total spend can exceed `max_budget_usd` by the cost of that final turn plus any tokens spent by concurrently executing subagents before they process the shutdown signal. `total_cost_usd` on `ResultMessage` retrieves exact final spend. Reasoning depth is controlled via `effort` (`low`, `medium`, `high`, `xhigh`, `max`), trading token consumption for detailed analysis.

## Architectural extensions: Subagents and MCP integration

Subagents are isolated child agent instances spawned via the `Agent` tool. Delegating work to subagents provides context isolation: subagents run inside independent context windows, executing intermediate tool turns privately and returning only a final summary report to the parent context.

![Subagent context isolation and MCP server deployment models](https://camnangai.com/articles/claude-agent-sdk-la-gi/05-en.webp)

Subagents can be defined programmatically inside `options` via `AgentDefinition` objects or loaded as markdown files from `.claude/agents/`:

```python
options = ClaudeAgentOptions(
    allowed_tools=["Read", "Glob", "Agent"],
    agents={
        "security-auditor": AgentDefinition(
            description="Specialized security auditing agent.",
            prompt="Audit code for security vulnerabilities. Report findings concisely.",
            tools=["Read", "Grep", "Glob"],
            model="sonnet",
            maxTurns=10,
        )
    },
)
```

Subagents inherit system settings and project `CLAUDE.md` rules, but start with fresh conversation histories. When a subagent completes execution, Claude Code scans its final message before delivering it to the parent agent. This output scanning neutralizes harness control tags (such as inserting a backslash to convert `<system-reminder>` to `<\system-reminder>`), which prevents child subagents from injecting harness commands into the parent context window. The scan retains permission references and backslashes conversational turn markers (`Human:`, `Assistant:`). Subagent context forking can be disabled globally by adding `disallowed_tools=["Agent(fork)"]`.

Model Context Protocol (MCP) integrations expand agent toolsets. The SDK supports two MCP deployment models:

```python
from claude_agent_sdk import tool, create_sdk_mcp_server, ClaudeAgentOptions

@tool("db_query", "Execute read-only SQL query", {"query": str})
async def db_query_handler(args):
    return {"content": [{"type": "text", "text": "Query results..."}]}

sdk_server = create_sdk_mcp_server(name="db_tools", tools=[db_query_handler])

options = ClaudeAgentOptions(
    mcp_servers={
        "in_process": sdk_server, # In-process SDK server (same Python process)
        "external": {             # External stdio subprocess server
            "type": "stdio",
            "command": "node",
            "args": ["server.js"]
        }
    }
)
```

In-process SDK MCP servers run inside your main application process, eliminating sub-process IPC management and reducing call latency. External `stdio` servers execute as isolated child processes. To prevent large MCP tool schemas from exhausting context windows, the engine uses MCP Tool Search to defer loading tool definitions into context until the agent explicitly searches for and requests them.

## When to choose the Claude Agent SDK — and when not to

Choose the Claude Agent SDK when you need to embed an autonomous, file-editing, tool-executing agent loop directly inside an application, service, or pipeline running on infrastructure you control. It is ideal when you require local binary execution, deep integration with local developer tools, project-level `.claude` configuration loading, and precise programmatic governance over tool calls via hooks and permission evaluation flows.

Do not use the Claude Agent SDK if your architecture requires hosted, serverless agent sandboxes without local executable binaries (use Managed Agents), if you only need single-turn text completions or plan to build a manual agent loop from scratch (use the Client SDK), or if you simply want an interactive terminal coding assistant on a developer workstation (use the Claude Code CLI).

## References

- [Agent SDK overview — Claude Code Docs](https://code.claude.com/docs/en/agent-sdk/overview)
- [Building Effective AI Agents — Anthropic](https://www.anthropic.com/research/building-effective-agents)
- [Configure permissions — Claude Code Docs](https://code.claude.com/docs/en/agent-sdk/permissions)
- [Claude Agent SDK for Python — GitHub](https://github.com/anthropics/claude-agent-sdk-python)
- [Claude Agent SDK for TypeScript — GitHub](https://github.com/anthropics/claude-agent-sdk-typescript)
- [How the agent loop works — Claude Code Docs](https://code.claude.com/docs/en/agent-sdk/agent-loop)
- [Quickstart — Claude Code Docs](https://code.claude.com/docs/en/agent-sdk/quickstart)
- [Subagents in the SDK — Claude Code Docs](https://code.claude.com/docs/en/agent-sdk/subagents)
