claude_agent_sdk/
lib.rs

1//! # Claude Agent SDK for Rust
2//!
3//! A comprehensive Rust SDK for building AI agents powered by Claude Code. This library
4//! provides idiomatic Rust bindings with full support for async/await, strong typing,
5//! and zero-cost abstractions.
6//!
7//! ## Quick Start
8//!
9//! The simplest way to use this SDK is with the [`query()`] function:
10//!
11//! ```no_run
12//! use claude_agent_sdk::query;
13//! use futures::StreamExt;
14//!
15//! #[tokio::main]
16//! async fn main() -> Result<(), Box<dyn std::error::Error>> {
17//!     let stream = query("What is 2 + 2?", None).await?;
18//!     let mut stream = Box::pin(stream);
19//!
20//!     while let Some(message) = stream.next().await {
21//!         match message? {
22//!             claude_agent_sdk::Message::Assistant { message, .. } => {
23//!                 println!("Claude: {:?}", message);
24//!             }
25//!             _ => {}
26//!         }
27//!     }
28//!     Ok(())
29//! }
30//! ```
31//!
32//! ## Core Features
33//!
34//! ### 1. Simple Queries with [`query()`]
35//!
36//! For one-shot interactions where you don't need bidirectional communication:
37//!
38//! ```no_run
39//! # use claude_agent_sdk::{query, ClaudeAgentOptions};
40//! # use futures::StreamExt;
41//! # async fn example() -> Result<(), Box<dyn std::error::Error>> {
42//! let options = ClaudeAgentOptions::builder()
43//!     .system_prompt("You are a helpful coding assistant")
44//!     .max_turns(5)
45//!     .build();
46//!
47//! let stream = query("Explain async/await in Rust", Some(options)).await?;
48//! # Ok(())
49//! # }
50//! ```
51//!
52//! ### 2. Interactive Client with [`ClaudeSDKClient`]
53//!
54//! For stateful conversations with bidirectional communication:
55//!
56//! ```no_run
57//! # use claude_agent_sdk::{ClaudeSDKClient, ClaudeAgentOptions};
58//! # async fn example() -> Result<(), Box<dyn std::error::Error>> {
59//! let options = ClaudeAgentOptions::builder()
60//!     .max_turns(10)
61//!     .build();
62//!
63//! let mut client = ClaudeSDKClient::new(options, None).await?;
64//! client.send_message("Hello, Claude!").await?;
65//!
66//! while let Some(message) = client.next_message().await {
67//!     // Process messages...
68//! }
69//!
70//! client.close().await?;
71//! # Ok(())
72//! # }
73//! ```
74//!
75//! ### 3. Custom Tools with SDK MCP Server
76//!
77//! Create in-process tools that Claude can invoke directly:
78//!
79//! ```no_run
80//! # use claude_agent_sdk::mcp::{SdkMcpServer, SdkMcpTool, ToolResult};
81//! # use serde_json::json;
82//! # async fn example() -> Result<(), Box<dyn std::error::Error>> {
83//! let calculator = SdkMcpServer::new("calculator")
84//!     .version("1.0.0")
85//!     .tool(SdkMcpTool::new(
86//!         "add",
87//!         "Add two numbers",
88//!         json!({"type": "object", "properties": {
89//!             "a": {"type": "number"},
90//!             "b": {"type": "number"}
91//!         }}),
92//!         |input| Box::pin(async move {
93//!             let sum = input["a"].as_f64().unwrap_or(0.0)
94//!                     + input["b"].as_f64().unwrap_or(0.0);
95//!             Ok(ToolResult::text(format!("Sum: {}", sum)))
96//!         }),
97//!     ));
98//! # Ok(())
99//! # }
100//! ```
101//!
102//! See the [`mcp`] module for more details.
103//!
104//! ### 4. Hooks for Custom Behavior
105//!
106//! Intercept and modify tool execution:
107//!
108//! ```no_run
109//! # use claude_agent_sdk::{ClaudeAgentOptions, HookManager, HookEvent, HookOutput};
110//! # use claude_agent_sdk::hooks::HookMatcherBuilder;
111//! # use std::collections::HashMap;
112//! # async fn example() -> Result<(), Box<dyn std::error::Error>> {
113//! let hook = HookManager::callback(|event_data, tool_name, _context| async move {
114//!     println!("Tool used: {:?}", tool_name);
115//!     Ok(HookOutput::default())
116//! });
117//!
118//! let matcher = HookMatcherBuilder::new(Some("*"))
119//!     .add_hook(hook)
120//!     .build();
121//!
122//! let mut hooks = HashMap::new();
123//! hooks.insert(HookEvent::PreToolUse, vec![matcher]);
124//!
125//! let options = ClaudeAgentOptions::builder()
126//!     .hooks(hooks)
127//!     .build();
128//! # Ok(())
129//! # }
130//! ```
131//!
132//! See the [`hooks`] module for more details.
133//!
134//! ### 5. Permission Control
135//!
136//! Control which tools Claude can use and how:
137//!
138//! ```no_run
139//! # use claude_agent_sdk::{ClaudeAgentOptions, PermissionManager};
140//! # use claude_agent_sdk::types::{PermissionResult, PermissionResultAllow, PermissionResultDeny};
141//! # async fn example() -> Result<(), Box<dyn std::error::Error>> {
142//! let permission_callback = PermissionManager::callback(
143//!     |tool_name, _tool_input, _context| async move {
144//!         match tool_name.as_str() {
145//!             "Read" | "Glob" => Ok(PermissionResult::Allow(PermissionResultAllow {
146//!                 updated_input: None,
147//!                 updated_permissions: None,
148//!             })),
149//!             _ => Ok(PermissionResult::Deny(PermissionResultDeny {
150//!                 message: "Tool not allowed".to_string(),
151//!                 interrupt: false,
152//!             }))
153//!         }
154//!     }
155//! );
156//!
157//! let options = ClaudeAgentOptions::builder()
158//!     .can_use_tool(permission_callback)
159//!     .build();
160//! # Ok(())
161//! # }
162//! ```
163//!
164//! See the [`permissions`] module for more details.
165//!
166//! ## Architecture
167//!
168//! The SDK is organized into several key modules:
169//!
170//! - [`types`]: Core type definitions, newtypes, and builders
171//! - [`query()`]: Simple one-shot query function
172//! - [`client`]: Interactive bidirectional client
173//! - [`mcp`]: SDK MCP server for custom tools
174//! - [`hooks`]: Hook system for intercepting events
175//! - [`permissions`]: Permission control for tool usage
176//! - [`transport`]: Communication layer with Claude Code CLI
177//! - [`control`]: Control protocol handler
178//! - [`message`]: Message parsing and types
179//! - [`error`]: Error types and handling
180//!
181//! ## Feature Flags
182//!
183//! This crate supports the following feature flags:
184//!
185//! - `http` - Enables HTTP transport support (requires `reqwest`)
186//! - `tracing-support` - Enables structured logging with `tracing`
187//!
188//! ## Examples
189//!
190//! The SDK comes with comprehensive examples:
191//!
192//! - `simple_query.rs` - Basic query usage
193//! - `interactive_client.rs` - Interactive conversation
194//! - `bidirectional_demo.rs` - Concurrent operations
195//! - `hooks_demo.rs` - Hook system with 3 examples
196//! - `permissions_demo.rs` - Permission control with 3 examples
197//! - `mcp_demo.rs` - Custom tools with MCP server
198//!
199//! Run examples with:
200//! ```bash
201//! cargo run --example simple_query
202//! ```
203//!
204//! ## Requirements
205//!
206//! - Rust 1.75.0 or later
207//! - Node.js (for Claude Code CLI)
208//! - Claude Code: `npm install -g @anthropic-ai/claude-code`
209//!
210//! ## Error Handling
211//!
212//! All fallible operations return [`Result<T, ClaudeError>`](Result). The SDK uses
213//! `thiserror` for ergonomic error types with full context:
214//!
215//! ```no_run
216//! # use claude_agent_sdk::{query, ClaudeError};
217//! # async fn example() {
218//! match query("Hello", None).await {
219//!     Ok(stream) => { /* ... */ }
220//!     Err(ClaudeError::CliNotFound(msg)) => {
221//!         eprintln!("Claude Code not installed: {}", msg);
222//!     }
223//!     Err(e) => {
224//!         eprintln!("Error: {}", e);
225//!     }
226//! }
227//! # }
228//! ```
229//!
230//! ## Safety and Best Practices
231//!
232//! - **No unsafe code** - The SDK is 100% safe Rust
233//! - **Type safety** - Newtypes prevent mixing incompatible values
234//! - **Async/await** - Built on tokio for efficient concurrency
235//! - **Resource management** - Proper cleanup via RAII and Drop
236//! - **Error handling** - Comprehensive error types with context
237//!
238//! ## Security
239//!
240//! This SDK includes multiple layers of security protection:
241//!
242//! - **Environment variable filtering** - Dangerous variables like `LD_PRELOAD`, `PATH`, `NODE_OPTIONS` are blocked
243//! - **Argument validation** - CLI flags are validated against an allowlist
244//! - **Timeout protection** - All I/O operations have 30-second timeouts
245//! - **Buffer limits** - Configurable max buffer size (default 1MB) prevents memory exhaustion
246//! - **Bounds checking** - Limits on configurable values (e.g., max_turns ≤ 1000)
247//! - **Secure logging** - Sensitive data only logged in debug builds with proper feature flags
248//!
249//! For complete security details, see `SECURITY_FIXES_APPLIED.md` in the repository.
250//!
251//! ## Version History
252//!
253//! - **0.1.0** (Current) - Initial release with full feature parity
254//!   - ✅ `query()` function for simple queries
255//!   - ✅ `ClaudeSDKClient` for bidirectional communication
256//!   - ✅ SDK MCP server for custom tools
257//!   - ✅ Hook system for event interception
258//!   - ✅ Permission control for tool usage
259//!   - ✅ Comprehensive test suite (55+ tests)
260//!   - ✅ Full documentation and examples
261
262#![warn(missing_docs)]
263#![warn(clippy::all)]
264
265pub mod client;
266pub mod control;
267pub mod error;
268pub mod hooks;
269pub mod mcp;
270pub mod message;
271pub mod permissions;
272pub mod query;
273pub mod transport;
274pub mod types;
275
276// Re-export commonly used types
277pub use client::ClaudeSDKClient;
278pub use error::{ClaudeError, Result};
279pub use hooks::{HookManager, HookMatcherBuilder};
280pub use message::parse_message;
281pub use permissions::{PermissionManager, PermissionManagerBuilder};
282pub use query::query;
283pub use transport::{PromptInput, SubprocessTransport, Transport};
284pub use types::{
285    AgentDefinition, CanUseToolCallback, ClaudeAgentOptions, ClaudeAgentOptionsBuilder,
286    ContentBlock, ContentValue, HookCallback, HookContext, HookDecision, HookEvent, HookMatcher,
287    HookOutput, McpHttpServerConfig, McpServerConfig, McpServers, McpSseServerConfig,
288    McpStdioServerConfig, Message, PermissionBehavior, PermissionMode, PermissionRequest,
289    PermissionResult, PermissionResultAllow, PermissionResultDeny, PermissionRuleValue,
290    PermissionUpdate, PermissionUpdateDestination, RequestId, SessionId, SettingSource,
291    SystemPrompt, SystemPromptPreset, ToolName, ToolPermissionContext, UserContent,
292};
293
294/// Version of the SDK
295pub const VERSION: &str = env!("CARGO_PKG_VERSION");