claude-agents-sdk
A Rust SDK for building agents that interact with the Claude Code CLI.
Inspired by the Python Claude Agent SDK, providing similar functionality with idiomatic Rust APIs.
Features
- Simple Query API: One-shot queries with
query()function - Streaming Client: Full bidirectional
ClaudeClientfor complex interactions - Tool Permissions: Control which tools Claude can use with callbacks
- Hooks: Register callbacks for various lifecycle events
- MCP Tools: Define custom tools that run in-process
- Type Safety: Strongly-typed messages, content blocks, and options
- Async/Await: Built on Tokio for efficient async operations
Installation
Add to your Cargo.toml:
[]
= "0.1"
= { = "1", = ["full"] }
= "0.1"
For MCP tool support:
[]
= { = "0.1", = ["mcp"] }
Prerequisites
- Claude Code CLI installed and authenticated
- Rust 1.75 or later
Quick Start
Simple Query
use ;
use StreamExt;
async
Streaming Client
use ;
async
With Tool Permissions
use ;
async
API Reference
Entry Points
query(prompt, options, transport)- One-shot query returning a message streamquery_all(prompt, options)- Collect all messages from a queryquery_result(prompt, options)- Get final response and result metadata
ClaudeClient
let mut client = new;
client.connect.await?;
client.query.await?;
let = client.receive_response.await?;
client.disconnect.await?;
Methods:
connect()- Connect to CLIquery(prompt)- Send a queryreceive_messages()- Stream of messagesreceive_response()- Collect response and resultinterrupt()- Interrupt current operationset_permission_mode(mode)- Change permission modeset_model(model)- Change modelrewind_files(message_id)- Rewind to checkpointdisconnect()- Disconnect from CLI
ClaudeAgentOptions
let options = new
.with_model
.with_system_prompt
.with_max_turns
.with_permission_mode
.with_allowed_tools
.with_partial_messages;
Message Types
// AssistantMessage has helpful methods
let text = assistant_msg.text;
let tool_uses = assistant_msg.tool_uses;
Content Blocks
Examples
Run the examples:
# Simple one-shot query
# Streaming client with multiple queries
# Tool permission callbacks
# Lifecycle hooks (PreToolUse, PostToolUse)
# Error handling patterns
# Streaming with progress indicators
# System prompt configuration
# Budget limits
# MCP tools (requires --features mcp)
See examples/ directory for the full list.
Testing
Unit Tests
Unit tests run without authentication:
# or
Integration Tests
Integration tests run against the real Claude API in Docker. They require authentication.
Setup (one-time):
# Generate an OAuth token (requires Claude Pro/Max subscription)
# Create .env file with your token
# Edit .env and paste your token
Run tests:
# Run all integration tests
# Run with verbose output
# Run specific test
# Interactive shell for debugging
What's tested:
- Core query functionality (one-shot and streaming)
- Multi-turn conversations with context
- Tool permission callbacks
- Cancellation and timeout handling
- Resource cleanup (no process leaks)
- Error handling and edge cases
See TESTING.md for the complete testing guide.
Error Handling
The SDK provides ClaudeSDKError, a comprehensive error type for all failure modes.
Error Types
use ClaudeSDKError;
match result
Recoverable Errors
Some errors can be retried:
if error.is_recoverable
Timeout Configuration
Configure timeouts to prevent indefinite hangs:
let options = new
.with_timeout_secs // 60 second timeout
.with_max_turns;
// Or disable timeout (not recommended)
let options = new
.with_timeout_secs; // No timeout
Default timeout is 300 seconds (5 minutes).
Stream Error Handling
When consuming message streams, handle errors per-message:
while let Some = stream.next.await
Result Type
All SDK functions return Result<T, ClaudeSDKError>:
use Result;
async
Architecture
The SDK communicates with the Claude Code CLI via a subprocess:
┌─────────────────┐ stdin/stdout ┌──────────────┐
│ Rust SDK │ ◄──── JSON-RPC ────► │ Claude CLI │
│ (your code) │ │ (subprocess)│
└─────────────────┘ └──────────────┘
Key internal components:
Transport- Abstract communication layerSubprocessTransport- Subprocess implementationQuery- Control protocol handlerInternalClient- Core query processing
Comparison with Python SDK
| Feature | Python | Rust |
|---|---|---|
| One-shot query | query() |
query() |
| Streaming client | ClaudeSDKClient |
ClaudeClient |
| Tool callback | can_use_tool |
can_use_tool |
| Hooks | hooks dict |
hooks HashMap |
| Async | asyncio | tokio |
| Type safety | TypedDict | Enums + Structs |
License
MIT License - see LICENSE for details.