Claude Agent SDK for Rust
Rust SDK for interacting with Claude Code CLI, enabling programmatic access to Claude's capabilities with full bidirectional streaming support.
Status: β 100% feature parity with Python SDK - Production Ready
β¨ Features
- π Simple Query API: One-shot queries for stateless interactions with both collecting and streaming modes
- π Bidirectional Streaming: Real-time streaming communication with
ClaudeClient - ποΈ Dynamic Control: Interrupt, change permissions, switch models mid-execution
- πͺ Hooks System: Intercept and control Claude's behavior with ergonomic builder API
- π οΈ Custom Tools: In-process MCP servers with ergonomic
tool!macro - π Plugin System: Load custom plugins to extend Claude's capabilities
- π Permission Management: Fine-grained control over tool execution
- π° Cost Control: Budget limits and fallback models for production reliability
- π§ Extended Thinking: Configure maximum thinking tokens for complex reasoning
- π Session Management: Separate contexts and memory clearing with fork_session
- π¦ Type Safety: Strongly-typed messages, configs, hooks, and permissions
- β‘ Zero Deadlock: Lock-free architecture for concurrent read/write
- π Comprehensive Examples: 23 complete examples covering all features
- πΌοΈ Multimodal Input: Send images alongside text with base64 or URL sources
- π§ͺ Well Tested: Extensive test coverage with unit and integration tests
π¦ Installation
Add this to your Cargo.toml:
[]
= "0.5"
= { = "1", = ["full"] }
Or use cargo-add:
π― Prerequisites
- Rust: 1.90 or higher
- Claude Code CLI: Version 2.0.0 or higher (Installation Guide)
- API Key: Anthropic API key set in environment or Claude Code config
π Quick Start
Simple Query (One-shot)
use ;
async
With custom options:
let options = ClaudeAgentOptions ;
let messages = query.await?;
Streaming Query (Memory-Efficient)
For large conversations or real-time processing, use query_stream():
use ;
use StreamExt;
async
When to use:
query(): Small to medium conversations, need all messages for post-processingquery_stream(): Large conversations, real-time processing, memory constraints
Bidirectional Conversation (Multi-turn)
use ;
async
Custom Tools (SDK MCP Servers)
Create custom in-process tools that Claude can use:
use ;
use json;
async
async
Note: Tools must be explicitly allowed using the format mcp__{server_name}__{tool_name}.
For a comprehensive guide, see examples/MCP_INTEGRATION.md.
Architecture
The SDK is structured in layers:
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β Public API Layer β
β (query(), ClaudeClient, tool!(), create_sdk_server()) β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β Control Protocol Layer β
β (Query: handles bidirectional control) β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β Transport Layer β
β (SubprocessTransport, custom implementations) β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β Claude Code CLI β
β (external process via stdio/subprocess) β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
Session Management & Memory Clearing
The SDK provides multiple ways to manage conversation context and clear memory:
Using Session IDs (Separate Contexts)
Different session IDs maintain completely separate conversation contexts:
let mut client = new;
client.connect.await?;
// Session 1: Math conversation
client.query_with_session.await?;
// Session 2: Programming conversation (different context)
client.query_with_session.await?;
// Back to Session 1 - Claude remembers math context
client.query_with_session.await?;
Fork Session (Fresh Start)
Use fork_session to start completely fresh without any history:
let options = builder
.fork_session // Each resumed session starts fresh
.build;
let mut client = new;
client.connect.await?;
Convenience Method
Use new_session() for quick session switching:
client.new_session.await?;
See examples/16_session_management.rs for complete examples.
Type System
The SDK provides strongly-typed Rust interfaces for all Claude interactions:
- Messages:
Message,ContentBlock,TextBlock,ToolUseBlock, etc. - Configuration:
ClaudeAgentOptions,SystemPrompt,PermissionMode - Hooks:
HookEvent,HookCallback,HookInput,HookJsonOutput - Permissions:
PermissionResult,PermissionUpdate,CanUseToolCallback - MCP:
McpServers,SdkMcpServer,ToolHandler,ToolResult
π Examples
The SDK includes 23 comprehensive examples demonstrating all features with 100% parity to Python SDK. See examples/README.md for details.
Quick Examples
# Basic usage
# Streaming & Conversations
# Hooks & Control
# Custom Tools & MCP
# Configuration
# Production Features
# Plugin System
# Multimodal
# Session Management
Example Categories
| Category | Examples | Description |
|---|---|---|
| Basics | 01-03 | Simple queries, tool control, monitoring |
| Advanced | 04-07 | Permissions, hooks, streaming, dynamic control |
| MCP | 08 | Custom tools and MCP server integration |
| Config | 09-13 | Agents, settings, prompts, debugging |
| Patterns | 14-16 | Comprehensive streaming, hooks, and sessions |
| Production | 17-20 | Fallback models, budgets, thinking limits, streaming |
| Plugins | 21-22 | Custom plugin loading and integration |
| Multimodal | 23 | Image input alongside text |
π API Overview
Core Types
// Main client for bidirectional streaming
ClaudeClient
// Simple query functions for one-shot interactions
query // Configuration
ClaudeAgentOptions
// Messages
Assistant
User
System
Result
ClaudeClient (Bidirectional Streaming)
// Create and connect
let mut client = new;
client.connect.await?;
// Send queries
client.query.await?;
// Receive messages
loop
// Session management - separate conversation contexts
client.query_with_session.await?;
client.query_with_session.await?;
client.new_session.await?;
// Dynamic control (mid-execution)
client.interrupt.await?; // Stop current operation
// Client will handle the interrupt automatically
// Disconnect
client.disconnect.await?;
Hooks System
use ;
async
let mut hooks = new;
hooks.insert;
let options = ClaudeAgentOptions ;
π§ͺ Development
Running Tests
# Run all tests
# Run tests with output
# Run specific test
Code Quality
# Check code with clippy
# Format code
# Check formatting
Building
# Build library
# Build with release optimizations
# Build all examples
# Build documentation
π§ Troubleshooting
Common Issues
"Claude Code CLI not found"
- Install Claude Code CLI: https://docs.claude.com/claude-code
- Ensure
claudeis in your PATH
"API key not configured"
- Set
ANTHROPIC_API_KEYenvironment variable - Or configure via Claude Code CLI settings
"Permission denied" errors
- Use
permission_mode: PermissionMode::AcceptEditsfor automated workflows - Or implement custom permission callbacks
Debug Mode
Enable debug output to see what's happening:
let options = ClaudeAgentOptions ;
Python SDK Comparison
The Rust SDK closely mirrors the Python SDK API:
| Python | Rust |
|---|---|
async with ClaudeClient() as client: |
client.connect().await? |
await client.query("...") |
client.query("...").await? |
async for msg in client.receive_response(): |
while let Some(msg) = stream.next().await |
await client.interrupt() |
client.interrupt().await? |
await client.disconnect() |
client.disconnect().await? |
π€ Contributing
Contributions are welcome! Please feel free to submit a Pull Request.
Development Setup
# Clone the repository
# Install dependencies
# Run tests
# Run examples
Guidelines
- Follow Rust conventions and idioms
- Add tests for new features
- Update documentation and examples
- Run
cargo fmtandcargo clippybefore submitting
This SDK is based on the claude-agent-sdk-python specification.
License
This project is distributed under the terms of MIT.
See LICENSE.md for details.
π Related Projects
- Claude Code CLI - Official Claude Code command-line interface
- Claude Agent SDK for Python - Official Python SDK
- Anthropic API - Claude API documentation
β Show Your Support
If you find this project useful, please consider giving it a star on GitHub!
π Changelog
See CHANGELOG.md for version history and changes.