claude-wrapper 0.13.3

A type-safe Claude Code CLI wrapper for Rust
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
//! Programmatic `.mcp.json` generation.
//!
//! [`McpConfigBuilder`] assembles HTTP and stdio MCP server entries and
//! serializes them to the `.mcp.json` shape the `claude` CLI expects,
//! either to a string, a caller-chosen path, or (with the `tempfile`
//! feature) a self-cleaning [`TempMcpConfig`] for one-shot use with
//! [`QueryCommand::mcp_config`](crate::QueryCommand::mcp_config).

use std::collections::HashMap;
use std::path::{Path, PathBuf};

use serde::Serialize;

use crate::error::Result;

/// Builder for generating `.mcp.json` config files programmatically.
///
/// This is useful when you need to dynamically configure MCP servers
/// for agent processes that communicate via MCP.
///
/// # Example
///
/// ```no_run
/// use claude_wrapper::McpConfigBuilder;
///
/// # fn example() -> claude_wrapper::Result<()> {
/// let config = McpConfigBuilder::new()
///     .http_server("my-hub", "http://127.0.0.1:9090")
///     .stdio_server("my-tool", "npx", ["my-mcp-server"])
///     .write_to("/tmp/my-project/.mcp.json")?;
/// # Ok(())
/// # }
/// ```
#[derive(Debug, Clone, Default)]
pub struct McpConfigBuilder {
    servers: HashMap<String, McpServerConfig>,
}

/// Configuration for a single MCP server entry.
#[derive(Debug, Clone, Serialize)]
#[serde(tag = "type")]
pub enum McpServerConfig {
    /// HTTP transport (streamable HTTP or SSE).
    #[serde(rename = "http")]
    Http {
        /// The server endpoint URL.
        url: String,
        /// Extra HTTP headers to send (e.g. auth).
        #[serde(skip_serializing_if = "HashMap::is_empty")]
        headers: HashMap<String, String>,
    },

    /// Stdio transport (subprocess).
    #[serde(rename = "stdio")]
    Stdio {
        /// The executable to launch.
        command: String,
        /// Arguments passed to the command.
        #[serde(skip_serializing_if = "Vec::is_empty")]
        args: Vec<String>,
        /// Environment variables set for the subprocess.
        #[serde(skip_serializing_if = "HashMap::is_empty")]
        env: HashMap<String, String>,
    },
}

/// Wrapper for serializing the full config file.
#[derive(Debug, Serialize)]
struct McpConfigFile {
    #[serde(rename = "mcpServers")]
    mcp_servers: HashMap<String, McpServerConfig>,
}

impl McpConfigBuilder {
    /// Create a new empty MCP config builder.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Add an HTTP MCP server.
    #[must_use]
    pub fn http_server(mut self, name: impl Into<String>, url: impl Into<String>) -> Self {
        self.servers.insert(
            name.into(),
            McpServerConfig::Http {
                url: url.into(),
                headers: HashMap::new(),
            },
        );
        self
    }

    /// Add an HTTP MCP server with custom headers.
    #[must_use]
    pub fn http_server_with_headers(
        mut self,
        name: impl Into<String>,
        url: impl Into<String>,
        headers: impl IntoIterator<Item = (impl Into<String>, impl Into<String>)>,
    ) -> Self {
        self.servers.insert(
            name.into(),
            McpServerConfig::Http {
                url: url.into(),
                headers: headers
                    .into_iter()
                    .map(|(k, v)| (k.into(), v.into()))
                    .collect(),
            },
        );
        self
    }

    /// Add a stdio MCP server.
    #[must_use]
    pub fn stdio_server(
        mut self,
        name: impl Into<String>,
        command: impl Into<String>,
        args: impl IntoIterator<Item = impl Into<String>>,
    ) -> Self {
        self.servers.insert(
            name.into(),
            McpServerConfig::Stdio {
                command: command.into(),
                args: args.into_iter().map(Into::into).collect(),
                env: HashMap::new(),
            },
        );
        self
    }

    /// Add a stdio MCP server with environment variables.
    #[must_use]
    pub fn stdio_server_with_env(
        mut self,
        name: impl Into<String>,
        command: impl Into<String>,
        args: impl IntoIterator<Item = impl Into<String>>,
        env: impl IntoIterator<Item = (impl Into<String>, impl Into<String>)>,
    ) -> Self {
        self.servers.insert(
            name.into(),
            McpServerConfig::Stdio {
                command: command.into(),
                args: args.into_iter().map(Into::into).collect(),
                env: env.into_iter().map(|(k, v)| (k.into(), v.into())).collect(),
            },
        );
        self
    }

    /// Add a raw server config.
    #[must_use]
    pub fn server(mut self, name: impl Into<String>, config: McpServerConfig) -> Self {
        self.servers.insert(name.into(), config);
        self
    }

    /// Serialize to JSON string.
    pub fn to_json(&self) -> Result<String> {
        let file = McpConfigFile {
            mcp_servers: self.servers.clone(),
        };

        #[cfg(feature = "json")]
        {
            serde_json::to_string_pretty(&file).map_err(|e| crate::error::Error::Json {
                message: "failed to serialize MCP config".to_string(),
                source: e,
            })
        }

        #[cfg(not(feature = "json"))]
        {
            let _ = file;
            Err(crate::error::Error::Io {
                message: "json feature required for MCP config serialization".to_string(),
                source: std::io::Error::new(
                    std::io::ErrorKind::Unsupported,
                    "json feature not enabled",
                ),
                working_dir: None,
            })
        }
    }

    /// Write the config to a file path, returning the path.
    pub fn write_to(&self, path: impl AsRef<Path>) -> Result<PathBuf> {
        let path = path.as_ref().to_path_buf();
        let json = self.to_json()?;

        if let Some(parent) = path.parent() {
            std::fs::create_dir_all(parent).map_err(|e| crate::error::Error::Io {
                message: format!("failed to create directory: {}", parent.display()),
                source: e,
                working_dir: None,
            })?;
        }

        std::fs::write(&path, json).map_err(|e| crate::error::Error::Io {
            message: format!("failed to write MCP config to {}", path.display()),
            source: e,
            working_dir: None,
        })?;

        Ok(path)
    }

    /// Write the config to a temporary file that is cleaned up on drop.
    ///
    /// Returns a [`TempMcpConfig`] that holds the temp file and provides
    /// the path for use with [`QueryCommand::mcp_config()`](crate::QueryCommand::mcp_config).
    ///
    /// # Example
    ///
    /// ```no_run
    /// use claude_wrapper::{Claude, ClaudeCommand, McpConfigBuilder, QueryCommand};
    ///
    /// # async fn example() -> claude_wrapper::Result<()> {
    /// let claude = Claude::builder().build()?;
    ///
    /// let config = McpConfigBuilder::new()
    ///     .http_server("hub", "http://localhost:9090")
    ///     .stdio_server("tool", "npx", ["my-server"])
    ///     .build_temp()?;
    ///
    /// let output = QueryCommand::new("list tools")
    ///     .mcp_config(config.path())
    ///     .execute(&claude)
    ///     .await?;
    /// // temp file is cleaned up when `config` is dropped
    /// # Ok(())
    /// # }
    /// ```
    #[cfg(feature = "tempfile")]
    pub fn build_temp(&self) -> Result<TempMcpConfig> {
        use std::io::Write;

        let json = self.to_json()?;
        let mut file = tempfile::Builder::new()
            .suffix(".mcp.json")
            .tempfile()
            .map_err(|e| crate::error::Error::Io {
                message: "failed to create temp MCP config file".to_string(),
                source: e,
                working_dir: None,
            })?;

        file.write_all(json.as_bytes())
            .map_err(|e| crate::error::Error::Io {
                message: "failed to write temp MCP config".to_string(),
                source: e,
                working_dir: None,
            })?;

        Ok(TempMcpConfig { file })
    }
}

/// A temporary MCP config file that is cleaned up when dropped.
///
/// Created by [`McpConfigBuilder::build_temp()`]. Use [`path()`](TempMcpConfig::path)
/// to get the file path for passing to [`QueryCommand::mcp_config()`](crate::QueryCommand::mcp_config).
#[cfg(feature = "tempfile")]
#[derive(Debug)]
pub struct TempMcpConfig {
    file: tempfile::NamedTempFile,
}

#[cfg(feature = "tempfile")]
impl TempMcpConfig {
    /// Get the path to the temporary config file.
    ///
    /// Returns a string suitable for passing to `QueryCommand::mcp_config()`.
    #[must_use]
    pub fn path(&self) -> &str {
        self.file
            .path()
            .to_str()
            .expect("temp file path is valid UTF-8")
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    #[cfg(feature = "json")]
    fn test_http_server_config() {
        let config = McpConfigBuilder::new().http_server("my-hub", "http://127.0.0.1:9090");

        let json = config.to_json().unwrap();
        assert!(json.contains("my-hub"));
        assert!(json.contains("http://127.0.0.1:9090"));
        assert!(json.contains(r#""type": "http""#));
    }

    #[test]
    #[cfg(feature = "json")]
    fn test_stdio_server_config() {
        let config = McpConfigBuilder::new().stdio_server(
            "my-tool",
            "npx",
            ["my-mcp-server", "--port", "3000"],
        );

        let json = config.to_json().unwrap();
        assert!(json.contains("my-tool"));
        assert!(json.contains("npx"));
        assert!(json.contains("my-mcp-server"));
        assert!(json.contains(r#""type": "stdio""#));
    }

    #[test]
    #[cfg(all(feature = "tempfile", feature = "json"))]
    fn test_build_temp() {
        let config = McpConfigBuilder::new()
            .http_server("hub", "http://localhost:9090")
            .stdio_server("tool", "echo", ["hello"]);

        let temp = config.build_temp().unwrap();
        let path = temp.path();
        assert!(path.ends_with(".mcp.json"));

        let contents = std::fs::read_to_string(path).unwrap();
        assert!(contents.contains("hub"));
        assert!(contents.contains("localhost:9090"));
    }

    #[test]
    #[cfg(feature = "json")]
    fn test_multiple_servers() {
        let config = McpConfigBuilder::new()
            .http_server("hub", "http://localhost:9090")
            .stdio_server("tool", "node", ["server.js"]);

        let json = config.to_json().unwrap();
        assert!(json.contains("hub"));
        assert!(json.contains("tool"));
    }

    // -- filesystem / constructor coverage (#681) -------------------

    #[test]
    #[cfg(feature = "json")]
    fn write_to_creates_parent_dirs_and_roundtrips() {
        // Nested path whose parent does not exist exercises create_dir_all.
        let dir = tempfile::tempdir().unwrap();
        let nested = dir.path().join("a/b/c/servers.mcp.json");

        let written = McpConfigBuilder::new()
            .http_server("hub", "http://localhost:9090")
            .stdio_server("tool", "node", ["server.js"])
            .write_to(&nested)
            .unwrap();

        assert_eq!(written, nested);
        assert!(nested.exists());

        let parsed: serde_json::Value =
            serde_json::from_str(&std::fs::read_to_string(&nested).unwrap()).unwrap();
        let servers = &parsed["mcpServers"];
        assert_eq!(servers["hub"]["type"], "http");
        assert_eq!(servers["hub"]["url"], "http://localhost:9090");
        assert_eq!(servers["tool"]["type"], "stdio");
        assert_eq!(servers["tool"]["command"], "node");
        assert_eq!(servers["tool"]["args"][0], "server.js");
    }

    #[test]
    #[cfg(feature = "json")]
    fn http_server_with_headers_serializes_headers() {
        let config = McpConfigBuilder::new().http_server_with_headers(
            "hub",
            "http://localhost:9090",
            [("Authorization", "Bearer token")],
        );
        let parsed: serde_json::Value = serde_json::from_str(&config.to_json().unwrap()).unwrap();
        let hub = &parsed["mcpServers"]["hub"];
        assert_eq!(hub["type"], "http");
        assert_eq!(hub["url"], "http://localhost:9090");
        assert_eq!(hub["headers"]["Authorization"], "Bearer token");
    }

    #[test]
    #[cfg(feature = "json")]
    fn stdio_server_with_env_serializes_env() {
        let config = McpConfigBuilder::new().stdio_server_with_env(
            "tool",
            "node",
            ["server.js"],
            [("API_KEY", "secret")],
        );
        let parsed: serde_json::Value = serde_json::from_str(&config.to_json().unwrap()).unwrap();
        let tool = &parsed["mcpServers"]["tool"];
        assert_eq!(tool["type"], "stdio");
        assert_eq!(tool["command"], "node");
        assert_eq!(tool["args"][0], "server.js");
        assert_eq!(tool["env"]["API_KEY"], "secret");
    }

    #[test]
    #[cfg(feature = "json")]
    fn raw_server_config_serializes() {
        let config = McpConfigBuilder::new().server(
            "raw",
            McpServerConfig::Http {
                url: "http://example.test".into(),
                headers: HashMap::new(),
            },
        );
        let parsed: serde_json::Value = serde_json::from_str(&config.to_json().unwrap()).unwrap();
        assert_eq!(parsed["mcpServers"]["raw"]["type"], "http");
        assert_eq!(parsed["mcpServers"]["raw"]["url"], "http://example.test");
    }

    #[test]
    #[cfg(all(feature = "tempfile", feature = "json"))]
    fn build_temp_roundtrips_to_parsed_servers() {
        let config = McpConfigBuilder::new().http_server_with_headers(
            "hub",
            "http://localhost:9090",
            [("X-Test", "1")],
        );

        let temp = config.build_temp().unwrap();
        assert!(temp.path().ends_with(".mcp.json"));

        let parsed: serde_json::Value =
            serde_json::from_str(&std::fs::read_to_string(temp.path()).unwrap()).unwrap();
        assert_eq!(parsed["mcpServers"]["hub"]["headers"]["X-Test"], "1");
    }
}