Expand description
§Claude Agents SDK
A Rust SDK for building agents that interact with the Claude Code CLI.
This SDK provides two main entry points:
query: One-shot, unidirectional queries that return an async stream of messagesClaudeClient: Full bidirectional client with control protocol support
§Quick Start
§Simple Query
use claude_agents_sdk::{query, ClaudeAgentOptions, Message};
use tokio_stream::StreamExt;
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let options = ClaudeAgentOptions::new()
.with_max_turns(3);
let mut stream = query("What is 2 + 2?", Some(options)).await?;
while let Some(message) = stream.next().await {
match message? {
Message::Assistant(msg) => print!("{}", msg.text()),
Message::Result(result) => {
println!("\nCost: ${:.4}", result.total_cost_usd.unwrap_or(0.0));
}
_ => {}
}
}
Ok(())
}§Bidirectional Client
use claude_agents_sdk::ClaudeClient;
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let mut client = ClaudeClient::new(None);
client.connect().await?;
// First query
client.query("What is the capital of France?").await?;
let (response, _) = client.receive_response().await?;
println!("Response: {}", response);
// Follow-up query (maintains context)
client.query("What's its population?").await?;
let (response, _) = client.receive_response().await?;
println!("Response: {}", response);
client.disconnect().await?;
Ok(())
}§Tool Permission Callbacks
Control which tools Claude can use by providing a permission callback:
use claude_agents_sdk::{ClaudeClientBuilder, PermissionResult, PermissionMode};
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let mut client = ClaudeClientBuilder::new()
.permission_mode(PermissionMode::Default)
.can_use_tool(|tool_name, input, _ctx| async move {
println!("Tool requested: {} with {:?}", tool_name, input);
// Allow Read, deny dangerous Bash commands
if tool_name == "Bash" {
if let Some(cmd) = input.get("command").and_then(|v| v.as_str()) {
if cmd.contains("rm -rf") {
return PermissionResult::deny_with_message("Dangerous command");
}
}
}
PermissionResult::allow()
})
.build();
client.connect().await?;
// ... use client
Ok(())
}§Error Handling
The SDK provides ClaudeSDKError for comprehensive error handling:
use claude_agents_sdk::{query, ClaudeAgentOptions, ClaudeSDKError, PermissionMode};
#[tokio::main]
async fn main() {
let options = ClaudeAgentOptions::new()
.with_permission_mode(PermissionMode::Default)
.with_timeout_secs(30);
match query("Hello", Some(options)).await {
Ok(stream) => {
// Process stream...
}
Err(ClaudeSDKError::CLINotFound { message }) => {
eprintln!("Claude CLI not installed: {}", message);
}
Err(ClaudeSDKError::Timeout { duration_ms }) => {
eprintln!("Operation timed out after {}ms", duration_ms);
}
Err(e) => {
eprintln!("Error: {}", e);
}
}
}§Configuration Options
Configure queries with ClaudeAgentOptions:
use claude_agents_sdk::{ClaudeAgentOptions, PermissionMode};
let options = ClaudeAgentOptions::new()
.with_model("claude-sonnet-4-20250514")
.with_system_prompt("You are a helpful coding assistant.")
.with_max_turns(10)
.with_permission_mode(PermissionMode::AcceptEdits)
.with_allowed_tools(vec!["Read".into(), "Write".into()])
.with_timeout_secs(60);§Feature Flags
- default: Core SDK functionality
- mcp: Enables MCP (Model Context Protocol) tool support for defining custom tools
Re-exports§
pub use mcp::create_sdk_mcp_server;mcppub use mcp::McpSdkServerConfig;mcppub use mcp::SdkMcpTool;mcppub use mcp::ToolAnnotations;mcp
Modules§
- _internal
- Internal implementation details for the Claude Agents SDK.
- mcp
mcp - MCP (Model Context Protocol) tool support.
Macros§
- tool
- Macro for defining tools with a simpler syntax.
Structs§
- Agent
Definition - Agent definition.
- Assistant
Message - Assistant message.
- Async
Hook Output - Async hook output that defers execution.
- Base
Hook Input - Base hook input fields.
- Claude
Agent Options - Query options for Claude SDK.
- Claude
Client - Bidirectional client for streaming Claude interactions.
- Claude
Client Builder - Builder for creating a
ClaudeClientwith configuration. - Client
Guard - A guard that automatically disconnects a
ClaudeClientwhen dropped. - Control
Error Response - Error response.
- Control
Request - Control request.
- Control
Response - Control response.
- Control
Success Response - Success response.
- Hook
Context - Context for hook callbacks.
- Hook
Matcher - Hook matcher configuration.
- McpHttp
Server Config - MCP HTTP server configuration.
- McpSSE
Server Config - MCP SSE server configuration.
- McpStdio
Server Config - MCP stdio server configuration.
- Notification
Hook Input - Input for Notification hook events.
- Notification
Hook Specific Output - Hook-specific output for Notification events.
- Permission
Request Hook Input - Input for PermissionRequest hook events.
- Permission
Request Hook Specific Output - Hook-specific output for PermissionRequest events.
- Permission
Result Allow - Allow permission result.
- Permission
Result Deny - Deny permission result.
- Permission
Rule Value - Permission rule value.
- Permission
Update - Permission update configuration.
- Post
Tool UseFailure Hook Input - Input for PostToolUseFailure hook events.
- Post
Tool UseFailure Hook Specific Output - Hook-specific output for PostToolUseFailure events.
- Post
Tool UseHook Input - Input for PostToolUse hook events.
- Post
Tool UseHook Specific Output - Hook-specific output for PostToolUse events.
- PreCompact
Hook Input - Input for PreCompact hook events.
- PreTool
UseHook Input - Input for PreToolUse hook events.
- PreTool
UseHook Specific Output - Hook-specific output for PreToolUse events.
- Result
Message - Result message with cost and usage information.
- Sandbox
Ignore Violations - Violations to ignore in sandbox.
- Sandbox
Network Config - Network configuration for sandbox.
- Sandbox
Settings - Sandbox settings configuration.
- SdkPlugin
Config - SDK plugin configuration.
- Stop
Hook Input - Input for Stop hook events.
- Stream
Event - Stream event for partial message updates.
- Subagent
Start Hook Input - Input for SubagentStart hook events.
- Subagent
Start Hook Specific Output - Hook-specific output for SubagentStart events.
- Subagent
Stop Hook Input - Input for SubagentStop hook events.
- Sync
Hook Output - Synchronous hook output with control fields.
- System
Message - System message.
- System
Prompt Preset - System prompt preset.
- Text
Block - Text content block.
- Thinking
Block - Thinking content block.
- Tool
Permission Context - Context information for tool permission callbacks.
- Tool
Result Block - Tool result content block.
- Tool
UseBlock - Tool use content block.
- Tools
Preset - Tools preset.
- User
Message - User message.
- User
Prompt Submit Hook Input - Input for UserPromptSubmit hook events.
- User
Prompt Submit Hook Specific Output - Hook-specific output for UserPromptSubmit events.
Enums§
- Agent
Model - Agent model.
- Assistant
Message Error - Assistant message error types.
- ClaudeSDK
Error - Main error type for the Claude Agents SDK.
- Compact
Trigger - Trigger for PreCompact hook.
- Content
Block - Content block union type.
- Control
Request Payload - Control request subtypes.
- Control
Response Payload - Control response payload.
- Effort
- Effort level for thinking depth.
- Hook
Event - Hook event types.
- Hook
Input - Union of all hook input types.
- Hook
Output - Hook output type.
- Hook
Specific Output - Union of hook-specific outputs.
- McpServer
Config - MCP server configuration union.
- McpServers
Config - MCP servers configuration.
- Message
- Message union type.
- Permission
Behavior - Permission behavior for tool use.
- Permission
Mode - Permission modes controlling how the CLI handles tool permissions.
- Permission
Result - Permission result from a tool permission callback.
- Permission
Update Destination - Destination for permission updates.
- Permission
Update Type - Type of permission update.
- SdkBeta
- SDK Beta features.
- Setting
Source - Setting source.
- System
Prompt Config - System prompt configuration.
- Thinking
Config - Configuration for extended thinking behavior.
- Tools
Config - Tools configuration.
- User
Message Content - User message content can be a string or content blocks.
Constants§
- MIN_
CLI_ VERSION - Minimum required Claude CLI version
- VERSION
- SDK version
Functions§
- query
- Execute a one-shot query to Claude.
- query_
all - Execute a query and collect all messages.
- query_
chunks - Execute a query with a prompt built from chunks.
- query_
result - Get the final result from a query.
Type Aliases§
- CanUse
Tool - Type alias for the tool permission callback function.
- CanUse
Tool Future - The async future type returned by tool permission callbacks.
- Hook
Callback - Type alias for hook callback functions.
- Hook
Callback Future - The async future type returned by hook callbacks.
- Result
- Result type alias for SDK operations.