turbomcp-client 2.0.0

MCP client implementation with connection management and error recovery
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
# TurboMCP Client

[![Crates.io](https://img.shields.io/crates/v/turbomcp-client.svg)](https://crates.io/crates/turbomcp-client)
[![Documentation](https://docs.rs/turbomcp-client/badge.svg)](https://docs.rs/turbomcp-client)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)

MCP client with complete MCP 2025-06-18 specification support and plugin middleware system.

## Table of Contents

- [Overview]#overview
- [Supported Transports]#supported-transports
- [Quick Start]#quick-start
- [Transport Configuration]#transport-configuration
- [Advanced Features]#advanced-features
- [Plugin Middleware]#plugin-middleware
- [Sampling Handler Integration]#sampling-handler-integration
- [Handler Registration]#handler-registration
- [Error Handling]#error-handling
- [Production Deployment]#production-deployment

## Overview

`turbomcp-client` provides a comprehensive MCP client implementation with:
- **Full MCP 2025-06-18 compliance** - All server and client features
-**Bidirectional communication** - Server-initiated requests (sampling, elicitation)
-**Plugin middleware** - Extensible request/response processing
-**Sampling protocol support** - Handle server-initiated sampling requests
-**Transport agnostic** - Works with STDIO, TCP, Unix, WebSocket transports
-**Thread-safe sharing** - Client is cheaply cloneable via Arc for concurrent async tasks

## Supported Transports

| Transport | Status | Feature Flag | Use Case |
|-----------|--------|--------------|----------|
| **STDIO** | ✅ Full | default | Local process communication |
| **HTTP/SSE** | ✅ Full | `http` | Web-compatible HTTP servers (New in 2.0!) |
| **TCP** | ✅ Full | `tcp` | Network socket communication |
| **Unix** | ✅ Full | `unix` | Fast local IPC |
| **WebSocket** | ✅ Full | `websocket` | Real-time bidirectional |

> **New in 2.0**: HTTP/SSE client transport with `Client::connect_http()` convenience API!

## Quick Start

### Basic Client (STDIO)

```rust
use turbomcp_client::Client;
use turbomcp_transport::stdio::StdioTransport;

#[tokio::main]
async fn main() -> turbomcp_protocol::Result<()> {
    // Create client with STDIO transport
    let transport = StdioTransport::new();
    let client = Client::new(transport);

    // Initialize connection
    let result = client.initialize().await?;
    println!("Connected to: {}", result.server_info.name);

    // List and call tools
    let tools = client.list_tools().await?;
    for tool in &tools {
        println!("Tool: {} - {}", tool.name,
            tool.description.as_deref().unwrap_or("No description"));
    }

    // Call a tool
    let result = client.call_tool("calculator", Some(
        std::collections::HashMap::from([
            ("operation".to_string(), serde_json::json!("add")),
            ("a".to_string(), serde_json::json!(5)),
            ("b".to_string(), serde_json::json!(3)),
        ])
    )).await?;

    println!("Result: {}", result);
    Ok(())
}
```

### HTTP Client (One-Liner)

```rust
use turbomcp_client::Client;

#[tokio::main]
async fn main() -> turbomcp_protocol::Result<()> {
    // One-liner - connects and initializes automatically
    let client = Client::connect_http("http://localhost:8080").await?;

    // Ready to use immediately
    let tools = client.list_tools().await?;
    println!("Found {} tools", tools.len());

    Ok(())
}
```

### TCP/Unix Clients

```rust
// TCP
let client = Client::connect_tcp("127.0.0.1:8765").await?;

// Unix socket
let client = Client::connect_unix("/tmp/mcp.sock").await?;
```

### With ClientBuilder

```rust
use turbomcp_client::ClientBuilder;
use turbomcp_transport::stdio::StdioTransport;

let client = ClientBuilder::new()
    .with_tools(true)
    .with_prompts(true)
    .with_resources(true)
    .with_sampling(false)
    .build(StdioTransport::new())
    .await?;
```

### Cloning Client for Concurrent Usage

```rust
use turbomcp_client::Client;
use turbomcp_transport::stdio::StdioTransport;

// Create client (cheaply cloneable via Arc)
let client = Client::new(StdioTransport::new());

// Initialize once
client.initialize().await?;

// Clone for multiple async tasks - this is cheap (just Arc clone)
let client1 = client.clone();
let client2 = client.clone();

let handle1 = tokio::spawn(async move {
    client1.list_tools().await
});

let handle2 = tokio::spawn(async move {
    client2.list_prompts().await
});

let (tools, prompts) = tokio::try_join!(handle1, handle2)?;
```

## Transport Configuration

### STDIO Transport (Default)

```rust
use turbomcp_transport::stdio::StdioTransport;

// Direct STDIO
let transport = StdioTransport::new();
let mut client = Client::new(transport);
```

### HTTP Transport (New in 2.0!)

```rust
use turbomcp_client::Client;

// One-liner - connects and initializes automatically
let client = Client::connect_http("http://localhost:8080").await?;
```

Or with custom configuration:

```rust
use turbomcp_client::Client;
use std::time::Duration;

let client = Client::connect_http_with("http://localhost:8080", |config| {
    config.timeout = Duration::from_secs(60);
    config.endpoint_path = "/api/mcp".to_string();
}).await?;
```

### TCP Transport

```rust
use turbomcp_client::Client;

// One-liner - connects and initializes automatically
let client = Client::connect_tcp("127.0.0.1:8765").await?;
```

Or using transport directly:

```rust
use turbomcp_transport::tcp::TcpTransport;
use std::net::SocketAddr;

let server_addr: SocketAddr = "127.0.0.1:8765".parse()?;
let bind_addr: SocketAddr = "0.0.0.0:0".parse()?;  // Any available port
let transport = TcpTransport::new_client(bind_addr, server_addr);
let mut client = Client::new(transport);
client.initialize().await?;
```

### Unix Socket Transport

```rust
use turbomcp_client::Client;

// One-liner - connects and initializes automatically
let client = Client::connect_unix("/tmp/mcp.sock").await?;
```

Or using transport directly:

```rust
use turbomcp_transport::unix::UnixTransport;
use std::path::PathBuf;

let transport = UnixTransport::new_client(PathBuf::from("/tmp/mcp.sock"));
let mut client = Client::new(transport);
client.initialize().await?;
```

### WebSocket Transport

```rust
use turbomcp_transport::websocket_bidirectional::{
    WebSocketBidirectionalTransport,
    WebSocketBidirectionalConfig,
};

let config = WebSocketBidirectionalConfig {
    url: Some("ws://localhost:8080".to_string()),
    ..Default::default()
};

let transport = WebSocketBidirectionalTransport::new(config).await?;
let mut client = Client::new(transport);
```

## Advanced Features

### Robust Transport with Retry & Circuit Breaker

```rust
use turbomcp_client::ClientBuilder;
use turbomcp_transport::stdio::StdioTransport;

// Configure retry and health checking
let client = ClientBuilder::new()
    .with_max_retries(3)      // Configure retry attempts
    .with_retry_delay(100)    // Retry delay in milliseconds
    .with_keepalive(30_000)   // Keepalive interval
    .build(StdioTransport::new())
    .await?;
```

### Additional Configuration Options

```rust
use turbomcp_client::ClientBuilder;
use turbomcp_transport::stdio::StdioTransport;
use std::time::Duration;

let client = ClientBuilder::new()
    // Configure capabilities needed from the server
    .with_tools(true)
    .with_prompts(true)
    .with_resources(true)
    // Configure timeouts and retries
    .with_timeout(30_000)          // 30 second timeout
    .with_max_retries(3)           // Retry up to 3 times
    .with_retry_delay(100)         // 100ms delay between retries
    .with_keepalive(30_000)        // 30 second keepalive
    // Build the client
    .build(StdioTransport::new())
    .await?;
```

### Plugin Middleware

```rust
use turbomcp_client::ClientBuilder;
use turbomcp_client::plugins::{MetricsPlugin, PluginConfig};
use std::sync::Arc;

let client = ClientBuilder::new()
    .with_plugin(Arc::new(MetricsPlugin::new(PluginConfig::Metrics)))
    .build(StdioTransport::new())
    .await?;
```

### Sampling Handler Integration

Handle server-initiated sampling requests by implementing a custom sampling handler:

```rust
use turbomcp_client::sampling::SamplingHandler;
use turbomcp_protocol::types::{CreateMessageRequest, CreateMessageResult, Role, Content, TextContent};
use async_trait::async_trait;
use std::sync::Arc;

#[derive(Debug)]
struct MySamplingHandler {
    // Your LLM integration (OpenAI, Anthropic, local model, etc.)
}

#[async_trait]
impl SamplingHandler for MySamplingHandler {
    async fn handle_create_message(&self, request_id: String, request: CreateMessageRequest)
        -> Result<CreateMessageResult, Box<dyn std::error::Error + Send + Sync>>
    {
        // Forward to your LLM service
        // Use request_id for correlation/tracking
        // Return the generated response
        Ok(CreateMessageResult {
            role: Role::Assistant,
            content: Content::Text(TextContent {
                text: "Generated response".to_string(),
                annotations: None,
                meta: None,
            }),
            model: Some("your-model".to_string()),
            stop_reason: None,
        })
    }
}

// Register the handler
let handler = Arc::new(MySamplingHandler { /* ... */ });
client.set_sampling_handler(handler);
```

**Note:** TurboMCP provides the sampling protocol infrastructure. You implement your own LLM integration (OpenAI SDK, Anthropic SDK, local models, etc.) as needed for your use case.

### Handler Registration

```rust
use turbomcp_client::handlers::{ElicitationHandler, ElicitationRequest, ElicitationResponse};
use async_trait::async_trait;
use std::sync::Arc;

#[derive(Debug)]
struct MyElicitationHandler;

#[async_trait]
impl ElicitationHandler for MyElicitationHandler {
    async fn handle_elicitation(&self, request: ElicitationRequest)
        -> Result<ElicitationResponse, Box<dyn std::error::Error + Send + Sync>>
    {
        // Prompt user for input based on request.schema
        let user_input = collect_user_input(request.schema)?;
        Ok(ElicitationResponse {
            action: ElicitationAction::Accept,
            content: Some(user_input),
        })
    }
}

let client = ClientBuilder::new()
    .with_elicitation_handler(Arc::new(MyElicitationHandler))
    .build(StdioTransport::new())
    .await?;
```

## MCP Operations

### Tools

```rust
// List available tools
let tools = client.list_tools().await?;
for tool in &tools {
    println!("{}: {}", tool.name, tool.description.as_deref().unwrap_or(""));
}

// List tool names only
let names = client.list_tool_names().await?;

// Call a tool
use std::collections::HashMap;
let mut args = HashMap::new();
args.insert("text".to_string(), serde_json::json!("Hello, world!"));
let result = client.call_tool("echo", Some(args)).await?;
```

### Prompts

```rust
use turbomcp_protocol::types::PromptInput;

// List prompts
let prompts = client.list_prompts().await?;

// Get prompt with arguments
let prompt_args = PromptInput {
    arguments: Some(std::collections::HashMap::from([
        ("language".to_string(), "rust".to_string()),
        ("topic".to_string(), "async programming".to_string()),
    ])),
};

let result = client.get_prompt("code_review", Some(prompt_args)).await?;
println!("Prompt: {}", result.description.unwrap_or_default());
for message in result.messages {
    println!("{:?}: {}", message.role, message.content);
}
```

### Resources

```rust
// List resources
let resources = client.list_resources().await?;

// Read a resource
let content = client.read_resource("file:///etc/hosts").await?;

// List resource templates
let templates = client.list_resource_templates().await?;
```

### Completions

```rust
use turbomcp_protocol::types::CompletionContext;

// Complete a prompt argument
let completions = client.complete_prompt(
    "code_review",
    "framework",
    "tok",  // Partial input
    None
).await?;

for value in completions.completion.values {
    println!("Suggestion: {}", value);
}

// Complete with context
let mut context_args = std::collections::HashMap::new();
context_args.insert("language".to_string(), "rust".to_string());
let context = CompletionContext { arguments: Some(context_args) };

let completions = client.complete_prompt(
    "code_review",
    "framework",
    "tok",
    Some(context)
).await?;
```

### Subscriptions

```rust
use turbomcp_protocol::types::LogLevel;

// Subscribe to resource updates
client.subscribe("file:///config.json").await?;

// Set logging level
client.set_log_level(LogLevel::Debug).await?;

// Unsubscribe
client.unsubscribe("file:///config.json").await?;
```

### Health Monitoring

```rust
// Send ping to check connection
let ping_result = client.ping().await?;
println!("Server responded: {:?}", ping_result);
```

## Bidirectional Communication

### Processing Server-Initiated Requests

```rust
use turbomcp_client::Client;
use turbomcp_transport::stdio::StdioTransport;

// Create and initialize client
let client = Client::new(StdioTransport::new());
client.initialize().await?;

// Message processing is automatic! The MessageDispatcher runs in the background.
// No need for manual message loops - just use the client directly.

// Perform operations - bidirectional communication works automatically
let tools = client.list_tools().await?;
```

## Error Handling

```rust
use turbomcp_protocol::Error;

match client.call_tool("my_tool", None).await {
    Ok(result) => println!("Success: {}", result),
    Err(Error::Transport(msg)) => eprintln!("Transport error: {}", msg),
    Err(Error::Protocol(msg)) => eprintln!("Protocol error: {}", msg),
    Err(Error::BadRequest(msg)) => eprintln!("Bad request: {}", msg),
    Err(e) => eprintln!("Error: {}", e),
}
```

## Examples

See the `examples/` directory for complete working examples:

- **`sampling_client.rs`** - Client with server-initiated sampling protocol
- **`elicitation_interactive_client.rs`** - Interactive elicitation handling

Run examples:
```bash
cargo run --example sampling_client --features websocket
cargo run --example elicitation_interactive_client
```

## Feature Flags

| Feature | Description | Status |
|---------|-------------|--------|
| `default` | STDIO transport only ||
| `tcp` | TCP transport ||
| `unix` | Unix socket transport ||
| `websocket` | WebSocket transport ||
| `http` | HTTP/SSE (server-side only) | ⚠️ |

Enable features in `Cargo.toml`:
```toml
[dependencies]
turbomcp-client = { version = "2.0.0", features = ["tcp", "websocket"] }
```

## Architecture

```
┌─────────────────────────────────────────────┐
│            Application Code                 │
└─────────────────────────────────────────────┘
┌─────────────────────────────────────────────┐
│           Client API (Clone-able)           │
│  ├── initialize(), list_tools(), etc.      │
│  ├── Handler Registry (elicitation, etc.)  │
│  └── Plugin Registry (metrics, etc.)       │
└─────────────────────────────────────────────┘
┌─────────────────────────────────────────────┐
│       Protocol Layer (JSON-RPC)             │
│  ├── Request/Response correlation          │
│  ├── Bidirectional message routing         │
│  └── Capability negotiation                │
└─────────────────────────────────────────────┘
┌─────────────────────────────────────────────┐
│       Transport Layer                       │
│  ├── STDIO, TCP, Unix, WebSocket           │
│  ├── RobustTransport (retry, circuit)      │
│  └── Connection management                 │
└─────────────────────────────────────────────┘
```

## Development

### Building

```bash
# Build with default features (STDIO only)
cargo build

# Build with all transport features
cargo build --features tcp,unix,websocket,http

# Build with robustness features
cargo build --all-features
```

### Testing

```bash
# Run unit tests
cargo test

# Run with specific features
cargo test --features websocket

# Run examples
cargo run --example sampling_client
```

## Related Crates

- **[turbomcp]../turbomcp/** - Main framework with server macros
- **[turbomcp-protocol]../turbomcp-protocol/** - Protocol types and core utilities
- **[turbomcp-transport]../turbomcp-transport/** - Transport implementations

## Resources

- **[MCP Specification]https://modelcontextprotocol.io/** - Official protocol docs
- **[MCP 2025-06-18 Spec]https://spec.modelcontextprotocol.io/2025-06-18/** - Current version
- **[TurboMCP Documentation]https://turbomcp.org** - Framework docs

## Roadmap

### Completed in 2.0

- [x] **HTTP/SSE Client Transport** - Client-side HTTP/SSE with `Client::connect_http()`
- [x] **Convenience Constructors** - One-liner client creation for all transports
- [x] **Ergonomic Config Builders** - Simplified configuration APIs

### Planned Features

- [ ] **Connection Pool Management** - Multi-server connection pooling
- [ ] **Session Persistence** - Automatic state preservation across reconnects
- [ ] **Roots Handler** - Complete filesystem roots implementation
- [ ] **Progress Reporting** - Client-side progress emission
- [ ] **Batch Requests** - Send multiple requests in single message

## License

Licensed under the [MIT License](../../LICENSE).

---

*Part of the [TurboMCP](../../) Rust SDK for the Model Context Protocol.*