turbomcp-client 3.0.8

MCP client with full protocol support, bidirectional communication, and plugin middleware
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
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
//! # `TurboMCP` Client
//!
//! MCP (Model Context Protocol) client implementation for connecting to MCP servers
//! and consuming their capabilities (tools, prompts, resources, and sampling).
//!
//! ## Features
//!
//! - Connection management with automatic reconnection
//! - Error handling and recovery mechanisms
//! - Support for all MCP capabilities including bidirectional sampling
//! - Elicitation response handling for server-initiated user input requests
//! - Transport-agnostic design (works with any `Transport` implementation)
//! - Type-safe protocol communication
//! - Request/response correlation tracking
//! - Timeout and cancellation support
//! - Automatic capability negotiation
//! - Handler support for server-initiated requests (sampling and elicitation)
//!
//! ## Architecture
//!
//! The client follows a layered architecture:
//!
//! ```text
//! Application Layer
//!//! Client API (this crate)
//!//! Protocol Layer (turbomcp-protocol)
//!//! Transport Layer (turbomcp-transport)
//! ```
//!
//! ## Usage
//!
//! ```rust,no_run
//! use turbomcp_client::{Client, ClientBuilder};
//! use turbomcp_transport::stdio::StdioTransport;
//!
//! # async fn example() -> turbomcp_protocol::Result<()> {
//! // Create a client with stdio transport
//! let transport = StdioTransport::new();
//! let mut client = Client::new(transport);
//!
//! // Initialize connection and negotiate capabilities
//! 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"));
//! }
//!
//! // Access resources
//! let resources = client.list_resources().await?;
//! for resource in resources {
//!     println!("Resource: {} ({})", resource.name, resource.uri);
//! }
//! # Ok(())
//! # }
//! ```
//!
//! ## Elicitation Response Handling
//!
//! The client supports handling server-initiated elicitation requests:
//!
//! ```rust,no_run
//! use turbomcp_client::Client;
//! use std::collections::HashMap;
//!
//! // Simple elicitation handling example
//! async fn handle_server_elicitation() {
//!     // When server requests user input, you would:
//!     // 1. Present the schema to the user
//!     // 2. Collect their input  
//!     // 3. Send response back to server
//!     
//!     let user_preferences: HashMap<String, String> = HashMap::new();
//!     // Your UI/CLI interaction logic here
//!     println!("Server requesting user preferences");
//! }
//! ```
//!
//! ## Sampling Support
//!
//! Handle server-initiated sampling requests for LLM capabilities:
//!
//! ```rust,no_run
//! use turbomcp_client::Client;
//! use turbomcp_client::sampling::SamplingHandler;
//! use turbomcp_protocol::types::{ContentBlock, CreateMessageRequest, CreateMessageResult, Role, StopReason, TextContent};
//! use std::future::Future;
//! use std::pin::Pin;
//!
//! #[derive(Debug)]
//! struct MySamplingHandler {
//!     // Your LLM client would go here
//! }
//!
//! impl SamplingHandler for MySamplingHandler {
//!     fn handle_create_message(
//!         &self,
//!         request_id: String,
//!         request: CreateMessageRequest
//!     ) -> Pin<Box<dyn Future<Output = Result<CreateMessageResult, Box<dyn std::error::Error + Send + Sync>>> + Send + '_>> {
//!         Box::pin(async move {
//!             // Forward to your LLM provider (OpenAI, Anthropic, etc.)
//!             // Use request_id for correlation tracking
//!             // Allows the server to request LLM sampling through the client
//!
//!             Ok(CreateMessageResult {
//!                 role: Role::Assistant,
//!                 content: ContentBlock::Text(
//!                     TextContent {
//!                         text: "Response from LLM".to_string(),
//!                         annotations: None,
//!                         meta: None,
//!                     }
//!                 ),
//!                 model: "gpt-4".to_string(),
//!                 stop_reason: Some(StopReason::EndTurn),
//!                 _meta: None,
//!             })
//!         })
//!     }
//! }
//! ```
//!
//! ## Error Handling
//!
//! The client provides comprehensive error handling with automatic retry logic:
//!
//! ```rust,no_run
//! # use turbomcp_client::Client;
//! # use turbomcp_transport::stdio::StdioTransport;
//! # async fn example() -> turbomcp_protocol::Result<()> {
//! # let mut client = Client::new(StdioTransport::new());
//! match client.call_tool("my_tool", None, None).await {
//!     Ok(result) => println!("Tool result: {:?}", result),
//!     Err(e) => eprintln!("Tool call failed: {}", e),
//! }
//! # Ok(())
//! # }
//! ```

/// TurboMCP Client version from Cargo.toml
///
/// This constant provides easy programmatic access to the current version.
///
/// # Example
///
/// ```rust
/// println!("TurboMCP Client version: {}", turbomcp_client::VERSION);
/// ```
pub const VERSION: &str = env!("CARGO_PKG_VERSION");

/// TurboMCP Client crate name
pub const CRATE_NAME: &str = env!("CARGO_PKG_NAME");

pub mod client;
pub mod handlers;
pub mod integration;
pub mod prelude;
pub mod sampling;

// v3.0 Tower-native middleware
pub mod middleware;

// Re-export key types for convenience
pub use client::{ConnectionInfo, ConnectionState, ManagerConfig, ServerGroup, SessionManager};

use std::sync::Arc;
use std::time::Duration;

// Re-export Transport trait for generic bounds in integrations
pub use turbomcp_transport::Transport;

// ============================================================================
// TOP-LEVEL RE-EXPORTS FOR ERGONOMIC IMPORTS
// ============================================================================

// Result/Error types - re-export from protocol for consistency
pub use turbomcp_protocol::{Error, Result};

// Handler types (most commonly used)
pub use handlers::{
    // Cancellation (current MCP spec)
    CancellationHandler,
    CancelledNotification,
    ElicitationAction,
    // Elicitation
    ElicitationHandler,
    ElicitationRequest,
    ElicitationResponse,
    // Error handling
    HandlerError,
    HandlerResult,
    // Logging (current MCP spec)
    LogHandler,
    LoggingNotification,
    // Progress (current MCP spec)
    ProgressHandler,
    ProgressNotification,
    PromptListChangedHandler,
    // List changed handlers (current MCP spec)
    ResourceListChangedHandler,
    // Resource updates (current MCP spec)
    ResourceUpdateHandler,
    ResourceUpdatedNotification,
    // Roots
    RootsHandler,
    ToolListChangedHandler,
};

// Sampling types
pub use sampling::{SamplingHandler, ServerInfo, UserInteractionHandler};

// v3.0 Tower middleware
pub use middleware::{
    Cache, CacheConfig, CacheLayer, CacheService, McpRequest, McpResponse, Metrics, MetricsLayer,
    MetricsService, MetricsSnapshot, TracingLayer, TracingService,
};

// Common protocol types
pub use turbomcp_protocol::types::{
    // Resource content types (for processing embedded resources)
    BlobResourceContents,
    // Tool result types (for LLM integrations like rig)
    CallToolResult,
    // Core types
    ContentBlock,
    EmbeddedResource,
    LogLevel,
    Prompt,
    Resource,
    ResourceContent,
    ResourceContents,
    Role,
    TextResourceContents,
    Tool,
};

// Transport re-exports (with feature gates)
#[cfg(feature = "stdio")]
pub use turbomcp_transport::stdio::StdioTransport;

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

#[cfg(feature = "tcp")]
pub use turbomcp_transport::tcp::{TcpTransport, TcpTransportBuilder};

#[cfg(feature = "unix")]
pub use turbomcp_transport::unix::{UnixTransport, UnixTransportBuilder};

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

/// Client capability configuration
///
/// Defines the capabilities that this client supports when connecting to MCP servers.
/// These capabilities are sent during the initialization handshake to negotiate
/// which features will be available during the session.
///
/// # Examples
///
/// ```
/// use turbomcp_client::ClientCapabilities;
///
/// let capabilities = ClientCapabilities {
///     tools: true,
///     prompts: true,
///     resources: true,
///     sampling: false,
///     max_concurrent_handlers: 100,
/// };
/// ```
#[derive(Debug, Clone)]
pub struct ClientCapabilities {
    /// Whether the client supports tool calling
    pub tools: bool,

    /// Whether the client supports prompts
    pub prompts: bool,

    /// Whether the client supports resources
    pub resources: bool,

    /// Whether the client supports sampling
    pub sampling: bool,

    /// Maximum concurrent request/notification handlers (default: 100)
    ///
    /// This limits how many server-initiated requests/notifications can be processed simultaneously.
    /// Provides automatic backpressure when the limit is reached.
    ///
    /// **Tuning Guide:**
    /// - Low-resource clients: 50
    /// - Standard clients: 100 (default)
    /// - High-performance: 200-500
    /// - Maximum recommended: 1000
    pub max_concurrent_handlers: usize,
}

impl Default for ClientCapabilities {
    fn default() -> Self {
        Self {
            tools: false,
            prompts: false,
            resources: false,
            sampling: false,
            max_concurrent_handlers: 100,
        }
    }
}

impl ClientCapabilities {
    /// All capabilities enabled (tools, prompts, resources, sampling)
    ///
    /// This is the most comprehensive configuration, enabling full MCP protocol support.
    ///
    /// # Example
    ///
    /// ```rust
    /// use turbomcp_client::ClientCapabilities;
    ///
    /// let capabilities = ClientCapabilities::all();
    /// assert!(capabilities.tools);
    /// assert!(capabilities.prompts);
    /// assert!(capabilities.resources);
    /// assert!(capabilities.sampling);
    /// ```
    #[must_use]
    pub fn all() -> Self {
        Self {
            tools: true,
            prompts: true,
            resources: true,
            sampling: true,
            max_concurrent_handlers: 100,
        }
    }

    /// Core capabilities without sampling (tools, prompts, resources)
    ///
    /// This is the recommended default for most applications. It enables
    /// all standard MCP features except server-initiated sampling requests.
    ///
    /// # Example
    ///
    /// ```rust
    /// use turbomcp_client::ClientCapabilities;
    ///
    /// let capabilities = ClientCapabilities::core();
    /// assert!(capabilities.tools);
    /// assert!(capabilities.prompts);
    /// assert!(capabilities.resources);
    /// assert!(!capabilities.sampling);
    /// ```
    #[must_use]
    pub fn core() -> Self {
        Self {
            tools: true,
            prompts: true,
            resources: true,
            sampling: false,
            max_concurrent_handlers: 100,
        }
    }

    /// Minimal capabilities (tools only)
    ///
    /// Use this for simple tool-calling clients that don't need prompts,
    /// resources, or sampling support.
    ///
    /// # Example
    ///
    /// ```rust
    /// use turbomcp_client::ClientCapabilities;
    ///
    /// let capabilities = ClientCapabilities::minimal();
    /// assert!(capabilities.tools);
    /// assert!(!capabilities.prompts);
    /// assert!(!capabilities.resources);
    /// assert!(!capabilities.sampling);
    /// ```
    #[must_use]
    pub fn minimal() -> Self {
        Self {
            tools: true,
            prompts: false,
            resources: false,
            sampling: false,
            max_concurrent_handlers: 100,
        }
    }

    /// Only tools enabled
    ///
    /// Same as `minimal()`, provided for clarity.
    #[must_use]
    pub fn only_tools() -> Self {
        Self::minimal()
    }

    /// Only resources enabled
    ///
    /// Use this for resource-focused clients that don't need tools or prompts.
    ///
    /// # Example
    ///
    /// ```rust
    /// use turbomcp_client::ClientCapabilities;
    ///
    /// let capabilities = ClientCapabilities::only_resources();
    /// assert!(!capabilities.tools);
    /// assert!(!capabilities.prompts);
    /// assert!(capabilities.resources);
    /// ```
    #[must_use]
    pub fn only_resources() -> Self {
        Self {
            tools: false,
            prompts: false,
            resources: true,
            sampling: false,
            max_concurrent_handlers: 100,
        }
    }

    /// Only prompts enabled
    ///
    /// Use this for prompt-focused clients that don't need tools or resources.
    ///
    /// # Example
    ///
    /// ```rust
    /// use turbomcp_client::ClientCapabilities;
    ///
    /// let capabilities = ClientCapabilities::only_prompts();
    /// assert!(!capabilities.tools);
    /// assert!(capabilities.prompts);
    /// assert!(!capabilities.resources);
    /// ```
    #[must_use]
    pub fn only_prompts() -> Self {
        Self {
            tools: false,
            prompts: true,
            resources: false,
            sampling: false,
            max_concurrent_handlers: 100,
        }
    }

    /// Only sampling enabled
    ///
    /// Use this for clients that exclusively handle server-initiated sampling requests.
    #[must_use]
    pub fn only_sampling() -> Self {
        Self {
            tools: false,
            prompts: false,
            resources: false,
            sampling: true,
            max_concurrent_handlers: 100,
        }
    }
}

/// JSON-RPC protocol handler for MCP communication
// Note: ProtocolClient implementation moved to client/protocol.rs for better modularity
/// MCP client for communicating with servers
///
/// The `Client` struct provides an ergonomic interface for interacting with MCP servers.
/// It handles protocol complexity internally, exposing clean, type-safe methods.
///
/// # Type Parameters
///
/// * `T` - The transport implementation used for communication
///
/// # Examples
///
/// ```rust,no_run
/// use turbomcp_client::Client;
/// use turbomcp_transport::stdio::StdioTransport;
///
/// # async fn example() -> turbomcp_protocol::Result<()> {
/// let transport = StdioTransport::new();
/// let mut client = Client::new(transport);
///
/// // Initialize and start using the client
/// client.initialize().await?;
/// # Ok(())
/// # }
/// ```
// Re-export Client from the core module
pub use client::core::Client;

// Thread-safe wrapper for sharing Client across async tasks
//
// This wrapper encapsulates the Arc/Mutex complexity and provides a clean API
// for concurrent access to MCP client functionality. It addresses the limitations
// identified in PR feedback where Client requires `&mut self` for all operations
// but needs to be shared across multiple async tasks.
//
// # Design Rationale
//
// All Client methods require `&mut self` because:
// - MCP connections maintain state (initialized flag, connection status)
// - Request correlation tracking for JSON-RPC requires mutation
// - Handler and plugin registries need mutable access
//
// Note: SharedClient has been removed in v2 - Client is now directly cloneable via Arc

// ----------------------------------------------------------------------------
// Re-exports
// ----------------------------------------------------------------------------

#[doc = "Result of client initialization"]
#[doc = ""]
#[doc = "Contains information about the server and the negotiated capabilities"]
#[doc = "after a successful initialization handshake."]
pub use client::config::InitializeResult;

// ServerCapabilities is now imported from turbomcp_protocol::types

/// Connection configuration for the client
#[derive(Debug, Clone)]
pub struct ConnectionConfig {
    /// Request timeout in milliseconds
    pub timeout_ms: u64,

    /// Maximum number of retry attempts
    pub max_retries: u32,

    /// Retry delay in milliseconds
    pub retry_delay_ms: u64,

    /// Keep-alive interval in milliseconds
    pub keepalive_ms: u64,
}

fn protocol_transport_config(
    connection_config: &ConnectionConfig,
) -> turbomcp_transport::TransportConfig {
    let timeout = Duration::from_millis(connection_config.timeout_ms);

    turbomcp_transport::TransportConfig {
        connect_timeout: timeout,
        keep_alive: Some(Duration::from_millis(connection_config.keepalive_ms)),
        timeouts: turbomcp_transport::config::TimeoutConfig {
            connect: timeout,
            request: Some(timeout),
            total: Some(timeout),
            read: Some(timeout),
        },
        ..Default::default()
    }
}

fn resilience_requested(builder: &ClientBuilder) -> bool {
    builder.enable_resilience
        || builder.retry_config.is_some()
        || builder.circuit_breaker_config.is_some()
        || builder.health_check_config.is_some()
}

impl Default for ConnectionConfig {
    fn default() -> Self {
        Self {
            timeout_ms: 30_000,    // 30 seconds
            max_retries: 3,        // 3 attempts
            retry_delay_ms: 1_000, // 1 second
            keepalive_ms: 60_000,  // 60 seconds
        }
    }
}

/// Builder for configuring and creating MCP clients
///
/// Provides a fluent interface for configuring client options before creation.
/// The enhanced builder pattern supports comprehensive configuration including:
/// - Protocol capabilities
/// - Plugin registration
/// - Handler registration
/// - Connection settings
/// - Resilience configuration
///
/// # Examples
///
/// Basic usage:
/// ```rust,no_run
/// use turbomcp_client::ClientBuilder;
/// use turbomcp_transport::stdio::StdioTransport;
///
/// # async fn example() -> turbomcp_protocol::Result<()> {
/// let client = ClientBuilder::new()
///     .with_tools(true)
///     .with_prompts(true)
///     .with_resources(false)
///     .build(StdioTransport::new());
/// # Ok(())
/// # }
/// ```
///
/// Advanced configuration with Tower middleware:
/// ```rust,no_run
/// use turbomcp_client::{ClientBuilder, ConnectionConfig};
/// use turbomcp_client::middleware::MetricsLayer;
/// use turbomcp_transport::stdio::StdioTransport;
/// use tower::ServiceBuilder;
///
/// # async fn example() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
/// let client = ClientBuilder::new()
///     .with_tools(true)
///     .with_prompts(true)
///     .with_resources(true)
///     .with_sampling(true)
///     .with_connection_config(ConnectionConfig {
///         timeout_ms: 60_000,
///         max_retries: 5,
///         retry_delay_ms: 2_000,
///         keepalive_ms: 30_000,
///     })
///     .build(StdioTransport::new())
///     .await?;
/// # Ok(())
/// # }
/// ```
#[derive(Debug, Default)]
pub struct ClientBuilder {
    capabilities: ClientCapabilities,
    connection_config: ConnectionConfig,
    elicitation_handler: Option<Arc<dyn crate::handlers::ElicitationHandler>>,
    log_handler: Option<Arc<dyn crate::handlers::LogHandler>>,
    resource_update_handler: Option<Arc<dyn crate::handlers::ResourceUpdateHandler>>,
    progress_handler: Option<Arc<dyn crate::handlers::ProgressHandler>>,
    // Robustness configuration
    enable_resilience: bool,
    retry_config: Option<turbomcp_transport::resilience::RetryConfig>,
    circuit_breaker_config: Option<turbomcp_transport::resilience::CircuitBreakerConfig>,
    health_check_config: Option<turbomcp_transport::resilience::HealthCheckConfig>,
}

// Default implementation is now derived

impl ClientBuilder {
    /// Create a new client builder
    ///
    /// Returns a new builder with default configuration.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    // ============================================================================
    // CAPABILITY CONFIGURATION
    // ============================================================================

    /// Enable or disable tool support
    ///
    /// # Arguments
    ///
    /// * `enabled` - Whether to enable tool support
    #[must_use]
    pub fn with_tools(mut self, enabled: bool) -> Self {
        self.capabilities.tools = enabled;
        self
    }

    /// Enable or disable prompt support
    ///
    /// # Arguments
    ///
    /// * `enabled` - Whether to enable prompt support
    #[must_use]
    pub fn with_prompts(mut self, enabled: bool) -> Self {
        self.capabilities.prompts = enabled;
        self
    }

    /// Enable or disable resource support
    ///
    /// # Arguments
    ///
    /// * `enabled` - Whether to enable resource support
    #[must_use]
    pub fn with_resources(mut self, enabled: bool) -> Self {
        self.capabilities.resources = enabled;
        self
    }

    /// Enable or disable sampling support
    ///
    /// # Arguments
    ///
    /// * `enabled` - Whether to enable sampling support
    #[must_use]
    pub fn with_sampling(mut self, enabled: bool) -> Self {
        self.capabilities.sampling = enabled;
        self
    }

    /// Set maximum concurrent request/notification handlers
    ///
    /// This limits how many server-initiated requests/notifications can be processed simultaneously.
    /// Provides automatic backpressure when the limit is reached.
    ///
    /// # Arguments
    ///
    /// * `limit` - Maximum concurrent handlers (default: 100)
    ///
    /// # Tuning Guide
    ///
    /// - Low-resource clients: 50
    /// - Standard clients: 100 (default)
    /// - High-performance: 200-500
    /// - Maximum recommended: 1000
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// use turbomcp_client::ClientBuilder;
    /// # use turbomcp_transport::StdioTransport;
    ///
    /// let builder = ClientBuilder::new()
    ///     .with_max_concurrent_handlers(200);
    /// ```
    #[must_use]
    pub fn with_max_concurrent_handlers(mut self, limit: usize) -> Self {
        self.capabilities.max_concurrent_handlers = limit;
        self
    }

    /// Configure all capabilities at once
    ///
    /// # Arguments
    ///
    /// * `capabilities` - The capabilities configuration
    #[must_use]
    pub fn with_capabilities(mut self, capabilities: ClientCapabilities) -> Self {
        self.capabilities = capabilities;
        self
    }

    // ============================================================================
    // CONNECTION CONFIGURATION
    // ============================================================================

    /// Configure connection settings
    ///
    /// # Arguments
    ///
    /// * `config` - The connection configuration
    #[must_use]
    pub fn with_connection_config(mut self, config: ConnectionConfig) -> Self {
        self.connection_config = config;
        self
    }

    /// Set request timeout
    ///
    /// # Arguments
    ///
    /// * `timeout_ms` - Timeout in milliseconds
    #[must_use]
    pub fn with_timeout(mut self, timeout_ms: u64) -> Self {
        self.connection_config.timeout_ms = timeout_ms;
        self
    }

    /// Set maximum retry attempts
    ///
    /// # Arguments
    ///
    /// * `max_retries` - Maximum number of retries
    #[must_use]
    pub fn with_max_retries(mut self, max_retries: u32) -> Self {
        self.connection_config.max_retries = max_retries;
        self
    }

    /// Set retry delay
    ///
    /// # Arguments
    ///
    /// * `delay_ms` - Retry delay in milliseconds
    #[must_use]
    pub fn with_retry_delay(mut self, delay_ms: u64) -> Self {
        self.connection_config.retry_delay_ms = delay_ms;
        self
    }

    /// Set keep-alive interval
    ///
    /// # Arguments
    ///
    /// * `interval_ms` - Keep-alive interval in milliseconds
    #[must_use]
    pub fn with_keepalive(mut self, interval_ms: u64) -> Self {
        self.connection_config.keepalive_ms = interval_ms;
        self
    }

    // ============================================================================
    // ROBUSTNESS & RESILIENCE CONFIGURATION
    // ============================================================================

    /// Enable resilient transport with circuit breaker, retry, and health checking
    ///
    /// When enabled, the transport layer will automatically:
    /// - Retry failed operations with exponential backoff
    /// - Use circuit breaker pattern to prevent cascade failures
    /// - Perform periodic health checks
    /// - Deduplicate messages
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use turbomcp_client::ClientBuilder;
    /// use turbomcp_transport::stdio::StdioTransport;
    ///
    /// let client = ClientBuilder::new()
    ///     .enable_resilience()
    ///     .build(StdioTransport::new());
    /// ```
    #[must_use]
    pub fn enable_resilience(mut self) -> Self {
        self.enable_resilience = true;
        self
    }

    /// Configure retry behavior for resilient transport
    ///
    /// # Arguments
    ///
    /// * `config` - Retry configuration
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use turbomcp_client::ClientBuilder;
    /// use turbomcp_transport::resilience::RetryConfig;
    /// use turbomcp_transport::stdio::StdioTransport;
    /// use std::time::Duration;
    ///
    /// let client = ClientBuilder::new()
    ///     .enable_resilience()
    ///     .with_retry_config(RetryConfig {
    ///         max_attempts: 5,
    ///         base_delay: Duration::from_millis(100),
    ///         max_delay: Duration::from_secs(30),
    ///         backoff_multiplier: 2.0,
    ///         jitter_factor: 0.1,
    ///         retry_on_connection_error: true,
    ///         retry_on_timeout: true,
    ///         custom_retry_conditions: Vec::new(),
    ///     })
    ///     .build(StdioTransport::new());
    /// ```
    #[must_use]
    pub fn with_retry_config(
        mut self,
        config: turbomcp_transport::resilience::RetryConfig,
    ) -> Self {
        self.retry_config = Some(config);
        self.enable_resilience = true; // Auto-enable resilience
        self
    }

    /// Configure circuit breaker for resilient transport
    ///
    /// # Arguments
    ///
    /// * `config` - Circuit breaker configuration
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use turbomcp_client::ClientBuilder;
    /// use turbomcp_transport::resilience::CircuitBreakerConfig;
    /// use turbomcp_transport::stdio::StdioTransport;
    /// use std::time::Duration;
    ///
    /// let client = ClientBuilder::new()
    ///     .enable_resilience()
    ///     .with_circuit_breaker_config(CircuitBreakerConfig {
    ///         failure_threshold: 5,
    ///         success_threshold: 2,
    ///         timeout: Duration::from_secs(60),
    ///         rolling_window_size: 100,
    ///         minimum_requests: 10,
    ///     })
    ///     .build(StdioTransport::new());
    /// ```
    #[must_use]
    pub fn with_circuit_breaker_config(
        mut self,
        config: turbomcp_transport::resilience::CircuitBreakerConfig,
    ) -> Self {
        self.circuit_breaker_config = Some(config);
        self.enable_resilience = true; // Auto-enable resilience
        self
    }

    /// Configure health checking for resilient transport
    ///
    /// # Arguments
    ///
    /// * `config` - Health check configuration
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use turbomcp_client::ClientBuilder;
    /// use turbomcp_transport::resilience::HealthCheckConfig;
    /// use turbomcp_transport::stdio::StdioTransport;
    /// use std::time::Duration;
    ///
    /// let client = ClientBuilder::new()
    ///     .enable_resilience()
    ///     .with_health_check_config(HealthCheckConfig {
    ///         interval: Duration::from_secs(30),
    ///         timeout: Duration::from_secs(5),
    ///         failure_threshold: 3,
    ///         success_threshold: 1,
    ///         custom_check: None,
    ///     })
    ///     .build(StdioTransport::new());
    /// ```
    #[must_use]
    pub fn with_health_check_config(
        mut self,
        config: turbomcp_transport::resilience::HealthCheckConfig,
    ) -> Self {
        self.health_check_config = Some(config);
        self.enable_resilience = true; // Auto-enable resilience
        self
    }

    // ============================================================================
    // HANDLER REGISTRATION
    // ============================================================================

    /// Register an elicitation handler for processing user input requests
    ///
    /// # Arguments
    ///
    /// * `handler` - The elicitation handler implementation
    pub fn with_elicitation_handler(
        mut self,
        handler: Arc<dyn crate::handlers::ElicitationHandler>,
    ) -> Self {
        self.elicitation_handler = Some(handler);
        self
    }

    /// Register a log handler for processing server log messages
    ///
    /// # Arguments
    ///
    /// * `handler` - The log handler implementation
    pub fn with_log_handler(mut self, handler: Arc<dyn crate::handlers::LogHandler>) -> Self {
        self.log_handler = Some(handler);
        self
    }

    /// Register a resource update handler for processing resource change notifications
    ///
    /// # Arguments
    ///
    /// * `handler` - The resource update handler implementation
    pub fn with_resource_update_handler(
        mut self,
        handler: Arc<dyn crate::handlers::ResourceUpdateHandler>,
    ) -> Self {
        self.resource_update_handler = Some(handler);
        self
    }

    /// Register a progress handler for processing progress notifications
    ///
    /// # Arguments
    ///
    /// * `handler` - The progress handler implementation
    pub fn with_progress_handler(
        mut self,
        handler: Arc<dyn crate::handlers::ProgressHandler>,
    ) -> Self {
        self.progress_handler = Some(handler);
        self
    }

    // ============================================================================
    // BUILD METHODS
    // ============================================================================

    /// Build a client with the configured options
    ///
    /// Creates a new client instance with all the configured options. The client
    /// will be initialized with the registered plugins, handlers, and providers.
    ///
    /// # Arguments
    ///
    /// * `transport` - The transport to use for the client
    ///
    /// # Returns
    ///
    /// Returns a configured `Client` instance wrapped in a Result for async setup.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use turbomcp_client::ClientBuilder;
    /// use turbomcp_transport::stdio::StdioTransport;
    ///
    /// # async fn example() -> turbomcp_protocol::Result<()> {
    /// let client = ClientBuilder::new()
    ///     .with_tools(true)
    ///     .with_prompts(true)
    ///     .build(StdioTransport::new())
    ///     .await?;
    /// # Ok(())
    /// # }
    /// ```
    pub async fn build<T: Transport + 'static>(self, transport: T) -> Result<Client<T>> {
        if resilience_requested(&self) {
            return Err(Error::configuration(
                "resilience settings require build_resilient(); build() would otherwise ignore them"
                    .to_string(),
            ));
        }

        // Create base client with capabilities
        let client = Client::with_capabilities_and_config(
            transport,
            self.capabilities,
            protocol_transport_config(&self.connection_config),
        );

        // Register handlers
        if let Some(handler) = self.elicitation_handler {
            client.set_elicitation_handler(handler);
        }
        if let Some(handler) = self.log_handler {
            client.set_log_handler(handler);
        }
        if let Some(handler) = self.resource_update_handler {
            client.set_resource_update_handler(handler);
        }
        if let Some(handler) = self.progress_handler {
            client.set_progress_handler(handler);
        }

        Ok(client)
    }

    /// Build a client with resilient transport (circuit breaker, retry, health checking)
    ///
    /// When resilience features are enabled via `enable_resilience()` or any resilience
    /// configuration method, this wraps the transport in a `TurboTransport` that provides:
    /// - Automatic retry with exponential backoff
    /// - Circuit breaker pattern for fast failure
    /// - Health checking and monitoring
    /// - Message deduplication
    ///
    /// # Arguments
    ///
    /// * `transport` - The base transport to wrap with resilience features
    ///
    /// # Returns
    ///
    /// Returns a configured `Client<TurboTransport>` instance.
    ///
    /// # Errors
    ///
    /// Returns an error if plugin initialization fails.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use turbomcp_client::ClientBuilder;
    /// use turbomcp_transport::stdio::StdioTransport;
    /// use turbomcp_transport::resilience::{RetryConfig, CircuitBreakerConfig, HealthCheckConfig};
    /// use std::time::Duration;
    ///
    /// # async fn example() -> turbomcp_protocol::Result<()> {
    /// let client = ClientBuilder::new()
    ///     .with_retry_config(RetryConfig {
    ///         max_attempts: 5,
    ///         base_delay: Duration::from_millis(200),
    ///         ..Default::default()
    ///     })
    ///     .with_circuit_breaker_config(CircuitBreakerConfig {
    ///         failure_threshold: 3,
    ///         timeout: Duration::from_secs(30),
    ///         ..Default::default()
    ///     })
    ///     .with_health_check_config(HealthCheckConfig {
    ///         interval: Duration::from_secs(15),
    ///         timeout: Duration::from_secs(5),
    ///         ..Default::default()
    ///     })
    ///     .build_resilient(StdioTransport::new())
    ///     .await?;
    /// # Ok(())
    /// # }
    /// ```
    pub async fn build_resilient<T: Transport + 'static>(
        self,
        transport: T,
    ) -> Result<Client<turbomcp_transport::resilience::TurboTransport>> {
        use turbomcp_transport::resilience::TurboTransport;

        // Get configurations or use defaults
        let retry_config =
            self.retry_config
                .unwrap_or_else(|| turbomcp_transport::resilience::RetryConfig {
                    max_attempts: self.connection_config.max_retries.max(1),
                    base_delay: Duration::from_millis(self.connection_config.retry_delay_ms),
                    ..Default::default()
                });
        let circuit_config = self.circuit_breaker_config.unwrap_or_default();
        let health_config = self.health_check_config.unwrap_or_else(|| {
            turbomcp_transport::resilience::HealthCheckConfig {
                timeout: Duration::from_millis(self.connection_config.timeout_ms),
                ..Default::default()
            }
        });

        // Wrap transport in TurboTransport
        let robust_transport = TurboTransport::new(
            Box::new(transport),
            retry_config,
            circuit_config,
            health_config,
        );

        // Create client with resilient transport
        let client = Client::with_capabilities_and_config(
            robust_transport,
            self.capabilities,
            protocol_transport_config(&self.connection_config),
        );

        // Register handlers
        if let Some(handler) = self.elicitation_handler {
            client.set_elicitation_handler(handler);
        }
        if let Some(handler) = self.log_handler {
            client.set_log_handler(handler);
        }
        if let Some(handler) = self.resource_update_handler {
            client.set_resource_update_handler(handler);
        }
        if let Some(handler) = self.progress_handler {
            client.set_progress_handler(handler);
        }

        Ok(client)
    }

    /// Build a client synchronously with basic configuration only
    ///
    /// This is a convenience method for simple use cases.
    ///
    /// # Arguments
    ///
    /// * `transport` - The transport to use for the client
    ///
    /// # Returns
    ///
    /// Returns a configured `Client` instance.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use turbomcp_client::ClientBuilder;
    /// use turbomcp_transport::stdio::StdioTransport;
    ///
    /// let client = ClientBuilder::new()
    ///     .with_tools(true)
    ///     .build_sync(StdioTransport::new());
    /// ```
    pub fn build_sync<T: Transport + 'static>(self, transport: T) -> Client<T> {
        assert!(
            !resilience_requested(&self),
            "resilience settings require build_resilient(); build_sync() would otherwise ignore them"
        );

        let client = Client::with_capabilities_and_config(
            transport,
            self.capabilities,
            protocol_transport_config(&self.connection_config),
        );

        // Register synchronous handlers only
        if let Some(handler) = self.elicitation_handler {
            client.set_elicitation_handler(handler);
        }
        if let Some(handler) = self.log_handler {
            client.set_log_handler(handler);
        }
        if let Some(handler) = self.resource_update_handler {
            client.set_resource_update_handler(handler);
        }
        if let Some(handler) = self.progress_handler {
            client.set_progress_handler(handler);
        }

        client
    }

    // ============================================================================
    // CONFIGURATION ACCESS
    // ============================================================================

    /// Get the current capabilities configuration
    #[must_use]
    pub fn capabilities(&self) -> &ClientCapabilities {
        &self.capabilities
    }

    /// Get the current connection configuration
    #[must_use]
    pub fn connection_config(&self) -> &ConnectionConfig {
        &self.connection_config
    }

    /// Check if any handlers are registered
    #[must_use]
    pub fn has_handlers(&self) -> bool {
        self.elicitation_handler.is_some()
            || self.log_handler.is_some()
            || self.resource_update_handler.is_some()
            || self.progress_handler.is_some()
    }
}

// Re-export types for public API
pub use turbomcp_protocol::types::ServerCapabilities as PublicServerCapabilities;

#[cfg(test)]
mod tests {
    use super::*;
    use std::future::Future;
    use std::pin::Pin;
    use turbomcp_transport::{
        TransportCapabilities, TransportConfig, TransportMessage, TransportMetrics,
        TransportResult, TransportState, TransportType,
    };

    #[derive(Debug, Default)]
    struct NoopTransport {
        capabilities: TransportCapabilities,
    }

    impl Transport for NoopTransport {
        fn transport_type(&self) -> TransportType {
            TransportType::Stdio
        }

        fn capabilities(&self) -> &TransportCapabilities {
            &self.capabilities
        }

        fn state(&self) -> Pin<Box<dyn Future<Output = TransportState> + Send + '_>> {
            Box::pin(async { TransportState::Disconnected })
        }

        fn connect(&self) -> Pin<Box<dyn Future<Output = TransportResult<()>> + Send + '_>> {
            Box::pin(async { Ok(()) })
        }

        fn disconnect(&self) -> Pin<Box<dyn Future<Output = TransportResult<()>> + Send + '_>> {
            Box::pin(async { Ok(()) })
        }

        fn send(
            &self,
            _message: TransportMessage,
        ) -> Pin<Box<dyn Future<Output = TransportResult<()>> + Send + '_>> {
            Box::pin(async { Ok(()) })
        }

        fn receive(
            &self,
        ) -> Pin<Box<dyn Future<Output = TransportResult<Option<TransportMessage>>> + Send + '_>>
        {
            Box::pin(async { Ok(None) })
        }

        fn metrics(&self) -> Pin<Box<dyn Future<Output = TransportMetrics> + Send + '_>> {
            Box::pin(async { TransportMetrics::default() })
        }

        fn configure(
            &self,
            _config: TransportConfig,
        ) -> Pin<Box<dyn Future<Output = TransportResult<()>> + Send + '_>> {
            Box::pin(async { Ok(()) })
        }
    }

    #[tokio::test]
    async fn build_rejects_resilience_flags() {
        let result = ClientBuilder::new()
            .enable_resilience()
            .build(NoopTransport::default())
            .await;

        assert!(result.is_err());
        let err = match result {
            Ok(_) => panic!("expected build() to reject resilience settings"),
            Err(err) => err,
        };
        assert!(err.to_string().contains("build_resilient"));
    }
}