Skip to main content

claude_code_agent/
lib.rs

1//! Run Claude Code from Rust.
2//!
3//! Each [`Session`] keeps one `claude` process running (Claude Code CLI
4//! 2.1.329 or newer). Send prompts with [`Agent`], approve or block tools with
5//! hooks and [`CanUseTool`], give Claude tools written in Rust, run many
6//! sessions with [`SessionPool`], and replay recorded sessions in tests.
7//!
8//! # Quick start
9//!
10//! ```rust,no_run
11//! use claude_code_agent::{Session, SessionOptions, Initialize, Agent, AgentEvent};
12//! use tokio_stream::StreamExt;
13//!
14//! #[tokio::main]
15//! async fn main() -> anyhow::Result<()> {
16//!     let session = Session::spawn(
17//!         SessionOptions { cwd: Some("/my/project".into()), ..Default::default() },
18//!         Initialize::default(),
19//!     ).await?;
20//!
21//!     let agent = Agent::new(session);
22//!     let mut stream = agent.prompt("hello").await?;
23//!
24//!     while let Some(event) = stream.next().await {
25//!         match event {
26//!             AgentEvent::Text(t) => print!("{}", t),
27//!             AgentEvent::Done(r) => {
28//!                 eprintln!("\ncost: ${:.4}", r.total_cost_usd.unwrap_or(0.0));
29//!                 break;
30//!             }
31//!             AgentEvent::Error(e) => eprintln!("error: {}", e),
32//!             _ => {}
33//!         }
34//!     }
35//!     Ok(())
36//! }
37//! ```
38//!
39//! # With hooks
40//!
41//! ```rust,no_run
42//! use claude_code_agent::{Agent, AgentEvent, CanUseTool, HookRegistry, Initialize, Session, SessionOptions};
43//! use claude_code_agent::protocol::{HookOutput, ToolDecision};
44//! use tokio_stream::StreamExt;
45//!
46//! #[tokio::main]
47//! async fn main() -> anyhow::Result<()> {
48//!     // Hooks are declared before spawn: the CLI learns them from `initialize`.
49//!     let mut hooks = HookRegistry::new();
50//!     hooks.on_pre_tool_use(|payload| async move {
51//!         match payload.tool_name.as_deref() {
52//!             Some("Bash") => HookOutput::allow(),
53//!             Some(name)   => HookOutput::block(format!("{name} not allowed")),
54//!             None         => HookOutput::allow(),
55//!         }
56//!     });
57//!
58//!     let opts = SessionOptions {
59//!         hooks,
60//!         // Asked whenever the CLI's own permission rules would prompt.
61//!         can_use_tool: Some(CanUseTool::new(|req| async move {
62//!             if req.tool_name == "Bash" { ToolDecision::allow() } else { ToolDecision::deny("read-only") }
63//!         })),
64//!         ..Default::default()
65//!     };
66//!     let session = Session::spawn(opts, Initialize::default()).await?;
67//!     let agent = Agent::new(session);
68//!
69//!     let mut stream = agent.prompt("list files in /tmp").await?;
70//!     while let Some(ev) = stream.next().await {
71//!         if let AgentEvent::Text(t) = &ev { print!("{}", t); }
72//!         if matches!(ev, AgentEvent::Done(_) | AgentEvent::Error(_)) { break; }
73//!     }
74//!     Ok(())
75//! }
76//! ```
77//!
78//! # With session pool (high throughput)
79//!
80//! ```rust,no_run
81//! use claude_code_agent::{SessionPool, PoolConfig, Agent, AgentEvent};
82//! use tokio_stream::StreamExt;
83//!
84//! #[tokio::main]
85//! async fn main() -> anyhow::Result<()> {
86//!     let pool = SessionPool::new(PoolConfig { max_sessions: 4, ..Default::default() });
87//!     pool.warm(2).await; // pre-warm 2 processes
88//!
89//!     // Parallel prompts — each reuses an idle session from the pool
90//!     let (r1, r2) = tokio::join!(
91//!         run_prompt(&pool, "task one"),
92//!         run_prompt(&pool, "task two"),
93//!     );
94//!     Ok(())
95//! }
96//!
97//! async fn run_prompt(pool: &SessionPool, text: &str) -> anyhow::Result<String> {
98//!     let borrowed = pool.acquire().await?;
99//!     let agent = Agent::new(borrowed.session.clone());
100//!     let mut stream = agent.prompt(text).await?;
101//!     let mut out = String::new();
102//!     while let Some(ev) = stream.next().await {
103//!         if let AgentEvent::Text(t) = &ev { out.push_str(t); }
104//!         if matches!(ev, AgentEvent::Done(_) | AgentEvent::Error(_)) { break; }
105//!     }
106//!     Ok(out)
107//! }
108//! ```
109
110#![forbid(unsafe_code)]
111#![warn(missing_docs)]
112#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
113
114pub mod agent;
115pub mod background;
116pub mod code_mode;
117pub mod compaction;
118pub mod fs_events;
119pub mod hooks;
120pub mod mcp;
121pub mod middleware;
122pub mod pool;
123#[cfg(unix)]
124mod process_tree;
125pub mod protocol;
126pub mod replay;
127pub mod session;
128
129// ── Top-level re-exports ───────────────────────────────────────────────────────
130
131pub use agent::{Agent, AgentError, AgentEvent, AgentStream, TurnError, TurnResult};
132pub use hooks::HookRegistry;
133pub use mcp::{SdkMcpServer, SdkTool, ToolContent, ToolContext, ToolResult};
134/// `#[claude_tool]` — enable with the `macros` feature.
135#[cfg(feature = "macros")]
136pub use claude_code_agent_macros::claude_tool;
137pub use pool::{Checkout, PoolConfig, PooledSession, SessionPool};
138pub use protocol::{
139    // Core messages
140    Initialize, UserMessage, ContentBlock, Priority,
141    // Session settings
142    Autocompact, Effort, PermissionMode, PermissionPrompts, Thinking, ThinkingDisplay,
143    // Inbound
144    InboundMessage, SystemMessage, AssistantMessage, ResultMessage, UsageSummary,
145    BackgroundTask, TurnErrorKind,
146    // Control
147    ToolDecision, HookOutput, HookDecision, ControlRequest, ControlRequestBody,
148    ControlResponse, CanUseToolRequest, ElicitationRequest, ElicitationResponse, UserDialogBehavior, UserDialogRequest, UserDialogResponse,
149    // Hook types
150    HookEventKind, HookEventPayload, HookCallbackRequest,
151    // Tools/MCP
152    ToolDef, ToolAnnotations, McpManifest,
153    // Background
154    BackgroundTasksRequest,
155};
156pub use session::{
157    CanUseTool, McpCall, OnElicitation, OnStderr, OnUserDialog, ReloadPlugins, Session, SessionError,
158    SessionOptions, WeakSession,
159};
160
161/// Re-exports used by code generated from `#[claude_tool]`. Not public API.
162#[doc(hidden)]
163pub mod __private {
164    pub use serde_json;
165
166    /// Turns a tool fn's return value into a [`ToolResult`](crate::ToolResult)
167    /// by its type, not its spelling (so `type MyRes<T> = Result<T, E>` is
168    /// still a `Result`). Generated code runs
169    /// `(&value).__claude_tool_kind().convert(value)`: the impls on `Result`,
170    /// `ToolResult` and `()` match `&V` directly and win over the
171    /// `Serialize` fallback, which needs one more auto-ref.
172    pub mod ret {
173        use crate::ToolResult;
174        use serde::Serialize;
175        use std::fmt::Display;
176
177        /// `Result<T, E>`: `T` as JSON, or an error result with `E: Display`.
178        pub struct ResultTag;
179        /// `ToolResult`: passed through.
180        pub struct ToolResultTag;
181        /// `()`: the text "ok".
182        pub struct UnitTag;
183        /// Anything else: serde JSON, strings verbatim.
184        pub struct SerializeTag;
185
186        /// Selects [`ResultTag`].
187        pub trait ResultKind {
188            #[inline]
189            fn __claude_tool_kind(&self) -> ResultTag {
190                ResultTag
191            }
192        }
193        impl<T, E> ResultKind for Result<T, E> {}
194
195        /// Selects [`ToolResultTag`].
196        pub trait ToolResultKind {
197            #[inline]
198            fn __claude_tool_kind(&self) -> ToolResultTag {
199                ToolResultTag
200            }
201        }
202        impl ToolResultKind for ToolResult {}
203
204        /// Selects [`UnitTag`].
205        pub trait UnitKind {
206            #[inline]
207            fn __claude_tool_kind(&self) -> UnitTag {
208                UnitTag
209            }
210        }
211        impl UnitKind for () {}
212
213        /// Selects [`SerializeTag`].
214        pub trait SerializeKind {
215            #[inline]
216            fn __claude_tool_kind(&self) -> SerializeTag {
217                SerializeTag
218            }
219        }
220        impl<T: ?Sized> SerializeKind for &T {}
221
222        fn serialize<T: Serialize + ?Sized>(value: &T) -> ToolResult {
223            match serde_json::to_value(value) {
224                Ok(v) => ToolResult::from_value(v),
225                Err(e) => ToolResult::error(e.to_string()),
226            }
227        }
228
229        impl ResultTag {
230            /// Convert the returned `Result`.
231            pub fn convert<T: Serialize, E: Display>(self, value: Result<T, E>) -> ToolResult {
232                match value {
233                    Ok(v) => serialize(&v),
234                    Err(e) => ToolResult::error(e.to_string()),
235                }
236            }
237        }
238        impl ToolResultTag {
239            /// Pass the returned `ToolResult` through.
240            pub fn convert(self, value: ToolResult) -> ToolResult {
241                value
242            }
243        }
244        impl UnitTag {
245            /// Convert the returned `()`.
246            pub fn convert(self, _: ()) -> ToolResult {
247                ToolResult::text("ok")
248            }
249        }
250        impl SerializeTag {
251            /// Convert any other returned value.
252            pub fn convert<T: Serialize>(self, value: T) -> ToolResult {
253                serialize(&value)
254            }
255        }
256    }
257}