Expand description
§Claude Agent SDK for Rust
A comprehensive Rust SDK for building AI agents powered by Claude Code. This library provides idiomatic Rust bindings with full support for async/await, strong typing, and zero-cost abstractions.
§Quick Start
The simplest way to use this SDK is with the query() function:
use claude_agent_sdk::query;
use futures::StreamExt;
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let stream = query("What is 2 + 2?", None).await?;
let mut stream = Box::pin(stream);
while let Some(message) = stream.next().await {
match message? {
claude_agent_sdk::Message::Assistant { message, .. } => {
println!("Claude: {:?}", message);
}
_ => {}
}
}
Ok(())
}§Core Features
§1. Simple Queries with query()
For one-shot interactions where you don’t need bidirectional communication:
let options = ClaudeAgentOptions::builder()
.system_prompt("You are a helpful coding assistant")
.max_turns(5)
.build();
let stream = query("Explain async/await in Rust", Some(options)).await?;§2. Interactive Client with ClaudeSDKClient
For stateful conversations with bidirectional communication:
let options = ClaudeAgentOptions::builder()
.max_turns(10)
.build();
let mut client = ClaudeSDKClient::new(options, None).await?;
client.send_message("Hello, Claude!").await?;
while let Some(message) = client.next_message().await {
// Process messages...
}
client.close().await?;§3. Custom Tools with SDK MCP Server
Create in-process tools that Claude can invoke directly:
let calculator = SdkMcpServer::new("calculator")
.version("1.0.0")
.tool(SdkMcpTool::new(
"add",
"Add two numbers",
json!({"type": "object", "properties": {
"a": {"type": "number"},
"b": {"type": "number"}
}}),
|input| Box::pin(async move {
let sum = input["a"].as_f64().unwrap_or(0.0)
+ input["b"].as_f64().unwrap_or(0.0);
Ok(ToolResult::text(format!("Sum: {}", sum)))
}),
));See the mcp module for more details.
§4. Hooks for Custom Behavior
Intercept and modify tool execution:
let hook = HookManager::callback(|event_data, tool_name, _context| async move {
println!("Tool used: {:?}", tool_name);
Ok(HookOutput::default())
});
let matcher = HookMatcherBuilder::new(Some("*"))
.add_hook(hook)
.build();
let mut hooks = HashMap::new();
hooks.insert(HookEvent::PreToolUse, vec![matcher]);
let options = ClaudeAgentOptions::builder()
.hooks(hooks)
.build();See the hooks module for more details.
§5. Permission Control
Control which tools Claude can use and how:
let permission_callback = PermissionManager::callback(
|tool_name, _tool_input, _context| async move {
match tool_name.as_str() {
"Read" | "Glob" => Ok(PermissionResult::Allow(PermissionResultAllow {
updated_input: None,
updated_permissions: None,
})),
_ => Ok(PermissionResult::Deny(PermissionResultDeny {
message: "Tool not allowed".to_string(),
interrupt: false,
}))
}
}
);
let options = ClaudeAgentOptions::builder()
.can_use_tool(permission_callback)
.build();See the permissions module for more details.
§Architecture
The SDK is organized into several key modules:
types: Core type definitions, newtypes, and buildersquery(): Simple one-shot query functionclient: Interactive bidirectional clientmcp: SDK MCP server for custom toolshooks: Hook system for intercepting eventspermissions: Permission control for tool usagetransport: Communication layer with Claude Code CLIcontrol: Control protocol handlermessage: Message parsing and typeserror: Error types and handling
§Feature Flags
This crate supports the following feature flags:
http- Enables HTTP transport support (requiresreqwest)tracing-support- Enables structured logging withtracing
§Examples
The SDK comes with comprehensive examples:
simple_query.rs- Basic query usageinteractive_client.rs- Interactive conversationbidirectional_demo.rs- Concurrent operationshooks_demo.rs- Hook system with 3 examplespermissions_demo.rs- Permission control with 3 examplesmcp_demo.rs- Custom tools with MCP server
Run examples with:
cargo run --example simple_query§Requirements
- Rust 1.75.0 or later
- Node.js (for Claude Code CLI)
- Claude Code:
npm install -g @anthropic-ai/claude-code
§Error Handling
All fallible operations return Result<T, ClaudeError>. The SDK uses
thiserror for ergonomic error types with full context:
match query("Hello", None).await {
Ok(stream) => { /* ... */ }
Err(ClaudeError::CliNotFound(msg)) => {
eprintln!("Claude Code not installed: {}", msg);
}
Err(e) => {
eprintln!("Error: {}", e);
}
}§Safety and Best Practices
- No unsafe code - The SDK is 100% safe Rust
- Type safety - Newtypes prevent mixing incompatible values
- Async/await - Built on tokio for efficient concurrency
- Resource management - Proper cleanup via RAII and Drop
- Error handling - Comprehensive error types with context
§Security
This SDK includes multiple layers of security protection:
- Environment variable filtering - Dangerous variables like
LD_PRELOAD,PATH,NODE_OPTIONSare blocked - Argument validation - CLI flags are validated against an allowlist
- Timeout protection - All I/O operations have 30-second timeouts
- Buffer limits - Configurable max buffer size (default 1MB) prevents memory exhaustion
- Bounds checking - Limits on configurable values (e.g., max_turns ≤ 1000)
- Secure logging - Sensitive data only logged in debug builds with proper feature flags
For complete security details, see SECURITY_FIXES_APPLIED.md in the repository.
§Version History
- 0.1.0 (Current) - Initial release with full feature parity
- ✅
query()function for simple queries - ✅
ClaudeSDKClientfor bidirectional communication - ✅ SDK MCP server for custom tools
- ✅ Hook system for event interception
- ✅ Permission control for tool usage
- ✅ Comprehensive test suite (55+ tests)
- ✅ Full documentation and examples
- ✅
Re-exports§
pub use client::ClaudeSDKClient;pub use error::ClaudeError;pub use error::Result;pub use hooks::HookManager;pub use hooks::HookMatcherBuilder;pub use message::parse_message;pub use permissions::PermissionManager;pub use permissions::PermissionManagerBuilder;pub use query::query;pub use transport::PromptInput;pub use transport::SubprocessTransport;pub use transport::Transport;pub use types::AgentDefinition;pub use types::CanUseToolCallback;pub use types::ClaudeAgentOptions;pub use types::ClaudeAgentOptionsBuilder;pub use types::ContentBlock;pub use types::ContentValue;pub use types::HookCallback;pub use types::HookContext;pub use types::HookDecision;pub use types::HookEvent;pub use types::HookMatcher;pub use types::HookOutput;pub use types::McpHttpServerConfig;pub use types::McpServerConfig;pub use types::McpServers;pub use types::McpSseServerConfig;pub use types::McpStdioServerConfig;pub use types::Message;pub use types::PermissionBehavior;pub use types::PermissionMode;pub use types::PermissionRequest;pub use types::PermissionResult;pub use types::PermissionResultAllow;pub use types::PermissionResultDeny;pub use types::PermissionRuleValue;pub use types::PermissionUpdate;pub use types::PermissionUpdateDestination;pub use types::RequestId;pub use types::SessionId;pub use types::SettingSource;pub use types::SystemPrompt;pub use types::SystemPromptPreset;pub use types::ToolName;pub use types::ToolPermissionContext;pub use types::UserContent;
Modules§
- client
- ClaudeSDKClient for bidirectional communication
- control
- Control protocol for bidirectional communication with Claude Code
- error
- Error types for the Claude Agent SDK
- hooks
- Hook system for intercepting agent events
- mcp
- SDK MCP Server Integration
- message
- Message parsing and handling
- permissions
- Permission system for tool access control
- query
- Simple query function for one-shot interactions
- transport
- Transport layer for communicating with Claude Code CLI
- types
- Type definitions for Claude Agent SDK
Constants§
- VERSION
- Version of the SDK