Skip to main content

claude_wrapper/
lib.rs

1//! A type-safe Claude Code CLI wrapper for Rust.
2//!
3//! `claude-wrapper` provides a builder-pattern interface for invoking the
4//! `claude` CLI programmatically. It follows the same design philosophy as
5//! [`docker-wrapper`](https://crates.io/crates/docker-wrapper) and
6//! [`terraform-wrapper`](https://crates.io/crates/terraform-wrapper):
7//! each CLI subcommand is a builder struct that produces typed output.
8//!
9//! # Quick Start
10//!
11//! ```no_run
12//! use claude_wrapper::{Claude, ClaudeCommand, QueryCommand, OutputFormat};
13//!
14//! # async fn example() -> claude_wrapper::Result<()> {
15//! let claude = Claude::builder().build()?;
16//!
17//! // Simple oneshot query
18//! let output = QueryCommand::new("explain this error: file not found")
19//!     .model("sonnet")
20//!     .output_format(OutputFormat::Json)
21//!     .execute(&claude)
22//!     .await?;
23//!
24//! println!("{}", output.stdout);
25//! # Ok(())
26//! # }
27//! ```
28//!
29//! # Two-Layer Builder
30//!
31//! The [`Claude`] client holds shared config (binary path, env vars, timeout).
32//! Command builders hold per-invocation options and call `execute(&claude)`.
33//!
34//! ```no_run
35//! use claude_wrapper::{Claude, ClaudeCommand, QueryCommand, PermissionMode, Effort};
36//!
37//! # async fn example() -> claude_wrapper::Result<()> {
38//! // Configure once, reuse across commands
39//! let claude = Claude::builder()
40//!     .env("AWS_REGION", "us-west-2")
41//!     .timeout_secs(300)
42//!     .build()?;
43//!
44//! // Each command is a separate builder
45//! let output = QueryCommand::new("review the code in src/main.rs")
46//!     .model("opus")
47//!     .system_prompt("You are a senior Rust developer")
48//!     .permission_mode(PermissionMode::Plan)
49//!     .effort(Effort::High)
50//!     .max_turns(5)
51//!     .no_session_persistence()
52//!     .execute(&claude)
53//!     .await?;
54//! # Ok(())
55//! # }
56//! ```
57//!
58//! # JSON Output Parsing
59//!
60//! Use `execute_json()` to get structured results:
61//!
62//! ```no_run
63//! use claude_wrapper::{Claude, QueryCommand};
64//!
65//! # async fn example() -> claude_wrapper::Result<()> {
66//! let claude = Claude::builder().build()?;
67//! let result = QueryCommand::new("what is 2+2?")
68//!     .execute_json(&claude)
69//!     .await?;
70//!
71//! println!("answer: {}", result.result);
72//! println!("cost: ${:.4}", result.cost_usd.unwrap_or(0.0));
73//! println!("session: {}", result.session_id);
74//! # Ok(())
75//! # }
76//! ```
77//!
78//! # MCP Config Generation
79//!
80//! Generate `.mcp.json` files for use with `--mcp-config`:
81//!
82//! ```no_run
83//! use claude_wrapper::{Claude, ClaudeCommand, McpConfigBuilder, QueryCommand};
84//!
85//! # async fn example() -> claude_wrapper::Result<()> {
86//! // Build a config file with multiple servers
87//! let config_path = McpConfigBuilder::new()
88//!     .http_server("my-hub", "http://127.0.0.1:9090")
89//!     .stdio_server("my-tool", "npx", ["my-mcp-server"])
90//!     .stdio_server_with_env(
91//!         "secure-tool", "node", ["server.js"],
92//!         [("API_KEY", "secret")],
93//!     )
94//!     .write_to("/tmp/my-project/.mcp.json")?;
95//!
96//! // Use it in a query
97//! let claude = Claude::builder().build()?;
98//! let output = QueryCommand::new("list available tools")
99//!     .mcp_config("/tmp/my-project/.mcp.json")
100//!     .execute(&claude)
101//!     .await?;
102//! # Ok(())
103//! # }
104//! ```
105//!
106//! # Working with Multiple Directories
107//!
108//! Clone the client with a different working directory:
109//!
110//! ```no_run
111//! use claude_wrapper::{Claude, ClaudeCommand, QueryCommand};
112//!
113//! # async fn example() -> claude_wrapper::Result<()> {
114//! let claude = Claude::builder().build()?;
115//!
116//! for project in &["/srv/project-a", "/srv/project-b"] {
117//!     let local = claude.with_working_dir(project);
118//!     QueryCommand::new("summarize this project")
119//!         .no_session_persistence()
120//!         .execute(&local)
121//!         .await?;
122//! }
123//! # Ok(())
124//! # }
125//! ```
126//!
127//! # Streaming
128//!
129//! Process NDJSON events in real time:
130//!
131//! ```no_run
132//! use claude_wrapper::{Claude, QueryCommand, OutputFormat};
133//! use claude_wrapper::streaming::{StreamEvent, stream_query};
134//!
135//! # async fn example() -> claude_wrapper::Result<()> {
136//! let claude = Claude::builder().build()?;
137//! let cmd = QueryCommand::new("explain quicksort")
138//!     .output_format(OutputFormat::StreamJson);
139//!
140//! let output = stream_query(&claude, &cmd, |event: StreamEvent| {
141//!     if event.is_result() {
142//!         println!("Result: {}", event.result_text().unwrap_or(""));
143//!     }
144//! }).await?;
145//! # Ok(())
146//! # }
147//! ```
148//!
149//! # Escape Hatch
150//!
151//! For subcommands or flags not yet covered by the typed API:
152//!
153//! ```no_run
154//! use claude_wrapper::{Claude, ClaudeCommand, RawCommand};
155//!
156//! # async fn example() -> claude_wrapper::Result<()> {
157//! let claude = Claude::builder().build()?;
158//! let output = RawCommand::new("some-future-command")
159//!     .arg("--new-flag")
160//!     .arg("value")
161//!     .execute(&claude)
162//!     .await?;
163//! # Ok(())
164//! # }
165//! ```
166
167pub mod command;
168pub mod error;
169pub mod exec;
170pub mod mcp_config;
171pub mod retry;
172pub mod streaming;
173pub mod types;
174pub mod version;
175
176use std::collections::HashMap;
177use std::path::{Path, PathBuf};
178use std::time::Duration;
179
180pub use command::ClaudeCommand;
181pub use command::agents::AgentsCommand;
182pub use command::auth::AuthStatusCommand;
183pub use command::doctor::DoctorCommand;
184pub use command::marketplace::{
185    MarketplaceAddCommand, MarketplaceListCommand, MarketplaceRemoveCommand,
186    MarketplaceUpdateCommand,
187};
188pub use command::mcp::{
189    McpAddCommand, McpAddFromDesktopCommand, McpAddJsonCommand, McpGetCommand, McpListCommand,
190    McpRemoveCommand, McpResetProjectChoicesCommand,
191};
192pub use command::plugin::{
193    PluginDisableCommand, PluginEnableCommand, PluginInstallCommand, PluginListCommand,
194    PluginUninstallCommand, PluginUpdateCommand, PluginValidateCommand,
195};
196pub use command::query::QueryCommand;
197pub use command::raw::RawCommand;
198pub use command::version::VersionCommand;
199pub use error::{Error, Result};
200pub use exec::CommandOutput;
201#[cfg(feature = "tempfile")]
202pub use mcp_config::TempMcpConfig;
203pub use mcp_config::{McpConfigBuilder, McpServerConfig};
204pub use retry::{BackoffStrategy, RetryPolicy};
205pub use types::*;
206pub use version::{CliVersion, VersionParseError};
207
208/// The Claude CLI client. Holds shared configuration applied to all commands.
209///
210/// Create one via [`Claude::builder()`] and reuse it across commands.
211#[derive(Debug, Clone)]
212pub struct Claude {
213    pub(crate) binary: PathBuf,
214    pub(crate) working_dir: Option<PathBuf>,
215    pub(crate) env: HashMap<String, String>,
216    pub(crate) global_args: Vec<String>,
217    pub(crate) timeout: Option<Duration>,
218    pub(crate) retry_policy: Option<RetryPolicy>,
219}
220
221impl Claude {
222    /// Create a new builder for configuring the Claude client.
223    #[must_use]
224    pub fn builder() -> ClaudeBuilder {
225        ClaudeBuilder::default()
226    }
227
228    /// Get the path to the claude binary.
229    #[must_use]
230    pub fn binary(&self) -> &Path {
231        &self.binary
232    }
233
234    /// Get the working directory, if set.
235    #[must_use]
236    pub fn working_dir(&self) -> Option<&Path> {
237        self.working_dir.as_deref()
238    }
239
240    /// Create a clone of this client with a different working directory.
241    #[must_use]
242    pub fn with_working_dir(&self, dir: impl Into<PathBuf>) -> Self {
243        let mut clone = self.clone();
244        clone.working_dir = Some(dir.into());
245        clone
246    }
247
248    /// Query the installed CLI version.
249    ///
250    /// Runs `claude --version` and parses the output into a [`CliVersion`].
251    ///
252    /// # Example
253    ///
254    /// ```no_run
255    /// # async fn example() -> claude_wrapper::Result<()> {
256    /// let claude = claude_wrapper::Claude::builder().build()?;
257    /// let version = claude.cli_version().await?;
258    /// println!("Claude CLI {version}");
259    /// # Ok(())
260    /// # }
261    /// ```
262    pub async fn cli_version(&self) -> Result<CliVersion> {
263        let output = VersionCommand::new().execute(self).await?;
264        CliVersion::parse_version_output(&output.stdout).map_err(|e| Error::Io {
265            message: format!("failed to parse CLI version: {e}"),
266            source: std::io::Error::new(std::io::ErrorKind::InvalidData, e.to_string()),
267        })
268    }
269
270    /// Check that the installed CLI version meets a minimum requirement.
271    ///
272    /// Returns the detected version on success, or an error if the version
273    /// is below the minimum.
274    ///
275    /// # Example
276    ///
277    /// ```no_run
278    /// use claude_wrapper::CliVersion;
279    ///
280    /// # async fn example() -> claude_wrapper::Result<()> {
281    /// let claude = claude_wrapper::Claude::builder().build()?;
282    /// let version = claude.check_version(&CliVersion::new(2, 1, 0)).await?;
283    /// println!("CLI version {version} meets minimum requirement");
284    /// # Ok(())
285    /// # }
286    /// ```
287    pub async fn check_version(&self, minimum: &CliVersion) -> Result<CliVersion> {
288        let version = self.cli_version().await?;
289        if version.satisfies_minimum(minimum) {
290            Ok(version)
291        } else {
292            Err(Error::VersionMismatch {
293                found: version,
294                minimum: *minimum,
295            })
296        }
297    }
298}
299
300/// Builder for creating a [`Claude`] client.
301///
302/// # Example
303///
304/// ```no_run
305/// use claude_wrapper::Claude;
306///
307/// # fn example() -> claude_wrapper::Result<()> {
308/// let claude = Claude::builder()
309///     .env("AWS_REGION", "us-west-2")
310///     .timeout_secs(120)
311///     .build()?;
312/// # Ok(())
313/// # }
314/// ```
315#[derive(Debug, Default)]
316pub struct ClaudeBuilder {
317    binary: Option<PathBuf>,
318    working_dir: Option<PathBuf>,
319    env: HashMap<String, String>,
320    global_args: Vec<String>,
321    timeout: Option<Duration>,
322    retry_policy: Option<RetryPolicy>,
323}
324
325impl ClaudeBuilder {
326    /// Set the path to the claude binary.
327    ///
328    /// If not set, the binary is resolved from PATH using `which`.
329    #[must_use]
330    pub fn binary(mut self, path: impl Into<PathBuf>) -> Self {
331        self.binary = Some(path.into());
332        self
333    }
334
335    /// Set the working directory for all commands.
336    ///
337    /// The spawned process will use this as its current directory.
338    #[must_use]
339    pub fn working_dir(mut self, path: impl Into<PathBuf>) -> Self {
340        self.working_dir = Some(path.into());
341        self
342    }
343
344    /// Add an environment variable to pass to all commands.
345    #[must_use]
346    pub fn env(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
347        self.env.insert(key.into(), value.into());
348        self
349    }
350
351    /// Add multiple environment variables.
352    #[must_use]
353    pub fn envs(
354        mut self,
355        vars: impl IntoIterator<Item = (impl Into<String>, impl Into<String>)>,
356    ) -> Self {
357        for (k, v) in vars {
358            self.env.insert(k.into(), v.into());
359        }
360        self
361    }
362
363    /// Set a default timeout for all commands (in seconds).
364    #[must_use]
365    pub fn timeout_secs(mut self, seconds: u64) -> Self {
366        self.timeout = Some(Duration::from_secs(seconds));
367        self
368    }
369
370    /// Set a default timeout for all commands.
371    #[must_use]
372    pub fn timeout(mut self, duration: Duration) -> Self {
373        self.timeout = Some(duration);
374        self
375    }
376
377    /// Add a global argument applied to all commands.
378    ///
379    /// This is an escape hatch for flags not yet covered by the API.
380    #[must_use]
381    pub fn arg(mut self, arg: impl Into<String>) -> Self {
382        self.global_args.push(arg.into());
383        self
384    }
385
386    /// Set a default retry policy for all commands.
387    ///
388    /// Individual commands can override this via their own retry settings.
389    ///
390    /// # Example
391    ///
392    /// ```no_run
393    /// use claude_wrapper::{Claude, RetryPolicy};
394    /// use std::time::Duration;
395    ///
396    /// # fn example() -> claude_wrapper::Result<()> {
397    /// let claude = Claude::builder()
398    ///     .retry(RetryPolicy::new()
399    ///         .max_attempts(3)
400    ///         .initial_backoff(Duration::from_secs(2))
401    ///         .exponential()
402    ///         .retry_on_timeout(true))
403    ///     .build()?;
404    /// # Ok(())
405    /// # }
406    /// ```
407    #[must_use]
408    pub fn retry(mut self, policy: RetryPolicy) -> Self {
409        self.retry_policy = Some(policy);
410        self
411    }
412
413    /// Build the Claude client, resolving the binary path.
414    pub fn build(self) -> Result<Claude> {
415        let binary = match self.binary {
416            Some(path) => path,
417            None => which::which("claude").map_err(|_| Error::NotFound)?,
418        };
419
420        Ok(Claude {
421            binary,
422            working_dir: self.working_dir,
423            env: self.env,
424            global_args: self.global_args,
425            timeout: self.timeout,
426            retry_policy: self.retry_policy,
427        })
428    }
429}
430
431#[cfg(test)]
432mod tests {
433    use super::*;
434
435    #[test]
436    fn test_builder_with_binary() {
437        let claude = Claude::builder()
438            .binary("/usr/local/bin/claude")
439            .env("FOO", "bar")
440            .timeout_secs(60)
441            .build()
442            .unwrap();
443
444        assert_eq!(claude.binary, PathBuf::from("/usr/local/bin/claude"));
445        assert_eq!(claude.env.get("FOO").unwrap(), "bar");
446        assert_eq!(claude.timeout, Some(Duration::from_secs(60)));
447    }
448
449    #[test]
450    fn test_builder_global_args() {
451        let claude = Claude::builder()
452            .binary("/usr/local/bin/claude")
453            .arg("--verbose")
454            .build()
455            .unwrap();
456
457        assert_eq!(claude.global_args, vec!["--verbose"]);
458    }
459}