# What is the Claude Agent SDK? How it works and when to use it

> The Claude Agent SDK embeds Claude Code's agent loop and tools in Python or TypeScript apps. How the loop, permissions and limits work, and how to trace it.

Source: https://www.honeyhive.ai/learn/claude-agent-sdk-framework (updated 2026-11-16)

The Claude Agent SDK is Anthropic's library for running the same [agent loop](/learn/agent-harness), tools and context management that power Claude Code inside your own Python or TypeScript application, as Anthropic's [overview](https://code.claude.com/docs/en/agent-sdk/overview) describes it. You give it a prompt and a set of permissions. It plans, calls tools such as file reads, edits and shell commands, and streams back each step until the task is done.

## Agent SDK, Client SDK, CLI or Managed Agents

Anthropic's [comparison](https://code.claude.com/docs/en/agent-sdk/overview) separates four ways to build with Claude by who runs the agent and what comes built in:

| You want to | Use | What you get |
|---|---|---|
| Embed Claude Code's agent in your own app, in a process you operate | Agent SDK | A library that runs the Claude Code binary, with built-in tools, permissions, sessions and hooks |
| Work interactively or run one-off tasks in a terminal | Claude Code CLI | The terminal interface |
| Call the Claude API from your own code | Client SDK | Direct API access; you write the tool loop, or use the beta tool runner |
| Have Anthropic host the agent | Managed Agents | A hosted agent harness with sessions in an Anthropic-managed or self-hosted sandbox |

For a language other than Python or TypeScript, the docs say to [run the CLI as a subprocess](https://code.claude.com/docs/en/headless) with `-p` and `--output-format json`.

## Install and run a first agent

The SDK needs Python 3.10 or newer, or Node.js 18.14 or newer. Install it with `pip install claude-agent-sdk` or `npm install @anthropic-ai/claude-agent-sdk`. Most installs bundle a native Claude Code binary, so no separate Claude Code install is needed ([quickstart](https://code.claude.com/docs/en/agent-sdk/quickstart)). The SDK reads `ANTHROPIC_API_KEY` from the process environment and does not load `.env` files.

The quickstart's agent is one call to `query`, which returns an async iterator of messages:

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


async def main():
    async for message in query(
        prompt="Review utils.py for bugs that would 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 hasattr(block, "text"):
                    print(block.text)
                elif hasattr(block, "name"):
                    print(f"Tool: {block.name}")
        elif isinstance(message, ResultMessage):
            print(f"Done: {message.subtype}")


asyncio.run(main())
```

Authentication also works through [Amazon Bedrock, Claude Platform on AWS, Google Cloud's Agent Platform and Microsoft Foundry](https://code.claude.com/docs/en/agent-sdk/quickstart) by setting an environment variable per provider. Anthropic [does not allow](https://code.claude.com/docs/en/agent-sdk/overview) third-party developers to offer claude.ai login or rate limits in products built on the SDK, unless it has approved them, so use API keys.

## How the agent loop works

A run [goes through five steps](https://code.claude.com/docs/en/agent-sdk/agent-loop):

1. Claude receives the prompt, system prompt, tool definitions and history.
2. It answers with text, tool calls, or both.
3. The SDK runs each requested tool and feeds the results back.
4. Steps 2 and 3 repeat until Claude responds with no tool calls.
5. The SDK yields a `ResultMessage` with the final text, token usage, cost and session ID.

One pass is a turn. A quick question may take two or three turns, and a refactor can chain dozens. The built-in tools cover file operations (`Read`, `Edit`, `Write`), search (`Glob`, `Grep`), `Bash`, web access (`WebSearch`, `WebFetch`), and orchestration (`Agent`, `Skill`, `AskUserQuestion`). Read-only tools can run concurrently, while `Edit`, `Write` and `Bash` run one at a time. You can add external tools through the [Model Context Protocol](/learn/model-context-protocol) or your own handlers.

## Limits and result subtypes

Neither `max_turns` nor `max_budget_usd` has a default, so an open-ended prompt can run long. Anthropic calls a budget [a good default](https://code.claude.com/docs/en/agent-sdk/agent-loop) for production agents.

- `max_turns` counts each turn with tool calls plus one for the final text-only reply. Without that extra turn, the run ends with `error_max_turns` and no final response.
- The budget check happens after a response arrives, so spend can pass the cap by up to the cost of that response, plus subagents still running. Subagent spend counts toward the cap.
- A single-shot `query()` raises after yielding an error result, so wrap the loop in a try block.
- The `result` field exists only when the subtype is `success`. Other subtypes are `error_max_turns`, `error_max_budget_usd`, `error_during_execution` and `error_max_structured_output_retries`.
- `usage` covers only the main loop. Use `model_usage` to account for subagents too.

## Permission modes

`allowed_tools` auto-approves the tools you list. It does not restrict the others: unlisted tools stay available and fall through to the permission mode. To limit what the agent can use, pass `tools`, or block specific tools with `disallowed_tools`, which applies regardless of other settings ([agent loop](https://code.claude.com/docs/en/agent-sdk/agent-loop), [quickstart](https://code.claude.com/docs/en/agent-sdk/quickstart)).

| Mode | Behavior |
|---|---|
| `default` | Calls needing approval go to your `canUseTool` callback; with no callback they are denied |
| `acceptEdits` | Auto-approves file edits and common filesystem commands in your working directories |
| `plan` | Claude explores and plans; edits go to your callback |
| `dontAsk` | Never prompts; anything not pre-approved is denied |
| `auto` | A model classifier reviews actions such as shell commands and network requests |
| `bypassPermissions` | Runs tool calls without approval, for isolated environments only |

`bypassPermissions` [cannot run as root](https://code.claude.com/docs/en/agent-sdk/agent-loop) on Unix, and the TypeScript SDK also requires `allowDangerouslySkipPermissions: true`. For approval patterns beyond these modes, see [human-in-the-loop AI](/learn/human-in-the-loop-ai) and [AI agent guardrails](/learn/ai-agent-guardrails).

## Hooks, subagents, sessions and context

[Hooks](https://code.claude.com/docs/en/agent-sdk/agent-loop) such as `PreToolUse`, `PostToolUse`, `Stop` and `PreCompact` run in your application process, not in the agent's context window, and a `PreToolUse` hook that rejects a call stops it from running. [Subagents](/learn/subagents) help with context: a subagent returns only its final response, so the main agent's context grows by a summary instead of the subtask's transcript.

Context accumulates across turns. When it nears the limit, the SDK compacts older history into a summary, and the docs [warn](https://code.claude.com/docs/en/agent-sdk/agent-loop) that early instructions may not survive, so put persistent rules in `CLAUDE.md`. For why this matters, see [context rot](/learn/context-rot). Each `ResultMessage` carries a session ID you can use to resume a run with its context restored, or fork it.

## Defaults that catch people

The SDK was renamed from the Claude Code SDK, so older tutorials use `claude-code-sdk` and `ClaudeCodeOptions`. Two behaviors from the [migration guide](https://code.claude.com/docs/en/agent-sdk/migration-guide) are worth knowing:

- Since v0.1.0 the SDK uses a minimal system prompt, not Claude Code's. To get Claude Code's prompt, pass `{"type": "preset", "preset": "claude_code"}` as the system prompt.
- Omitting `settingSources` loads user, project and local filesystem settings, including `CLAUDE.md`, matching the CLI. For CI, deployed apps and multi-tenant systems, pass an empty list to isolate the run. Python SDK 0.1.59 and earlier treated an empty list as omitted.

## How to evaluate a Claude Agent SDK app

Because the SDK streams every message, you can log tool calls, turn counts, cost and the result subtype for each run. Start with the failure subtypes above, then read traces for wrong tool choices or runs that hit a limit. The general method is in [how to test AI agents](/learn/testing-ai-agents) and [AI agent evaluation](/learn/ai-agent-evaluation). HoneyHive experiments [run a function on a curated dataset](https://docs.honeyhive.ai/v2/evaluation/introduction) and score each output with evaluators.

## Tracing a Claude Agent SDK app in HoneyHive

HoneyHive traces the SDK with the OpenInference `ClaudeAgentSDKInstrumentor`, so agent code runs unchanged. The [integration page](https://docs.honeyhive.ai/v2/integrations/claude-agent-sdk) lists Python 3.10 or newer and `claude-agent-sdk` 0.1.45 or newer. It says traces capture agent runs, tool executions with arguments and results, multi-turn conversations through `ClaudeSDKClient`, and token usage per request, with each turn as an agent span and tool calls nested under it.

```python
from honeyhive import HoneyHiveTracer
from openinference.instrumentation.claude_agent_sdk import ClaudeAgentSDKInstrumentor

tracer = HoneyHiveTracer.init()  # Reads HH_INGESTION_API_KEY from your environment
ClaudeAgentSDKInstrumentor().instrument(tracer_provider=tracer.provider)
```

Import `claude_agent_sdk` after this block, and call `tracer.force_flush()` before the process exits, or short scripts can drop spans. Setup, single-query and multi-turn examples, and troubleshooting are on the [HoneyHive Claude Agent SDK integration page](https://docs.honeyhive.ai/v2/integrations/claude-agent-sdk). For background, see [agent observability](/learn/agent-observability).

## FAQ

### What is the Claude Agent SDK?

It is Anthropic's library for running Claude Code's agent loop, built-in tools and context management inside your own Python or TypeScript application ([overview](https://code.claude.com/docs/en/agent-sdk/overview)).

### How do I install the Claude Agent SDK?

Run `pip install claude-agent-sdk` for Python 3.10 or newer, or `npm install @anthropic-ai/claude-agent-sdk` for Node.js 18.14 or newer, and set `ANTHROPIC_API_KEY` in the process environment. Both packages bundle a native Claude Code binary in most installs ([quickstart](https://code.claude.com/docs/en/agent-sdk/quickstart)).

### Is the Claude Agent SDK the same as the Claude Code SDK?

Yes. Anthropic renamed the Claude Code SDK to the Claude Agent SDK, with new package names (`claude-agent-sdk` and `@anthropic-ai/claude-agent-sdk`) and `ClaudeCodeOptions` renamed to `ClaudeAgentOptions` ([migration guide](https://code.claude.com/docs/en/agent-sdk/migration-guide)).

### Can I use the Claude Agent SDK with Amazon Bedrock or Google Cloud?

Yes. Set `CLAUDE_CODE_USE_BEDROCK=1` for Amazon Bedrock, `CLAUDE_CODE_USE_VERTEX=1` for Google Cloud's Agent Platform or `CLAUDE_CODE_USE_FOUNDRY=1` for Microsoft Foundry, and configure that cloud's credentials ([quickstart](https://code.claude.com/docs/en/agent-sdk/quickstart)).

### How do I stop a Claude Agent SDK run from looping too long?

Set `max_turns` and `max_budget_usd`. Both default to no limit, and hitting either ends the run with an `error_max_turns` or `error_max_budget_usd` result ([agent loop](https://code.claude.com/docs/en/agent-sdk/agent-loop)).
