claude-wrapper 0.12.2

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
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
#[cfg(feature = "async")]
use crate::Claude;
use crate::command::ClaudeCommand;
#[cfg(feature = "async")]
use crate::error::Result;
#[cfg(feature = "async")]
use crate::exec;
use crate::exec::CommandOutput;
use crate::types::{Scope, Transport};

/// List configured MCP servers.
///
/// # Example
///
/// ```no_run
/// use claude_wrapper::{Claude, ClaudeCommand, McpListCommand};
///
/// # async fn example() -> claude_wrapper::Result<()> {
/// let claude = Claude::builder().build()?;
/// let output = McpListCommand::new().execute(&claude).await?;
/// println!("{}", output.stdout);
/// # Ok(())
/// # }
/// ```
#[derive(Debug, Clone, Default)]
pub struct McpListCommand;

impl McpListCommand {
    /// Creates a new MCP list command.
    #[must_use]
    pub fn new() -> Self {
        Self
    }
}

impl ClaudeCommand for McpListCommand {
    type Output = CommandOutput;

    fn args(&self) -> Vec<String> {
        vec!["mcp".to_string(), "list".to_string()]
    }

    #[cfg(feature = "async")]
    async fn execute(&self, claude: &Claude) -> Result<CommandOutput> {
        exec::run_claude(claude, self.args()).await
    }
}

/// Get details about a specific MCP server.
#[derive(Debug, Clone)]
pub struct McpGetCommand {
    name: String,
}

impl McpGetCommand {
    /// Creates a command to get details for a named MCP server.
    #[must_use]
    pub fn new(name: impl Into<String>) -> Self {
        Self { name: name.into() }
    }
}

impl ClaudeCommand for McpGetCommand {
    type Output = CommandOutput;

    fn args(&self) -> Vec<String> {
        vec!["mcp".to_string(), "get".to_string(), self.name.clone()]
    }

    #[cfg(feature = "async")]
    async fn execute(&self, claude: &Claude) -> Result<CommandOutput> {
        exec::run_claude(claude, self.args()).await
    }
}

/// Add an MCP server.
///
/// # Example
///
/// ```no_run
/// use claude_wrapper::{Claude, ClaudeCommand, McpAddCommand, Scope, Transport};
///
/// # async fn example() -> claude_wrapper::Result<()> {
/// let claude = Claude::builder().build()?;
///
/// // Add an HTTP MCP server
/// McpAddCommand::new("sentry", "https://mcp.sentry.dev/mcp")
///     .transport(Transport::Http)
///     .scope(Scope::User)
///     .execute(&claude)
///     .await?;
///
/// // Add a stdio MCP server with env vars
/// McpAddCommand::new("my-server", "npx")
///     .server_args(["my-mcp-server"])
///     .env("API_KEY", "xxx")
///     .scope(Scope::Local)
///     .execute(&claude)
///     .await?;
/// # Ok(())
/// # }
/// ```
#[derive(Debug, Clone)]
pub struct McpAddCommand {
    name: String,
    command_or_url: String,
    server_args: Vec<String>,
    transport: Option<Transport>,
    scope: Option<Scope>,
    env: Vec<(String, String)>,
    headers: Vec<String>,
    callback_port: Option<u16>,
    client_id: Option<String>,
    client_secret: bool,
}

impl McpAddCommand {
    /// Create a new MCP add command.
    #[must_use]
    pub fn new(name: impl Into<String>, command_or_url: impl Into<String>) -> Self {
        Self {
            name: name.into(),
            command_or_url: command_or_url.into(),
            server_args: Vec::new(),
            transport: None,
            scope: None,
            env: Vec::new(),
            headers: Vec::new(),
            callback_port: None,
            client_id: None,
            client_secret: false,
        }
    }

    /// Set the transport type.
    #[must_use]
    pub fn transport(mut self, transport: Transport) -> Self {
        self.transport = Some(transport);
        self
    }

    /// Set the configuration scope.
    #[must_use]
    pub fn scope(mut self, scope: Scope) -> Self {
        self.scope = Some(scope);
        self
    }

    /// Add an environment variable.
    #[must_use]
    pub fn env(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
        self.env.push((key.into(), value.into()));
        self
    }

    /// Add a header (for HTTP/SSE transport).
    #[must_use]
    pub fn header(mut self, header: impl Into<String>) -> Self {
        self.headers.push(header.into());
        self
    }

    /// Set additional arguments for the server command.
    #[must_use]
    pub fn server_args(mut self, args: impl IntoIterator<Item = impl Into<String>>) -> Self {
        self.server_args.extend(args.into_iter().map(Into::into));
        self
    }

    /// Set a fixed port for OAuth callback.
    #[must_use]
    pub fn callback_port(mut self, port: u16) -> Self {
        self.callback_port = Some(port);
        self
    }

    /// Set the OAuth client ID for HTTP/SSE servers.
    #[must_use]
    pub fn client_id(mut self, id: impl Into<String>) -> Self {
        self.client_id = Some(id.into());
        self
    }

    /// Enable prompting for OAuth client secret.
    #[must_use]
    pub fn client_secret(mut self) -> Self {
        self.client_secret = true;
        self
    }
}

impl ClaudeCommand for McpAddCommand {
    type Output = CommandOutput;

    fn args(&self) -> Vec<String> {
        let mut args = vec!["mcp".to_string(), "add".to_string()];

        if let Some(transport) = self.transport {
            args.push("--transport".to_string());
            args.push(transport.to_string());
        }

        if let Some(ref scope) = self.scope {
            args.push("--scope".to_string());
            args.push(scope.as_arg().to_string());
        }

        for (key, value) in &self.env {
            args.push("-e".to_string());
            args.push(format!("{key}={value}"));
        }

        for header in &self.headers {
            args.push("-H".to_string());
            args.push(header.clone());
        }

        if let Some(port) = self.callback_port {
            args.push("--callback-port".to_string());
            args.push(port.to_string());
        }

        if let Some(ref id) = self.client_id {
            args.push("--client-id".to_string());
            args.push(id.clone());
        }

        if self.client_secret {
            args.push("--client-secret".to_string());
        }

        args.push(self.name.clone());
        args.push(self.command_or_url.clone());

        if !self.server_args.is_empty() {
            args.push("--".to_string());
            args.extend(self.server_args.clone());
        }

        args
    }

    #[cfg(feature = "async")]
    async fn execute(&self, claude: &Claude) -> Result<CommandOutput> {
        exec::run_claude(claude, self.args()).await
    }
}

/// Add an MCP server using raw JSON configuration.
#[derive(Debug, Clone)]
pub struct McpAddJsonCommand {
    name: String,
    json: String,
    scope: Option<Scope>,
    client_secret: bool,
}

impl McpAddJsonCommand {
    /// Create a new MCP add-json command.
    #[must_use]
    pub fn new(name: impl Into<String>, json: impl Into<String>) -> Self {
        Self {
            name: name.into(),
            json: json.into(),
            scope: None,
            client_secret: false,
        }
    }

    /// Set the configuration scope.
    #[must_use]
    pub fn scope(mut self, scope: Scope) -> Self {
        self.scope = Some(scope);
        self
    }

    /// Prompt for the OAuth client secret (`--client-secret`; or set
    /// it via the `MCP_CLIENT_SECRET` env var).
    ///
    /// Parity with [`McpAddCommand::client_secret`].
    #[must_use]
    pub fn client_secret(mut self) -> Self {
        self.client_secret = true;
        self
    }
}

impl ClaudeCommand for McpAddJsonCommand {
    type Output = CommandOutput;

    fn args(&self) -> Vec<String> {
        let mut args = vec!["mcp".to_string(), "add-json".to_string()];

        if let Some(ref scope) = self.scope {
            args.push("--scope".to_string());
            args.push(scope.as_arg().to_string());
        }

        if self.client_secret {
            args.push("--client-secret".to_string());
        }

        args.push(self.name.clone());
        args.push(self.json.clone());

        args
    }

    #[cfg(feature = "async")]
    async fn execute(&self, claude: &Claude) -> Result<CommandOutput> {
        exec::run_claude(claude, self.args()).await
    }
}

/// Remove an MCP server.
#[derive(Debug, Clone)]
pub struct McpRemoveCommand {
    name: String,
    scope: Option<Scope>,
}

impl McpRemoveCommand {
    /// Creates a command to remove a named MCP server.
    #[must_use]
    pub fn new(name: impl Into<String>) -> Self {
        Self {
            name: name.into(),
            scope: None,
        }
    }

    /// Set the configuration scope.
    #[must_use]
    pub fn scope(mut self, scope: Scope) -> Self {
        self.scope = Some(scope);
        self
    }
}

impl ClaudeCommand for McpRemoveCommand {
    type Output = CommandOutput;

    fn args(&self) -> Vec<String> {
        let mut args = vec!["mcp".to_string(), "remove".to_string()];

        if let Some(ref scope) = self.scope {
            args.push("--scope".to_string());
            args.push(scope.as_arg().to_string());
        }

        args.push(self.name.clone());

        args
    }

    #[cfg(feature = "async")]
    async fn execute(&self, claude: &Claude) -> Result<CommandOutput> {
        exec::run_claude(claude, self.args()).await
    }
}

/// Import MCP servers from Claude Desktop (Mac and WSL only).
#[derive(Debug, Clone, Default)]
pub struct McpAddFromDesktopCommand {
    scope: Option<Scope>,
}

impl McpAddFromDesktopCommand {
    /// Creates a command to import MCP servers from the Claude Desktop config.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Set the configuration scope.
    #[must_use]
    pub fn scope(mut self, scope: Scope) -> Self {
        self.scope = Some(scope);
        self
    }
}

impl ClaudeCommand for McpAddFromDesktopCommand {
    type Output = CommandOutput;

    fn args(&self) -> Vec<String> {
        let mut args = vec!["mcp".to_string(), "add-from-claude-desktop".to_string()];
        if let Some(ref scope) = self.scope {
            args.push("--scope".to_string());
            args.push(scope.as_arg().to_string());
        }
        args
    }

    #[cfg(feature = "async")]
    async fn execute(&self, claude: &Claude) -> Result<CommandOutput> {
        exec::run_claude(claude, self.args()).await
    }
}

/// Start the Claude Code MCP server.
///
/// # Example
///
/// ```no_run
/// use claude_wrapper::{Claude, ClaudeCommand, McpServeCommand};
///
/// # async fn example() -> claude_wrapper::Result<()> {
/// let claude = Claude::builder().build()?;
/// McpServeCommand::new()
///     .verbose()
///     .execute(&claude)
///     .await?;
/// # Ok(())
/// # }
/// ```
#[derive(Debug, Clone, Default)]
pub struct McpServeCommand {
    debug: bool,
    verbose: bool,
}

impl McpServeCommand {
    /// Create a new MCP serve command.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Enable debug output.
    #[must_use]
    pub fn debug(mut self) -> Self {
        self.debug = true;
        self
    }

    /// Enable verbose output.
    #[must_use]
    pub fn verbose(mut self) -> Self {
        self.verbose = true;
        self
    }
}

impl ClaudeCommand for McpServeCommand {
    type Output = CommandOutput;

    fn args(&self) -> Vec<String> {
        let mut args = vec!["mcp".to_string(), "serve".to_string()];
        if self.debug {
            args.push("--debug".to_string());
        }
        if self.verbose {
            args.push("--verbose".to_string());
        }
        args
    }

    #[cfg(feature = "async")]
    async fn execute(&self, claude: &Claude) -> Result<CommandOutput> {
        exec::run_claude(claude, self.args()).await
    }
}

/// Reset all approved and rejected project-scoped MCP servers.
#[derive(Debug, Clone, Default)]
pub struct McpResetProjectChoicesCommand;

impl McpResetProjectChoicesCommand {
    #[must_use]
    pub fn new() -> Self {
        Self
    }
}

impl ClaudeCommand for McpResetProjectChoicesCommand {
    type Output = CommandOutput;

    fn args(&self) -> Vec<String> {
        vec!["mcp".to_string(), "reset-project-choices".to_string()]
    }

    #[cfg(feature = "async")]
    async fn execute(&self, claude: &Claude) -> Result<CommandOutput> {
        exec::run_claude(claude, self.args()).await
    }
}

/// Authenticate with an MCP server (HTTP, SSE, or claude.ai connector).
///
/// Drives an interactive OAuth flow. By default the CLI opens a browser;
/// use [`Self::no_browser`] for SSH/headless sessions, where the CLI
/// prints the authorization URL and waits for the redirect URL to be
/// pasted back.
#[derive(Debug, Clone)]
pub struct McpLoginCommand {
    name: String,
    no_browser: bool,
}

impl McpLoginCommand {
    /// Creates a command to authenticate with a named MCP server.
    #[must_use]
    pub fn new(name: impl Into<String>) -> Self {
        Self {
            name: name.into(),
            no_browser: false,
        }
    }

    /// Print the authorization URL instead of opening a browser
    /// (`--no-browser`), for SSH/headless sessions.
    #[must_use]
    pub fn no_browser(mut self) -> Self {
        self.no_browser = true;
        self
    }
}

impl ClaudeCommand for McpLoginCommand {
    type Output = CommandOutput;

    fn args(&self) -> Vec<String> {
        let mut args = vec!["mcp".to_string(), "login".to_string()];
        if self.no_browser {
            args.push("--no-browser".to_string());
        }
        args.push(self.name.clone());
        args
    }

    #[cfg(feature = "async")]
    async fn execute(&self, claude: &Claude) -> Result<CommandOutput> {
        exec::run_claude(claude, self.args()).await
    }
}

/// Clear stored OAuth credentials for an MCP server.
#[derive(Debug, Clone)]
pub struct McpLogoutCommand {
    name: String,
}

impl McpLogoutCommand {
    /// Creates a command to clear stored credentials for a named MCP server.
    #[must_use]
    pub fn new(name: impl Into<String>) -> Self {
        Self { name: name.into() }
    }
}

impl ClaudeCommand for McpLogoutCommand {
    type Output = CommandOutput;

    fn args(&self) -> Vec<String> {
        vec!["mcp".to_string(), "logout".to_string(), self.name.clone()]
    }

    #[cfg(feature = "async")]
    async fn execute(&self, claude: &Claude) -> Result<CommandOutput> {
        exec::run_claude(claude, self.args()).await
    }
}

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

    #[test]
    fn test_mcp_list_args() {
        let cmd = McpListCommand::new();
        assert_eq!(cmd.args(), vec!["mcp", "list"]);
    }

    #[test]
    fn test_mcp_get_args() {
        let cmd = McpGetCommand::new("my-server");
        assert_eq!(cmd.args(), vec!["mcp", "get", "my-server"]);
    }

    #[test]
    fn test_mcp_add_http() {
        let cmd = McpAddCommand::new("sentry", "https://mcp.sentry.dev/mcp")
            .transport(Transport::Http)
            .scope(Scope::User);

        let args = cmd.args();
        assert_eq!(
            args,
            vec![
                "mcp",
                "add",
                "--transport",
                "http",
                "--scope",
                "user",
                "sentry",
                "https://mcp.sentry.dev/mcp"
            ]
        );
    }

    #[test]
    fn test_mcp_add_stdio_with_env() {
        let cmd = McpAddCommand::new("my-server", "npx")
            .env("API_KEY", "xxx")
            .server_args(["my-mcp-server"]);

        let args = cmd.args();
        assert_eq!(
            args,
            vec![
                "mcp",
                "add",
                "-e",
                "API_KEY=xxx",
                "my-server",
                "npx",
                "--",
                "my-mcp-server"
            ]
        );
    }

    #[test]
    fn test_mcp_add_oauth_flags() {
        let cmd = McpAddCommand::new("my-server", "https://example.com/mcp")
            .transport(Transport::Http)
            .callback_port(8080)
            .client_id("my-app-id")
            .client_secret();

        let args = cmd.args();
        assert_eq!(
            args,
            vec![
                "mcp",
                "add",
                "--transport",
                "http",
                "--callback-port",
                "8080",
                "--client-id",
                "my-app-id",
                "--client-secret",
                "my-server",
                "https://example.com/mcp"
            ]
        );
    }

    #[test]
    fn test_mcp_add_json_basic() {
        let cmd = McpAddJsonCommand::new("srv", r#"{"command":"npx"}"#).scope(Scope::User);
        assert_eq!(
            cmd.args(),
            vec![
                "mcp",
                "add-json",
                "--scope",
                "user",
                "srv",
                r#"{"command":"npx"}"#
            ]
        );
    }

    #[test]
    fn test_mcp_add_json_client_secret() {
        // #601 parity: add-json accepts --client-secret like add does.
        let cmd = McpAddJsonCommand::new("srv", "{}").client_secret();
        assert_eq!(
            cmd.args(),
            vec!["mcp", "add-json", "--client-secret", "srv", "{}"]
        );
    }

    #[test]
    fn test_mcp_add_json_no_client_secret_by_default() {
        let cmd = McpAddJsonCommand::new("srv", "{}");
        assert!(!cmd.args().contains(&"--client-secret".to_string()));
    }

    #[test]
    fn test_mcp_remove_args() {
        let cmd = McpRemoveCommand::new("old-server").scope(Scope::Project);
        assert_eq!(
            cmd.args(),
            vec!["mcp", "remove", "--scope", "project", "old-server"]
        );
    }

    #[test]
    fn test_mcp_add_from_desktop() {
        let cmd = McpAddFromDesktopCommand::new().scope(Scope::User);
        assert_eq!(
            cmd.args(),
            vec!["mcp", "add-from-claude-desktop", "--scope", "user"]
        );
    }

    #[test]
    fn test_mcp_reset_project_choices() {
        let cmd = McpResetProjectChoicesCommand::new();
        assert_eq!(cmd.args(), vec!["mcp", "reset-project-choices"]);
    }

    #[test]
    fn test_mcp_serve_default() {
        let cmd = McpServeCommand::new();
        assert_eq!(cmd.args(), vec!["mcp", "serve"]);
    }

    #[test]
    fn test_mcp_serve_with_flags() {
        let cmd = McpServeCommand::new().debug().verbose();
        assert_eq!(cmd.args(), vec!["mcp", "serve", "--debug", "--verbose"]);
    }

    #[test]
    fn test_mcp_login_args() {
        let cmd = McpLoginCommand::new("sentry");
        assert_eq!(cmd.args(), vec!["mcp", "login", "sentry"]);
    }

    #[test]
    fn test_mcp_login_no_browser() {
        let cmd = McpLoginCommand::new("sentry").no_browser();
        assert_eq!(cmd.args(), vec!["mcp", "login", "--no-browser", "sentry"]);
    }

    #[test]
    fn test_mcp_logout_args() {
        let cmd = McpLogoutCommand::new("sentry");
        assert_eq!(cmd.args(), vec!["mcp", "logout", "sentry"]);
    }
}