Rust SDK for Claude Agent. A Rust implementation mirroring the Python Claude Agent SDK with idiomatic Rust patterns and best practices.
✅ Feature Parity - v0.1.0 - Full feature parity with Python SDK
- ✅ Core error types with
thiserror - ✅ Comprehensive type system with newtypes for type safety
- ✅ Transport layer with subprocess CLI integration (lock-free architecture)
- ✅ Basic
query()function for simple queries - ✅ Message parsing with full message type support
- ✅ Builder pattern for options
- ✅ Control protocol handler (16 integration tests)
- ✅ ClaudeSDKClient for bidirectional communication (10 tests, working demo)
- ✅ Hook system - Fully integrated with automatic handling
- ✅ Permission callbacks - Fully integrated with automatic handling
- ✅ SDK MCP server - In-process custom tools with JSONRPC protocol
- ✅ Comprehensive test suite (70 tests: 42 unit + 28 doc, all passing)
- ✅ Full documentation with examples and API docs (6,200+ LOC)
simple_query.rs- Basic query usageinteractive_client.rs- Interactive conversationbidirectional_demo.rs- Concurrent operations demonstrationhooks_demo.rs- Hook system with 3 examplespermissions_demo.rs- Permission system with 3 examplesmcp_demo.rs- Custom tools with SDK MCP server
Prerequisites:
- Rust 1.75.0 or later
- Node.js
- Claude Code:
npm install -g @anthropic-ai/claude-code
Add to your Cargo.toml:
[dependencies]
claude-agent-sdk = "0.1.0"
tokio = { version = "1", features = ["full"] }
futures = "0.3"use claude_agent_sdk::query;
use futures::StreamExt;
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let stream = query("What is 2 + 2?", None).await?;
let mut stream = Box::pin(stream);
while let Some(message) = stream.next().await {
println!("{:?}", message?);
}
Ok(())
}query() is an async function for querying Claude Code. It returns a Stream of response messages.
use claude_agent_sdk::{query, ClaudeAgentOptions, Message, ContentBlock};
use futures::StreamExt;
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
// Simple query
let stream = query("Hello Claude", None).await?;
let mut stream = Box::pin(stream);
while let Some(message) = stream.next().await {
match message? {
Message::Assistant { message, .. } => {
for block in &message.content {
if let ContentBlock::Text { text } = block {
println!("Claude: {}", text);
}
}
}
Message::Result { total_cost_usd, .. } => {
if let Some(cost) = total_cost_usd {
println!("Cost: ${:.4}", cost);
}
}
_ => {}
}
}
Ok(())
}use claude_agent_sdk::{query, ClaudeAgentOptions, PermissionMode};
let options = ClaudeAgentOptions::builder()
.system_prompt("You are a helpful coding assistant")
.max_turns(5)
.permission_mode(PermissionMode::AcceptEdits)
.add_allowed_tool("Read")
.add_allowed_tool("Write")
.build();
let stream = query("Create a hello.py file", Some(options)).await?;The SDK follows Rust best practices and idiomatic patterns:
- Newtypes for IDs (
SessionId,ToolName,RequestId) - Strong typing prevents mixing incompatible values
- Builder pattern for complex configuration
- Uses
thiserrorfor ergonomic error types - All errors are
Result<T, ClaudeError> - Rich error context with exit codes and stderr
- Built on
tokioruntime async-traitfor trait methods- Streams for message handling
src/
├── error.rs # Error types
├── types.rs # Type definitions
├── transport/ # Communication layer
│ ├── mod.rs # Transport trait
│ └── subprocess.rs # CLI subprocess
├── message/ # Message parsing
├── query.rs # Simple query function
└── lib.rs # Public API
| Feature | Rust | Python |
|---|---|---|
query() function |
✅ | ✅ |
ClaudeSDKClient |
✅ | ✅ |
| Custom Tools (SDK MCP) | ✅ | ✅ |
| Hooks | ✅ | ✅ |
| Permission callbacks | ✅ | ✅ |
| Type safety | ✅✅ | ✅ |
| Error handling | ✅✅ | ✅ |
| Documentation | ✅✅ | ✅ |
| Performance | ✅✅ | ✅ |
Legend: ✅ = Supported, ✅✅ = Enhanced implementation
Run examples with:
cargo run --example simple_querySee examples/ directory for more:
simple_query.rs- Basic usage with optionsinteractive_client.rs- Interactive conversationbidirectional_demo.rs- Concurrent operations demonstrationhooks_demo.rs- Hook system with 3 examplespermissions_demo.rs- Permission system with 3 examplesmcp_demo.rs- Custom tools with SDK MCP server
cargo buildcargo testcargo clippy
cargo fmtcargo doc --openThis SDK follows principles from:
- Rust Security Handbook
- Rust Error Handling Guide
- Rust Ownership Best Practices
- Rust Newtype Pattern
- Hexagonal Architecture in Rust
Key principles applied:
- Type safety with newtypes
- Memory safety without unsafe code
- Clear error propagation with Result types
- Ownership patterns for resource management
- Builder pattern for complex types
- Trait abstraction for extensibility
This SDK has undergone security hardening with multiple layers of protection:
- Environment variable filtering - Blocks dangerous variables like
LD_PRELOAD,PATH,NODE_OPTIONS - Argument validation - Allowlist for CLI flags prevents injection attacks
- Timeout protection - All I/O operations have configurable timeouts
- Buffer limits - Prevents memory exhaustion from unbounded growth
- Secure defaults - Conservative defaults for all security-sensitive options
- No unsafe code - 100% safe Rust with compiler guarantees
For details on security improvements, see:
fixes.md- Complete security audit reportSECURITY_FIXES_APPLIED.md- Implementation details
This is a reference implementation demonstrating Rust SDK development best practices. See PLAN.md for the complete implementation roadmap.
MIT