Expand description
§Claude Agent SDK for Rust
Rust SDK for building AI agents powered by Claude Code. Async/await, strong typing, tokio-based.
§Quick Start
Basic usage with query():
use anthropic_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? {
anthropic_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. MCP Tools with rmcp
Create custom MCP tools that Claude can discover and use. Enable the rmcp feature
to use the official rmcp crate:
use anthropic_agent_sdk::mcp::{
tool, tool_router, tool_handler, Parameters, ServerCapabilities, ServerHandler,
ServerInfo, ToolRouter,
};
use schemars::JsonSchema;
use serde::Deserialize;
#[derive(Deserialize, JsonSchema)]
struct AddParams {
/// First number
a: f64,
/// Second number
b: f64,
}
#[derive(Clone)]
struct Calculator { tool_router: ToolRouter<Self> }
#[tool_router]
impl Calculator {
fn new() -> Self { Self { tool_router: Self::tool_router() } }
#[tool(description = "Add two numbers")]
fn add(&self, Parameters(params): Parameters<AddParams>) -> String {
format!("{} + {} = {}", params.a, params.b, params.a + params.b)
}
}
#[tool_handler]
impl ServerHandler for Calculator {
fn get_info(&self) -> ServerInfo {
ServerInfo {
capabilities: ServerCapabilities::builder().enable_tools().build(),
..Default::default()
}
}
}See examples/mcp_server.rs for a complete demo.
§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, identifiers, 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:
rmcp- Enables SDK MCP server support via the official rmcp crate
§Logging
This crate uses tracing for structured logging.
Tracing events are always emitted but are zero-cost when no subscriber is attached.
To see logs, attach a tracing subscriber in your application:
tracing_subscriber::fmt::init();§Examples
simple_query.rs- Basic query usageinteractive_client.rs- Interactive REPL conversationbidirectional_demo.rs- Concurrent operationshooks_demo.rs- Hook system for tool interceptionpermissions_demo.rs- Permission control for toolsmcp_server.rs- MCP server with custom tools (requires--features rmcp)mcp_integration.rs- Full E2E with Claude using MCP toolsintrospection_demo.rs- Session info, models, commands, MCP statusplan_mode_demo.rs- Plan mode with approval workflowoauth_demo.rs- OAuth authentication with PKCE
Run examples with:
cargo run --example simple_query
cargo run --example oauth_demo
cargo run --example mcp_server --features rmcp§Requirements
- Rust 1.85.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>:
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 - Typed errors with context
§Security
- Environment variable filtering - Dangerous variables like
LD_PRELOAD,PATH,NODE_OPTIONSare blocked - Callback timeouts - Hook and permission callbacks have configurable timeouts (default 60 seconds)
- Buffer limits - Configurable max buffer size (default 1MB) prevents memory exhaustion
- Cancellation support - Callbacks receive cancellation tokens for graceful abort
For complete security details, see SECURITY.md in the repository.
§Version History
-
0.2.0 (Current) - TypeScript SDK parity release
- MCP integration via official rmcp crate
- Hooks, introspection, runtime setters
- Plan mode, slash commands, skills support
- Model usage tracking, permission denials
-
0.1.0 - Initial release
query()function for simple queriesClaudeSDKClientfor bidirectional communication- Hook system for event interception
- Permission control for tool usage
Re-exports§
pub use callbacks::FnHookCallback;pub use callbacks::FnPermissionCallback;pub use callbacks::HookCallback;pub use callbacks::PermissionCallback;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::MIN_CLI_VERSION;pub use transport::PromptInput;pub use transport::SubprocessTransport;pub use transport::Transport;pub use transport::check_claude_version;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::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::OutputFormat;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::SdkMcpServerConfig;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::UsageData;pub use types::UsageLimit;pub use types::UserContent;
Modules§
- auth
- OAuth authentication module for Claude
- callbacks
- Trait-based callback definitions for hooks and permissions.
- client
ClaudeSDKClientfor 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
- MCP (Model Context Protocol) integration for Claude Agent SDK
- 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
- utils
- Utility functions for the Claude Agent SDK
Constants§
- VERSION
- Version of the SDK
Traits§
- Stream
Ext - An extension trait for
Streams that provides a variety of convenient combinator functions.