| Crates.io | claude-sdk |
| lib.rs | claude-sdk |
| version | 1.0.0 |
| created_at | 2025-12-11 19:11:26.384789+00 |
| updated_at | 2025-12-11 23:06:34.120504+00 |
| description | Native Rust SDK for the Claude API with streaming support and tool execution |
| homepage | |
| repository | https://github.com/mcfearsome/claude-agent-sdk-rust |
| max_upload_size | |
| id | 1980355 |
| size | 343,216 |
A native Rust implementation of the Claude API client with streaming support, tool execution, and programmatic tool calling.
Add this to your Cargo.toml:
[dependencies]
claude-sdk = "0.1"
tokio = { version = "1", features = ["full"] }
use claude_sdk::{ClaudeClient, Message, MessagesRequest};
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
// Create the client
let client = ClaudeClient::anthropic(
std::env::var("ANTHROPIC_API_KEY")?
);
// Create a request
let request = MessagesRequest::new(
"claude-3-5-sonnet-20241022",
1024,
vec![Message::user("Hello, Claude!")],
);
// Send the message
let response = client.send_message(request).await?;
// Print the response
for content in &response.content {
if let claude_sdk::ContentBlock::Text { text, .. } = content {
println!("{}", text);
}
}
Ok(())
}
use claude_sdk::{ClaudeClient, Message, MessagesRequest, StreamEvent};
use futures::StreamExt;
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let client = ClaudeClient::anthropic(
std::env::var("ANTHROPIC_API_KEY")?
);
let request = MessagesRequest::new(
claude_sdk::models::CLAUDE_SONNET_4_5.anthropic_id,
1024,
vec![Message::user("Tell me a story")],
);
let mut stream = client.send_streaming(request).await?;
while let Some(event) = stream.next().await {
match event? {
StreamEvent::ContentBlockDelta { delta, .. } => {
if let Some(text) = delta.text() {
print!("{}", text);
}
}
StreamEvent::MessageStop => break,
_ => {}
}
}
Ok(())
}
use claude_sdk::{ClaudeClient, ConversationBuilder, Tool, StreamEvent};
use futures::StreamExt;
use serde_json::json;
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let client = ClaudeClient::anthropic(
std::env::var("ANTHROPIC_API_KEY")?
);
// Define a tool
let weather_tool = Tool {
name: "get_weather".into(),
description: "Get weather for a location".into(),
input_schema: json!({
"type": "object",
"properties": {
"location": {"type": "string"}
},
"required": ["location"]
}),
disable_user_input: Some(true), // Programmatic!
cache_control: None,
};
// Build conversation with tool
let mut conversation = ConversationBuilder::new()
.with_system("You are a helpful assistant")
.with_tool(weather_tool);
conversation.add_user_message("What's the weather in NYC?");
// First turn - Claude requests tool use
let request = conversation.build(
claude_sdk::models::CLAUDE_SONNET_4_5.anthropic_id,
1024
);
let response = client.send_message(request).await?;
// Extract tool use
for content in &response.content {
if let claude_sdk::ContentBlock::ToolUse { id, name, input, .. } = content {
println!("Claude wants to use: {}", name);
// Execute tool (your implementation here)
let result = r#"{"temp": 72, "condition": "sunny"}"#;
// Add tool result
conversation.add_tool_result(id, result);
}
}
// Second turn - Claude uses the tool result
let request = conversation.build(
claude_sdk::models::CLAUDE_SONNET_4_5.anthropic_id,
1024
);
let response = client.send_message(request).await?;
// Claude responds with the answer
for content in &response.content {
if let claude_sdk::ContentBlock::Text { text, .. } = content {
println!("Claude: {}", text);
}
}
Ok(())
}
use claude_sdk::{ClaudeClient, MessagesRequest, Message};
use claude_sdk::retry::RetryConfig;
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let client = ClaudeClient::anthropic(
std::env::var("ANTHROPIC_API_KEY")?
);
let request = MessagesRequest::new(
claude_sdk::models::CLAUDE_SONNET_4_5.anthropic_id,
1024,
vec![Message::user("Hello!")],
);
// Configure retry behavior
let retry_config = RetryConfig::new()
.with_max_attempts(5)
.with_initial_backoff(std::time::Duration::from_secs(1))
.with_max_backoff(std::time::Duration::from_secs(60));
// Automatically retries on rate limits and server errors
let response = client.send_message_with_retry(request, retry_config).await?;
Ok(())
}
Run the examples with your API key:
export ANTHROPIC_API_KEY="your-api-key"
cargo run --example simple_chat
cargo run --example streaming_chat
cargo run --example tool_use
cargo run --example prompt_caching
Available examples:
simple_chat - Basic message sending with complete responsesstreaming_chat - Real-time streaming responses with token displaytool_use - Tool definitions, multi-turn conversations, programmatic tool callingprompt_caching - Cost reduction with prompt caching (90% savings on cached tokens)claude-3-5-sonnet-20241022 - Most capable, balanced performanceclaude-3-5-haiku-20241022 - Fast and cost-effectiveclaude-3-opus-20240229 - Most powerful for complex tasksPhase 1 (Foundation) - COMPLETE ✅
Phase 2 (Tools & Conversations) - COMPLETE ✅
Phase 3 (Platform & Management) - COMPLETE ✅
Phase 4 (Developer Experience) - COMPLETE ✅
Phase 5 (Advanced Features) - COMPLETE ✅
Progress: 20 of 20 features complete (100%) 🎉
See .claude/system/features.json for detailed feature tracking.
claude-agent-sdk-rust/
├── src/
│ ├── lib.rs # Public API
│ ├── client.rs # HTTP client
│ ├── types.rs # Request/response types
│ └── error.rs # Error types
├── examples/
│ └── simple_chat.rs # Example usage
└── .claude/
└── system/ # Development tracking
We use pre-commit hooks to ensure code quality. Install them with:
./scripts/install-hooks.sh
The pre-commit hook automatically runs:
cargo test - All tests must passcargo clippy -- -D warnings - No clippy warnings allowedcargo fmt --check - Code must be formattedcargo doc - Documentation must buildTo bypass the hook (not recommended): git commit --no-verify
# Run all checks
cargo test --all-features
cargo clippy --all-targets --all-features -- -D warnings
cargo fmt --all -- --check
cargo doc --no-deps --all-features
# Auto-fix formatting
cargo fmt --all
Interactive REPL:
Test the SDK interactively with a full-featured terminal interface:
export ANTHROPIC_API_KEY="your-api-key"
cargo run --features repl --bin claude-repl
Features:
Automated Changelog Generation:
Use Claude to generate changelog entries from git commits:
export ANTHROPIC_API_KEY="your-api-key"
cargo run --bin update-changelog
This analyzes commits since the last release and generates Keep a Changelog format entries.
This project is part of Colony Shell (F015 - Claude ADK integration) but can be used standalone.
See CONTRIBUTING.md for development guidelines.
MIT