| Crates.io | claude-sdk-rs |
| lib.rs | claude-sdk-rs |
| version | 1.0.1 |
| created_at | 2025-06-21 15:01:25.094475+00 |
| updated_at | 2025-06-21 21:22:15.779288+00 |
| description | Rust SDK for Claude AI with CLI integration - type-safe async API for Claude Code and direct SDK usage |
| homepage | https://github.com/bredmond1019/claude-sdk-rust |
| repository | https://github.com/bredmond1019/claude-sdk-rust |
| max_upload_size | |
| id | 1720863 |
| size | 4,096,367 |
A type-safe, async-first Rust SDK that wraps the Claude Code CLI to provide a powerful programmatic API for interacting with Claude AI. Build AI-powered applications with confidence using Rust's safety guarantees.
Bash(command) and MCP supportInstall Claude Code CLI (required for SDK operation):
# Install via npm (recommended)
npm install -g @anthropic-ai/claude-code
# Or install via Homebrew on macOS
brew install claude-code
# Authenticate with your Claude account
claude auth
Verify Installation:
claude --version # Should show the CLI version
claude auth status # Should show authentication status
Add claude-sdk-rs to your Cargo.toml:
[dependencies]
claude-sdk-rs = "1.0"
tokio = { version = "1.40", features = ["full"] }
The SDK uses feature flags to provide only the functionality you need:
# Core SDK only (default) - minimal dependencies
claude-sdk-rs = "1.0"
# With CLI binary - adds command-line interface
claude-sdk-rs = { version = "1.0", features = ["cli"] }
# With analytics - usage metrics and performance tracking
claude-sdk-rs = { version = "1.0", features = ["analytics"] }
# With MCP support - Model Context Protocol for tools
claude-sdk-rs = { version = "1.0", features = ["mcp"] }
# With SQLite storage - persistent session management
claude-sdk-rs = { version = "1.0", features = ["sqlite"] }
# Everything enabled - all features
claude-sdk-rs = { version = "1.0", features = ["full"] }
To install the claude-sdk-rs CLI tool globally:
cargo install claude-sdk-rs --features cli
use claude_sdk_rs::{Client, Config};
#[tokio::main]
async fn main() -> Result<(), claude_sdk_rs::Error> {
// Create a client with default configuration
let client = Client::new(Config::default());
// Send a query and get the response
let response = client
.query("Explain Rust ownership in simple terms")
.send()
.await?;
println!("Claude says: {}", response);
Ok(())
}
The SDK provides two patterns for sending queries to Claude:
1. Builder Pattern (Recommended for new code)
let response = client.query("Your message").send().await?;
let full_response = client.query("Your message").send_full().await?;
let stream = client.query("Your message").stream().await?;
2. Direct Methods (Backward compatible)
let response = client.send("Your message").await?;
let full_response = client.send_full("Your message").await?;
When to use each pattern:
use claude_sdk_rs::{Client, Config, StreamFormat};
let client = Client::builder()
.model("claude-3-sonnet-20240229")
.system_prompt("You are a helpful Rust programming assistant")
.timeout_secs(60)
.stream_format(StreamFormat::Json)
.build();
The SDK now supports advanced configuration features for better control:
use claude_sdk_rs::{Client, ToolPermission, SecurityLevel};
// Configure with system prompt extension and tool permissions
let client = Client::builder()
.append_system_prompt("Additionally, be concise in your responses.")
.max_turns(5) // Limit conversation turns
.disallowed_tools(vec![
"Bash(rm)".to_string(), // Block specific bash commands
"mcp__dangerous__delete".to_string(), // Block MCP tools
])
.skip_permissions(false) // Require permission prompts
.security_level(SecurityLevel::Balanced) // Configure input validation
.build();
// Tool-specific permissions
let tools_client = Client::builder()
.allowed_tools(vec![
ToolPermission::bash("git").to_cli_format(),
ToolPermission::mcp("filesystem", "read").to_cli_format(),
ToolPermission::All.to_cli_format(), // Allow all tools
])
.build();
The SDK provides configurable security validation to balance usability with protection:
use claude_sdk_rs::{Client, SecurityLevel};
// Strict mode - blocks most special characters (high security)
let strict_client = Client::builder()
.security_level(SecurityLevel::Strict)
.build();
// Balanced mode - context-aware validation (default, recommended)
let balanced_client = Client::builder()
.security_level(SecurityLevel::Balanced) // Allows "create file.md"
.build();
// Relaxed mode - only blocks obvious attacks (for trusted environments)
let relaxed_client = Client::builder()
.security_level(SecurityLevel::Relaxed)
.build();
// Disabled - no input validation (use with extreme caution)
let unsafe_client = Client::builder()
.security_level(SecurityLevel::Disabled)
.build();
Security Level Guide:
Strict: Blocks most special characters, safest for untrusted inputBalanced: Smart context-aware validation, allows legitimate queries like "create project-design-doc.md"Relaxed: Only blocks obvious attack patterns, good for controlled environmentsDisabled: No validation, only use in completely trusted scenarios// Get response with metadata
let response = client
.query("Write a haiku about Rust")
.send_full()
.await?;
println!("Response: {}", response.content);
if let Some(metadata) = response.metadata {
println!("Cost: ${:.6}", metadata.cost_usd.unwrap_or(0.0));
println!("Tokens: {:?}", metadata.tokens_used);
println!("Session: {}", metadata.session_id);
}
use futures::StreamExt;
let mut stream = client
.query("Write a short story about a robot")
.stream()
.await?;
while let Some(chunk) = stream.next().await {
match chunk {
Ok(message) => {
if let Some(content) = message.content {
print!("{}", content);
}
}
Err(e) => eprintln!("Error: {}", e),
}
}
// Sessions are automatically managed - context is preserved
let client = Client::builder()
.stream_format(StreamFormat::Json)
.build();
// First message
let response1 = client
.query("My name is Alice and I love Rust programming")
.send_full()
.await?;
// Claude remembers the context
let response2 = client
.query("What's my favorite programming language?")
.send()
.await?;
// Response: "Based on our conversation, your favorite programming language is Rust!"
use claude_sdk_rs::Error;
match client.query("Hello").send().await {
Ok(response) => println!("Success: {}", response),
Err(Error::BinaryNotFound) => {
eprintln!("Claude CLI not found. Install with: npm install -g @anthropic-ai/claude-code");
}
Err(Error::ProcessError(msg)) => {
eprintln!("Process error: {}", msg);
}
Err(Error::Timeout) => {
eprintln!("Request timed out");
}
Err(e) => eprintln!("Other error: {}", e),
}
The SDK is built as a single crate with modular organization and feature flags:
claude-sdk-rs/
โโโ src/
โ โโโ lib.rs # Main SDK public API
โ โโโ core/ # Core types, config, errors
โ โโโ runtime/ # Process execution and streaming
โ โโโ mcp/ # Model Context Protocol (feature: mcp)
โ โโโ cli/ # CLI interface (feature: cli)
โโโ examples/ # Working examples
โโโ tests/ # Integration tests
โโโ benches/ # Performance benchmarks
cli: Adds command-line interface and interactive featuresmcp: Enables Model Context Protocol for tool integrationsqlite: Adds SQLite-based session persistenceanalytics: Enables usage analytics (requires cli)full: Enables all featuresExplore the examples/ directory for complete working examples:
basic_usage.rs - Simple queries and configurationstreaming.rs - Real-time streaming responsessession_management.rs - Multi-turn conversationserror_handling.rs - Comprehensive error handlingconfiguration.rs - Advanced configuration optionssystem_prompts.rs - System prompt extension and conversation control NEWadvanced_permissions.rs - Granular tool permissions and security NEWsession_persistence.rs - SQLite-based session storage (requires sqlite feature)cli_interactive.rs - Interactive CLI usage (requires cli feature)Run examples:
# Basic examples
cargo run --example basic_usage
cargo run --example streaming
# New features - advanced configuration
cargo run --example system_prompts
cargo run --example advanced_permissions
# Examples requiring features
cargo run --example session_persistence --features sqlite
cargo run --example cli_interactive --features cli
We welcome contributions! Please see our Contributing Guide for details.
# Clone the repository
git clone https://github.com/bredmond1019/claude-sdk-rust.git
cd claude-sdk-rust
# Build the crate
cargo build
# Build with all features
cargo build --all-features
# Run tests
cargo test
# Run tests with all features
cargo test --all-features
# Run linter
cargo clippy --all-features
# Format code
cargo fmt
# Run benchmarks
cargo bench
The SDK is designed for minimal overhead:
serde"create project-design-doc.md" while blocking "$(rm -rf /)"This project is licensed under the MIT License - see the LICENSE file for details.
๐ Quick Start โข ๐ง Dev Setup โข ๐ API Docs โข ๐ฌ Discussions
Made with โค๏ธ for the Rust community