turbomcp-cli 3.0.12

Command-line tools for managing and testing MCP servers
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
//! Transport factory and auto-detection

use crate::cli::{Connection, TransportKind};
use crate::error::{CliError, CliResult};
use std::collections::HashMap;
use std::time::Duration;
use turbomcp_client::Client;
use turbomcp_protocol::types::Tool;

#[cfg(feature = "stdio")]
use turbomcp_transport::child_process::{ChildProcessConfig, ChildProcessTransport};

#[cfg(feature = "tcp")]
use turbomcp_transport::tcp::TcpTransportBuilder;

#[cfg(feature = "unix")]
use turbomcp_transport::unix::UnixTransportBuilder;

#[cfg(feature = "http")]
use turbomcp_transport::streamable_http_client::{
    StreamableHttpClientConfig, StreamableHttpClientTransport,
};

#[cfg(feature = "websocket")]
use turbomcp_transport::{WebSocketBidirectionalConfig, WebSocketBidirectionalTransport};

/// Wrapper for unified client operations, hiding transport implementation details
pub struct UnifiedClient {
    inner: ClientInner,
}

enum ClientInner {
    #[cfg(feature = "stdio")]
    Stdio(Client<ChildProcessTransport>),
    #[cfg(feature = "tcp")]
    Tcp(Client<turbomcp_transport::tcp::TcpTransport>),
    #[cfg(feature = "unix")]
    Unix(Client<turbomcp_transport::unix::UnixTransport>),
    #[cfg(feature = "http")]
    Http(Client<StreamableHttpClientTransport>),
    #[cfg(feature = "websocket")]
    WebSocket(Client<WebSocketBidirectionalTransport>),
}

impl UnifiedClient {
    pub async fn initialize(&self) -> CliResult<turbomcp_client::InitializeResult> {
        match &self.inner {
            #[cfg(feature = "stdio")]
            ClientInner::Stdio(client) => Ok(client.initialize().await?),
            #[cfg(feature = "tcp")]
            ClientInner::Tcp(client) => Ok(client.initialize().await?),
            #[cfg(feature = "unix")]
            ClientInner::Unix(client) => Ok(client.initialize().await?),
            #[cfg(feature = "http")]
            ClientInner::Http(client) => Ok(client.initialize().await?),
            #[cfg(feature = "websocket")]
            ClientInner::WebSocket(client) => Ok(client.initialize().await?),
        }
    }

    pub async fn list_tools(&self) -> CliResult<Vec<Tool>> {
        match &self.inner {
            #[cfg(feature = "stdio")]
            ClientInner::Stdio(client) => Ok(client.list_tools().await?),
            #[cfg(feature = "tcp")]
            ClientInner::Tcp(client) => Ok(client.list_tools().await?),
            #[cfg(feature = "unix")]
            ClientInner::Unix(client) => Ok(client.list_tools().await?),
            #[cfg(feature = "http")]
            ClientInner::Http(client) => Ok(client.list_tools().await?),
            #[cfg(feature = "websocket")]
            ClientInner::WebSocket(client) => Ok(client.list_tools().await?),
        }
    }

    pub async fn call_tool(
        &self,
        name: &str,
        arguments: Option<HashMap<String, serde_json::Value>>,
    ) -> CliResult<serde_json::Value> {
        let result = match &self.inner {
            #[cfg(feature = "stdio")]
            ClientInner::Stdio(client) => client.call_tool(name, arguments, None).await?,
            #[cfg(feature = "tcp")]
            ClientInner::Tcp(client) => client.call_tool(name, arguments, None).await?,
            #[cfg(feature = "unix")]
            ClientInner::Unix(client) => client.call_tool(name, arguments, None).await?,
            #[cfg(feature = "http")]
            ClientInner::Http(client) => client.call_tool(name, arguments, None).await?,
            #[cfg(feature = "websocket")]
            ClientInner::WebSocket(client) => client.call_tool(name, arguments, None).await?,
        };

        // Serialize CallToolResult to JSON for CLI display
        Ok(serde_json::to_value(result)?)
    }

    pub async fn list_resources(&self) -> CliResult<Vec<turbomcp_protocol::types::Resource>> {
        match &self.inner {
            #[cfg(feature = "stdio")]
            ClientInner::Stdio(client) => Ok(client.list_resources().await?),
            #[cfg(feature = "tcp")]
            ClientInner::Tcp(client) => Ok(client.list_resources().await?),
            #[cfg(feature = "unix")]
            ClientInner::Unix(client) => Ok(client.list_resources().await?),
            #[cfg(feature = "http")]
            ClientInner::Http(client) => Ok(client.list_resources().await?),
            #[cfg(feature = "websocket")]
            ClientInner::WebSocket(client) => Ok(client.list_resources().await?),
        }
    }

    pub async fn read_resource(
        &self,
        uri: &str,
    ) -> CliResult<turbomcp_protocol::types::ReadResourceResult> {
        match &self.inner {
            #[cfg(feature = "stdio")]
            ClientInner::Stdio(client) => Ok(client.read_resource(uri).await?),
            #[cfg(feature = "tcp")]
            ClientInner::Tcp(client) => Ok(client.read_resource(uri).await?),
            #[cfg(feature = "unix")]
            ClientInner::Unix(client) => Ok(client.read_resource(uri).await?),
            #[cfg(feature = "http")]
            ClientInner::Http(client) => Ok(client.read_resource(uri).await?),
            #[cfg(feature = "websocket")]
            ClientInner::WebSocket(client) => Ok(client.read_resource(uri).await?),
        }
    }

    pub async fn list_resource_templates(&self) -> CliResult<Vec<String>> {
        match &self.inner {
            #[cfg(feature = "stdio")]
            ClientInner::Stdio(client) => Ok(client.list_resource_templates().await?),
            #[cfg(feature = "tcp")]
            ClientInner::Tcp(client) => Ok(client.list_resource_templates().await?),
            #[cfg(feature = "unix")]
            ClientInner::Unix(client) => Ok(client.list_resource_templates().await?),
            #[cfg(feature = "http")]
            ClientInner::Http(client) => Ok(client.list_resource_templates().await?),
            #[cfg(feature = "websocket")]
            ClientInner::WebSocket(client) => Ok(client.list_resource_templates().await?),
        }
    }

    pub async fn subscribe(&self, uri: &str) -> CliResult<turbomcp_protocol::types::EmptyResult> {
        match &self.inner {
            #[cfg(feature = "stdio")]
            ClientInner::Stdio(client) => Ok(client.subscribe(uri).await?),
            #[cfg(feature = "tcp")]
            ClientInner::Tcp(client) => Ok(client.subscribe(uri).await?),
            #[cfg(feature = "unix")]
            ClientInner::Unix(client) => Ok(client.subscribe(uri).await?),
            #[cfg(feature = "http")]
            ClientInner::Http(client) => Ok(client.subscribe(uri).await?),
            #[cfg(feature = "websocket")]
            ClientInner::WebSocket(client) => Ok(client.subscribe(uri).await?),
        }
    }

    pub async fn unsubscribe(&self, uri: &str) -> CliResult<turbomcp_protocol::types::EmptyResult> {
        match &self.inner {
            #[cfg(feature = "stdio")]
            ClientInner::Stdio(client) => Ok(client.unsubscribe(uri).await?),
            #[cfg(feature = "tcp")]
            ClientInner::Tcp(client) => Ok(client.unsubscribe(uri).await?),
            #[cfg(feature = "unix")]
            ClientInner::Unix(client) => Ok(client.unsubscribe(uri).await?),
            #[cfg(feature = "http")]
            ClientInner::Http(client) => Ok(client.unsubscribe(uri).await?),
            #[cfg(feature = "websocket")]
            ClientInner::WebSocket(client) => Ok(client.unsubscribe(uri).await?),
        }
    }

    pub async fn list_prompts(&self) -> CliResult<Vec<turbomcp_protocol::types::Prompt>> {
        match &self.inner {
            #[cfg(feature = "stdio")]
            ClientInner::Stdio(client) => Ok(client.list_prompts().await?),
            #[cfg(feature = "tcp")]
            ClientInner::Tcp(client) => Ok(client.list_prompts().await?),
            #[cfg(feature = "unix")]
            ClientInner::Unix(client) => Ok(client.list_prompts().await?),
            #[cfg(feature = "http")]
            ClientInner::Http(client) => Ok(client.list_prompts().await?),
            #[cfg(feature = "websocket")]
            ClientInner::WebSocket(client) => Ok(client.list_prompts().await?),
        }
    }

    pub async fn get_prompt(
        &self,
        name: &str,
        arguments: Option<HashMap<String, serde_json::Value>>,
    ) -> CliResult<turbomcp_protocol::types::GetPromptResult> {
        match &self.inner {
            #[cfg(feature = "stdio")]
            ClientInner::Stdio(client) => Ok(client.get_prompt(name, arguments).await?),
            #[cfg(feature = "tcp")]
            ClientInner::Tcp(client) => Ok(client.get_prompt(name, arguments).await?),
            #[cfg(feature = "unix")]
            ClientInner::Unix(client) => Ok(client.get_prompt(name, arguments).await?),
            #[cfg(feature = "http")]
            ClientInner::Http(client) => Ok(client.get_prompt(name, arguments).await?),
            #[cfg(feature = "websocket")]
            ClientInner::WebSocket(client) => Ok(client.get_prompt(name, arguments).await?),
        }
    }

    pub async fn complete_prompt(
        &self,
        prompt_name: &str,
        argument_name: &str,
        argument_value: &str,
        context: Option<turbomcp_protocol::types::CompletionContext>,
    ) -> CliResult<turbomcp_protocol::types::CompletionResponse> {
        match &self.inner {
            #[cfg(feature = "stdio")]
            ClientInner::Stdio(client) => Ok(client
                .complete_prompt(prompt_name, argument_name, argument_value, context)
                .await?),
            #[cfg(feature = "tcp")]
            ClientInner::Tcp(client) => Ok(client
                .complete_prompt(prompt_name, argument_name, argument_value, context)
                .await?),
            #[cfg(feature = "unix")]
            ClientInner::Unix(client) => Ok(client
                .complete_prompt(prompt_name, argument_name, argument_value, context)
                .await?),
            #[cfg(feature = "http")]
            ClientInner::Http(client) => Ok(client
                .complete_prompt(prompt_name, argument_name, argument_value, context)
                .await?),
            #[cfg(feature = "websocket")]
            ClientInner::WebSocket(client) => Ok(client
                .complete_prompt(prompt_name, argument_name, argument_value, context)
                .await?),
        }
    }

    pub async fn complete_resource(
        &self,
        resource_uri: &str,
        argument_name: &str,
        argument_value: &str,
        context: Option<turbomcp_protocol::types::CompletionContext>,
    ) -> CliResult<turbomcp_protocol::types::CompletionResponse> {
        match &self.inner {
            #[cfg(feature = "stdio")]
            ClientInner::Stdio(client) => Ok(client
                .complete_resource(resource_uri, argument_name, argument_value, context)
                .await?),
            #[cfg(feature = "tcp")]
            ClientInner::Tcp(client) => Ok(client
                .complete_resource(resource_uri, argument_name, argument_value, context)
                .await?),
            #[cfg(feature = "unix")]
            ClientInner::Unix(client) => Ok(client
                .complete_resource(resource_uri, argument_name, argument_value, context)
                .await?),
            #[cfg(feature = "http")]
            ClientInner::Http(client) => Ok(client
                .complete_resource(resource_uri, argument_name, argument_value, context)
                .await?),
            #[cfg(feature = "websocket")]
            ClientInner::WebSocket(client) => Ok(client
                .complete_resource(resource_uri, argument_name, argument_value, context)
                .await?),
        }
    }

    pub async fn ping(&self) -> CliResult<()> {
        match &self.inner {
            #[cfg(feature = "stdio")]
            ClientInner::Stdio(client) => {
                client.ping().await?;
                Ok(())
            }
            #[cfg(feature = "tcp")]
            ClientInner::Tcp(client) => {
                client.ping().await?;
                Ok(())
            }
            #[cfg(feature = "unix")]
            ClientInner::Unix(client) => {
                client.ping().await?;
                Ok(())
            }
            #[cfg(feature = "http")]
            ClientInner::Http(client) => {
                client.ping().await?;
                Ok(())
            }
            #[cfg(feature = "websocket")]
            ClientInner::WebSocket(client) => {
                client.ping().await?;
                Ok(())
            }
        }
    }

    pub async fn set_log_level(&self, level: turbomcp_protocol::types::LogLevel) -> CliResult<()> {
        match &self.inner {
            #[cfg(feature = "stdio")]
            ClientInner::Stdio(client) => {
                client.set_log_level(level).await?;
                Ok(())
            }
            #[cfg(feature = "tcp")]
            ClientInner::Tcp(client) => {
                client.set_log_level(level).await?;
                Ok(())
            }
            #[cfg(feature = "unix")]
            ClientInner::Unix(client) => {
                client.set_log_level(level).await?;
                Ok(())
            }
            #[cfg(feature = "http")]
            ClientInner::Http(client) => {
                client.set_log_level(level).await?;
                Ok(())
            }
            #[cfg(feature = "websocket")]
            ClientInner::WebSocket(client) => {
                client.set_log_level(level).await?;
                Ok(())
            }
        }
    }
}

/// Create a unified client that hides transport type complexity from the executor
pub async fn create_client(conn: &Connection) -> CliResult<UnifiedClient> {
    let transport_kind = determine_transport(conn);

    match transport_kind {
        #[cfg(feature = "stdio")]
        TransportKind::Stdio => {
            let transport = create_stdio_transport(conn)?;
            Ok(UnifiedClient {
                inner: ClientInner::Stdio(Client::new(transport)),
            })
        }
        #[cfg(not(feature = "stdio"))]
        TransportKind::Stdio => {
            Err(CliError::NotSupported(
                "STDIO transport is not enabled (missing 'stdio' feature)".to_string(),
            ))
        }
        #[cfg(feature = "http")]
        TransportKind::Http => {
            let transport = create_http_transport(conn).await?;
            Ok(UnifiedClient {
                inner: ClientInner::Http(Client::new(transport)),
            })
        }
        #[cfg(not(feature = "http"))]
        TransportKind::Http => {
            Err(CliError::NotSupported(
                "HTTP transport is not enabled. Rebuild with --features http or --features all"
                    .to_string(),
            ))
        }
        #[cfg(feature = "websocket")]
        TransportKind::Ws => {
            let transport = create_websocket_transport(conn).await?;
            Ok(UnifiedClient {
                inner: ClientInner::WebSocket(Client::new(transport)),
            })
        }
        #[cfg(not(feature = "websocket"))]
        TransportKind::Ws => {
            Err(CliError::NotSupported(
                "WebSocket transport is not enabled. Rebuild with --features websocket or --features all"
                    .to_string(),
            ))
        }
        #[cfg(feature = "tcp")]
        TransportKind::Tcp => {
            let transport = create_tcp_transport(conn).await?;
            Ok(UnifiedClient {
                inner: ClientInner::Tcp(Client::new(transport)),
            })
        }
        #[cfg(not(feature = "tcp"))]
        TransportKind::Tcp => {
            Err(CliError::NotSupported(
                "TCP transport is not enabled (missing 'tcp' feature)".to_string(),
            ))
        }
        #[cfg(feature = "unix")]
        TransportKind::Unix => {
            let transport = create_unix_transport(conn).await?;
            Ok(UnifiedClient {
                inner: ClientInner::Unix(Client::new(transport)),
            })
        }
        #[cfg(not(feature = "unix"))]
        TransportKind::Unix => {
            Err(CliError::NotSupported(
                "Unix socket transport is not enabled (missing 'unix' feature)".to_string(),
            ))
        }
    }
}

/// Determine transport type from connection config
pub fn determine_transport(conn: &Connection) -> TransportKind {
    // Use explicit transport if provided
    if let Some(transport) = &conn.transport {
        return transport.clone();
    }

    // Auto-detect based on URL/command patterns
    let url = &conn.url;

    if conn.command.is_some() {
        return TransportKind::Stdio;
    }

    if url.starts_with("tcp://") {
        return TransportKind::Tcp;
    }

    if url.starts_with("unix://") || url.starts_with("/") {
        return TransportKind::Unix;
    }

    if url.starts_with("ws://") || url.starts_with("wss://") {
        return TransportKind::Ws;
    }

    if url.starts_with("http://") || url.starts_with("https://") {
        return TransportKind::Http;
    }

    // Default to STDIO for executable paths
    TransportKind::Stdio
}

/// Create STDIO transport from connection
#[cfg(feature = "stdio")]
fn create_stdio_transport(conn: &Connection) -> CliResult<ChildProcessTransport> {
    // Use --command if provided, otherwise use --url
    let command_str = conn.command.as_deref().unwrap_or(&conn.url);

    // Parse command and arguments
    let parts: Vec<&str> = command_str.split_whitespace().collect();
    if parts.is_empty() {
        return Err(CliError::InvalidArguments(
            "No command specified for STDIO transport".to_string(),
        ));
    }

    let command = parts[0].to_string();
    let args: Vec<String> = parts[1..].iter().map(|s| s.to_string()).collect();

    // Create config
    let config = ChildProcessConfig {
        command,
        args,
        working_directory: None,
        environment: None,
        startup_timeout: Duration::from_secs(conn.timeout),
        shutdown_timeout: Duration::from_secs(5),
        max_message_size: 10 * 1024 * 1024, // 10MB
        buffer_size: 8192,                  // 8KB buffer
        kill_on_drop: true,                 // Kill process when client is dropped
    };

    // Create transport
    Ok(ChildProcessTransport::new(config))
}

/// Create TCP transport from connection
#[cfg(feature = "tcp")]
async fn create_tcp_transport(
    conn: &Connection,
) -> CliResult<turbomcp_transport::tcp::TcpTransport> {
    let url = &conn.url;

    // Parse TCP URL
    let addr_str = url
        .strip_prefix("tcp://")
        .ok_or_else(|| CliError::InvalidArguments(format!("Invalid TCP URL: {}", url)))?;

    // Parse into SocketAddr
    let socket_addr: std::net::SocketAddr = addr_str.parse().map_err(|e| {
        CliError::InvalidArguments(format!("Invalid address '{}': {}", addr_str, e))
    })?;

    let transport = TcpTransportBuilder::new().remote_addr(socket_addr).build();

    Ok(transport)
}

/// Create Unix socket transport from connection
#[cfg(feature = "unix")]
async fn create_unix_transport(
    conn: &Connection,
) -> CliResult<turbomcp_transport::unix::UnixTransport> {
    let path = conn.url.strip_prefix("unix://").unwrap_or(&conn.url);

    let transport = UnixTransportBuilder::new_client().socket_path(path).build();

    Ok(transport)
}

/// Create HTTP transport from connection
#[cfg(feature = "http")]
async fn create_http_transport(conn: &Connection) -> CliResult<StreamableHttpClientTransport> {
    let url = &conn.url;

    // Parse HTTP URL (remove http:// or https://)
    let base_url = if let Some(stripped) = url.strip_prefix("https://") {
        format!("https://{}", stripped)
    } else if let Some(stripped) = url.strip_prefix("http://") {
        format!("http://{}", stripped)
    } else {
        url.clone()
    };

    let config = StreamableHttpClientConfig {
        base_url,
        endpoint_path: "/mcp".to_string(),
        timeout: Duration::from_secs(conn.timeout),
        ..Default::default()
    };

    Ok(StreamableHttpClientTransport::new(config))
}

/// Create WebSocket transport from connection
#[cfg(feature = "websocket")]
async fn create_websocket_transport(
    conn: &Connection,
) -> CliResult<WebSocketBidirectionalTransport> {
    let url = &conn.url;

    // Validate URL is a proper WebSocket URL
    if !url.starts_with("ws://") && !url.starts_with("wss://") {
        return Err(CliError::InvalidArguments(format!(
            "Invalid WebSocket URL: {} (must start with ws:// or wss://)",
            url
        )));
    }

    let config = WebSocketBidirectionalConfig::client(url.clone());

    WebSocketBidirectionalTransport::new(config)
        .await
        .map_err(|e| CliError::ConnectionFailed(e.to_string()))
}

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

    #[test]
    fn test_determine_transport() {
        // STDIO detection
        let conn = Connection {
            transport: None,
            url: "./my-server".to_string(),
            command: None,
            auth: None,
            timeout: 30,
        };
        assert_eq!(determine_transport(&conn), TransportKind::Stdio);

        // Command override
        let conn = Connection {
            transport: None,
            url: "http://localhost".to_string(),
            command: Some("python server.py".to_string()),
            auth: None,
            timeout: 30,
        };
        assert_eq!(determine_transport(&conn), TransportKind::Stdio);

        // TCP detection
        let conn = Connection {
            transport: None,
            url: "tcp://localhost:8080".to_string(),
            command: None,
            auth: None,
            timeout: 30,
        };
        assert_eq!(determine_transport(&conn), TransportKind::Tcp);

        // Unix detection
        let conn = Connection {
            transport: None,
            url: "/tmp/mcp.sock".to_string(),
            command: None,
            auth: None,
            timeout: 30,
        };
        assert_eq!(determine_transport(&conn), TransportKind::Unix);

        // Explicit override
        let conn = Connection {
            transport: Some(TransportKind::Tcp),
            url: "http://localhost".to_string(),
            command: None,
            auth: None,
            timeout: 30,
        };
        assert_eq!(determine_transport(&conn), TransportKind::Tcp);
    }
}