"Wouldn't it be great if you could just give AI an instruction and it would think and work on its own?" That's exactly what AI agents make possible. Anthropic's Claude Agent SDK is a library that lets you build AI agents powered by Claude using Python or TypeScript. It gives your own programs the same tools, agent loop, and context management that power Claude Code, Anthropic's official coding agent.

This article provides a comprehensive walkthrough of Claude Agent SDK, from core concepts to implementation and practical use cases.

What Is an AI Agent?

AI agents are fundamentally different from traditional "question and answer" AI. Their defining characteristic is the ability to autonomously break down tasks, use tools, evaluate results, and decide what to do next.

For example, if you ask an agent to "fix the bug in auth.py," it will work through these steps:

  1. Read the file to understand the code
  2. Search related files to grasp the bigger picture
  3. Identify the root cause of the bug
  4. Apply the fix
  5. Run tests to verify the solution
  6. Report the results

The agent handles this entire workflow on its own, without human intervention at each step. That's the power of agents.

Claude Agent SDK Overview

Claude Agent SDK is Anthropic's official library for building agents. The official documentation describes it as "a library that runs the Claude Code binary." In other words, the direction is the SDK drives Claude Code, not the other way around. Both the Python and TypeScript SDKs bundle that binary, so most setups don't need a separate Claude Code install.

Here are its key features:

FeatureDescription
Automatic agent loopThe SDK manages the tool call → result processing → next decision cycle automatically
Built-in toolsReady-to-use tools for file operations, command execution, web search, and more
Custom toolsEasily add your own tools for API calls, database operations, etc.
MCP integrationConnect to external tool servers via MCP to extend capabilities
Cost controlsSet budget caps and turn limits
Sub-agentsSplit tasks and run them in parallel
Supported languagesPython / TypeScript

The Agent SDK is how you take the agent that runs in Claude's Code (Claude Code) and embed it in your own apps and scripts, outside that interface.

How the Agent Loop Works

At the heart of the Agent SDK is the agent loop — an automated cycle where Claude thinks, uses tools, checks results, and thinks again.

How the Agent Loop Works

1. Prompt
User instructions
2. Claude Decides
Determines next action
3. Tool Execution
Bash, Edit, Read etc.
4. Process Results
Feed back to Claude
↻ Repeats until no more tool calls
5. Return Final Result
Text response (no tool calls)
Main Built-in Tools
Bash Read Edit Write Grep WebSearch Agent

Here's how it flows step by step:

  1. Receive prompt: The user's instruction is passed to Claude
  2. Claude reasons: It analyzes the instruction and determines what actions are needed
  3. Execute tools: Tools like Bash, Edit, and Read are called to perform the work
  4. Process results: Tool output is fed back to Claude
  5. Continue or finish: If more work is needed, go back to step 2. Otherwise, return a text response

The key point is that the loop ends when there are no more tool calls. Once Claude determines that no further tools are needed, it returns a final text response.

Getting Started: Installation & Basic Code

Installation

The SDK is available for both Python and TypeScript.

# Python
pip install claude-agent-sdk

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

You need Node.js 18+ or Python 3.10+ (official quickstart).

Authentication: Use an API Key (Not a claude.ai Login)

The SDK runs on the API key in the ANTHROPIC_API_KEY environment variable. To go through Amazon Bedrock, Google Cloud (the version operated by Google), or Microsoft Foundry instead, set CLAUDE_CODE_USE_BEDROCK=1, CLAUDE_CODE_USE_VERTEX=1, or CLAUDE_CODE_USE_FOUNDRY=1 and configure that cloud's credentials. The SDK doesn't load .env files automatically, so set the variable in the shell where the agent runs. Setup and pricing for Claude on Google Cloud are covered in How to Use Claude on Vertex AI.

Watch out for claude.ai logins (Pro, Max, and other subscriptions). Unless previously approved, the official documentation doesn't allow third-party developers to offer claude.ai login or rate limits in their products, including agents built on the Agent SDK. Apps you build with the SDK should authenticate with an API key.

Minimal Agent (Python)

import asyncio
from claude_agent_sdk import query, ClaudeAgentOptions, ResultMessage

async def main():
    async for message in query(
        prompt="Find and fix the bug in src/auth.py",
        options=ClaudeAgentOptions(
            allowed_tools=["Read", "Edit", "Bash", "Grep"],
            max_turns=30,
        ),
    ):
        if isinstance(message, ResultMessage):
            if message.subtype == "success":
                print(message.result)
            if message.total_cost_usd is not None:
                print(f"Cost: ${message.total_cost_usd:.4f}")

asyncio.run(main())

Minimal Agent (TypeScript)

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

for await (const message of query({
  prompt: "Find and fix the bug in src/auth.py",
  options: {
    allowedTools: ["Read", "Edit", "Bash", "Grep"],
    maxTurns: 30,
  }
})) {
  if (message.type === "result" && message.subtype === "success") {
    console.log(message.result);
  }
}

With just this code, you have an agent that reads files, hunts for bugs, applies fixes, and reports results — all on its own. Note, however, that allowed_tools is not a list of tools Claude may use; it's a list of tools auto-approved without prompting. Because this example includes Bash, whatever shell commands Claude chooses run without confirmation (apart from a few actions, such as certain deletions, that no setting auto-approves). Because this example doesn't set permission_mode, the mode comes from permissions.defaultMode in your settings files or, failing that, the built-in default, and from v2.1.285 that default was auto in sessions that don't fetch feature flags, such as on a third-party provider (Bedrock, Google Cloud, Microsoft Foundry) or with telemetry off (official docs). However, v2.1.302 (October 16, 2026) changed this: Agent SDK and claude -p sessions that don't set a permission mode now start in default, including through third-party providers. To use auto, you need to set it explicitly (in the CLI, --permission-mode auto; see the changelog, checked October 18, 2026). Auto mode drops broad allow rules like Bash, so if you rely on the behavior above, pass permission_mode="default" (TS: permissionMode: "default") explicitly (official docs). Try it in a scratch directory you don't mind breaking. The next section covers how to actually narrow the tool set.

Built-in Tools

The Agent SDK comes with a rich set of tools you can use right away, without writing any extra code.

ToolFunctionExample Use
BashExecute shell commandsRun tests, build projects, git operations
ReadRead filesInspect source code and config files
EditPartially modify filesBug fixes, refactoring
WriteCreate new filesGenerate new modules
GlobSearch files by patternList all TypeScript files with **/*.ts
GrepSearch file contentsFind function definitions or error messages
WebSearchSearch the webLook up the latest docs or API specs
WebFetchFetch web pagesRetrieve information from a URL
AgentLaunch sub-agentsSplit tasks for parallel processing

You don't need to write any tool-handling code to use the built-in tools. What matters is that "which tools Claude can see" and "which tools run without prompting" are separate settings. Here is how the official documentation describes them:

OptionLayerEffect
toolsWhich tools Claude seesOnly the listed built-in tools are in Claude's context. [] removes every built-in, leaving only your MCP tools.
allowed_tools
(TS: allowedTools)
ApprovalListed tools are auto-approved without prompting. It does not restrict the tool set. Unlisted tools stay available, and calls that need approval fall through to the permission mode and can_use_tool (TS: canUseTool).
disallowed_tools
(TS: disallowedTools)
BothA bare name such as "Bash" removes the tool entirely. A scoped rule such as "Bash(rm *)" keeps the tool but denies matching calls in every permission mode.

For example, combining allowed_tools=["Read"] with permission_mode="bypassPermissions" still approves everything, including the unlisted Bash, Write, and Edit — a combination the official documentation explicitly warns about. To keep a tool out of reach, remove it with tools or disallowed_tools. To run only with a fixed set of tools, pair allowed_tools with permission_mode="dontAsk", which denies anything that would otherwise prompt.

One more detail: on macOS, Linux, and WSL, Glob and Grep are not in the default tool set (they are on Windows). There, Claude searches with find and grep through the Bash tool instead. Naming either tool in tools or allowed_tools brings them back (official tools reference).

Creating Custom Tools

When built-in tools aren't enough, you can create your own. Let's build a custom tool that connects to a weather API.

Python

from claude_agent_sdk import tool, create_sdk_mcp_server

@tool(
    "get_weather",
    "Get the current weather for a given city",
    {"city": str}
)
async def get_weather(args: dict) -> dict:
    city = args["city"]
    # In practice, call an actual API
    weather_data = await fetch_weather_api(city)
    return {
        "content": [
            {"type": "text", "text": f"Weather in {city}: {weather_data}"}
        ]
    }

weather_server = create_sdk_mcp_server(
    name="weather",
    version="1.0.0",
    tools=[get_weather]
)

TypeScript

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

const getWeather = tool(
  "get_weather",
  "Get the current weather for a given city",
  { city: z.string().describe("City name") },
  async (args) => {
    const data = await fetchWeatherApi(args.city);
    return {
      content: [{ type: "text", text: `Weather in ${args.city}: ${data}` }]
    };
  }
);

Custom tools are built as MCP servers and passed to your agent through mcp_servers (TS: mcpServers). Each tool's full name becomes mcp__server-name__tool-name, so to let it run without prompting, list that name in allowed_tools:

options=ClaudeAgentOptions(
    mcp_servers={"weather": weather_server},
    allowed_tools=["mcp__weather__get_weather"],
)

If your tool raises an exception, the agent loop does not stop. The SDK's MCP server catches it and hands the raw exception message to Claude as an error result. If you catch the error yourself and return "is_error": True (TypeScript: isError: true), you get to write the message Claude reads — which request failed, and what to try instead. Either way, Claude can retry, try a different tool, or explain the failure (official docs: custom tools).

Parallel Processing with Sub-Agents

For large tasks, splitting the work across sub-agents and running them in parallel is much more efficient. Sub-agents handle specialized tasks without polluting the main agent's context (memory).

When Sub-Agents Are Useful

  • Running extensive test suites: Even if test logs are enormous, they don't affect the main agent's context
  • Parallel research: Investigate multiple modules simultaneously and collect the results
  • Separating specialized work: Assign "code review" and "test execution" to different agents

Custom Sub-Agents in Claude Code

In Claude Code (CLI), you can define custom sub-agents simply by placing Markdown files in the .claude/agents/ directory.

# .claude/agents/reviewer.md
---
name: code-reviewer
description: A sub-agent specialized in code review
tools: Read, Glob, Grep
model: sonnet
---

You are a senior code reviewer.
Review code for quality, security,
and best practices.

By limiting tool access (in this example, read-only tools), you prevent the reviewer from accidentally modifying code.

Permissions, Hooks, and Sessions

These three matter most once an agent runs in production. The official documentation lists all of them among the Claude Code capabilities available in the SDK.

Permissions: Every Call Is Checked in a Fixed Order

When Claude requests a tool, the SDK checks hooks → deny rules → ask rules → permission mode → allow rules → the can_use_tool callback, in that order. A call matching a deny rule (from disallowed_tools, for example) is blocked even in bypassPermissions mode. One exception: a mod (a plugin whose hooks are functions) also runs in Agent SDK sessions that load it (official docs), and a mod that answers tool.check can approve a call a deny rule refused, except on machines with managed settings or when signed in with a Team or Enterprise plan (official docs). Install mods only from authors you trust; see Claude Code Mods Explained for details. You choose the permission mode with permission_mode (per the official documentation as of September 2026):

ModeBehavior
defaultNo mode-based auto-approvals. Calls that need approval and match no allow rule go to can_use_tool.
acceptEditsAuto-approves file edits and filesystem operations such as mkdir, rm, and mv.
planExplores and plans only. Edits to source files are never auto-approved.
dontAskDenies anything that would otherwise prompt. can_use_tool is never called.
bypassPermissionsRuns tools without prompting, apart from a few actions no mode auto-approves. Use with caution.
autoA model classifier approves or denies permission prompts.

Hooks: Run Your Own Code at Key Points

Hooks are callbacks that fire on events such as before a tool runs (PreToolUse), after it runs (PostToolUse), or when execution stops (Stop). They run before the permission checks, so an action you want blocked in every mode belongs here. This example, trimmed from the official documentation, blocks writes to .env files:

from claude_agent_sdk import ClaudeAgentOptions, HookMatcher

async def protect_env_files(input_data, tool_use_id, context):
    file_path = input_data["tool_input"].get("file_path", "")
    if file_path.split("/")[-1] == ".env":
        return {
            "hookSpecificOutput": {
                "hookEventName": input_data["hook_event_name"],
                "permissionDecision": "deny",
                "permissionDecisionReason": "Cannot modify .env files",
            }
        }
    return {}

options = ClaudeAgentOptions(
    hooks={"PreToolUse": [HookMatcher(matcher="Write|Edit", hooks=[protect_env_files])]}
)

Sessions: Resume Where You Left Off, or Branch

The SDK automatically saves the conversation history — prompts, tool calls, results, and responses — to disk as a session. Keep the session_id from the result message and pass it to resume on your next query(), and the agent continues with the files it read and the decisions it made. To pick up the most recent session, use continue_conversation=True (TS: continue: true); to try a different approach while keeping the original intact, use fork_session=True (TS: forkSession: true). Sessions store the conversation only; file changes are not rolled back (official docs: sessions).

Beyond these, skills, commands, and memory in your project's .claude/ and in ~/.claude/ load automatically, just as in Claude Code. Plugins, which package skills, agents, hooks, and MCP servers, can be loaded from a local path.

Agent SDK vs Client SDK vs Claude Code

The official comparison lists four ways to build with Claude: the Agent SDK, the Claude Code CLI, the Client SDK, and Managed Agents. Let's start with the three you run on your own machine or servers.

Agent SDK vs Client SDK vs Claude Code CLI

Agent SDK
Features
· Automatic loop management
· Built-in tools included
· MCP integration
· Cost control
Best For
· Production automation
· CI/CD pipelines
· Build custom apps
Difficulty
Intermediate
Language
Python / TypeScript
Client SDK (API)
Features
· Low-level API control
· Write your own tool loop (or use the beta tool runner)
· Full customization
· Streaming support
Best For
· Chatbot development
· Custom tool integration
· When fine-grained control matters
Difficulty
Advanced
Language
Python / TypeScript
Claude Code CLI
Features
· Interact via terminal
· Zero setup
· IDE integration
· Sub-agent feature
Best For
· Daily dev work
· Interactive development
· Prototyping
Difficulty
Beginner
Language
No code (CLI)
AspectAgent SDKClient SDK (API)Claude Code CLI
Loop managementAutomaticManual (or the beta tool runner)Automatic
ToolsBuilt-in + customYou define and execute themBuilt-in
Best forAutomation & productionFull custom controlInteractive development
DifficultyIntermediateAdvancedBeginner
Coding requiredYesYesNo

Quick decision guide:

  • Day-to-day development work → Claude Code CLI
  • Building automated systems → Agent SDK
  • Creating your own AI-powered app → Client SDK
  • Hand off running the loop and sandbox as well → Managed Agents (an Anthropic-hosted agent harness that runs sessions in an Anthropic-managed cloud sandbox or a self-hosted sandbox, used from the SDK for your language, the ant CLI, or the REST API)

Real-World Use Cases

Claude Agent Use Cases

💻
Code Development
Bug fixes, refactoring, test execution, and code review autonomously
🔎
Research & Analysis
Codebase exploration, data analysis, and document generation in parallel
⚙️
CI/CD Automation
PR reviews, auto-fix testfailures, and deploypipeline management
🚀
Product Development
API development, DB design, full-stack implementation end-to-end
👥
Team Collaboration
Parallel work with sub-agents, efficient task distribution with context isolation

Automated Code Development

This is the most common use case. Tell the agent "implement this feature," and it will explore the file structure, write the code, and run the tests.

# Automated bug fixing
async for msg in query(
    prompt="The auth module tests are failing. Investigate and fix the issue",
    options=ClaudeAgentOptions(
        allowed_tools=["Read", "Edit", "Bash", "Grep"],
        max_turns=20,
        max_budget_usd=2.00,  # Cost cap: $2
    ),
):
    pass

CI/CD Pipeline Integration

Integrate with GitHub Actions or similar tools to build workflows that automatically review code on every PR or attempt auto-fixes when tests fail.

Data Analysis & Research

Multi-step research tasks like "analyze the error patterns from last month's logs" can be delegated to an agent. Combine with the WebSearch tool to pull in the latest information as well.

Best Practices

1. Always Set Cost Controls

Because agents loop, they can consume more tokens than expected. Always set max_budget_usd and max_turns.

options=ClaudeAgentOptions(
    max_budget_usd=5.00,   # Stop at $5
    max_turns=30,           # Stop after 30 turns
    effort="medium",        # Reasoning depth (low/medium/high/xhigh/max)
)

xhigh falls back to high on models that don't support it. When a limit ends the run, the final result message has subtype set to "error_max_budget_usd" for max_budget_usd or "error_max_turns" for max_turns, and result is empty (None). Check subtype to tell why the agent stopped.

Keep in mind that the dollar amount is an estimate the SDK computes from a bundled price table, not your actual bill. The budget counts only that call's own spend; earlier spend from a session you resume doesn't count against it. For authoritative figures, use the Usage page in the Claude Console or the Usage and Cost API (official docs: cost tracking).

2. Keep Tools to a Minimum

To keep unneeded tools out of Claude's view, list only the tools you need in tools, or remove tools by bare name in disallowed_tools. allowed_tools only skips the approval prompt; it does not narrow the tool set. Keep the auto-approved list to the minimum the task needs, too.

3. Report Tool Errors with is_error

An exception in a custom tool does not stop the agent loop; the SDK passes the exception message to Claude as an error result. A raw exception message isn't always enough for Claude to decide what to do next, though. Catch it yourself and return "is_error": True (TypeScript: isError: true) along with what failed and what to try instead, and Claude can recover more easily.

4. Offload Heavy Work to Sub-Agents

Delegate tasks with large outputs, like test execution or log analysis, to sub-agents. This prevents the main agent's context from getting overloaded.

5. Be Specific in Your Prompts

Instead of "improve the code," say "add rate limiting to the login function in auth.py and write tests for it." Specific instructions lead to much more efficient results.

Summary

Claude Agent SDK dramatically lowers the barrier to building AI agents. Powered by the same engine as Claude Code, it lets you create autonomous task-executing agents in Python or TypeScript.

A great approach is to start by using Claude Code interactively to experience how agents work, and then move to the Agent SDK when you need automation — a smooth, step-by-step transition.

If you would rather not run the loop, sandbox, and state yourself, Anthropic's fully managed alternative is Claude Managed Agents.

For more on the basics of using Claude, check out Claude's Chat, Cowork and Code.

FAQ

Is Claude Agent SDK free to use?

The SDK itself is free, but you'll pay for Claude API usage (unless previously approved, claude.ai subscription logins can't be used for products you build with the SDK). You can set a spending cap with max_budget_usd, but that figure is the SDK's own estimate, so check actual charges in the Claude Console. During development and testing, set effort to "low" to keep costs down.

What's the difference between Agent SDK and Claude Code?

Claude Code is an interactive tool for the terminal and IDE, while the Agent SDK is a library you embed in your programs for automation. Because the SDK runs the Claude Code binary internally, the built-in tools, permissions, sessions, and hooks work the same way in both. Use Claude Code for everyday development, and the Agent SDK for CI/CD or production automation.

Which programming languages are supported?

Python and TypeScript are supported. However, the targets the agent operates on (file editing, command execution, etc.) have no language restrictions, so you can use it with projects in Go, Rust, PHP, or any other language.

What is MCP?

MCP (Model Context Protocol) is a standard protocol for connecting AI models with external tools. You can implement databases, browser automation, APIs, and other tools as MCP servers and connect them to your agent. Since the Agent SDK supports MCP, third-party MCP servers are also compatible.