claude_agents_sdk/lib.rs
1//! # Claude Agents SDK
2//!
3//! A Rust SDK for building agents that interact with the Claude Code CLI.
4//!
5//! This SDK provides two main entry points:
6//!
7//! - [`query`]: One-shot, unidirectional queries that return an async stream of messages
8//! - [`ClaudeClient`]: Full bidirectional client with control protocol support
9//!
10//! ## Quick Start
11//!
12//! ### Simple Query
13//!
14//! ```rust,no_run
15//! use claude_agents_sdk::{query, ClaudeAgentOptions, Message};
16//! use tokio_stream::StreamExt;
17//!
18//! #[tokio::main]
19//! async fn main() -> Result<(), Box<dyn std::error::Error>> {
20//! let options = ClaudeAgentOptions::new()
21//! .with_max_turns(3);
22//!
23//! let mut stream = query("What is 2 + 2?", Some(options)).await?;
24//!
25//! while let Some(message) = stream.next().await {
26//! match message? {
27//! Message::Assistant(msg) => print!("{}", msg.text()),
28//! Message::Result(result) => {
29//! println!("\nCost: ${:.4}", result.total_cost_usd.unwrap_or(0.0));
30//! }
31//! _ => {}
32//! }
33//! }
34//!
35//! Ok(())
36//! }
37//! ```
38//!
39//! ### Bidirectional Client
40//!
41//! ```rust,no_run
42//! use claude_agents_sdk::ClaudeClient;
43//!
44//! #[tokio::main]
45//! async fn main() -> Result<(), Box<dyn std::error::Error>> {
46//! let mut client = ClaudeClient::new(None);
47//! client.connect().await?;
48//!
49//! // First query
50//! client.query("What is the capital of France?").await?;
51//! let (response, _) = client.receive_response().await?;
52//! println!("Response: {}", response);
53//!
54//! // Follow-up query (maintains context)
55//! client.query("What's its population?").await?;
56//! let (response, _) = client.receive_response().await?;
57//! println!("Response: {}", response);
58//!
59//! client.disconnect().await?;
60//! Ok(())
61//! }
62//! ```
63//!
64//! ## Tool Permission Callbacks
65//!
66//! Control which tools Claude can use by providing a permission callback:
67//!
68//! ```rust,no_run
69//! use claude_agents_sdk::{ClaudeClientBuilder, PermissionResult, PermissionMode};
70//!
71//! #[tokio::main]
72//! async fn main() -> Result<(), Box<dyn std::error::Error>> {
73//! let mut client = ClaudeClientBuilder::new()
74//! .permission_mode(PermissionMode::Default)
75//! .can_use_tool(|tool_name, input, _ctx| async move {
76//! println!("Tool requested: {} with {:?}", tool_name, input);
77//!
78//! // Allow Read, deny dangerous Bash commands
79//! if tool_name == "Bash" {
80//! if let Some(cmd) = input.get("command").and_then(|v| v.as_str()) {
81//! if cmd.contains("rm -rf") {
82//! return PermissionResult::deny_with_message("Dangerous command");
83//! }
84//! }
85//! }
86//!
87//! PermissionResult::allow()
88//! })
89//! .build();
90//!
91//! client.connect().await?;
92//! // ... use client
93//! Ok(())
94//! }
95//! ```
96//!
97//! ## Error Handling
98//!
99//! The SDK provides [`ClaudeSDKError`] for comprehensive error handling:
100//!
101//! ```rust,no_run
102//! use claude_agents_sdk::{query, ClaudeAgentOptions, ClaudeSDKError, PermissionMode};
103//!
104//! #[tokio::main]
105//! async fn main() {
106//! let options = ClaudeAgentOptions::new()
107//! .with_permission_mode(PermissionMode::Default)
108//! .with_timeout_secs(30);
109//!
110//! match query("Hello", Some(options)).await {
111//! Ok(stream) => {
112//! // Process stream...
113//! }
114//! Err(ClaudeSDKError::CLINotFound { message }) => {
115//! eprintln!("Claude CLI not installed: {}", message);
116//! }
117//! Err(ClaudeSDKError::Timeout { duration_ms }) => {
118//! eprintln!("Operation timed out after {}ms", duration_ms);
119//! }
120//! Err(e) => {
121//! eprintln!("Error: {}", e);
122//! }
123//! }
124//! }
125//! ```
126//!
127//! ## Configuration Options
128//!
129//! Configure queries with [`ClaudeAgentOptions`]:
130//!
131//! ```rust
132//! use claude_agents_sdk::{ClaudeAgentOptions, PermissionMode};
133//!
134//! let options = ClaudeAgentOptions::new()
135//! .with_model("claude-sonnet-4-20250514")
136//! .with_system_prompt("You are a helpful coding assistant.")
137//! .with_max_turns(10)
138//! .with_permission_mode(PermissionMode::AcceptEdits)
139//! .with_allowed_tools(vec!["Read".into(), "Write".into()])
140//! .with_timeout_secs(60);
141//! ```
142//!
143//! ## Feature Flags
144//!
145//! - **default**: Core SDK functionality
146//! - **mcp**: Enables MCP (Model Context Protocol) tool support for defining custom tools
147
148#![warn(missing_docs)]
149#![cfg_attr(docsrs, feature(doc_cfg))]
150
151mod client;
152mod errors;
153mod query;
154mod types;
155
156pub mod _internal;
157
158// Re-export public API
159pub use client::{ClaudeClient, ClaudeClientBuilder, ClientGuard};
160pub use errors::*;
161pub use query::{query, query_all, query_chunks, query_result};
162pub use types::*;
163
164// Re-export MCP tools when feature enabled
165#[cfg(feature = "mcp")]
166#[cfg_attr(docsrs, doc(cfg(feature = "mcp")))]
167pub mod mcp;
168
169#[cfg(feature = "mcp")]
170pub use mcp::{create_sdk_mcp_server, McpSdkServerConfig, SdkMcpTool, ToolAnnotations};
171
172/// SDK version
173pub const VERSION: &str = env!("CARGO_PKG_VERSION");
174
175/// Minimum required Claude CLI version
176pub const MIN_CLI_VERSION: &str = "2.0.0";