| Crates.io | claudecode |
| lib.rs | claudecode |
| version | 0.1.9 |
| created_at | 2025-08-07 16:12:20.47003+00 |
| updated_at | 2026-01-04 14:56:04.354048+00 |
| description | A Rust SDK for programmatically interacting with Claude Code |
| homepage | https://github.com/allisoneer/agentic_auxilary |
| repository | https://github.com/allisoneer/agentic_auxilary |
| max_upload_size | |
| id | 1785493 |
| size | 193,010 |
A Rust SDK for programmatically interacting with Claude Code, providing a type-safe, asynchronous API to launch Claude sessions, send queries, and handle responses in various formats.
To use claudecode_rs in your Rust project, add the following to your Cargo.toml:
[dependencies]
claudecode = "0.1.0"
Note: If the crate is not yet published on crates.io, you can include it via a git repository or local path:
[dependencies]
claudecode = { git = "https://github.com/AdjectiveAllison/claudecode_rs" }
Ensure the Claude CLI is installed and available in your system's PATH. Verify this by running:
which claude
Send a simple query to Claude and print the response:
use claudecode::{Client, SessionConfig, Model};
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let client = Client::new().await?;
let config = SessionConfig::builder("What is the capital of France?")
.model(Model::Sonnet)
.build()?;
let result = client.launch_and_wait(config).await?;
if let Some(content) = result.content {
println!("Claude says: {}", content);
}
Ok(())
}
Receive real-time events from Claude using streaming JSON output:
use claudecode::{Client, SessionConfig, OutputFormat, Event};
use futures::StreamExt;
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let client = Client::new().await?;
let config = SessionConfig::builder("Tell me a story")
.output_format(OutputFormat::StreamingJson)
.build()?;
let mut session = client.launch(config).await?;
if let Some(mut events) = session.take_event_stream() {
while let Some(event) = events.recv().await {
match event {
Event::Assistant(msg) => {
for content in &msg.message.content {
if let Content::Text { text } = content {
print!("{}", text);
}
}
}
Event::Result(result) => {
if let Some(cost) = result.total_cost_usd {
println!("\nTotal cost: ${:.4}", cost);
}
}
_ => {}
}
}
}
let result = session.wait().await?;
Ok(())
}
Use SessionConfig::builder to configure Claude sessions:
let config = SessionConfig::builder("Your query here")
.model(Model::Opus)
.output_format(OutputFormat::Json)
.max_turns(5)
.verbose(true)
.build()?;
Available options include:
model: Model::Sonnet, Model::Opus, or Model::Haikuoutput_format: OutputFormat::Text, OutputFormat::Json, or OutputFormat::StreamingJsonmax_turns: Limit interaction turnssystem_prompt: Custom system promptappend_system_prompt: Append to existing system promptcustom_instructions: Provide custom instructions for the sessionallowed_tools / disallowed_tools: Control which tools Claude can useverbose: Enable verbose outputUse MCPConfig to configure Model Context Protocol servers:
use std::collections::HashMap;
let mut servers = HashMap::new();
servers.insert(
"calculator".to_string(),
MCPServer {
command: "npx".to_string(),
args: vec!["@modelcontextprotocol/server-calculator".to_string()],
env: None,
},
);
let mcp_config = MCPConfig {
mcp_servers: servers,
};
let config = SessionConfig::builder("What is 42 * 17?")
.mcp_config(mcp_config)
.build()?;
Sessions can be controlled after launching:
let mut session = client.launch(config).await?;
// Check if session is running
if session.is_running().await {
// Send interrupt signal (graceful shutdown on Unix)
session.interrupt().await?;
// Or forcefully kill the process
session.kill().await?;
}
// Wait for completion
let result = session.wait().await?;
The SDK uses Result<T, ClaudeError> for operations that can fail. The ClaudeResult type includes an is_error flag and an optional error message:
match client.launch_and_wait(config).await {
Ok(result) => {
if result.is_error {
eprintln!("Error: {}", result.error.unwrap_or_default());
} else {
println!("Success: {}", result.content.unwrap_or_default());
}
}
Err(e) => eprintln!("SDK Error: {}", e),
}
Contributions are welcome! See CLAUDE.md for guidelines on building, testing, and contributing to this project.
This project is licensed under the MIT License - see the LICENSE file for details.