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 first runs
169    /// `(&value).__claude_tool_unwrap_kind().unwrap(value)`, which takes the
170    /// `Ok` value out of a `Result` (its error becomes an error result), then
171    /// `(&ok).__claude_tool_kind().convert(ok)`. In both steps the impls on
172    /// the specific types match `&V` directly and win over the fallback,
173    /// which needs one more auto-ref.
174    pub mod ret {
175        use crate::ToolResult;
176        use serde::Serialize;
177        use std::fmt::Display;
178
179        /// `Result<T, E>`: `T`, converted by its own type, or an error
180        /// result with `E: Display`.
181        pub struct ResultTag;
182        /// Not a `Result`: the value itself.
183        pub struct PlainTag;
184        /// `ToolResult`: passed through.
185        pub struct ToolResultTag;
186        /// `()`: the text "ok".
187        pub struct UnitTag;
188        /// Anything else: serde JSON, strings verbatim.
189        pub struct SerializeTag;
190
191        /// Selects [`ResultTag`].
192        pub trait ResultKind {
193            #[inline]
194            fn __claude_tool_unwrap_kind(&self) -> ResultTag {
195                ResultTag
196            }
197        }
198        impl<T, E> ResultKind for Result<T, E> {}
199
200        /// Selects [`PlainTag`].
201        pub trait PlainKind {
202            #[inline]
203            fn __claude_tool_unwrap_kind(&self) -> PlainTag {
204                PlainTag
205            }
206        }
207        impl<T: ?Sized> PlainKind for &T {}
208
209        /// Selects [`ToolResultTag`].
210        pub trait ToolResultKind {
211            #[inline]
212            fn __claude_tool_kind(&self) -> ToolResultTag {
213                ToolResultTag
214            }
215        }
216        impl ToolResultKind for ToolResult {}
217
218        /// Selects [`UnitTag`].
219        pub trait UnitKind {
220            #[inline]
221            fn __claude_tool_kind(&self) -> UnitTag {
222                UnitTag
223            }
224        }
225        impl UnitKind for () {}
226
227        /// Selects [`SerializeTag`].
228        pub trait SerializeKind {
229            #[inline]
230            fn __claude_tool_kind(&self) -> SerializeTag {
231                SerializeTag
232            }
233        }
234        impl<T: ?Sized> SerializeKind for &T {}
235
236        fn serialize<T: Serialize + ?Sized>(value: &T) -> ToolResult {
237            match serde_json::to_value(value) {
238                Ok(v) => ToolResult::from_value(v),
239                Err(e) => ToolResult::error(e.to_string()),
240            }
241        }
242
243        impl ResultTag {
244            /// The `Ok` value, or the error as an error result.
245            pub fn unwrap<T, E: Display>(self, value: Result<T, E>) -> Result<T, ToolResult> {
246                value.map_err(|e| ToolResult::error(e.to_string()))
247            }
248        }
249        impl PlainTag {
250            /// The value itself.
251            pub fn unwrap<T>(self, value: T) -> Result<T, ToolResult> {
252                Ok(value)
253            }
254        }
255        impl ToolResultTag {
256            /// Pass the returned `ToolResult` through.
257            pub fn convert(self, value: ToolResult) -> ToolResult {
258                value
259            }
260        }
261        impl UnitTag {
262            /// Convert the returned `()`.
263            pub fn convert(self, _: ()) -> ToolResult {
264                ToolResult::text("ok")
265            }
266        }
267        impl SerializeTag {
268            /// Convert any other returned value.
269            pub fn convert<T: Serialize>(self, value: T) -> ToolResult {
270                serialize(&value)
271            }
272        }
273    }
274}