Claude Agent SDK Python: Build Autonomous AI Agents with Claude Code

Oct 10, 2025

Introduction

Developers often struggle to move from simple LLM chat interfaces to truly autonomous agents that can read files, execute terminal commands, and manage complex software engineering tasks without constant manual oversight. Claude Agent SDK Python (repository: anthropics/claude-agent-sdk-python) solves this by providing the official programmatic interface to the agentic loop that powers Claude Code. With over 7k GitHub stars, this SDK allows Python developers to embed the same tool-use, context management, and autonomous reasoning capabilities of the Claude Code CLI directly into their own applications.

What Is Claude Agent SDK Python?

Claude Agent SDK Python is a developer toolkit that provides a programmatic way to build autonomous AI agents using the Claude Code engine. It wraps a bundled Claude Code CLI binary over stdio, giving Python code direct access to file operations, terminal commands, and multi-step workflow chaining without requiring the developer to manually manage the tool-call loop.

Maintained by Anthropic, the SDK is released under the MIT license and requires Python 3.10 or higher. It is designed for developers who want to move beyond the raw Messages API and create specialized agents that can interact with a local environment or a sandbox to solve real-world engineering problems.

Why Claude Agent SDK Python Matters

Before this SDK, building a coding agent required significant “glue code”—developers had to write the loop that catches tool calls, executes the bash command or file read, and feeds the result back to the model. This process is error-prone and often fails at scale. Claude Agent SDK Python removes this friction by internalizing the agentic loop, allowing the model to autonomously iterate toward a goal.

The SDK’s significance lies in its tight integration with the Claude Code ecosystem. Because it uses the same harness as the official CLI, it inherits high-fidelity tool execution and context compaction. This makes it the most reliable path for building SRE diagnostics tools, automated PR reviewers, and autonomous codebase navigators in Python.

As the industry shifts from “chatbots” to “agents,” this SDK provides a production-ready foundation that avoids the abstraction overhead of multi-provider frameworks while giving developers immediate access to the latest Claude reasoning capabilities.

Key Features

  • Autonomous Agent Loop: The SDK handles the internal loop of tool calling and result feeding, meaning you define the goal and the agent iterates autonomously until the task is complete.
  • Bundled Claude Code CLI: The SDK comes with the Claude Code CLI binary bundled in the wheel, eliminating the need for separate installation and PATH configuration for most users.
  • Rich Built-in Toolset: Agents have immediate access to a powerful set of tools for reading files, writing code, editing text, and executing bash commands in the local environment.
  • Model Context Protocol (MCP) Support: You can extend the agent’s capabilities by integrating custom MCP servers, allowing the agent to interact with external APIs, databases, or proprietary internal tools.
  • Fine-grained Permission System: Use allowed_tools and disallowed_tools to strictly control which capabilities the agent can use, ensuring security in autonomous environments.
  • Async Streaming API: The query() function and ClaudeSDKClient provide an asynchronous iterator of messages, allowing for real-time UI updates as the agent thinks and acts.
  • Context Compaction: The SDK automatically manages the token budget by compacting context, ensuring the agent remains performant over long-running sessions.
  • Multi-Provider Routing: Support for routing requests through the standard Anthropic API, Amazon Bedrock, or Google Cloud Vertex AI.

How Claude Agent SDK Python Compares

When choosing an agent framework, developers often compare the official SDK against general-purpose frameworks like LangGraph or CrewAI. The primary differentiator is the level of abstraction and the target use case.

Feature Claude Agent SDK LangGraph CrewAI
Primary Focus Autonomous Coding/SRE State Machine Graphs Role-based Teams
Tool Loop Internalized/Automatic Explicitly Defined Managed by Framework
Local Env Access Native/Deep Via Custom Tools Via Custom Tools
Setup Complexity Low (Bundled CLI) High (Graph Design) Medium
Model Lock-in Claude-native Model Agnostic Model Agnostic

The Claude Agent SDK is the right choice when you need an agent that can actually do things on a filesystem or in a terminal with high reliability. While LangGraph offers superior control over the exact state transitions of a workflow, it requires you to build the tool-execution environment from scratch. CrewAI is excellent for simulating a team of agents with different roles, but it lacks the deep, native integration with the local OS that the Claude Agent SDK provides.

The tradeoff is model lock-in. By using the official SDK, you are committing to the Claude ecosystem. However, for developers building coding assistants, the specialized reasoning of Claude 3.5 Sonnet and 4.5 is often more valuable than the flexibility of a model-agnostic framework.

Getting Started: Installation

The Claude Agent SDK is designed for a streamlined installation process. Because the CLI is bundled, you can get started with a single command.

Prerequisites

  • Python 3.10 or higher
  • An Anthropic API Key

Install via pip

pip install claude-agent-sdk

Environment Configuration

Set your API key as an environment variable to allow the SDK to authenticate requests:

export ANTHROPIC_API_KEY="your_api_key_here"

If you are using a different provider, you can set the following flags:

  • Amazon Bedrock: export CLAUDE_CODE_USE_BEDROCK=1
  • Google Vertex AI: export CLAUDE_CODE_USE_VERTEX=1

Custom CLI Path (Optional)

If you prefer to use a system-wide installation of Claude Code instead of the bundled version, you can specify the path in your options:

options = ClaudeAgentOptions(cli_path="/path/to/claude")

How to Use Claude Agent SDK Python

The SDK provides two primary interaction patterns: stateless one-shot queries and stateful sessions. The most basic way to interact with an agent is using the query() function.

When you call query(), the SDK initiates the agentic loop. Claude will analyze the prompt, decide if it needs to use a tool (like reading a file), execute that tool, and repeat this process until it has a final answer. All of this happens asynchronously, and the responses are streamed back to you.

For more complex interactions, the ClaudeSDKClient allows you to maintain a session, reusing context across multiple turns of conversation. This is essential for building interactive chat-based agents where the user can provide feedback or steer the agent’s progress.

Code Examples

The following examples demonstrate the core capabilities of the SDK, from simple queries to custom tool integration.

Basic Streaming Query

This example shows how to perform a simple, stateless query that streams the agent’s thought process and final response.

import anyio
from claude_agent_sdk import query, ClaudeAgentOptions, AssistantMessage, TextBlock

async def main():
    async for message in query(prompt="What is the current directory structure?", options=ClaudeAgentOptions(allowed_tools=["Read", "Bash"])):
        if isinstance(message, AssistantMessage):
            for block in message.content:
                if isinstance(block, TextBlock):
                    print(block.text)

anyio.run(main)

Stateful Session with ClaudeSDKClient

This example demonstrates how to maintain a conversation history and use the agent for multi-turn interactions.

import anyio
from claude_agent_sdk import ClaudeSDKClient, ClaudeAgentOptions

async def chat():
    client = ClaudeSDKClient()
    options = ClaudeAgentOptions(system_prompt="You are a senior software engineer.")
    
    await client.start(prompt="Analyze the current project files.", options=options)
    response = await client.send("Now, suggest a performance optimization for the main loop.")
    print(response)

anyio.run(chat)

Defining Custom Tools via MCP

You can extend the agent’s capabilities by defining Python functions as tools using the @tool decorator and wrapping them in an MCP server.

import anyio
from claude_agent_sdk import tool, create_sdk_mcp_server, query, ClaudeAgentOptions

@tool("get_weather", "Get the current weather for a city", {"city": str})
async def weather_tool(args):
    return {"content": [{"type": "text", "text": f"The weather in {args['city']} is sunny, 25C."}]}

# Create an MCP server and register the tool
mcp = create_sdk_mcp_server(name="weather_service", version="1.0.0", tools=[weather_tool])

async def main():
    options = ClaudeAgentOptions(mcp_servers={"weather": mcp}, allowed_tools=["mcp__weather_service__get_weather"])
    async for message in query(prompt="What is the weather in London?", options=options):
        print(message)

anyio.run(main)

Advanced Configuration

The ClaudeAgentOptions class is the primary way to customize the agent’s behavior, permissions, and environment. Proper configuration is key to ensuring the agent operates safely and efficiently.

Key configuration options include:

  • system_prompt: Define the agent’s persona and constraints.
  • max_turns: Limit the number of iterations the agent can take to prevent infinite loops and token waste.
  • allowed_tools: An allowlist of tools the agent can use without explicit approval.
  • disallowed_tools: A blocklist of tools that are strictly forbidden.
  • permission_mode: Controls how the agent handles tools not in the allowlist (e.g., acceptEdits).
  • cli_path: Specify a custom path to the Claude Code CLI binary.
  • mcp_servers: A dictionary mapping server names to MCP server instances for external tool integration.

Real-World Use Cases

The Claude Agent SDK Python is most effective when the agent needs to interact with a local environment to perform complex, multi-step tasks.

  • Autonomous SRE Diagnostics: An agent can be programmed to monitor logs, detect an error, read the relevant source code, run a reproduction script, and suggest a fix—all autonomously.
  • Automated PR Reviewer: Instead of a simple linting tool, an agent can read the changed files, run the existing test suite, and provide a nuanced architectural review of the pull request.
  • Codebase Migration Tool: An agent can be tasked with updating a library version across a large codebase, updating all call sites, running tests to verify the fix, and committing the changes.
  • Custom DevOps Bot: By integrating MCP servers for Jira or Slack, an agent can triage GitHub issues, create corresponding Jira tickets, and then attempt to fix the bug autonomously.

Contributing to Claude Agent SDK Python

Anthropic encourages contributions to the SDK. While the core agent loop is proprietary, the Python wrapper and tool integration layers are open for improvement.

To contribute, start by exploring the CONTRIBUTING.md file in the repository. The standard GitHub flow is used: fork the repository, create a feature branch, and submit a pull request. Developers are encouraged to report bugs via the GitHub Issues tracker and look for “good first issues” to get started.

Ensure that all new features include corresponding tests and that the Python code follows the project’s established coding conventions and type hinting standards.

Community and Support

Since this is an official Anthropic project, the primary source of truth is the official documentation and the GitHub repository.

  • Official Documentation: The Claude Agent SDK Python API Reference provides a complete list of all functions and types.
  • GitHub Discussions: Use the repository’s Discussions tab to ask questions and share examples of agents you’ve built.
  • Anthropic Engineering Blog: The engineering blog often publishes deep dives into agentic workflows and the design philosophy of the SDK.
  • Community Tutorials: Many developers have shared their experience building “vibe-coding” agents and specialized SRE bots using the SDK.

Conclusion

The Claude Agent SDK Python provides a powerful, production-ready bridge between high-level AI reasoning and low-level system execution. By internalizing the agentic loop and bundling the Claude Code CLI, it removes the majority of the boilerplate code required to build autonomous agents that can actually interact with a real codebase.

While it is a Claude-native tool, the ability to integrate custom tools via MCP and the routing options for Bedrock and Vertex AI make it a flexible choice for enterprise environments. It is the ideal tool for developers who want to build specialized, autonomous agents for software engineering, DevOps, and SRE tasks.

Star the repo, try the quickstart, and start building your first autonomous agent today.

What is Claude Agent SDK Python and what problem does it solve?

Claude Agent SDK Python is an official toolkit from Anthropic that allows developers to build autonomous AI agents. It solves the problem of having to manually write the tool-execution loop (the “agentic loop”) that allows an LLM to use tools like bash and file reads to solve a task autonomously.

How do I install Claude Agent SDK Python?

You can install the SDK using pip: pip install claude-agent-sdk. The Claude Code CLI is bundled with the package, so no separate installation of the CLI is required for most users.

How does Claude Agent SDK compare to LangGraph?

Claude Agent SDK is specialized for autonomous coding and SRE tasks with a built-in agent loop and native local environment access. LangGraph is a general-purpose state machine framework for building complex, multi-agent workflows with explicit control over every state transition.

Can I use Claude Agent SDK for building a custom SRE bot?

The SDK is la a perfect fit for building SRE bots because it can autonomously read logs, execute terminal commands to check system health, and edit source code to fix bugs, all within a single programmatic interface.

What is the difference between query() and ClaudeSDKClient?

The query() function is used for stateless, one-shot interactions where each call is independent. The ClaudeSDKClient is used for stateful sessions where conversation history and context are reused across multiple turns of interaction.

Does the SDK support custom tools?

Yes, the SDK supports custom tools via the Model Context Protocol (MCP). You can define Python functions as tools using the @tool decorator and register them in the SDK’s ClaudeAgentOptions.

Can I use the SDK with Amazon Bedrock or Google Vertex AI?

Yes, by setting the environment variables CLAUDE_CODE_USE_BEDROCK=1 or CLAUDE_CODE_USE_VERTEX=1, you can route the agent’s requests through these cloud providers instead of the standard Anthropic API.