claudecode_rs
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.
Table of Contents
Installation
To use claudecode_rs in your Rust project, add the following to your Cargo.toml:
[]
= "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:
[]
= { = "https://github.com/AdjectiveAllison/claudecode_rs" }
Ensure the Claude CLI is installed and available in your system's PATH. Verify this by running:
Usage
Basic Query
Send a simple query to Claude and print the response:
use ;
async
Streaming Events
Receive real-time events from Claude using streaming JSON output:
use ;
use StreamExt;
async
Features
- Asynchronous API using the Tokio runtime for non-blocking operations.
- Type-safe event handling with enums for different event types.
- Multiple output formats: Text, JSON, and Streaming JSON.
- Flexible session configuration including model selection, max turns, and system prompts.
- Model Context Protocol (MCP) integration for extended functionality.
- Automatic resource cleanup and robust error handling.
Configuration
Session Configuration
Use SessionConfig::builder to configure Claude sessions:
let config = builder
.model
.output_format
.max_turns
.verbose
.build?;
Available options include:
model:Model::Sonnet,Model::Opus, orModel::Haikuoutput_format:OutputFormat::Text,OutputFormat::Json, orOutputFormat::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 output
MCP Configuration
Use MCPConfig to configure Model Context Protocol servers:
use HashMap;
let mut servers = new;
servers.insert;
let mcp_config = MCPConfig ;
let config = builder
.mcp_config
.build?;
Session Management
Sessions can be controlled after launching:
let mut session = client.launch.await?;
// Check if session is running
if session.is_running.await
// Wait for completion
let result = session.wait.await?;
Error Handling
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.await
Contributing
Contributions are welcome! See CLAUDE.md for guidelines on building, testing, and contributing to this project.
License
This project is licensed under the MIT License - see the LICENSE file for details.