Claude Code SDK for Rust
Rust SDK for Claude Code. See the Claude Code SDK documentation for more information.
Installation
Add this to your Cargo.toml:
[]
= "0.0.3"
= { = "1.0", = ["full"] }
Prerequisites:
- Rust 1.70+
- Node.js
- Claude Code:
npm install -g @anthropic-ai/claude-code
Quick Start
use query;
use StreamExt;
async
Usage
Basic Query
use ;
use StreamExt;
// Simple query
let mut stream = query.await?;
while let Some = stream.next.await
// With options
let options = ClaudeCodeOptions ;
let mut stream = query.await?;
while let Some = stream.next.await
Using Tools
let options = ClaudeCodeOptions ;
let mut stream = query.await?;
while let Some = stream.next.await
Working Directory
use PathBuf;
let options = ClaudeCodeOptions ;
Logging
The Claude Code SDK provides comprehensive structured logging using the tracing ecosystem. This helps with debugging, monitoring, and understanding SDK operations.
Quick Setup
use claude_code_sdk;
async
Environment Variables
Control logging levels with the RUST_LOG environment variable:
# Show info and above (default)
RUST_LOG=claude_code_sdk=info
# Show debug messages (recommended for development)
RUST_LOG=claude_code_sdk=debug
# Show all messages including trace
RUST_LOG=claude_code_sdk=trace
# Show only errors
RUST_LOG=claude_code_sdk=error
# Multiple modules
RUST_LOG=claude_code_sdk=debug,tokio=info
Custom Logging Setup
For more control over logging, set up tracing-subscriber directly:
use ;
// JSON structured logging
registry
.with
.with
.init;
// Custom formatting
registry
.with
.with
.init;
// File logging
let file = new
.create
.write
.truncate
.open?;
registry
.with
.with
.init;
What Gets Logged
The SDK logs various operations at different levels:
- ERROR: CLI not found, connection failures, JSON decode errors
- WARN: Process termination issues, unexpected states
- INFO: Query start/completion, connection events, major operations
- DEBUG: Message processing, command building, subprocess management
- TRACE: Individual message parsing, detailed state changes
Log Fields
Structured logs include useful fields:
Performance Monitoring
Enable performance monitoring with tracing spans:
use ;
async
Safety & Long Text Handling
The Claude Code SDK includes comprehensive safety mechanisms to handle long text responses safely and prevent common issues like memory exhaustion and performance degradation.
Safety Limits
Configure safety limits to protect against resource exhaustion:
use ;
// Default limits (balanced)
let default_limits = default;
// Conservative limits (memory-constrained environments)
let conservative = conservative;
// Generous limits (high-memory servers)
let generous = generous;
// Custom limits
let custom = SafetyLimits ;
Protected Operations
The SDK automatically protects against:
- Memory Exhaustion: Line size and text block limits prevent runaway memory usage
- JSON Parsing Timeouts: Large JSON objects are monitored for parsing time
- Log Explosion: Automatic truncation of log messages with size indicators
- Buffer Overflow: Channel size limits prevent message queue buildup
Error Handling
Safety violations are reported through structured errors:
match query.await
Risk Mitigation
| Risk | Mitigation | Configuration |
|---|---|---|
| Memory exhaustion | Line and text block size limits | max_line_size, max_text_block_size |
| JSON parsing hangs | Parsing timeout monitoring | json_parse_timeout_ms |
| Log file explosion | Safe preview truncation | max_log_preview_chars |
| Message queue buildup | Buffer size and count limits | max_buffer_size, max_buffered_messages |
| Process blocking | Async processing with backpressure | Automatic |
Monitoring
The SDK provides detailed monitoring of resource usage:
use ;
// Automatic logging of resource usage
// INFO: Text block size monitoring
// WARN: Approaching safety limits
// ERROR: Safety limit violations
// Example log output:
// INFO text_length=1048576 limit=5242880 "Large text block detected"
// WARN "Text block is approaching size limit"
// ERROR actual=10485760 limit=5242880 "Line exceeds safety limit"
API Reference
query(prompt: &str, options: Option<ClaudeCodeOptions>)
Main async function for querying Claude.
Parameters:
prompt: The prompt to send to Claudeoptions: Optional configuration
Returns: Result<Pin<Box<dyn Stream<Item = Message>>>, ClaudeSDKError>
Types
See src/types.rs for complete type definitions:
ClaudeCodeOptions- Configuration optionsMessagevariants -Assistant,User,System,ResultContentBlockvariants -Text,ToolUse,ToolResult
Error Handling
use ;
match query.await
Available Tools
See the Claude Code documentation for a complete list of available tools.
Examples
- examples/quick_start.rs - Complete working example with logging
- examples/logging_demo.rs - Advanced logging configurations
- examples/safety_demo.rs - Safety mechanisms and long text handling
Running Examples
# Basic example with default logging
# Advanced logging demo with JSON output
# File logging
# Performance monitoring
RUST_LOG=claude_code_sdk=debug
# Safety demonstration
License
MIT