The AI agent ecosystem has exploded in 2026, with dozens of frameworks competing for developer attention. But when Anthropic — the company behind Claude — releases its official SDK, the entire landscape shifts overnight. Introducing the Claude Agent SDK for Python, a purpose-built toolkit that lets you programmatically control Claude Code from your own Python applications. With over 6,700 GitHub stars and rapid community adoption, this SDK represents Anthropic’s commitment to empowering developers who want to build autonomous AI coding agents without reinventing the wheel.

This article provides a comprehensive technical review of the Claude Agent SDK for Python: its architecture, key features, real-world use cases, code examples, and how it compares to alternatives. Whether you’re an experienced Python developer or just getting started with AI agents, this guide will help you understand why the official SDK is the smartest choice for building production-grade Claude-based agents.


What Is the Claude Agent SDK for Python?

The Claude Agent SDK for Python is Anthropic’s officially maintained SDK that enables programmatic interaction with Claude Code from within Python applications. Unlike higher-level frameworks that abstract away the underlying mechanics, this SDK gives you direct, low-level access to Claude Code’s full capabilities — reading files, executing code, running shell commands, editing source code, and much more — all orchestrated through a clean, well-documented Python API.

The SDK wraps Claude Code internally, meaning you get the same powerful toolset that Claude Code users enjoy daily, but exposed through a programmatic interface suitable for automation, integration, and building custom agent applications.

Key Project Statistics

MetricValue
GitHub Stars6,775+
Forks973
LicenseMIT
Primary LanguagePython
Python Version Required3.10+
Package Nameclaude-agent-sdk
MaintainerAnthropic
Documentationplatform.claude.com/docs/en/agent-sdk/python

Core Architecture: Two Interaction Patterns

The SDK offers two fundamentally different ways to interact with Claude Code, each designed for different use cases. Understanding this distinction is critical for choosing the right approach for your application.

Pattern 1: Simple One-Shot Queries (query())

The simplest interface is the query() function, which sends a prompt to Claude Code and returns streaming responses:

import anyio
from claude_agent_sdk import query

async def main():
    async for message in query(prompt="Create a Flask app with /api/users endpoint"):
        print(message)

anyio.run(main)

This pattern is ideal for quick tasks where you send a single request and process the response stream. It requires zero configuration — the bundled Claude Code CLI handles everything automatically.

Pattern 2: Interactive Conversations (ClaudeSDKClient)

For more complex scenarios requiring multiple turns, custom tools, or fine-grained control, the ClaudeSDKClient class provides a bidirectional interactive session:

from claude_agent_sdk import ClaudeAgentOptions, ClaudeSDKClient

options = ClaudeAgentOptions(
    system_prompt="You are a senior Python architect.",
    max_turns=5,
    permission_mode='autoApprove'
)

async with ClaudeSDKClient(options=options) as client:
    await client.query("Design a microservice architecture for this repo")
    async for msg in client.receive_response():
        print(msg)

With ClaudeSDKClient, you maintain a persistent conversation state, enable custom tools, set permission policies, and control every aspect of Claude’s behavior. This is the pattern used for production agent applications.


Feature Deep Dive

Custom Tools via In-Process MCP Servers

One of the most powerful features is the ability to define custom tools directly in Python using the @tool decorator. These tools run in-process as MCP servers, eliminating the overhead of separate subprocess management:

from claude_agent_sdk import tool, create_sdk_mcp_server, ClaudeAgentOptions, ClaudeSDKClient

@tool("deploy", "Deploy application to production", {
    "environment": str,
    "branch": str
})
async def deploy_app(args):
    env = args["environment"]
    branch = args["branch"]
    # Run deployment logic here
    return {"status": f"Deployed {branch} to {env}"}

server = create_sdk_mcp_server(
    name="deployment-tools",
    tools=[deploy_app]
)

options = ClaudeAgentOptions(
    mcp_servers={"deploy": server},
    allowed_tools=["mcp__tools__deploy"]
)

Benefits over external MCP servers:

  • No subprocess lifecycle management
  • Better performance with no IPC overhead
  • Simpler debugging — all code in one process
  • Type safety with Python decorators

Permission System and Security Controls

Production AI agents need robust security controls. The SDK includes a sophisticated permission system:

options = ClaudeAgentOptions(
    allowed_tools=["Read", "Write", "Bash"],       # Auto-approved
    disallowed_tools=["WebFetch"],                   # Always blocked
    permission_mode='acceptEdits',                   # Auto-approve edits
    can_use_tool=lambda tool_name, context: ...     # Custom logic
)

Available permissions include:

  • default: Full human-like control with approval prompts
  • editFiles: Read + edit files only, no terminal access
  • acceptEdits: Edit files with auto-approval; Bash requires confirmation
  • autoApprove: Full autonomy with pre-approved permissions

This graduated permission model ensures you can start safely and gradually grant more access based on trust levels and operational needs.

Hooks: Intercept and Control Agent Behavior

Hooks allow you to intercept Claude’s tool use decisions before they execute, enabling safety checks, audit logging, and conditional execution:

from claude_agent_sdk import HookMatcher

async def block_destructive_commands(input_data, tool_use_id, context):
    if input_data["tool_name"] == "Bash":
        command = input_data["tool_input"].get("command", "")
        dangerous_patterns = ["rm -rf", "drop table", "> /dev/sda"]
        for pattern in dangerous_patterns:
            if pattern in command:
                return {
                    "hookSpecificOutput": {
                        "hookEventName": "PreToolUse",
                        "permissionDecision": "deny",
                        "permissionDecisionReason": f"Dangerous pattern detected: {pattern}"
                    }
                }
    return {}

options = ClaudeAgentOptions(
    hooks={
        "PreToolUse": [
            HookMatcher(matcher="Bash", hooks=[block_destructive_commands])
        ]
    }
)

This hook system is critical for enterprise deployments where uncontrolled shell execution poses security risks.

Supported Toolset

By default, Claude Agent SDK exposes Claude Code’s full toolset:

Tool CategoryCapabilities
File OperationsRead, Write, Edit, Grep, Glob, List Directory
Code ExecutionRun arbitrary code (Python, bash, node, etc.)
Shell AccessExecute terminal commands with full environment
SearchMulti-file search across entire codebases
Browser AutomationWeb scanning and JavaScript execution

Real-World Use Cases

Use Case 1: Automated Code Review Pipeline

Build a CI/CD-integrated code review agent that runs before merge:

from claude_agent_sdk import query, ClaudeAgentOptions

async def review_code(pr_diff):
    options = ClaudeAgentOptions(
        system_prompt="""You are an expert code reviewer. Focus on:
        - Security vulnerabilities
        - Performance issues  
        - Code style and best practices
        - Test coverage gaps""",
        allowed_tools=["Read", "Grep"],
        permission_mode='editFiles',
        max_turns=3
    )
    
    results = []
    async for message in query(
        prompt=f"Review this PR diff:\n{pr_diff}",
        options=options
    ):
        results.append(str(message))
    
    return "\n".join(results)

Use Case 2: Self-Healing Infrastructure Scripts

Create agents that detect and fix production issues autonomously:

from claude_agent_sdk import ClaudeSDKClient, ClaudeAgentOptions

async def self_heal_alert(alert_json):
    options = ClaudeAgentOptions(
        system_prompt="You are an SRE agent. Diagnose and fix production issues.",
        allowed_tools=["Bash", "Read", "Edit", "code_run"],
        permission_mode='acceptEdits',
        hooks={
            "PreToolUse": [HookMatcher(
                matcher="Bash", 
                hooks=[block_destructive_commands]
            )]
        }
    )
    
    async with ClaudeSDKClient(options=options) as client:
        await client.query(f"Investigate alert: {alert_json}")
        async for msg in client.receive_response():
            log_action(msg)

Use Case 3: AI-Powered Data Analytics Platform

Wrap Claude Code as a service layer that converts natural language queries into data analysis:

from claude_agent_sdk import ClaudeSDKClient, ClaudeAgentOptions

class AnalyticsAgent:
    def __init__(self):
        self.options = ClaudeAgentOptions(
            system_prompt="""You are a data analyst assistant.
            Turn SQL queries, data visualizations, and insights 
            from natural language requests.""",
            allowed_tools=["code_run", "Read", "Write"],
            cwd="/data/reports/"
        )
    
    async def analyze(self, question: str) -> str:
        async with ClaudeSDKClient(options=self.options) as client:
            await client.query(question)
            return await client.receive_response()

Comparison with Alternatives

FeatureClaude Agent SDKOpenClawGenericAgentAutoGen
Official Vendor Support✅ Anthropic❌ Community❌ Community❌ Microsoft
Installation Complexitypip installMulti-serviceMinimal depsComplex orchestration
Custom Tool IntegrationIn-process MCPPlugin ecosystemDynamic scriptsCustom adapters
Permission Granularity4-tier modelBasicNoneLimited
Hook System✅ PreToolUsePartial
Token EfficiencyOptimized by AnthropicVariableExcellent (30K window)Standard
Deployment TargetProduction agentsMulti-agent teamsSingle-machineEnterprise

The Claude Agent SDK stands out because it’s backed by the company that built Claude itself. You get guaranteed compatibility, regular updates, and direct access to Claude Code’s latest features — advantages that community-maintained frameworks simply cannot match.


Getting Started: Quick Start Guide

Step 1: Install

pip install claude-agent-sdk

That’s it. The Claude Code CLI is bundled automatically — no separate installation needed. If you prefer managing Claude Code yourself:

curl -fsSL https://claude.ai/install.sh | bash

Step 2: Configure API Access

Your Anthropic API key is automatically handled through standard environment variables:

export ANTHROPIC_API_KEY="sk-ant-your-key-here"

Step 3: Run Your First Agent

# hello_agent.py
from claude_agent_sdk import query

import anyio

async def main():
    async for message in query(
        prompt="Write a Python function that calculates Fibonacci numbers iteratively",
        options=ClaudeAgentOptions(max_turns=1)
    ):
        if hasattr(message, 'content'):
            for block in message.content:
                if hasattr(block, 'text'):
                    print(block.text)

anyio.run(main)

Run with:

python hello_agent.py

Step 4: Add Custom Tools

Build a deployment pipeline with custom tools:

# deploy_agent.py
from claude_agent_sdk import (
    tool, create_sdk_mcp_server, 
    ClaudeAgentOptions, ClaudeSDKClient
)

@tool("git_status", "Check current git status", {})
async def git_status(_args):
    import subprocess
    result = subprocess.run(["git", "status", "--short"], 
                          capture_output=True, text=True)
    return {"content": [{"type": "text", "text": result.stdout}]}

server = create_sdk_mcp_server(
    name="git-tools", 
    tools=[git_status]
)

options = ClaudeAgentOptions(
    mcp_servers={"git": server},
    allowed_tools=["mcp__tools__git_status"]
)

import anyio

async def main():
    async with ClaudeSDKClient(options=options) as client:
        await client.query("Show current git status and suggest improvements")
        async for msg in client.receive_response():
            print(msg)

anyio.run(main)

Common Error Handling Patterns

Robust agent applications handle errors gracefully:

from claude_agent_sdk import (
    CLINotFoundError,      # Claude Code not installed
    CLIConnectionError,    # Connection failed
    ProcessError,          # Subprocess exit code issue
    CLIJSONDecodeError     # Response parsing failure
)

try:
    async for message in query(prompt="Execute migration"):
        process_result(message)
except CLINotFoundError:
    print("Claude Code is not installed. Run: pip install claude-agent-sdk")
except CLIConnectionError as e:
    print(f"Connection error: {e}. Check API key.")
except ProcessError as e:
    print(f"Process failed with code {e.exit_code}")
except CLIJSONDecodeError as e:
    print(f"Parse error: {e}")

Best Practices for Production

  1. Always define explicit permission modes — never use unrestricted mode in production environments. Start with editFiles and progressively relax as trust builds.

  2. Use hooks for security boundaries — even with permissive tool lists, PreToolUse hooks provide a final safety net against destructive operations.

  3. Set reasonable turn limits — cap max_turns to prevent runaway agent loops. Typical values range from 3–10 for most tasks.

  4. Isolate working directories — always specify cwd to prevent agents from operating outside intended scopes.

  5. Implement structured logging — use hooks to log every tool invocation for audit compliance and debugging.

  6. Version-pinned dependencies — pin claude-agent-sdk to specific versions in production to avoid unexpected breaking changes.


Conclusion

The Claude Agent SDK for Python represents a significant milestone in the evolution of AI-assisted development. By providing official, vendor-backed programmatic access to Claude Code, Anthropic has given developers the foundation they need to build production-grade autonomous agents — without compromising on security, reliability, or compatibility.

Whether you’re automating code reviews, building self-healing infrastructure tools, or creating AI-powered analytics platforms, this SDK gives you the building blocks to ship confidently. With its clean API, robust permission system, in-process MCP support, and growing community, the Claude Agent SDK is the definitive choice for Python developers serious about AI agent development.

If you haven’t tried it yet, head to the Anthropic documentation and start experimenting today. The future of programmatic AI development is here, and it’s written in Python.