Claude Agent SDK for Rust
Rust SDK for building production-ready AI agents with Claude. Replicate the full feature set of the Python Claude Agent SDK with idiomatic Rust patterns.
Overview
The Claude Agent SDK enables you to build powerful AI agents using Claude Code's agent harness. This SDK wraps the Claude Code CLI, providing type-safe access to:
- Automatic context management and compaction
- 20+ built-in tools (file operations, code execution, web search)
- Custom MCP (Model Context Protocol) tools
- Fine-grained permission controls
- Hook system for deterministic behavior
- Interactive bidirectional conversations
- Usage tracking and quota monitoring (Max Plan)
Important Notes
Structured output requires more than 1 turn. When using
output_formatwith a JSON schema, the CLI may need additional turns internally to produce structured JSON. Setmax_turnsto at least 2-3 (or omit it entirely) — usingmax_turns(1)will likely result inerror_max_turnswith no structured output.
max_budget_usdis a soft cap. The budget limit is checked between turns, not mid-generation. The current turn will always complete before the budget is evaluated, so actual spend may slightly exceed the configured limit.
No nested Claude Code instances. As of CLI v2.1.41, Claude Code prevents spawning nested instances of itself. The CLI sets
CLAUDECODE=1in the environment; any child process that tries to start another Claude Code instance will detect this and refuse to launch. This means you cannot test SDK examples from within a Claude Code session (e.g. from Claude Code's Bash tool). Run them from a regular terminal instead. If you need to bypass this, unset theCLAUDECODEenv var before spawning — but beware of recursive agent loops and contention issues on shared resources (files, sessions, API quota).
Prerequisites
- Rust: 1.85 or higher (edition 2024)
- Claude Code CLI: 2.0.0 or higher
- Authentication: Claude subscription (Pro, Max, Team, or Enterprise) or Anthropic API key
Installation
1. Install Claude Code CLI
Native installer (recommended):
# macOS / Linux
|
# Windows (PowerShell)
|
Alternative (npm):
Verify installation:
# Should output: 2.0.0 or higher
2. Add SDK to Your Project
[]
= "1"
= { = "1", = ["full"] }
= "0.3"
Authentication Setup
Claude Code supports multiple authentication methods:
Option 1: Claude Subscription (Recommended)
If you have a Claude Pro, Team, or Enterprise subscription:
This will authenticate using your Claude subscription. No additional configuration needed!
Option 2: API Key
If you're using an Anthropic API key:
- Get your API key from https://console.anthropic.com/account/keys
- Set the environment variable:
Linux/macOS:
Windows (PowerShell):
$env:ANTHROPIC_API_KEY="sk-ant-..."
Windows (Command Prompt):
set ANTHROPIC_API_KEY=sk-ant-...
Verify authentication works:
Quick Start
Simple Query
use ;
use StreamExt;
async
With Configuration
use ;
async
Interactive Conversation
use ;
use StreamExt;
async
Key Features
Tool Control
let options = builder
.allowed_tools
.disallowed_tools // Block specific tools
.build;
Permission Modes
- Default: Prompt for dangerous operations
- AcceptEdits: Auto-accept file edits
- Plan: Plan mode (no execution)
- BypassPermissions: Allow all tools (use with caution!)
.permission_mode
System Prompts
// Text prompt
.system_prompt
// Or use Claude Code preset
.system_prompt
Working Directory
.cwd
Model Selection
.model
Thinking and Effort
Control Claude's reasoning depth:
use ;
let options = builder
.thinking // Let Claude decide when to think
.effort // More thorough responses
.build;
let messages = query.await?;
ThinkingConfig variants:
Adaptive— Claude decides when extended thinking is usefulEnabled { budget_tokens }— Always think, with a token budgetDisabled— No extended thinking
Effort levels: Low, Medium, High, Max
Structured Output
Get responses as validated JSON matching a schema:
use ;
let schema = json!;
let options = builder
.output_format
.max_turns // Structured output needs >1 turn
.build;
let mut messages = query.await?;
while let Some = messages.next.await
Budget Limits
Set a soft spending cap per query:
let options = builder
.max_budget_usd // Soft cap — see Important Notes above
.build;
Fallback Model
Specify a fallback model if the primary is unavailable:
let options = builder
.model
.fallback_model
.build;
Advanced Features
Permission Callbacks
Programmatically control tool usage with the PermissionCallback trait:
use ;
use ;
use async_trait;
use Value;
;
// Use with client
let mut client = new;
client.set_permission_callback;
client.connect.await?;
Hook System
Execute custom code at specific points in the agent loop:
use ;
use ;
use async_trait;
;
// Register hook
let mut client = new;
client.register_hook;
client.connect.await?;
MCP Server Configuration
Use external MCP servers for custom tools:
use HashMap;
use ;
let mut mcp_servers = new;
mcp_servers.insert;
let options = builder
.mcp_servers
.allowed_tools
.build;
Available Tools
Claude Code includes 20+ built-in tools:
- File Operations: Read, Write, Edit, Glob
- Code Execution: Bash, NotebookEdit
- Search: Grep, WebSearch, WebFetch
- Communication: Task (subagents), SlashCommand
- And more: See Claude Code documentation
Error Handling
use ClaudeSDKError;
match query.await
Session Management
The SDK provides full support for managing conversation sessions, allowing you to:
- Capture session IDs from conversations
- Resume previous conversations with full context
- Continue from the most recent conversation
Capturing Session IDs
Session IDs are automatically captured from messages:
use ;
use StreamExt;
let mut client = new;
client.connect.await?;
// Process messages
let mut messages = client.receive_messages?;
while let Some = messages.next.await
// Or get it directly from the client
if let Some = client.get_session_id
Resuming Sessions
Resume a specific conversation by session ID:
let options = builder
.resume
.build;
let mut client = new;
client.connect.await?;
Continuing Most Recent
Continue the most recent conversation:
let options = builder
.continue_conversation
.build;
let mut client = new;
client.connect.await?;
Forking Sessions
Create a new session ID when resuming (for experimentation):
let options = builder
.resume
.fork_session // Creates new ID instead of reusing
.build;
Sessions are stored in ~/.claude/projects/<project>/<session-id>.jsonl and preserve full conversation context including:
- All messages
- Tool usage history
- Context and state
See examples/session_resume.rs for a complete working example.
Examples
See the examples/ directory for complete working examples:
basic.rs- Simple one-shot querywith_options.rs- Configuration examplesinteractive.rs- Bidirectional conversationwith_callbacks.rs- Hooks and permission callbackssession_resume.rs- Session management and resuming conversationsusage_tracking.rs- Monitor Claude Code usage and quotas (Max Plan)new_features.rs- Thinking, effort, budget limits, structured output, MCP status
Run examples:
Documentation
API Guide
See docs/API_GUIDE.md for comprehensive documentation.
Rust API Documentation
Generate and view full API documentation:
Troubleshooting
CLI Not Found
Error: Claude Code CLI not found
Solution: Install CLI and ensure it's in PATH:
# Native installer (recommended)
|
# Or via npm
Or set custom path:
.cli_path
Authentication Failed
Error: Authentication failed
Solutions:
- If using Claude subscription: Run
claude setup-token - If using API key: Set
ANTHROPIC_API_KEYenvironment variable - Verify: Run
claude --print "test"to check authentication
Version Mismatch
Warning: Claude Code version 1.x.x < minimum 2.0.0
Solution: Update Claude Code:
Process Timeouts
If you're getting timeout errors for initialization or control requests:
// The SDK uses 60s timeouts by default for control protocol messages
// If your queries need more time, consider using streaming mode with
// the ClaudeSDKClient instead of the one-shot query() function
Development
Build the project:
Run tests:
# Unit tests
# Integration tests (requires authentication)
Format and lint:
Resources
- API Guide - Comprehensive API documentation
- Claude Code Documentation
- Anthropic Console
License
MIT
Support
- GitHub Issues: For bug reports and feature requests
- Documentation:
cargo doc --openfor API reference - Claude Code Help: https://docs.claude.com/en/docs/claude-code
Note: This SDK wraps the Claude Code CLI. Make sure it's installed and authenticated before use.