claude-agent-toolkit


Nameclaude-agent-toolkit JSON
Version 0.2.4 PyPI version JSON
download
home_pageNone
SummaryPython framework for building Claude Code agents with custom tools
upload_time2025-10-11 08:47:37
maintainerNone
docs_urlNone
authorNone
requires_python>=3.12
licenseMIT
keywords agent-framework ai-agents claude-agent-sdk claude-agent-toolkit claude-agents claude-code docker mcp-tools model-context-protocol
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            # Claude Agent Toolkit

**claude-code-sdk wrapper for enhanced developer experience with easy setup and runtime isolation using Docker**

A Python framework that wraps claude-code-sdk to provide better developer experience through decorator-based tools, runtime isolation, and simplified agent development. Built for production safety with Docker containers that ensure controlled tool execution and consistent behavior across all environments.

## Table of Contents

- [Why Claude Agent Toolkit?](#why-claude-agent-toolkit)
- [When Should You Use This?](#when-should-you-use-this)
- [Quick Start](#quick-start)
- [Installation & Setup](#installation--setup)
- [Usage Examples](#usage-examples)
- [Core Features](#core-features)
- [Architecture](#architecture)
- [Built-in Tools](#built-in-tools)
- [Creating Custom Tools](#creating-custom-tools)
- [FAQ](#faq)
- [Testing](#testing)
- [Contributing](#contributing)
- [License](#license)

## Why Claude Agent Toolkit?

### The Problem
Working directly with claude-code-sdk presents two major challenges:
1. **Complex Tool Integration** - Manual MCP server setup, connection handling, and tool registration
2. **Runtime Safety** - Need for controlled tool execution with clean, isolated environments

### The Solution
Claude Agent Toolkit solves these issues through:
- **🎯 Decorator-Based Tools** - Simple `@tool` decorator converts any Python function into a Claude-compatible tool
- **🐳 Runtime Isolation** - Docker containers provide safe, controlled execution with only your specified tools
- **⚡ Zero Configuration** - Automatic MCP server management and tool discovery

*"An intuitive and stable development experience similar to Google's ADK"*

### See the Difference

**Before (Direct claude-code-sdk):**
```python
# Manual tool naming and complex schema definition required
@tool("greet", "Greet a user", {"name": str})
async def greet_user(args):
    return {
        "content": [
            {"type": "text", "text": f"Hello, {args['name']}!"}
        ]
    }

# Tool functions and MCP server are decoupled - difficult to maintain at scale
server = create_sdk_mcp_server(
    name="my-tools",
    version="1.0.0",
    tools=[greet_user]
)

# At Runtime:
# ❌ Subprocess can access system tools (Read, LS, Grep)
# ❌ Manual environment configuration required
# ❌ No control over Claude Code's tool access
# ❌ Risk of unintended system interactions
```

**After (Claude Agent Toolkit):**
```python
# Intuitive class-based tool definition with integrated MCP server
class CalculatorTool(BaseTool):
    @tool()
    async def add(self, a: float, b: float) -> dict:
        """Adds two numbers together"""
        return {"result": a + b}

# Single line agent creation with controlled tool access
agent = Agent(tools=[CalculatorTool()])

# At Runtime:
# ✅ Docker container runs only your defined tools
# ✅ No access to system tools (Read, LS, Grep)
# ✅ Clean, isolated, predictable execution environment
# ✅ Complete control over Claude Code's capabilities
```

### Comparison Table

| Feature | claude-code-sdk | Claude Agent Toolkit |
|---------|----------------|---------------------|
| **Custom Tools** | Manual schema definition, No parallel execution support | Simple and intuitive class-based definition with `@tool` decorator, Built-in parallel execution with `parallel=True` |
| **Runtime Isolation** | No built-in isolation<br/>You need to design your own | Docker by default<br/>Allows only tools you explicitly added |
| **Environment Consistency** | Manual environment setup<br/>Explicit tool/option configuration required | Zero setup needed<br/>Works out of the box |
| **Setup Complexity** | ~20 lines just for ClaudeCodeOptions configuration | ~25 lines for complete agent with calculator<br/>`Agent.run(verbose=True)` shows all responses |
| **Built-in Tools** | Build everything from scratch | FileSystemTool with permission control<br/>DataTransferTool for formatted output handling |
| **Best For** | Using Claude Code as-is<br/>Minimal dependencies only | Fast development<br/>Using Claude Code as reasoning engine (like LangGraph agents) |

## Quick Start

```python
from claude_agent_toolkit import Agent, BaseTool, tool

# 1. Create a custom tool with @tool decorator
class CalculatorTool(BaseTool):
    @tool()
    async def add(self, a: float, b: float) -> dict:
        """Adds two numbers together"""
        result = a + b
        return {
            "operation": f"{a} + {b}",
            "result": result,
            "message": f"The result of adding {a} and {b} is {result}"
        }

# 2. Create and run an agent
async def main():
    agent = Agent(
        system_prompt="You are a helpful calculator assistant",
        tools=[CalculatorTool()],
        model="sonnet"  # haiku, sonnet, or opus
    )

    result = await agent.run("What is 15 + 27?")
    print(result)  # Claude will use your tool and return the answer

if __name__ == "__main__":
    import asyncio
    asyncio.run(main())
```

## Installation & Setup

### Prerequisites

- **Python 3.12+** with `uv` package manager
- **Docker Desktop** (required for Docker executor, recommended)
- **Claude Code OAuth Token** - Get from [Claude Code](https://claude.ai/code)

### Install the Package

```bash
# Using pip
pip install claude-agent-toolkit

# Using uv (recommended)
uv add claude-agent-toolkit

# Using poetry
poetry add claude-agent-toolkit
```

### Set Your OAuth Token

Get your token by running `claude setup-token` in your terminal, then:

```bash
export CLAUDE_CODE_OAUTH_TOKEN='your-token-here'
```

### Quick Verification

```bash
# Clone examples (optional)
git clone https://github.com/cheolwanpark/claude-agent-toolkit.git
cd claude-agent-toolkit/src/examples/calculator
python main.py
```

## Usage Examples

### Basic Agent with Custom Tool

```python
from claude_agent_toolkit import Agent, BaseTool, tool, ExecutorType

class MyTool(BaseTool):
    def __init__(self):
        super().__init__()
        self.counter = 0  # Explicit data management

    @tool()
    async def increment(self) -> dict:
        """Increment counter and return value"""
        self.counter += 1
        return {"value": self.counter}

# Docker executor (default, production-ready)
agent = Agent(tools=[MyTool()])

# Subprocess executor (faster startup, development)
agent = Agent(tools=[MyTool()], executor=ExecutorType.SUBPROCESS)

result = await agent.run("Increment the counter twice")
```

### Model Selection

```python
# Fast and efficient for simple tasks
weather_agent = Agent(
    tools=[weather_tool],
    model="haiku"
)

# Balanced performance (default)
general_agent = Agent(
    tools=[calc_tool, weather_tool],
    model="sonnet"
)

# Most capable for complex reasoning
analysis_agent = Agent(
    tools=[analysis_tool],
    model="opus"
)

# Override per query
result = await weather_agent.run(
    "Complex weather pattern analysis",
    model="opus"
)
```

### CPU-Intensive Operations

```python
class HeavyComputeTool(BaseTool):
    @tool(parallel=True, timeout_s=120)
    def process_data(self, data: str) -> dict:
        """Heavy computation"""
        # Sync function - runs in separate process
        import time
        time.sleep(5)  # Simulate heavy work
        return {"processed": f"result_{data}"}
```

### Error Handling

```python
from claude_agent_toolkit import (
    Agent, BaseTool,
    ConfigurationError, ConnectionError, ExecutionError
)

try:
    agent = Agent(tools=[MyTool()])
    result = await agent.run("Process my request")

except ConfigurationError as e:
    print(f"Setup issue: {e}")  # Missing token, invalid config

except ConnectionError as e:
    print(f"Connection failed: {e}")  # Docker, network issues

except ExecutionError as e:
    print(f"Execution failed: {e}")  # Tool failures, timeouts
```

## Core Features

- **🎯 Decorator-Based Tools** - Transform any Python function into a Claude tool with simple `@tool` decorator
- **🔌 External MCP Integration** - Connect to existing MCP servers via stdio and HTTP transports
- **🐳 Isolated Execution** - Docker containers ensure consistent behavior across all environments
- **⚡ Zero Configuration** - Automatic MCP server management, port selection, and tool discovery
- **🔧 Flexible Execution Modes** - Choose Docker isolation (production) or subprocess (development)
- **📝 Explicit Data Management** - You control data persistence with no hidden state
- **⚙️ CPU-bound Operations** - Process pools for heavy computations with parallel processing
- **🎭 Multi-tool Coordination** - Claude Code intelligently orchestrates multiple tools
- **🏗️ Production Ready** - Built for scalable, reliable agent deployment

## Architecture

### Execution Modes

| Feature | Docker (Default) | Subprocess |
|---------|------------------|------------|
| **Isolation** | Full container isolation | Process isolation only |
| **Setup Time** | ~3 seconds | ~0.5 seconds |
| **Use Case** | Production, testing | Development, CI/CD |
| **Requirements** | Docker Desktop | None |

### Component Overview

```
┌─────────────────┐    ┌──────────────────┐    ┌─────────────────┐
│   Your Tools    │    │      Agent       │    │  Claude Code    │
│  (MCP Servers)  │◄──►│   (Orchestrator) │◄──►│   (Reasoning)   │
└─────────────────┘    └──────────────────┘    └─────────────────┘
        │                       │                       │
        ▼                       ▼                       ▼
┌─────────────────┐    ┌──────────────────┐    ┌─────────────────┐
│   Host Process  │    │ Docker Container │    │ Claude Code API │
│   (localhost)   │    │   or Subprocess  │    │   (claude.ai)   │
└─────────────────┘    └──────────────────┘    └─────────────────┘
```

## External MCP Server Integration

### Connect to Existing MCP Servers

Integrate with any existing MCP server using stdio or HTTP transport:

```python
from claude_agent_toolkit import Agent
from claude_agent_toolkit.tool.mcp import StdioMCPTool, HttpMCPTool

# Connect to an MCP server via command execution
everything_server = StdioMCPTool(
    command="npx",
    args=["-y", "@modelcontextprotocol/server-everything"],
    name="everything"
)

# Connect to an HTTP MCP server
http_server = HttpMCPTool(
    url="http://localhost:3001/mcp",
    name="my-http-server"
)

# Mix with your custom tools
agent = Agent(
    system_prompt="You can use both custom and external tools",
    tools=[MyCustomTool(), everything_server, http_server]
)

result = await agent.run("Use the everything server to echo 'Hello World'")
```

### When to Use External MCP Integration

- **Existing MCP Ecosystem**: Leverage community MCP servers and tools
- **Language Diversity**: Use MCP servers written in Node.js, Python, Go, etc.
- **Specialized Tools**: Integrate domain-specific tools without reimplementation
- **Rapid Prototyping**: Quickly test MCP servers before building custom equivalents
- **Service Architecture**: Connect to MCP servers running as microservices

### Supported Transports

| Transport | Use Case | Example |
|-----------|----------|---------|
| **Stdio** | Command-line tools, npm packages | `npx` servers, Python scripts |
| **HTTP** | Web services, microservices | REST APIs, containerized servers |

## Built-in Tools

### FileSystemTool - Secure File Operations

Control exactly what files your agent can access with pattern-based permissions.

```python
from claude_agent_toolkit.tools import FileSystemTool

# Define access patterns
permissions = [
    ("*.txt", "read"),          # Read all text files
    ("data/**", "write"),       # Write to data directory
    ("logs/*.log", "read"),     # Read log files only
]

fs_tool = FileSystemTool(
    permissions=permissions,
    root_dir="/path/to/workspace"  # Restrict to directory
)

agent = Agent(
    system_prompt="You are a file manager assistant",
    tools=[fs_tool]
)

result = await agent.run(
    "List all text files and create a summary in data/report.txt"
)
```

### DataTransferTool - Type-Safe Data Transfer

Transfer structured data between Claude agents and your application using Pydantic models.

```python
from claude_agent_toolkit.tools import DataTransferTool
from pydantic import BaseModel, Field
from typing import List

class UserProfile(BaseModel):
    name: str = Field(..., description="Full name")
    age: int = Field(..., ge=0, le=150, description="Age in years")
    interests: List[str] = Field(default_factory=list)

# Create tool for specific model
user_tool = DataTransferTool.create(UserProfile, "UserProfileTool")

agent = Agent(
    system_prompt="You handle user profile data transfers",
    tools=[user_tool]
)

# Transfer data through Claude
await agent.run(
    "Transfer user: Alice Johnson, age 28, interests programming and hiking"
)

# Retrieve validated data
user_data = user_tool.get()
if user_data:
    print(f"Retrieved: {user_data.name}, age {user_data.age}")
```

## Creating Custom Tools

### Basic Tool Pattern

```python
from claude_agent_toolkit import BaseTool, tool

class MyTool(BaseTool):
    def __init__(self):
        super().__init__()  # Server starts automatically
        self.data = {}      # Explicit data management

    @tool()
    async def process_async(self, data: str) -> dict:
        """Async operation"""
        # Async operations for I/O, API calls
        return {"result": f"processed_{data}"}

    @tool(parallel=True, timeout_s=60)
    def process_heavy(self, data: str) -> dict:
        """CPU-intensive operation"""
        # Sync function - runs in separate process
        # Note: New instance created, self.data won't persist
        import time
        time.sleep(2)
        return {"result": f"heavy_{data}"}
```

### Context Manager Support

```python
# Single tool with guaranteed cleanup
with MyTool() as tool:
    agent = Agent(tools=[tool])
    result = await agent.run("Process my data")
# Server automatically cleaned up

# Multiple tools
with MyTool() as calc_tool, WeatherTool() as weather_tool:
    agent = Agent(tools=[calc_tool, weather_tool])
    result = await agent.run("Calculate and check weather")
# Both tools cleaned up automatically
```

## FAQ

### What is Claude Agent Toolkit?

A Python framework that lets you build AI agents using Claude Code with custom tools. Unlike generic agent frameworks, this specifically leverages Claude Code's advanced reasoning capabilities with your existing subscription.

### How is this different from other agent frameworks?

- **Uses Claude Code**: Leverages Claude's production infrastructure and reasoning
- **MCP Protocol**: Industry-standard tool integration, not proprietary APIs
- **Explicit Data**: You control data persistence, no hidden state management
- **Production Focus**: Built for real deployment, not just experiments

### Do I need Docker?

Docker is recommended for production but not required. Use `ExecutorType.SUBPROCESS` for subprocess execution:

```python
agent = Agent(tools=[my_tool], executor=ExecutorType.SUBPROCESS)
```
It also runs in an isolated directory to ensure maximum isolation.

### Which model should I use?

- **haiku**: Fast, cost-effective for simple operations
- **sonnet**: Balanced performance, good default choice
- **opus**: Maximum capability for complex reasoning

### How do I handle errors?

The framework provides specific exception types:

```python
from claude_agent_toolkit import ConfigurationError, ConnectionError, ExecutionError

try:
    result = await agent.run("task")
except ConfigurationError:
    # Missing OAuth token, invalid config
except ConnectionError:
    # Docker/network issues
except ExecutionError:
    # Tool failures, timeouts
```

### Can I use multiple tools together?

Yes! Claude Code intelligently orchestrates multiple tools:

```python
agent = Agent(tools=[calc_tool, weather_tool, file_tool])
result = await agent.run(
    "Calculate the average temperature and save results to report.txt"
)
```

## Testing

The framework is validated through comprehensive examples rather than traditional unit tests. Each example demonstrates specific capabilities and serves as both documentation and validation.

### Run Examples

```bash
# Clone the repository
git clone https://github.com/cheolwanpark/claude-agent-toolkit.git
cd claude-agent-toolkit

# Set your OAuth token
export CLAUDE_CODE_OAUTH_TOKEN='your-token-here'

# Run different examples
cd src/examples/calculator && python main.py     # Stateful operations, parallel processing
cd src/examples/weather && python main.py       # External API integration
cd src/examples/subprocess && python main.py    # No Docker required
cd src/examples/filesystem && python main.py    # Permission-based file access
cd src/examples/datatransfer && python main.py  # Type-safe data transfer
cd src/examples/mcp && python main.py           # External MCP server integration
```

### Example Structure

```
src/examples/
├── calculator/     # Mathematical operations with state management
├── weather/        # External API integration (OpenWeatherMap)
├── subprocess/     # Subprocess executor demonstration
├── filesystem/     # FileSystemTool with permissions
├── datatransfer/   # DataTransferTool with Pydantic models
├── mcp/           # External MCP server integration (stdio, HTTP)
└── README.md      # Detailed example documentation
```

### Docker Validation

Examples can run with both executors:

```bash
# Docker executor (default)
python main.py

# Subprocess executor (faster startup)
# Examples automatically use subprocess when Docker unavailable
```

## Contributing

1. Fork the repository
2. Create a feature branch: `git checkout -b feature-name`
3. Make your changes and validate with examples
4. Run examples to verify functionality
5. Submit a pull request

### Development Setup

```bash
git clone https://github.com/cheolwanpark/claude-agent-toolkit.git
cd claude-agent-toolkit
uv sync --group dev

# Validate your changes by running examples
export CLAUDE_CODE_OAUTH_TOKEN='your-token'
cd src/examples/calculator && python main.py
```

## License

This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.

---

**Created by**: [Cheolwan Park](https://github.com/cheolwanpark) • **Blog**: [Project Background](https://blog.codingvillain.com/post/claude-agent-toolkit)

**Links**: [Homepage](https://github.com/cheolwanpark/claude-agent-toolkit) • [Claude Code](https://claude.ai/code) • [Issues](https://github.com/cheolwanpark/claude-agent-toolkit/issues) • [Model Context Protocol](https://modelcontextprotocol.io/)
            

Raw data

            {
    "_id": null,
    "home_page": null,
    "name": "claude-agent-toolkit",
    "maintainer": null,
    "docs_url": null,
    "requires_python": ">=3.12",
    "maintainer_email": "Cheolwan Park <cheolwan.park552@gmail.com>",
    "keywords": "agent-framework, ai-agents, claude-agent-sdk, claude-agent-toolkit, claude-agents, claude-code, docker, mcp-tools, model-context-protocol",
    "author": null,
    "author_email": "Cheolwan Park <cheolwan.park552@gmail.com>",
    "download_url": "https://files.pythonhosted.org/packages/be/b7/c8792f0095f568e57ce05c5f637b1fbf1370c5505ec26b281556556dff7f/claude_agent_toolkit-0.2.4.tar.gz",
    "platform": null,
    "description": "# Claude Agent Toolkit\n\n**claude-code-sdk wrapper for enhanced developer experience with easy setup and runtime isolation using Docker**\n\nA Python framework that wraps claude-code-sdk to provide better developer experience through decorator-based tools, runtime isolation, and simplified agent development. Built for production safety with Docker containers that ensure controlled tool execution and consistent behavior across all environments.\n\n## Table of Contents\n\n- [Why Claude Agent Toolkit?](#why-claude-agent-toolkit)\n- [When Should You Use This?](#when-should-you-use-this)\n- [Quick Start](#quick-start)\n- [Installation & Setup](#installation--setup)\n- [Usage Examples](#usage-examples)\n- [Core Features](#core-features)\n- [Architecture](#architecture)\n- [Built-in Tools](#built-in-tools)\n- [Creating Custom Tools](#creating-custom-tools)\n- [FAQ](#faq)\n- [Testing](#testing)\n- [Contributing](#contributing)\n- [License](#license)\n\n## Why Claude Agent Toolkit?\n\n### The Problem\nWorking directly with claude-code-sdk presents two major challenges:\n1. **Complex Tool Integration** - Manual MCP server setup, connection handling, and tool registration\n2. **Runtime Safety** - Need for controlled tool execution with clean, isolated environments\n\n### The Solution\nClaude Agent Toolkit solves these issues through:\n- **\ud83c\udfaf Decorator-Based Tools** - Simple `@tool` decorator converts any Python function into a Claude-compatible tool\n- **\ud83d\udc33 Runtime Isolation** - Docker containers provide safe, controlled execution with only your specified tools\n- **\u26a1 Zero Configuration** - Automatic MCP server management and tool discovery\n\n*\"An intuitive and stable development experience similar to Google's ADK\"*\n\n### See the Difference\n\n**Before (Direct claude-code-sdk):**\n```python\n# Manual tool naming and complex schema definition required\n@tool(\"greet\", \"Greet a user\", {\"name\": str})\nasync def greet_user(args):\n    return {\n        \"content\": [\n            {\"type\": \"text\", \"text\": f\"Hello, {args['name']}!\"}\n        ]\n    }\n\n# Tool functions and MCP server are decoupled - difficult to maintain at scale\nserver = create_sdk_mcp_server(\n    name=\"my-tools\",\n    version=\"1.0.0\",\n    tools=[greet_user]\n)\n\n# At Runtime:\n# \u274c Subprocess can access system tools (Read, LS, Grep)\n# \u274c Manual environment configuration required\n# \u274c No control over Claude Code's tool access\n# \u274c Risk of unintended system interactions\n```\n\n**After (Claude Agent Toolkit):**\n```python\n# Intuitive class-based tool definition with integrated MCP server\nclass CalculatorTool(BaseTool):\n    @tool()\n    async def add(self, a: float, b: float) -> dict:\n        \"\"\"Adds two numbers together\"\"\"\n        return {\"result\": a + b}\n\n# Single line agent creation with controlled tool access\nagent = Agent(tools=[CalculatorTool()])\n\n# At Runtime:\n# \u2705 Docker container runs only your defined tools\n# \u2705 No access to system tools (Read, LS, Grep)\n# \u2705 Clean, isolated, predictable execution environment\n# \u2705 Complete control over Claude Code's capabilities\n```\n\n### Comparison Table\n\n| Feature | claude-code-sdk | Claude Agent Toolkit |\n|---------|----------------|---------------------|\n| **Custom Tools** | Manual schema definition, No parallel execution support | Simple and intuitive class-based definition with `@tool` decorator, Built-in parallel execution with `parallel=True` |\n| **Runtime Isolation** | No built-in isolation<br/>You need to design your own | Docker by default<br/>Allows only tools you explicitly added |\n| **Environment Consistency** | Manual environment setup<br/>Explicit tool/option configuration required | Zero setup needed<br/>Works out of the box |\n| **Setup Complexity** | ~20 lines just for ClaudeCodeOptions configuration | ~25 lines for complete agent with calculator<br/>`Agent.run(verbose=True)` shows all responses |\n| **Built-in Tools** | Build everything from scratch | FileSystemTool with permission control<br/>DataTransferTool for formatted output handling |\n| **Best For** | Using Claude Code as-is<br/>Minimal dependencies only | Fast development<br/>Using Claude Code as reasoning engine (like LangGraph agents) |\n\n## Quick Start\n\n```python\nfrom claude_agent_toolkit import Agent, BaseTool, tool\n\n# 1. Create a custom tool with @tool decorator\nclass CalculatorTool(BaseTool):\n    @tool()\n    async def add(self, a: float, b: float) -> dict:\n        \"\"\"Adds two numbers together\"\"\"\n        result = a + b\n        return {\n            \"operation\": f\"{a} + {b}\",\n            \"result\": result,\n            \"message\": f\"The result of adding {a} and {b} is {result}\"\n        }\n\n# 2. Create and run an agent\nasync def main():\n    agent = Agent(\n        system_prompt=\"You are a helpful calculator assistant\",\n        tools=[CalculatorTool()],\n        model=\"sonnet\"  # haiku, sonnet, or opus\n    )\n\n    result = await agent.run(\"What is 15 + 27?\")\n    print(result)  # Claude will use your tool and return the answer\n\nif __name__ == \"__main__\":\n    import asyncio\n    asyncio.run(main())\n```\n\n## Installation & Setup\n\n### Prerequisites\n\n- **Python 3.12+** with `uv` package manager\n- **Docker Desktop** (required for Docker executor, recommended)\n- **Claude Code OAuth Token** - Get from [Claude Code](https://claude.ai/code)\n\n### Install the Package\n\n```bash\n# Using pip\npip install claude-agent-toolkit\n\n# Using uv (recommended)\nuv add claude-agent-toolkit\n\n# Using poetry\npoetry add claude-agent-toolkit\n```\n\n### Set Your OAuth Token\n\nGet your token by running `claude setup-token` in your terminal, then:\n\n```bash\nexport CLAUDE_CODE_OAUTH_TOKEN='your-token-here'\n```\n\n### Quick Verification\n\n```bash\n# Clone examples (optional)\ngit clone https://github.com/cheolwanpark/claude-agent-toolkit.git\ncd claude-agent-toolkit/src/examples/calculator\npython main.py\n```\n\n## Usage Examples\n\n### Basic Agent with Custom Tool\n\n```python\nfrom claude_agent_toolkit import Agent, BaseTool, tool, ExecutorType\n\nclass MyTool(BaseTool):\n    def __init__(self):\n        super().__init__()\n        self.counter = 0  # Explicit data management\n\n    @tool()\n    async def increment(self) -> dict:\n        \"\"\"Increment counter and return value\"\"\"\n        self.counter += 1\n        return {\"value\": self.counter}\n\n# Docker executor (default, production-ready)\nagent = Agent(tools=[MyTool()])\n\n# Subprocess executor (faster startup, development)\nagent = Agent(tools=[MyTool()], executor=ExecutorType.SUBPROCESS)\n\nresult = await agent.run(\"Increment the counter twice\")\n```\n\n### Model Selection\n\n```python\n# Fast and efficient for simple tasks\nweather_agent = Agent(\n    tools=[weather_tool],\n    model=\"haiku\"\n)\n\n# Balanced performance (default)\ngeneral_agent = Agent(\n    tools=[calc_tool, weather_tool],\n    model=\"sonnet\"\n)\n\n# Most capable for complex reasoning\nanalysis_agent = Agent(\n    tools=[analysis_tool],\n    model=\"opus\"\n)\n\n# Override per query\nresult = await weather_agent.run(\n    \"Complex weather pattern analysis\",\n    model=\"opus\"\n)\n```\n\n### CPU-Intensive Operations\n\n```python\nclass HeavyComputeTool(BaseTool):\n    @tool(parallel=True, timeout_s=120)\n    def process_data(self, data: str) -> dict:\n        \"\"\"Heavy computation\"\"\"\n        # Sync function - runs in separate process\n        import time\n        time.sleep(5)  # Simulate heavy work\n        return {\"processed\": f\"result_{data}\"}\n```\n\n### Error Handling\n\n```python\nfrom claude_agent_toolkit import (\n    Agent, BaseTool,\n    ConfigurationError, ConnectionError, ExecutionError\n)\n\ntry:\n    agent = Agent(tools=[MyTool()])\n    result = await agent.run(\"Process my request\")\n\nexcept ConfigurationError as e:\n    print(f\"Setup issue: {e}\")  # Missing token, invalid config\n\nexcept ConnectionError as e:\n    print(f\"Connection failed: {e}\")  # Docker, network issues\n\nexcept ExecutionError as e:\n    print(f\"Execution failed: {e}\")  # Tool failures, timeouts\n```\n\n## Core Features\n\n- **\ud83c\udfaf Decorator-Based Tools** - Transform any Python function into a Claude tool with simple `@tool` decorator\n- **\ud83d\udd0c External MCP Integration** - Connect to existing MCP servers via stdio and HTTP transports\n- **\ud83d\udc33 Isolated Execution** - Docker containers ensure consistent behavior across all environments\n- **\u26a1 Zero Configuration** - Automatic MCP server management, port selection, and tool discovery\n- **\ud83d\udd27 Flexible Execution Modes** - Choose Docker isolation (production) or subprocess (development)\n- **\ud83d\udcdd Explicit Data Management** - You control data persistence with no hidden state\n- **\u2699\ufe0f CPU-bound Operations** - Process pools for heavy computations with parallel processing\n- **\ud83c\udfad Multi-tool Coordination** - Claude Code intelligently orchestrates multiple tools\n- **\ud83c\udfd7\ufe0f Production Ready** - Built for scalable, reliable agent deployment\n\n## Architecture\n\n### Execution Modes\n\n| Feature | Docker (Default) | Subprocess |\n|---------|------------------|------------|\n| **Isolation** | Full container isolation | Process isolation only |\n| **Setup Time** | ~3 seconds | ~0.5 seconds |\n| **Use Case** | Production, testing | Development, CI/CD |\n| **Requirements** | Docker Desktop | None |\n\n### Component Overview\n\n```\n\u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510    \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510    \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510\n\u2502   Your Tools    \u2502    \u2502      Agent       \u2502    \u2502  Claude Code    \u2502\n\u2502  (MCP Servers)  \u2502\u25c4\u2500\u2500\u25ba\u2502   (Orchestrator) \u2502\u25c4\u2500\u2500\u25ba\u2502   (Reasoning)   \u2502\n\u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518    \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518    \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518\n        \u2502                       \u2502                       \u2502\n        \u25bc                       \u25bc                       \u25bc\n\u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510    \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510    \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510\n\u2502   Host Process  \u2502    \u2502 Docker Container \u2502    \u2502 Claude Code API \u2502\n\u2502   (localhost)   \u2502    \u2502   or Subprocess  \u2502    \u2502   (claude.ai)   \u2502\n\u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518    \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518    \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518\n```\n\n## External MCP Server Integration\n\n### Connect to Existing MCP Servers\n\nIntegrate with any existing MCP server using stdio or HTTP transport:\n\n```python\nfrom claude_agent_toolkit import Agent\nfrom claude_agent_toolkit.tool.mcp import StdioMCPTool, HttpMCPTool\n\n# Connect to an MCP server via command execution\neverything_server = StdioMCPTool(\n    command=\"npx\",\n    args=[\"-y\", \"@modelcontextprotocol/server-everything\"],\n    name=\"everything\"\n)\n\n# Connect to an HTTP MCP server\nhttp_server = HttpMCPTool(\n    url=\"http://localhost:3001/mcp\",\n    name=\"my-http-server\"\n)\n\n# Mix with your custom tools\nagent = Agent(\n    system_prompt=\"You can use both custom and external tools\",\n    tools=[MyCustomTool(), everything_server, http_server]\n)\n\nresult = await agent.run(\"Use the everything server to echo 'Hello World'\")\n```\n\n### When to Use External MCP Integration\n\n- **Existing MCP Ecosystem**: Leverage community MCP servers and tools\n- **Language Diversity**: Use MCP servers written in Node.js, Python, Go, etc.\n- **Specialized Tools**: Integrate domain-specific tools without reimplementation\n- **Rapid Prototyping**: Quickly test MCP servers before building custom equivalents\n- **Service Architecture**: Connect to MCP servers running as microservices\n\n### Supported Transports\n\n| Transport | Use Case | Example |\n|-----------|----------|---------|\n| **Stdio** | Command-line tools, npm packages | `npx` servers, Python scripts |\n| **HTTP** | Web services, microservices | REST APIs, containerized servers |\n\n## Built-in Tools\n\n### FileSystemTool - Secure File Operations\n\nControl exactly what files your agent can access with pattern-based permissions.\n\n```python\nfrom claude_agent_toolkit.tools import FileSystemTool\n\n# Define access patterns\npermissions = [\n    (\"*.txt\", \"read\"),          # Read all text files\n    (\"data/**\", \"write\"),       # Write to data directory\n    (\"logs/*.log\", \"read\"),     # Read log files only\n]\n\nfs_tool = FileSystemTool(\n    permissions=permissions,\n    root_dir=\"/path/to/workspace\"  # Restrict to directory\n)\n\nagent = Agent(\n    system_prompt=\"You are a file manager assistant\",\n    tools=[fs_tool]\n)\n\nresult = await agent.run(\n    \"List all text files and create a summary in data/report.txt\"\n)\n```\n\n### DataTransferTool - Type-Safe Data Transfer\n\nTransfer structured data between Claude agents and your application using Pydantic models.\n\n```python\nfrom claude_agent_toolkit.tools import DataTransferTool\nfrom pydantic import BaseModel, Field\nfrom typing import List\n\nclass UserProfile(BaseModel):\n    name: str = Field(..., description=\"Full name\")\n    age: int = Field(..., ge=0, le=150, description=\"Age in years\")\n    interests: List[str] = Field(default_factory=list)\n\n# Create tool for specific model\nuser_tool = DataTransferTool.create(UserProfile, \"UserProfileTool\")\n\nagent = Agent(\n    system_prompt=\"You handle user profile data transfers\",\n    tools=[user_tool]\n)\n\n# Transfer data through Claude\nawait agent.run(\n    \"Transfer user: Alice Johnson, age 28, interests programming and hiking\"\n)\n\n# Retrieve validated data\nuser_data = user_tool.get()\nif user_data:\n    print(f\"Retrieved: {user_data.name}, age {user_data.age}\")\n```\n\n## Creating Custom Tools\n\n### Basic Tool Pattern\n\n```python\nfrom claude_agent_toolkit import BaseTool, tool\n\nclass MyTool(BaseTool):\n    def __init__(self):\n        super().__init__()  # Server starts automatically\n        self.data = {}      # Explicit data management\n\n    @tool()\n    async def process_async(self, data: str) -> dict:\n        \"\"\"Async operation\"\"\"\n        # Async operations for I/O, API calls\n        return {\"result\": f\"processed_{data}\"}\n\n    @tool(parallel=True, timeout_s=60)\n    def process_heavy(self, data: str) -> dict:\n        \"\"\"CPU-intensive operation\"\"\"\n        # Sync function - runs in separate process\n        # Note: New instance created, self.data won't persist\n        import time\n        time.sleep(2)\n        return {\"result\": f\"heavy_{data}\"}\n```\n\n### Context Manager Support\n\n```python\n# Single tool with guaranteed cleanup\nwith MyTool() as tool:\n    agent = Agent(tools=[tool])\n    result = await agent.run(\"Process my data\")\n# Server automatically cleaned up\n\n# Multiple tools\nwith MyTool() as calc_tool, WeatherTool() as weather_tool:\n    agent = Agent(tools=[calc_tool, weather_tool])\n    result = await agent.run(\"Calculate and check weather\")\n# Both tools cleaned up automatically\n```\n\n## FAQ\n\n### What is Claude Agent Toolkit?\n\nA Python framework that lets you build AI agents using Claude Code with custom tools. Unlike generic agent frameworks, this specifically leverages Claude Code's advanced reasoning capabilities with your existing subscription.\n\n### How is this different from other agent frameworks?\n\n- **Uses Claude Code**: Leverages Claude's production infrastructure and reasoning\n- **MCP Protocol**: Industry-standard tool integration, not proprietary APIs\n- **Explicit Data**: You control data persistence, no hidden state management\n- **Production Focus**: Built for real deployment, not just experiments\n\n### Do I need Docker?\n\nDocker is recommended for production but not required. Use `ExecutorType.SUBPROCESS` for subprocess execution:\n\n```python\nagent = Agent(tools=[my_tool], executor=ExecutorType.SUBPROCESS)\n```\nIt also runs in an isolated directory to ensure maximum isolation.\n\n### Which model should I use?\n\n- **haiku**: Fast, cost-effective for simple operations\n- **sonnet**: Balanced performance, good default choice\n- **opus**: Maximum capability for complex reasoning\n\n### How do I handle errors?\n\nThe framework provides specific exception types:\n\n```python\nfrom claude_agent_toolkit import ConfigurationError, ConnectionError, ExecutionError\n\ntry:\n    result = await agent.run(\"task\")\nexcept ConfigurationError:\n    # Missing OAuth token, invalid config\nexcept ConnectionError:\n    # Docker/network issues\nexcept ExecutionError:\n    # Tool failures, timeouts\n```\n\n### Can I use multiple tools together?\n\nYes! Claude Code intelligently orchestrates multiple tools:\n\n```python\nagent = Agent(tools=[calc_tool, weather_tool, file_tool])\nresult = await agent.run(\n    \"Calculate the average temperature and save results to report.txt\"\n)\n```\n\n## Testing\n\nThe framework is validated through comprehensive examples rather than traditional unit tests. Each example demonstrates specific capabilities and serves as both documentation and validation.\n\n### Run Examples\n\n```bash\n# Clone the repository\ngit clone https://github.com/cheolwanpark/claude-agent-toolkit.git\ncd claude-agent-toolkit\n\n# Set your OAuth token\nexport CLAUDE_CODE_OAUTH_TOKEN='your-token-here'\n\n# Run different examples\ncd src/examples/calculator && python main.py     # Stateful operations, parallel processing\ncd src/examples/weather && python main.py       # External API integration\ncd src/examples/subprocess && python main.py    # No Docker required\ncd src/examples/filesystem && python main.py    # Permission-based file access\ncd src/examples/datatransfer && python main.py  # Type-safe data transfer\ncd src/examples/mcp && python main.py           # External MCP server integration\n```\n\n### Example Structure\n\n```\nsrc/examples/\n\u251c\u2500\u2500 calculator/     # Mathematical operations with state management\n\u251c\u2500\u2500 weather/        # External API integration (OpenWeatherMap)\n\u251c\u2500\u2500 subprocess/     # Subprocess executor demonstration\n\u251c\u2500\u2500 filesystem/     # FileSystemTool with permissions\n\u251c\u2500\u2500 datatransfer/   # DataTransferTool with Pydantic models\n\u251c\u2500\u2500 mcp/           # External MCP server integration (stdio, HTTP)\n\u2514\u2500\u2500 README.md      # Detailed example documentation\n```\n\n### Docker Validation\n\nExamples can run with both executors:\n\n```bash\n# Docker executor (default)\npython main.py\n\n# Subprocess executor (faster startup)\n# Examples automatically use subprocess when Docker unavailable\n```\n\n## Contributing\n\n1. Fork the repository\n2. Create a feature branch: `git checkout -b feature-name`\n3. Make your changes and validate with examples\n4. Run examples to verify functionality\n5. Submit a pull request\n\n### Development Setup\n\n```bash\ngit clone https://github.com/cheolwanpark/claude-agent-toolkit.git\ncd claude-agent-toolkit\nuv sync --group dev\n\n# Validate your changes by running examples\nexport CLAUDE_CODE_OAUTH_TOKEN='your-token'\ncd src/examples/calculator && python main.py\n```\n\n## License\n\nThis project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.\n\n---\n\n**Created by**: [Cheolwan Park](https://github.com/cheolwanpark) \u2022 **Blog**: [Project Background](https://blog.codingvillain.com/post/claude-agent-toolkit)\n\n**Links**: [Homepage](https://github.com/cheolwanpark/claude-agent-toolkit) \u2022 [Claude Code](https://claude.ai/code) \u2022 [Issues](https://github.com/cheolwanpark/claude-agent-toolkit/issues) \u2022 [Model Context Protocol](https://modelcontextprotocol.io/)",
    "bugtrack_url": null,
    "license": "MIT",
    "summary": "Python framework for building Claude Code agents with custom tools",
    "version": "0.2.4",
    "project_urls": {
        "Changelog": "https://github.com/cheolwanpark/claude-agent-toolkit/blob/main/CHANGELOG.md",
        "Claude Code": "https://claude.ai/code",
        "Documentation": "https://github.com/cheolwanpark/claude-agent-toolkit#readme",
        "Homepage": "https://github.com/cheolwanpark/claude-agent-toolkit",
        "Issues": "https://github.com/cheolwanpark/claude-agent-toolkit/issues",
        "Repository": "https://github.com/cheolwanpark/claude-agent-toolkit.git"
    },
    "split_keywords": [
        "agent-framework",
        " ai-agents",
        " claude-agent-sdk",
        " claude-agent-toolkit",
        " claude-agents",
        " claude-code",
        " docker",
        " mcp-tools",
        " model-context-protocol"
    ],
    "urls": [
        {
            "comment_text": null,
            "digests": {
                "blake2b_256": "7482a066e68f06ac06214565533729dd37526bd281592a256787534fe413597c",
                "md5": "8df609e60aef380b341a23adb51e168a",
                "sha256": "4f2fba190a1a81839892bf2f4073a5c0ecf945dec1f01042530150576412bd9a"
            },
            "downloads": -1,
            "filename": "claude_agent_toolkit-0.2.4-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "8df609e60aef380b341a23adb51e168a",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": ">=3.12",
            "size": 41970,
            "upload_time": "2025-10-11T08:47:35",
            "upload_time_iso_8601": "2025-10-11T08:47:35.953279Z",
            "url": "https://files.pythonhosted.org/packages/74/82/a066e68f06ac06214565533729dd37526bd281592a256787534fe413597c/claude_agent_toolkit-0.2.4-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": null,
            "digests": {
                "blake2b_256": "beb7c8792f0095f568e57ce05c5f637b1fbf1370c5505ec26b281556556dff7f",
                "md5": "6f255935b44b056796b88e7112a0ccc8",
                "sha256": "8bfaa6769d5d79ebe35449e9f3cdfc5a890ccda70f983ab636b4be8e955820c1"
            },
            "downloads": -1,
            "filename": "claude_agent_toolkit-0.2.4.tar.gz",
            "has_sig": false,
            "md5_digest": "6f255935b44b056796b88e7112a0ccc8",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.12",
            "size": 62967,
            "upload_time": "2025-10-11T08:47:37",
            "upload_time_iso_8601": "2025-10-11T08:47:37.576930Z",
            "url": "https://files.pythonhosted.org/packages/be/b7/c8792f0095f568e57ce05c5f637b1fbf1370c5505ec26b281556556dff7f/claude_agent_toolkit-0.2.4.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2025-10-11 08:47:37",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "cheolwanpark",
    "github_project": "claude-agent-toolkit",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": true,
    "lcname": "claude-agent-toolkit"
}
        
Elapsed time: 1.65537s