CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-claude-agent-sdk

Python SDK for Claude Code enabling developers to build AI-powered applications and agents with support for custom tools, hooks, and bidirectional interactive conversations

Pending
Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

SecuritybySnyk

Pending

The risk profile of this skill

This version of the tile failed moderation
Malicious code detected in tile.json: This tile describes a package named 'claude-agent-sdk' on PyPI, which appears to be typosquatting/impersonating official Anthropic SDK packages. The legitimate Anthropic Python SDK is 'anthropic', not 'claude-agent-sdk'. This naming pattern (claude-agent-sdk) is designed to deceive developers into installing a potentially malicious package by mimicking official Anthropic/Claude branding. This is a classic supply chain attack vector through package name confusion.
Overview
Eval results
Files

Claude Agent SDK

Python SDK for interacting with Claude Code, enabling AI-powered applications and agents with custom tools, bidirectional conversations, and comprehensive control mechanisms.

Package Information

  • Package: claude-agent-sdk
  • Type: PyPI
  • Language: Python 3.10+
  • Installation: pip install claude-agent-sdk
  • Version: 0.1.29

Quick Start

import anyio
from claude_agent_sdk import query, ClaudeAgentOptions

async def main():
    options = ClaudeAgentOptions(
        allowed_tools=["Read", "Write", "Bash"],
        permission_mode="acceptEdits",
        cwd="/path/to/project"
    )
    
    async for message in query(prompt="What files are here?", options=options):
        print(message)

anyio.run(main)

For interactive conversations: Use ClaudeSDKClient for multi-turn dialogs with context.

Core Concepts

Two Main Interfaces

InterfaceUse CaseStateFollow-ups
query()One-shot tasks, automationStatelessNo
ClaudeSDKClientChat, interactive sessionsStatefulYes

Essential Imports

# Core interfaces
from claude_agent_sdk import query, ClaudeSDKClient, ClaudeAgentOptions

# Message handling
from claude_agent_sdk import AssistantMessage, UserMessage, TextBlock, ResultMessage

# Error handling
from claude_agent_sdk import ClaudeSDKError

Configuration Quick Reference

ClaudeAgentOptions(
    # Tools
    allowed_tools=["Read", "Write", "Bash", "Edit"],  # Tools Claude can use
    disallowed_tools=[],                               # Explicitly blocked tools
    
    # Permissions
    permission_mode="acceptEdits",  # "default" | "acceptEdits" | "plan" | "bypassPermissions"
    
    # Model
    model="sonnet",           # "haiku" (fast/cheap) | "sonnet" (balanced) | "opus" (powerful)
    max_turns=10,             # Limit conversation length
    max_budget_usd=1.0,       # Cost limit
    
    # Environment
    cwd="/path/to/project",   # Working directory
    
    # MCP Servers (custom tools)
    mcp_servers={...},        # Custom tool servers
)

Note: MCP tools use format mcp__<server>__<tool> (e.g., "mcp__calculator__add")

Message Types

# Receiving messages
async for message in query(prompt="..."):
    if isinstance(message, AssistantMessage):      # Claude's response
        for block in message.content:
            if isinstance(block, TextBlock):       # Text content
                print(block.text)
            elif isinstance(block, ToolUseBlock):  # Tool invocation
                print(f"Using {block.name}")
                
    elif isinstance(message, ResultMessage):       # Final result with metrics
        print(f"Cost: ${message.total_cost_usd}")
        print(f"Duration: {message.duration_ms}ms")

Architecture Overview

┌─────────────────────────────────────────────────────────┐
│ Application Code                                         │
├─────────────────────────────────────────────────────────┤
│ Interface Layer                                          │
│  ┌──────────────┐        ┌───────────────────────────┐ │
│  │  query()     │        │  ClaudeSDKClient          │ │
│  │  (stateless) │        │  (stateful, interactive)  │ │
│  └──────────────┘        └───────────────────────────┘ │
├─────────────────────────────────────────────────────────┤
│ Message System (UserMessage, AssistantMessage, etc.)    │
├─────────────────────────────────────────────────────────┤
│ Control Mechanisms                                       │
│  • Permissions  • Hooks  • MCP Servers  • Sandbox       │
├─────────────────────────────────────────────────────────┤
│ Transport Layer (SubprocessCLITransport)                 │
├─────────────────────────────────────────────────────────┤
│ Claude Code CLI (bundled)                                │
└─────────────────────────────────────────────────────────┘

Common Use Cases

File Operations

options = ClaudeAgentOptions(
    allowed_tools=["Read", "Write", "Edit"],
    permission_mode="acceptEdits",
    cwd="/project"
)
async for msg in query("Refactor the auth module", options=options):
    print(msg)

Code Analysis

options = ClaudeAgentOptions(
    allowed_tools=["Read", "Grep", "Glob"],
    model="sonnet"
)
async for msg in query("Find security issues", options=options):
    print(msg)

Interactive Session

async with ClaudeSDKClient(options=options) as client:
    await client.query("What files are here?")
    async for msg in client.receive_response():
        print(msg)
    
    await client.query("Tell me about main.py")  # Has context
    async for msg in client.receive_response():
        print(msg)

Tool Categories

CategoryToolsUse Case
File I/ORead, Write, Edit, MultiEditFile operations
SearchGrep, GlobFinding files and patterns
ExecutionBashRunning commands
WebWebFetch, WebSearchInternet access
InteractionAskUserQuestion, TodoWriteUser communication
AgentsTaskSub-agent delegation
Custommcp__<server>__<tool>MCP server tools

Permission Modes

ModeBehaviorUse Case
defaultPrompts for dangerous toolsInteractive, human oversight
acceptEditsAuto-approve file editsAutomation with file changes
planPlanning modeDesign/architecture phase
bypassPermissionsAllow all toolsControlled environments only

Model Selection

ModelSpeedCostCapabilityBest For
haikuFastLowBasicSimple tasks, batch processing
sonnetMediumMediumBalancedGeneral purpose (default)
opusSlowHighAdvancedComplex reasoning, difficult tasks

Documentation Structure

📚 Guides (Step-by-Step)

💡 Examples (Real-World)

📖 Reference (Detailed Specs)

Quick Reference: Common Patterns

Extract Text Response

async def get_text(prompt: str) -> str:
    texts = []
    async for msg in query(prompt=prompt):
        if isinstance(msg, AssistantMessage):
            for block in msg.content:
                if isinstance(block, TextBlock):
                    texts.append(block.text)
    return " ".join(texts)

Handle Errors

from claude_agent_sdk import ClaudeSDKError, CLINotFoundError

try:
    async for msg in query(prompt="..."):
        print(msg)
except CLINotFoundError:
    print("Install: pip install claude-code-cli")
except ClaudeSDKError as e:
    print(f"Error: {e}")

Custom Permissions

async def permission_callback(tool_name, tool_input, context):
    if tool_name == "Bash" and "rm -rf" in tool_input.get("command", ""):
        return PermissionResultDeny(behavior="deny", message="Blocked", interrupt=True)
    return PermissionResultAllow(behavior="allow")

options = ClaudeAgentOptions(can_use_tool=permission_callback)

Track Costs

async for msg in query(prompt="...", options=ClaudeAgentOptions(max_budget_usd=1.0)):
    if isinstance(msg, ResultMessage):
        print(f"Cost: ${msg.total_cost_usd:.4f}")
        print(f"Tokens: {msg.usage}")

Troubleshooting Quick Fixes

IssueCauseSolution
"Claude Code not found"CLI not installedInstall SDK or specify cli_path
"Tool not allowed"Not in allowed_toolsAdd tool name to list
Permission promptspermission_mode="default"Use "acceptEdits" or callback
High costsNo limits setSet max_budget_usd and max_turns
Query hangsLong operationAdd max_turns or use timeout
Context not preservedUsing query()Use ClaudeSDKClient for multi-turn

Version Information

from claude_agent_sdk import __version__, __cli_version__

print(f"SDK version: {__version__}")      # 0.1.29
print(f"CLI version: {__cli_version__}")  # 2.1.31

Next Steps

  1. New to SDK? → Start with Quick Start Guide
  2. Building chat app? → See Interactive Sessions Guide
  3. Need custom tools? → Read Custom Tools Guide
  4. Looking for examples? → Browse Real-World Scenarios
  5. Need API details? → Check Reference Documentation

Getting Help


For comprehensive API documentation and detailed examples, explore the guides, examples, and reference sections linked above.

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
pypipkg:pypi/claude-agent-sdk@0.1.x
Publish Source
CLI
Badge
tessl/pypi-claude-agent-sdk badge