Skip to main content

turbomcp_client/client/
core.rs

1//! Core Client implementation for MCP communication
2//!
3//! This module contains the main `Client<T>` struct and its implementation,
4//! providing the core MCP client functionality including:
5//!
6//! - Connection initialization and lifecycle management
7//! - Message processing and bidirectional communication
8//! - MCP operation support (tools, prompts, resources, sampling, etc.)
9//! - Plugin middleware integration
10//! - Handler registration and management
11//!
12//! # Architecture
13//!
14//! `Client<T>` is implemented as a cheaply-cloneable Arc wrapper with interior
15//! mutability (same pattern as reqwest and AWS SDK):
16//!
17//! - **AtomicBool** for initialized flag (lock-free)
18//! - **Arc<Mutex<...>>** for handlers/plugins (infrequent mutation)
19//! - **`Arc<ClientInner<T>>`** for cheap cloning
20
21use parking_lot::Mutex;
22use std::sync::Arc;
23use std::sync::atomic::{AtomicBool, Ordering};
24
25use tokio::sync::Semaphore;
26
27use turbomcp_protocol::jsonrpc::*;
28#[cfg(feature = "experimental-tasks")]
29use turbomcp_protocol::types::tasks::*;
30use turbomcp_protocol::types::{
31    ClientCapabilities as ProtocolClientCapabilities, InitializeResult as ProtocolInitializeResult,
32    *,
33};
34use turbomcp_protocol::{Error, PROTOCOL_VERSION, Result};
35use turbomcp_transport::{Transport, TransportConfig, TransportMessage};
36
37use super::config::InitializeResult;
38use super::protocol::ProtocolClient;
39use crate::{
40    ClientCapabilities,
41    handlers::{HandlerError, HandlerRegistry},
42    sampling::SamplingHandler,
43};
44
45/// Inner client state with interior mutability
46///
47/// This structure contains the actual client state and is wrapped in Arc<...>
48/// to enable cheap cloning (same pattern as reqwest and AWS SDK).
49pub(super) struct ClientInner<T: Transport + 'static> {
50    /// Protocol client for low-level communication
51    pub(super) protocol: ProtocolClient<T>,
52
53    /// Client capabilities (immutable after construction)
54    pub(super) capabilities: ClientCapabilities,
55
56    /// Initialization state (lock-free atomic boolean)
57    pub(super) initialized: AtomicBool,
58
59    /// Tracks whether graceful shutdown has already been requested.
60    pub(super) shutdown_requested: AtomicBool,
61
62    /// Optional sampling handler (mutex for dynamic updates)
63    pub(super) sampling_handler: Arc<Mutex<Option<Arc<dyn SamplingHandler>>>>,
64
65    /// Handler registry for bidirectional communication (mutex for registration)
66    pub(super) handlers: Arc<Mutex<HandlerRegistry>>,
67
68    /// ✅ Semaphore for bounded concurrency of request/notification handlers
69    /// Limits concurrent server-initiated request handlers to prevent resource exhaustion
70    pub(super) handler_semaphore: Arc<Semaphore>,
71}
72
73/// The core MCP client implementation
74///
75/// Client provides a comprehensive interface for communicating with MCP servers,
76/// supporting all protocol features including tools, prompts, resources, sampling,
77/// elicitation, and bidirectional communication patterns.
78///
79/// # Clone Pattern
80///
81/// `Client<T>` is cheaply cloneable via Arc (same pattern as reqwest and AWS SDK).
82/// All clones share the same underlying connection and state:
83///
84/// ```rust,no_run
85/// use turbomcp_client::Client;
86/// use turbomcp_transport::stdio::StdioTransport;
87///
88/// # async fn example() -> turbomcp_protocol::Result<()> {
89/// let client = Client::new(StdioTransport::new());
90/// client.initialize().await?;
91///
92/// // Cheap clone - shares same connection
93/// let client2 = client.clone();
94/// tokio::spawn(async move {
95///     client2.list_tools().await.ok();
96/// });
97/// # Ok(())
98/// # }
99/// ```
100///
101/// The client must be initialized before use by calling `initialize()` to perform
102/// the MCP handshake and capability negotiation.
103///
104/// # Features
105///
106/// - **Protocol Compliance**: Full current MCP specification support
107/// - **Bidirectional Communication**: Server-initiated requests and client responses
108/// - **Plugin Middleware**: Extensible request/response processing
109/// - **Handler Registry**: Callbacks for server-initiated operations
110/// - **Connection Management**: Robust error handling and recovery
111/// - **Type Safety**: Compile-time guarantees for MCP message types
112/// - **Cheap Cloning**: Arc-based sharing like reqwest/AWS SDK
113///
114/// # Examples
115///
116/// ```rust,no_run
117/// use turbomcp_client::Client;
118/// use turbomcp_transport::stdio::StdioTransport;
119/// use std::collections::HashMap;
120///
121/// # async fn example() -> turbomcp_protocol::Result<()> {
122/// // Create and initialize client (no mut needed!)
123/// let client = Client::new(StdioTransport::new());
124/// let init_result = client.initialize().await?;
125/// println!("Connected to: {}", init_result.server_info.name);
126///
127/// // Use MCP operations
128/// let tools = client.list_tools().await?;
129/// let mut args = HashMap::new();
130/// args.insert("input".to_string(), serde_json::json!("test"));
131/// let result = client.call_tool("my_tool", Some(args), None).await?;
132/// # Ok(())
133/// # }
134/// ```
135pub struct Client<T: Transport + 'static> {
136    pub(super) inner: Arc<ClientInner<T>>,
137}
138
139/// Clone implementation via Arc (same pattern as reqwest/AWS SDK)
140///
141/// Cloning a Client is cheap (just an Arc clone) and all clones share
142/// the same underlying connection and state.
143impl<T: Transport + 'static> Clone for Client<T> {
144    fn clone(&self) -> Self {
145        Self {
146            inner: Arc::clone(&self.inner),
147        }
148    }
149}
150
151impl<T: Transport + 'static> Drop for ClientInner<T> {
152    fn drop(&mut self) {
153        // Best-effort cleanup if shutdown() wasn't called
154        // This is a safety net, but applications SHOULD call shutdown() explicitly
155
156        // Single clear warning
157        if !self.shutdown_requested.load(Ordering::Relaxed) {
158            tracing::warn!(
159                "MCP Client dropped without explicit shutdown(). \
160                 Call client.shutdown().await before dropping for clean resource cleanup. \
161                 Background tasks (WebSocket reconnection) may continue running."
162            );
163        }
164
165        // We can shutdown the dispatcher (it's synchronous)
166        self.protocol.dispatcher().shutdown();
167    }
168}
169
170impl<T: Transport + 'static> Client<T> {
171    /// Create a new client with the specified transport
172    ///
173    /// Creates a new MCP client instance with default capabilities.
174    /// The client must be initialized before use by calling `initialize()`.
175    ///
176    /// # Arguments
177    ///
178    /// * `transport` - The transport implementation to use for communication
179    ///
180    /// # Examples
181    ///
182    /// ```rust,no_run
183    /// use turbomcp_client::Client;
184    /// use turbomcp_transport::stdio::StdioTransport;
185    ///
186    /// let transport = StdioTransport::new();
187    /// let client = Client::new(transport);
188    /// ```
189    pub fn new(transport: T) -> Self {
190        Self::new_with_config(transport, TransportConfig::default())
191    }
192
193    /// Create a new client with an explicit transport configuration.
194    pub fn new_with_config(transport: T, config: TransportConfig) -> Self {
195        let capabilities = ClientCapabilities::default();
196        let client = Self {
197            inner: Arc::new(ClientInner {
198                protocol: ProtocolClient::with_config(transport, config),
199                capabilities: capabilities.clone(),
200                initialized: AtomicBool::new(false),
201                shutdown_requested: AtomicBool::new(false),
202                sampling_handler: Arc::new(Mutex::new(None)),
203                handlers: Arc::new(Mutex::new(HandlerRegistry::new())),
204                handler_semaphore: Arc::new(Semaphore::new(capabilities.max_concurrent_handlers)), // ✅ Configurable concurrent handlers
205            }),
206        };
207
208        // Register dispatcher handlers for bidirectional communication
209        client.register_dispatcher_handlers();
210
211        client
212    }
213
214    /// Create a new client with custom capabilities
215    ///
216    /// # Arguments
217    ///
218    /// * `transport` - The transport implementation to use
219    /// * `capabilities` - The client capabilities to negotiate
220    ///
221    /// # Examples
222    ///
223    /// ```rust,no_run
224    /// use turbomcp_client::{Client, ClientCapabilities};
225    /// use turbomcp_transport::stdio::StdioTransport;
226    ///
227    /// let capabilities = ClientCapabilities {
228    ///     tools: true,
229    ///     prompts: true,
230    ///     resources: false,
231    ///     sampling: false,
232    ///     max_concurrent_handlers: 100,
233    /// };
234    ///
235    /// let transport = StdioTransport::new();
236    /// let client = Client::with_capabilities(transport, capabilities);
237    /// ```
238    pub fn with_capabilities(transport: T, capabilities: ClientCapabilities) -> Self {
239        Self::with_capabilities_and_config(transport, capabilities, TransportConfig::default())
240    }
241
242    /// Create a new client with custom capabilities and transport configuration.
243    pub fn with_capabilities_and_config(
244        transport: T,
245        capabilities: ClientCapabilities,
246        config: TransportConfig,
247    ) -> Self {
248        let client = Self {
249            inner: Arc::new(ClientInner {
250                protocol: ProtocolClient::with_config(transport, config),
251                capabilities: capabilities.clone(),
252                initialized: AtomicBool::new(false),
253                shutdown_requested: AtomicBool::new(false),
254                sampling_handler: Arc::new(Mutex::new(None)),
255                handlers: Arc::new(Mutex::new(HandlerRegistry::new())),
256                handler_semaphore: Arc::new(Semaphore::new(capabilities.max_concurrent_handlers)), // ✅ Configurable concurrent handlers
257            }),
258        };
259
260        // Register dispatcher handlers for bidirectional communication
261        client.register_dispatcher_handlers();
262
263        client
264    }
265
266    /// Shutdown the client and clean up all resources
267    ///
268    /// This method performs a **graceful shutdown** of the MCP client by:
269    /// 1. Stopping the message dispatcher background task
270    /// 2. Disconnecting the transport (closes connection, stops background tasks)
271    ///
272    /// **CRITICAL**: After calling `shutdown()`, the client can no longer be used.
273    ///
274    /// # Why This Method Exists
275    ///
276    /// The `Drop` implementation cannot call async methods like `transport.disconnect()`,
277    /// which is required for proper cleanup of WebSocket connections and background tasks.
278    /// Without calling `shutdown()`, WebSocket reconnection tasks will continue running.
279    ///
280    /// # Best Practices
281    ///
282    /// - **Always call `shutdown()` before dropping** for clean resource cleanup
283    /// - For applications: call in signal handlers (`SIGINT`, `SIGTERM`)
284    /// - For tests: call in cleanup/teardown
285    /// - If forgotten, Drop will log warnings and do best-effort cleanup
286    ///
287    /// # Examples
288    ///
289    /// ```rust,no_run
290    /// # use turbomcp_client::Client;
291    /// # use turbomcp_transport::stdio::StdioTransport;
292    /// # async fn example() -> turbomcp_protocol::Result<()> {
293    /// let client = Client::new(StdioTransport::new());
294    /// client.initialize().await?;
295    ///
296    /// // Use client...
297    /// let _tools = client.list_tools().await?;
298    ///
299    /// // ✅ Clean shutdown
300    /// client.shutdown().await?;
301    /// # Ok(())
302    /// # }
303    /// ```
304    pub async fn shutdown(&self) -> Result<()> {
305        self.inner.shutdown_requested.store(true, Ordering::Relaxed);
306        tracing::info!("🛑 Shutting down MCP client");
307
308        // 1. Shutdown message dispatcher
309        self.inner.protocol.dispatcher().shutdown();
310        tracing::debug!("✅ Message dispatcher stopped");
311
312        // 2. Disconnect transport (WebSocket: stops reconnection, HTTP: closes connections)
313        match self.inner.protocol.transport().disconnect().await {
314            Ok(()) => {
315                tracing::info!("✅ Transport disconnected successfully");
316            }
317            Err(e) => {
318                tracing::warn!("Transport disconnect error (may already be closed): {}", e);
319            }
320        }
321
322        tracing::info!("✅ MCP client shutdown complete");
323        Ok(())
324    }
325}
326
327// ============================================================================
328// HTTP-Specific Convenience Constructors (Feature-Gated)
329// ============================================================================
330
331#[cfg(feature = "http")]
332impl Client<turbomcp_transport::streamable_http_client::StreamableHttpClientTransport> {
333    /// Connect to an HTTP MCP server (convenience method)
334    ///
335    /// This is a convenient one-liner alternative to manual configuration.
336    /// Creates an HTTP client, connects, and initializes in one call.
337    ///
338    /// # Arguments
339    ///
340    /// * `url` - The base URL of the MCP server (e.g., "http://localhost:8080")
341    ///
342    /// # Returns
343    ///
344    /// Returns an initialized `Client` ready to use.
345    ///
346    /// # Errors
347    ///
348    /// Returns an error if:
349    /// - The URL is invalid
350    /// - Connection to the server fails
351    /// - Initialization handshake fails
352    ///
353    /// # Examples
354    ///
355    /// ```rust,no_run
356    /// use turbomcp_client::Client;
357    ///
358    /// # async fn example() -> turbomcp_protocol::Result<()> {
359    /// // Convenient one-liner - balanced with server DX
360    /// let client = Client::connect_http("http://localhost:8080").await?;
361    ///
362    /// // Now use it directly
363    /// let tools = client.list_tools().await?;
364    /// # Ok(())
365    /// # }
366    /// ```
367    ///
368    /// Compare to verbose approach (10+ lines):
369    /// ```rust,no_run
370    /// use turbomcp_client::Client;
371    /// use turbomcp_transport::streamable_http_client::{
372    ///     StreamableHttpClientConfig, StreamableHttpClientTransport
373    /// };
374    ///
375    /// # async fn example() -> turbomcp_protocol::Result<()> {
376    /// let config = StreamableHttpClientConfig {
377    ///     base_url: "http://localhost:8080".to_string(),
378    ///     ..Default::default()
379    /// };
380    /// let transport = StreamableHttpClientTransport::new(config)
381    ///     .map_err(|e| turbomcp_protocol::Error::transport(e.to_string()))?;
382    /// let client = Client::new(transport);
383    /// client.initialize().await?;
384    /// # Ok(())
385    /// # }
386    /// ```
387    pub async fn connect_http(url: impl Into<String>) -> Result<Self> {
388        use turbomcp_transport::streamable_http_client::{
389            StreamableHttpClientConfig, StreamableHttpClientTransport,
390        };
391
392        let config = StreamableHttpClientConfig {
393            base_url: url.into(),
394            ..Default::default()
395        };
396
397        let transport = StreamableHttpClientTransport::new(config).map_err(|e| {
398            turbomcp_protocol::Error::transport(format!("Failed to build HTTP transport: {e}"))
399        })?;
400        let client = Self::new(transport);
401
402        // Initialize connection immediately
403        client.initialize().await?;
404
405        Ok(client)
406    }
407
408    /// Connect to an HTTP MCP server with custom configuration
409    ///
410    /// Provides more control than `connect_http()` while still being ergonomic.
411    ///
412    /// # Arguments
413    ///
414    /// * `url` - The base URL of the MCP server
415    /// * `config_fn` - Function to customize the configuration
416    ///
417    /// # Examples
418    ///
419    /// ```rust,no_run
420    /// use turbomcp_client::Client;
421    /// use std::time::Duration;
422    ///
423    /// # async fn example() -> turbomcp_protocol::Result<()> {
424    /// let client = Client::connect_http_with("http://localhost:8080", |config| {
425    ///     config.timeout = Duration::from_secs(60);
426    ///     config.endpoint_path = "/api/mcp".to_string();
427    /// }).await?;
428    /// # Ok(())
429    /// # }
430    /// ```
431    pub async fn connect_http_with<F>(url: impl Into<String>, config_fn: F) -> Result<Self>
432    where
433        F: FnOnce(&mut turbomcp_transport::streamable_http_client::StreamableHttpClientConfig),
434    {
435        use turbomcp_transport::streamable_http_client::{
436            StreamableHttpClientConfig, StreamableHttpClientTransport,
437        };
438
439        let mut config = StreamableHttpClientConfig {
440            base_url: url.into(),
441            ..Default::default()
442        };
443
444        config_fn(&mut config);
445
446        let transport = StreamableHttpClientTransport::new(config).map_err(|e| {
447            turbomcp_protocol::Error::transport(format!("Failed to build HTTP transport: {e}"))
448        })?;
449        let client = Self::new(transport);
450
451        client.initialize().await?;
452
453        Ok(client)
454    }
455}
456
457// ============================================================================
458// TCP-Specific Convenience Constructors (Feature-Gated)
459// ============================================================================
460
461#[cfg(feature = "tcp")]
462impl Client<turbomcp_transport::tcp::TcpTransport> {
463    /// Connect to a TCP MCP server (convenience method)
464    ///
465    /// Convenient one-liner for TCP connections - balanced DX.
466    ///
467    /// # Arguments
468    ///
469    /// * `addr` - Server address (e.g., "127.0.0.1:8765" or localhost:8765")
470    ///
471    /// # Returns
472    ///
473    /// Returns an initialized `Client` ready to use.
474    ///
475    /// # Examples
476    ///
477    /// ```rust,no_run
478    /// # #[cfg(feature = "tcp")]
479    /// use turbomcp_client::Client;
480    ///
481    /// # async fn example() -> turbomcp_protocol::Result<()> {
482    /// let client = Client::connect_tcp("127.0.0.1:8765").await?;
483    /// let tools = client.list_tools().await?;
484    /// # Ok(())
485    /// # }
486    /// ```
487    pub async fn connect_tcp(addr: impl AsRef<str>) -> Result<Self> {
488        use std::net::SocketAddr;
489        use turbomcp_transport::tcp::TcpTransport;
490
491        let server_addr: SocketAddr = addr
492            .as_ref()
493            .parse()
494            .map_err(|e| Error::invalid_request(format!("Invalid address: {}", e)))?;
495
496        // Client binds to 0.0.0.0:0 (any available port)
497        let bind_addr: SocketAddr = if server_addr.is_ipv6() {
498            "[::]:0".parse().expect("valid IPv6 any-port address")
499        } else {
500            "0.0.0.0:0".parse().expect("valid IPv4 any-port address")
501        };
502
503        let transport = TcpTransport::new_client(bind_addr, server_addr);
504        let client = Self::new(transport);
505
506        client.initialize().await?;
507
508        Ok(client)
509    }
510}
511
512// ============================================================================
513// Unix Socket-Specific Convenience Constructors (Feature-Gated)
514// ============================================================================
515
516#[cfg(all(unix, feature = "unix"))]
517impl Client<turbomcp_transport::unix::UnixTransport> {
518    /// Connect to a Unix socket MCP server (convenience method)
519    ///
520    /// Convenient one-liner for Unix socket IPC - balanced DX.
521    ///
522    /// # Arguments
523    ///
524    /// * `path` - Socket file path (e.g., "/tmp/mcp.sock")
525    ///
526    /// # Returns
527    ///
528    /// Returns an initialized `Client` ready to use.
529    ///
530    /// # Examples
531    ///
532    /// ```rust,no_run
533    /// # #[cfg(all(unix, feature = "unix"))]
534    /// use turbomcp_client::Client;
535    ///
536    /// # async fn example() -> turbomcp_protocol::Result<()> {
537    /// let client = Client::connect_unix("/tmp/mcp.sock").await?;
538    /// let tools = client.list_tools().await?;
539    /// # Ok(())
540    /// # }
541    /// ```
542    pub async fn connect_unix(path: impl Into<std::path::PathBuf>) -> Result<Self> {
543        use turbomcp_transport::unix::UnixTransport;
544
545        let transport = UnixTransport::new_client(path.into());
546        let client = Self::new(transport);
547
548        client.initialize().await?;
549
550        Ok(client)
551    }
552}
553
554impl<T: Transport + 'static> Client<T> {
555    /// Register message handlers with the dispatcher
556    ///
557    /// This method sets up the callbacks that handle server-initiated requests
558    /// and notifications. The dispatcher's background task routes incoming
559    /// messages to these handlers.
560    ///
561    /// This is called automatically during Client construction (in `new()` and
562    /// `with_capabilities()`), so you don't need to call it manually.
563    ///
564    /// ## How It Works
565    ///
566    /// The handlers are synchronous closures that spawn async tasks to do the
567    /// actual work. This allows the dispatcher to continue routing messages
568    /// without blocking on handler execution.
569    fn register_dispatcher_handlers(&self) {
570        let dispatcher = self.inner.protocol.dispatcher();
571        let client_for_requests = self.clone();
572        let client_for_notifications = self.clone();
573
574        // Request handler (elicitation, sampling, etc.)
575        let semaphore = Arc::clone(&self.inner.handler_semaphore);
576        let request_handler = Arc::new(move |request: JsonRpcRequest| {
577            let client = client_for_requests.clone();
578            let method = request.method.clone();
579            let req_id = request.id.clone();
580            let semaphore = Arc::clone(&semaphore);
581
582            // ✅ Spawn async task with bounded concurrency
583            tokio::spawn(async move {
584                // Acquire permit (blocks if 100 requests already in flight)
585                let _permit = match semaphore.acquire().await {
586                    Ok(permit) => permit,
587                    Err(_) => {
588                        tracing::warn!(
589                            "Handler semaphore closed, dropping request: method={}",
590                            method
591                        );
592                        return;
593                    }
594                };
595
596                tracing::debug!(
597                    "🔄 [request_handler] Handling server-initiated request: method={}, id={:?}",
598                    method,
599                    req_id
600                );
601                if let Err(e) = client.handle_request(request).await {
602                    tracing::error!(
603                        "❌ [request_handler] Error handling server request '{}': {}",
604                        method,
605                        e
606                    );
607                    tracing::error!("   Request ID: {:?}", req_id);
608                    tracing::error!("   Error kind: {:?}", e.kind);
609                } else {
610                    tracing::debug!(
611                        "✅ [request_handler] Successfully handled server request: method={}, id={:?}",
612                        method,
613                        req_id
614                    );
615                }
616                // Permit automatically released on drop ✅
617            });
618            Ok(())
619        });
620
621        // Notification handler
622        let semaphore_notif = Arc::clone(&self.inner.handler_semaphore);
623        let notification_handler = Arc::new(move |notification: JsonRpcNotification| {
624            let client = client_for_notifications.clone();
625            let semaphore = Arc::clone(&semaphore_notif);
626
627            // ✅ Spawn async task with bounded concurrency
628            tokio::spawn(async move {
629                // Acquire permit (blocks if 100 handlers already in flight)
630                let _permit = match semaphore.acquire().await {
631                    Ok(permit) => permit,
632                    Err(_) => {
633                        tracing::warn!("Handler semaphore closed, dropping notification");
634                        return;
635                    }
636                };
637
638                if let Err(e) = client.handle_notification(notification).await {
639                    tracing::error!("Error handling server notification: {}", e);
640                }
641                // Permit automatically released on drop ✅
642            });
643            Ok(())
644        });
645
646        // Register handlers synchronously - no race condition!
647        // The set_* methods are now synchronous with std::sync::Mutex
648        dispatcher.set_request_handler(request_handler);
649        dispatcher.set_notification_handler(notification_handler);
650        tracing::debug!("Dispatcher handlers registered successfully");
651    }
652
653    /// Handle server-initiated requests (elicitation, sampling, roots)
654    ///
655    /// This method is called by the MessageDispatcher when it receives a request
656    /// from the server. It routes the request to the appropriate handler based on
657    /// the method name.
658    async fn handle_request(&self, request: JsonRpcRequest) -> Result<()> {
659        match request.method.as_str() {
660            "sampling/createMessage" => {
661                let handler_opt = self.inner.sampling_handler.lock().clone();
662                if let Some(handler) = handler_opt {
663                    // Extract request ID for proper correlation
664                    let request_id = match &request.id {
665                        turbomcp_protocol::MessageId::String(s) => s.clone(),
666                        turbomcp_protocol::MessageId::Number(n) => n.to_string(),
667                        turbomcp_protocol::MessageId::Uuid(u) => u.to_string(),
668                    };
669
670                    let params: CreateMessageRequest =
671                        serde_json::from_value(request.params.unwrap_or(serde_json::Value::Null))
672                            .map_err(|e| {
673                            Error::internal(format!("Invalid createMessage params: {}", e))
674                        })?;
675
676                    match handler.handle_create_message(request_id, params).await {
677                        Ok(result) => {
678                            let result_value = serde_json::to_value(result).map_err(|e| {
679                                Error::internal(format!("Failed to serialize response: {}", e))
680                            })?;
681                            let response = JsonRpcResponse::success(result_value, request.id);
682                            self.send_response(response).await?;
683                        }
684                        Err(e) => {
685                            tracing::warn!(
686                                "⚠️  [handle_request] Sampling handler returned error: {}",
687                                e
688                            );
689
690                            // Preserve error semantics by checking actual error type
691                            // This allows proper error code propagation for retry logic
692                            let (code, message) = if let Some(handler_err) =
693                                e.downcast_ref::<HandlerError>()
694                            {
695                                // HandlerError has explicit JSON-RPC code mapping
696                                let json_err = handler_err.into_jsonrpc_error();
697                                tracing::info!(
698                                    "📋 [handle_request] HandlerError mapped to JSON-RPC code: {}",
699                                    json_err.code
700                                );
701                                (json_err.code, json_err.message)
702                            } else if let Some(proto_err) =
703                                e.downcast_ref::<turbomcp_protocol::Error>()
704                            {
705                                // Protocol errors have ErrorKind-based mapping
706                                tracing::info!(
707                                    "📋 [handle_request] Protocol error mapped to code: {}",
708                                    proto_err.jsonrpc_error_code()
709                                );
710                                (proto_err.jsonrpc_error_code(), proto_err.to_string())
711                            } else {
712                                // Generic errors default to Internal (-32603)
713                                // Log the error type for debugging (should rarely hit this path)
714                                tracing::warn!(
715                                    "📋 [handle_request] Sampling handler returned unknown error type (not HandlerError or Protocol error): {}",
716                                    std::any::type_name_of_val(&*e)
717                                );
718                                (-32603, format!("Sampling handler error: {}", e))
719                            };
720
721                            let error = turbomcp_protocol::jsonrpc::JsonRpcError {
722                                code,
723                                message,
724                                data: None,
725                            };
726                            let response =
727                                JsonRpcResponse::error_response(error, request.id.clone());
728
729                            tracing::info!(
730                                "🔄 [handle_request] Attempting to send error response for request: {:?}",
731                                request.id
732                            );
733                            self.send_response(response).await?;
734                            tracing::info!(
735                                "✅ [handle_request] Error response sent successfully for request: {:?}",
736                                request.id
737                            );
738                        }
739                    }
740                } else {
741                    // No handler configured
742                    let error = turbomcp_protocol::jsonrpc::JsonRpcError {
743                        code: -32601,
744                        message: "Sampling not supported".to_string(),
745                        data: None,
746                    };
747                    let response = JsonRpcResponse::error_response(error, request.id);
748                    self.send_response(response).await?;
749                }
750            }
751            "roots/list" => {
752                // Handle roots/list request from server
753                // Clone the handler Arc to avoid holding mutex across await
754                let handler_opt = self.inner.handlers.lock().roots.clone();
755
756                let roots_result = if let Some(handler) = handler_opt {
757                    handler.handle_roots_request().await
758                } else {
759                    // No handler - return empty list per MCP spec
760                    Ok(Vec::new())
761                };
762
763                match roots_result {
764                    Ok(roots) => {
765                        let result_value =
766                            serde_json::to_value(turbomcp_protocol::types::ListRootsResult {
767                                roots,
768                                _meta: None,
769                            })
770                            .map_err(|e| {
771                                Error::internal(format!(
772                                    "Failed to serialize roots response: {}",
773                                    e
774                                ))
775                            })?;
776                        let response = JsonRpcResponse::success(result_value, request.id);
777                        self.send_response(response).await?;
778                    }
779                    Err(e) => {
780                        // FIXED: Extract error code from HandlerError instead of hardcoding -32603
781                        // Roots handler returns HandlerResult<Vec<Root>>, so error is HandlerError
782                        let json_err = e.into_jsonrpc_error();
783                        let response = JsonRpcResponse::error_response(json_err, request.id);
784                        self.send_response(response).await?;
785                    }
786                }
787            }
788            "elicitation/create" => {
789                // Clone handler Arc before await to avoid holding mutex across await
790                let handler_opt = self.inner.handlers.lock().elicitation.clone();
791                if let Some(handler) = handler_opt {
792                    // Parse elicitation request params as MCP protocol type
793                    let proto_request: turbomcp_protocol::types::ElicitRequest =
794                        serde_json::from_value(request.params.unwrap_or(serde_json::Value::Null))
795                            .map_err(|e| {
796                            Error::internal(format!("Invalid elicitation params: {}", e))
797                        })?;
798
799                    // Wrap protocol request with ID for handler (preserves type safety!)
800                    let handler_request =
801                        crate::handlers::ElicitationRequest::new(request.id.clone(), proto_request);
802
803                    // Call the registered elicitation handler
804                    match handler.handle_elicitation(handler_request).await {
805                        Ok(elicit_response) => {
806                            // Convert handler response back to protocol type
807                            let proto_result = elicit_response.into_protocol();
808                            let result_value = serde_json::to_value(proto_result).map_err(|e| {
809                                Error::internal(format!(
810                                    "Failed to serialize elicitation response: {}",
811                                    e
812                                ))
813                            })?;
814                            let response = JsonRpcResponse::success(result_value, request.id);
815                            self.send_response(response).await?;
816                        }
817                        Err(e) => {
818                            // Convert handler error to JSON-RPC error using centralized mapping
819                            let response =
820                                JsonRpcResponse::error_response(e.into_jsonrpc_error(), request.id);
821                            self.send_response(response).await?;
822                        }
823                    }
824                } else {
825                    // No handler configured - elicitation not supported
826                    let error = turbomcp_protocol::jsonrpc::JsonRpcError {
827                        code: -32601,
828                        message: "Elicitation not supported - no handler registered".to_string(),
829                        data: None,
830                    };
831                    let response = JsonRpcResponse::error_response(error, request.id);
832                    self.send_response(response).await?;
833                }
834            }
835            _ => {
836                // Unknown method
837                let error = turbomcp_protocol::jsonrpc::JsonRpcError {
838                    code: -32601,
839                    message: format!("Method not found: {}", request.method),
840                    data: None,
841                };
842                let response = JsonRpcResponse::error_response(error, request.id);
843                self.send_response(response).await?;
844            }
845        }
846        Ok(())
847    }
848
849    /// Handle server-initiated notifications
850    ///
851    /// Routes notifications to appropriate handlers based on method name.
852    /// MCP defines several notification types that servers can send to clients:
853    ///
854    /// - `notifications/progress` - Progress updates for long-running operations
855    /// - `notifications/message` - Log messages from server
856    /// - `notifications/resources/updated` - Resource content changed
857    /// - `notifications/resources/list_changed` - Resource list changed
858    async fn handle_notification(&self, notification: JsonRpcNotification) -> Result<()> {
859        match notification.method.as_str() {
860            "notifications/progress" => {
861                // Route to progress handler
862                let handler_opt = self.inner.handlers.lock().get_progress_handler();
863
864                if let Some(handler) = handler_opt {
865                    let progress: crate::handlers::ProgressNotification = serde_json::from_value(
866                        notification.params.unwrap_or(serde_json::Value::Null),
867                    )
868                    .map_err(|e| {
869                        Error::internal(format!("Invalid progress notification: {}", e))
870                    })?;
871
872                    if let Err(e) = handler.handle_progress(progress).await {
873                        tracing::error!("Progress handler error: {}", e);
874                    }
875                } else {
876                    tracing::debug!("Progress notification received (no handler registered)");
877                }
878            }
879
880            "notifications/message" => {
881                // Route to log handler
882                let handler_opt = self.inner.handlers.lock().get_log_handler();
883
884                if let Some(handler) = handler_opt {
885                    // Parse log message
886                    let log: crate::handlers::LoggingNotification = serde_json::from_value(
887                        notification.params.unwrap_or(serde_json::Value::Null),
888                    )
889                    .map_err(|e| Error::internal(format!("Invalid log notification: {}", e)))?;
890
891                    // Call handler
892                    if let Err(e) = handler.handle_log(log).await {
893                        tracing::error!("Log handler error: {}", e);
894                    }
895                } else {
896                    tracing::debug!("Received log notification but no handler registered");
897                }
898            }
899
900            "notifications/resources/updated" => {
901                // Route to resource update handler
902                let handler_opt = self.inner.handlers.lock().get_resource_update_handler();
903
904                if let Some(handler) = handler_opt {
905                    // Parse resource update notification
906                    let update: crate::handlers::ResourceUpdatedNotification =
907                        serde_json::from_value(
908                            notification.params.unwrap_or(serde_json::Value::Null),
909                        )
910                        .map_err(|e| {
911                            Error::internal(format!("Invalid resource update notification: {}", e))
912                        })?;
913
914                    // Call handler
915                    if let Err(e) = handler.handle_resource_update(update).await {
916                        tracing::error!("Resource update handler error: {}", e);
917                    }
918                } else {
919                    tracing::debug!(
920                        "Received resource update notification but no handler registered"
921                    );
922                }
923            }
924
925            "notifications/resources/list_changed" => {
926                // Route to resource list changed handler
927                let handler_opt = self
928                    .inner
929                    .handlers
930                    .lock()
931                    .get_resource_list_changed_handler();
932
933                if let Some(handler) = handler_opt {
934                    if let Err(e) = handler.handle_resource_list_changed().await {
935                        tracing::error!("Resource list changed handler error: {}", e);
936                    }
937                } else {
938                    tracing::debug!(
939                        "Resource list changed notification received (no handler registered)"
940                    );
941                }
942            }
943
944            "notifications/prompts/list_changed" => {
945                // Route to prompt list changed handler
946                let handler_opt = self.inner.handlers.lock().get_prompt_list_changed_handler();
947
948                if let Some(handler) = handler_opt {
949                    if let Err(e) = handler.handle_prompt_list_changed().await {
950                        tracing::error!("Prompt list changed handler error: {}", e);
951                    }
952                } else {
953                    tracing::debug!(
954                        "Prompt list changed notification received (no handler registered)"
955                    );
956                }
957            }
958
959            "notifications/tools/list_changed" => {
960                // Route to tool list changed handler
961                let handler_opt = self.inner.handlers.lock().get_tool_list_changed_handler();
962
963                if let Some(handler) = handler_opt {
964                    if let Err(e) = handler.handle_tool_list_changed().await {
965                        tracing::error!("Tool list changed handler error: {}", e);
966                    }
967                } else {
968                    tracing::debug!(
969                        "Tool list changed notification received (no handler registered)"
970                    );
971                }
972            }
973
974            "notifications/cancelled" => {
975                // Route to cancellation handler
976                let handler_opt = self.inner.handlers.lock().get_cancellation_handler();
977
978                if let Some(handler) = handler_opt {
979                    // Parse cancellation notification
980                    let cancellation: crate::handlers::CancelledNotification =
981                        serde_json::from_value(
982                            notification.params.unwrap_or(serde_json::Value::Null),
983                        )
984                        .map_err(|e| {
985                            Error::internal(format!("Invalid cancellation notification: {}", e))
986                        })?;
987
988                    // Call handler
989                    if let Err(e) = handler.handle_cancellation(cancellation).await {
990                        tracing::error!("Cancellation handler error: {}", e);
991                    }
992                } else {
993                    tracing::debug!("Cancellation notification received (no handler registered)");
994                }
995            }
996
997            _ => {
998                // Unknown notification type
999                tracing::debug!("Received unknown notification: {}", notification.method);
1000            }
1001        }
1002
1003        Ok(())
1004    }
1005
1006    async fn send_response(&self, response: JsonRpcResponse) -> Result<()> {
1007        tracing::info!(
1008            "📤 [send_response] Sending JSON-RPC response: id={:?}",
1009            response.id
1010        );
1011
1012        let payload = serde_json::to_vec(&response).map_err(|e| {
1013            tracing::error!("❌ [send_response] Failed to serialize response: {}", e);
1014            Error::internal(format!("Failed to serialize response: {}", e))
1015        })?;
1016
1017        tracing::debug!(
1018            "📤 [send_response] Response payload: {} bytes",
1019            payload.len()
1020        );
1021        tracing::debug!(
1022            "📤 [send_response] Response JSON: {}",
1023            String::from_utf8_lossy(&payload)
1024        );
1025
1026        let message = TransportMessage::new(
1027            turbomcp_protocol::MessageId::from("response".to_string()),
1028            payload.into(),
1029        );
1030
1031        self.inner
1032            .protocol
1033            .transport()
1034            .send(message)
1035            .await
1036            .map_err(|e| {
1037                tracing::error!("❌ [send_response] Transport send failed: {}", e);
1038                Error::transport(format!("Failed to send response: {}", e))
1039            })?;
1040
1041        tracing::info!(
1042            "✅ [send_response] Response sent successfully: id={:?}",
1043            response.id
1044        );
1045        Ok(())
1046    }
1047
1048    /// Initialize the connection with the MCP server
1049    ///
1050    /// Performs the initialization handshake with the server, negotiating capabilities
1051    /// and establishing the protocol version. This method must be called before
1052    /// any other operations can be performed.
1053    ///
1054    /// # Returns
1055    ///
1056    /// Returns an `InitializeResult` containing server information and negotiated capabilities.
1057    ///
1058    /// # Errors
1059    ///
1060    /// Returns an error if:
1061    /// - The transport connection fails
1062    /// - The server rejects the initialization request
1063    /// - Protocol negotiation fails
1064    ///
1065    /// # Examples
1066    ///
1067    /// ```rust,no_run
1068    /// # use turbomcp_client::Client;
1069    /// # use turbomcp_transport::stdio::StdioTransport;
1070    /// # async fn example() -> turbomcp_protocol::Result<()> {
1071    /// let mut client = Client::new(StdioTransport::new());
1072    ///
1073    /// let result = client.initialize().await?;
1074    /// println!("Server: {} v{}", result.server_info.name, result.server_info.version);
1075    /// # Ok(())
1076    /// # }
1077    /// ```
1078    pub async fn initialize(&self) -> Result<InitializeResult> {
1079        // Build client capabilities based on registered handlers (automatic detection)
1080        let mut client_caps = ProtocolClientCapabilities::default();
1081
1082        // Detect sampling capability from handler
1083        if let Some(sampling_caps) = self.get_sampling_capabilities() {
1084            client_caps.sampling = Some(sampling_caps);
1085        }
1086
1087        // Detect elicitation capability from handler
1088        if let Some(elicitation_caps) = self.get_elicitation_capabilities() {
1089            client_caps.elicitation = Some(elicitation_caps);
1090        }
1091
1092        // Detect roots capability from handler
1093        if let Some(roots_caps) = self.get_roots_capabilities() {
1094            client_caps.roots = Some(roots_caps);
1095        }
1096
1097        let request = InitializeRequest {
1098            protocol_version: PROTOCOL_VERSION.into(),
1099            capabilities: client_caps,
1100            client_info: turbomcp_protocol::types::Implementation {
1101                name: "turbomcp-client".to_string(),
1102                version: env!("CARGO_PKG_VERSION").to_string(),
1103                title: Some("TurboMCP Client".to_string()),
1104                ..Default::default()
1105            },
1106            _meta: None,
1107        };
1108
1109        self.initialize_with_request(request).await
1110    }
1111
1112    /// Initialize the MCP session with an explicit initialize request.
1113    ///
1114    /// This is the opt-in path for draft protocol versions and capability
1115    /// fields such as official MCP `extensions`.
1116    pub async fn initialize_with_request(
1117        &self,
1118        request: InitializeRequest,
1119    ) -> Result<InitializeResult> {
1120        // Auto-connect transport if not already connected
1121        // This provides consistent DX across all transports (Stdio, TCP, HTTP, WebSocket, Unix)
1122        let transport = self.inner.protocol.transport();
1123        let transport_state = transport.state().await;
1124        if !matches!(
1125            transport_state,
1126            turbomcp_transport::TransportState::Connected
1127        ) {
1128            tracing::debug!(
1129                "Auto-connecting transport (current state: {:?})",
1130                transport_state
1131            );
1132            transport
1133                .connect()
1134                .await
1135                .map_err(|e| Error::transport(format!("Failed to connect transport: {}", e)))?;
1136            tracing::info!("Transport connected successfully");
1137        }
1138
1139        let protocol_response: ProtocolInitializeResult = self
1140            .inner
1141            .protocol
1142            .request("initialize", Some(serde_json::to_value(request)?))
1143            .await?;
1144
1145        // AtomicBool: lock-free store with Ordering::Relaxed
1146        self.inner.initialized.store(true, Ordering::Relaxed);
1147
1148        // Send initialized notification
1149        self.inner
1150            .protocol
1151            .notify("notifications/initialized", None)
1152            .await?;
1153
1154        // Convert protocol response to client response type
1155        Ok(InitializeResult {
1156            server_info: protocol_response.server_info,
1157            server_capabilities: protocol_response.capabilities,
1158        })
1159    }
1160
1161    /// Subscribe to resource change notifications
1162    ///
1163    /// Registers interest in receiving notifications when the specified
1164    /// resource changes. The server will send notifications when the
1165    /// resource is modified, created, or deleted.
1166    ///
1167    /// # Arguments
1168    ///
1169    /// * `uri` - The URI of the resource to monitor
1170    ///
1171    /// # Returns
1172    ///
1173    /// Returns `EmptyResult` on successful subscription.
1174    ///
1175    /// # Errors
1176    ///
1177    /// Returns an error if:
1178    /// - The client is not initialized
1179    /// - The URI is invalid or empty
1180    /// - The server doesn't support subscriptions
1181    /// - The request fails
1182    ///
1183    /// # Examples
1184    ///
1185    /// ```rust,no_run
1186    /// # use turbomcp_client::Client;
1187    /// # use turbomcp_transport::stdio::StdioTransport;
1188    /// # async fn example() -> turbomcp_protocol::Result<()> {
1189    /// let mut client = Client::new(StdioTransport::new());
1190    /// client.initialize().await?;
1191    ///
1192    /// // Subscribe to file changes
1193    /// client.subscribe("file:///watch/directory").await?;
1194    /// println!("Subscribed to resource changes");
1195    /// # Ok(())
1196    /// # }
1197    /// ```
1198    pub async fn subscribe(&self, uri: &str) -> Result<EmptyResult> {
1199        if !self.inner.initialized.load(Ordering::Relaxed) {
1200            return Err(Error::invalid_request("Client not initialized"));
1201        }
1202
1203        if uri.is_empty() {
1204            return Err(Error::invalid_request("Subscription URI cannot be empty"));
1205        }
1206
1207        // Send resources/subscribe request
1208        let request = SubscribeRequest { uri: uri.into() };
1209
1210        self.inner
1211            .protocol
1212            .request(
1213                "resources/subscribe",
1214                Some(serde_json::to_value(request).map_err(|e| {
1215                    Error::internal(format!("Failed to serialize subscribe request: {}", e))
1216                })?),
1217            )
1218            .await
1219    }
1220
1221    /// Unsubscribe from resource change notifications
1222    ///
1223    /// Cancels a previous subscription to resource changes. After unsubscribing,
1224    /// the client will no longer receive notifications for the specified resource.
1225    ///
1226    /// # Arguments
1227    ///
1228    /// * `uri` - The URI of the resource to stop monitoring
1229    ///
1230    /// # Returns
1231    ///
1232    /// Returns `EmptyResult` on successful unsubscription.
1233    ///
1234    /// # Errors
1235    ///
1236    /// Returns an error if:
1237    /// - The client is not initialized
1238    /// - The URI is invalid or empty
1239    /// - No active subscription exists for the URI
1240    /// - The request fails
1241    ///
1242    /// # Examples
1243    ///
1244    /// ```rust,no_run
1245    /// # use turbomcp_client::Client;
1246    /// # use turbomcp_transport::stdio::StdioTransport;
1247    /// # async fn example() -> turbomcp_protocol::Result<()> {
1248    /// let mut client = Client::new(StdioTransport::new());
1249    /// client.initialize().await?;
1250    ///
1251    /// // Unsubscribe from file changes
1252    /// client.unsubscribe("file:///watch/directory").await?;
1253    /// println!("Unsubscribed from resource changes");
1254    /// # Ok(())
1255    /// # }
1256    /// ```
1257    pub async fn unsubscribe(&self, uri: &str) -> Result<EmptyResult> {
1258        if !self.inner.initialized.load(Ordering::Relaxed) {
1259            return Err(Error::invalid_request("Client not initialized"));
1260        }
1261
1262        if uri.is_empty() {
1263            return Err(Error::invalid_request("Unsubscription URI cannot be empty"));
1264        }
1265
1266        // Send resources/unsubscribe request
1267        let request = UnsubscribeRequest { uri: uri.into() };
1268
1269        self.inner
1270            .protocol
1271            .request(
1272                "resources/unsubscribe",
1273                Some(serde_json::to_value(request).map_err(|e| {
1274                    Error::internal(format!("Failed to serialize unsubscribe request: {}", e))
1275                })?),
1276            )
1277            .await
1278    }
1279
1280    /// Get the client's capabilities configuration
1281    #[must_use]
1282    pub fn capabilities(&self) -> &ClientCapabilities {
1283        &self.inner.capabilities
1284    }
1285
1286    // ============================================================================
1287    // Tasks API Methods (MCP 2025-11-25 Draft - SEP-1686)
1288    // ============================================================================
1289
1290    /// Retrieve the status of a task (tasks/get)
1291    ///
1292    /// Polls the server for the current status of a specific task.
1293    ///
1294    /// # Arguments
1295    ///
1296    /// * `task_id` - The ID of the task to query
1297    ///
1298    /// # Returns
1299    ///
1300    /// Returns the current `Task` state including status, timestamps, and messages.
1301    #[cfg(feature = "experimental-tasks")]
1302    pub async fn get_task(&self, task_id: &str) -> Result<Task> {
1303        let request = GetTaskRequest {
1304            task_id: task_id.to_string(),
1305        };
1306
1307        self.inner
1308            .protocol
1309            .request(
1310                "tasks/get",
1311                Some(serde_json::to_value(request).map_err(|e| {
1312                    Error::internal(format!("Failed to serialize get_task request: {}", e))
1313                })?),
1314            )
1315            .await
1316    }
1317
1318    /// Cancel a running task (tasks/cancel)
1319    ///
1320    /// Attempts to cancel a task execution. This is a best-effort operation.
1321    ///
1322    /// # Arguments
1323    ///
1324    /// * `task_id` - The ID of the task to cancel
1325    ///
1326    /// # Returns
1327    ///
1328    /// Returns the updated `Task` state (typically with status "cancelled").
1329    #[cfg(feature = "experimental-tasks")]
1330    pub async fn cancel_task(&self, task_id: &str) -> Result<Task> {
1331        let request = CancelTaskRequest {
1332            task_id: task_id.to_string(),
1333        };
1334
1335        self.inner
1336            .protocol
1337            .request(
1338                "tasks/cancel",
1339                Some(serde_json::to_value(request).map_err(|e| {
1340                    Error::internal(format!("Failed to serialize cancel_task request: {}", e))
1341                })?),
1342            )
1343            .await
1344    }
1345
1346    /// List all tasks (tasks/list)
1347    ///
1348    /// Retrieves a paginated list of tasks known to the server.
1349    ///
1350    /// # Arguments
1351    ///
1352    /// * `cursor` - Optional pagination cursor from a previous response
1353    /// * `limit` - Optional maximum number of tasks to return
1354    ///
1355    /// # Returns
1356    ///
1357    /// Returns a `ListTasksResult` containing the list of tasks and next cursor.
1358    #[cfg(feature = "experimental-tasks")]
1359    pub async fn list_tasks(
1360        &self,
1361        cursor: Option<String>,
1362        limit: Option<usize>,
1363    ) -> Result<ListTasksResult> {
1364        let request = ListTasksRequest { cursor, limit };
1365
1366        self.inner
1367            .protocol
1368            .request(
1369                "tasks/list",
1370                Some(serde_json::to_value(request).map_err(|e| {
1371                    Error::internal(format!("Failed to serialize list_tasks request: {}", e))
1372                })?),
1373            )
1374            .await
1375    }
1376
1377    /// Retrieve the result of a completed task (tasks/result)
1378    ///
1379    /// Blocks until the task reaches a terminal state (completed, failed, or cancelled),
1380    /// then returns the operation result.
1381    ///
1382    /// # Arguments
1383    ///
1384    /// * `task_id` - The ID of the task to retrieve results for
1385    ///
1386    /// # Returns
1387    ///
1388    /// Returns a `GetTaskPayloadResult` containing the operation result (e.g. CallToolResult).
1389    #[cfg(feature = "experimental-tasks")]
1390    pub async fn get_task_result(&self, task_id: &str) -> Result<GetTaskPayloadResult> {
1391        let request = GetTaskPayloadRequest {
1392            task_id: task_id.to_string(),
1393        };
1394
1395        self.inner
1396            .protocol
1397            .request(
1398                "tasks/result",
1399                Some(serde_json::to_value(request).map_err(|e| {
1400                    Error::internal(format!(
1401                        "Failed to serialize get_task_result request: {}",
1402                        e
1403                    ))
1404                })?),
1405            )
1406            .await
1407    }
1408
1409    // Note: Capability detection methods (has_*_handler, get_*_capabilities)
1410    // are defined in their respective operation modules:
1411    // - sampling.rs: has_sampling_handler, get_sampling_capabilities
1412    // - handlers.rs: has_elicitation_handler, has_roots_handler
1413    //
1414    // Additional capability getters for elicitation and roots added below
1415    // since they're used during initialization
1416
1417    /// Get elicitation capabilities if handler is registered
1418    /// Automatically detects capability based on registered handler
1419    fn get_elicitation_capabilities(
1420        &self,
1421    ) -> Option<turbomcp_protocol::types::ElicitationCapabilities> {
1422        if self.has_elicitation_handler() {
1423            // Currently returns default capabilities. In the future, schema_validation support
1424            // could be detected from handler traits by adding a HasSchemaValidation marker trait
1425            // that handlers could implement. For now, handlers validate schemas themselves.
1426            Some(turbomcp_protocol::types::ElicitationCapabilities::default())
1427        } else {
1428            None
1429        }
1430    }
1431
1432    /// Get roots capabilities if handler is registered
1433    fn get_roots_capabilities(&self) -> Option<turbomcp_protocol::types::RootsCapabilities> {
1434        if self.has_roots_handler() {
1435            // Roots capabilities indicate whether list can change
1436            Some(turbomcp_protocol::types::RootsCapabilities {
1437                list_changed: Some(true), // Support dynamic roots by default
1438            })
1439        } else {
1440            None
1441        }
1442    }
1443}
1444
1445#[cfg(test)]
1446mod tests {
1447    use super::*;
1448    use std::future::Future;
1449    use std::pin::Pin;
1450    use turbomcp_transport::{
1451        TransportCapabilities, TransportConfig, TransportMessage, TransportMetrics,
1452        TransportResult, TransportState, TransportType,
1453    };
1454
1455    #[derive(Debug, Default)]
1456    struct NoopTransport {
1457        capabilities: TransportCapabilities,
1458    }
1459
1460    impl Transport for NoopTransport {
1461        fn transport_type(&self) -> TransportType {
1462            TransportType::Stdio
1463        }
1464
1465        fn capabilities(&self) -> &TransportCapabilities {
1466            &self.capabilities
1467        }
1468
1469        fn state(&self) -> Pin<Box<dyn Future<Output = TransportState> + Send + '_>> {
1470            Box::pin(async { TransportState::Disconnected })
1471        }
1472
1473        fn connect(&self) -> Pin<Box<dyn Future<Output = TransportResult<()>> + Send + '_>> {
1474            Box::pin(async { Ok(()) })
1475        }
1476
1477        fn disconnect(&self) -> Pin<Box<dyn Future<Output = TransportResult<()>> + Send + '_>> {
1478            Box::pin(async { Ok(()) })
1479        }
1480
1481        fn send(
1482            &self,
1483            _message: TransportMessage,
1484        ) -> Pin<Box<dyn Future<Output = TransportResult<()>> + Send + '_>> {
1485            Box::pin(async { Ok(()) })
1486        }
1487
1488        fn receive(
1489            &self,
1490        ) -> Pin<Box<dyn Future<Output = TransportResult<Option<TransportMessage>>> + Send + '_>>
1491        {
1492            Box::pin(async { Ok(None) })
1493        }
1494
1495        fn metrics(&self) -> Pin<Box<dyn Future<Output = TransportMetrics> + Send + '_>> {
1496            Box::pin(async { TransportMetrics::default() })
1497        }
1498
1499        fn configure(
1500            &self,
1501            _config: TransportConfig,
1502        ) -> Pin<Box<dyn Future<Output = TransportResult<()>> + Send + '_>> {
1503            Box::pin(async { Ok(()) })
1504        }
1505    }
1506
1507    #[tokio::test]
1508    async fn test_with_capabilities_and_config_uses_handler_limit() {
1509        let capabilities = ClientCapabilities {
1510            max_concurrent_handlers: 7,
1511            ..Default::default()
1512        };
1513
1514        let client = Client::with_capabilities_and_config(
1515            NoopTransport::default(),
1516            capabilities,
1517            TransportConfig::default(),
1518        );
1519
1520        assert_eq!(client.inner.handler_semaphore.available_permits(), 7);
1521    }
1522
1523    #[tokio::test]
1524    async fn test_shutdown_sets_shutdown_flag() {
1525        let client = Client::new(NoopTransport::default());
1526        assert!(!client.inner.shutdown_requested.load(Ordering::Relaxed));
1527
1528        client.shutdown().await.expect("shutdown should succeed");
1529
1530        assert!(client.inner.shutdown_requested.load(Ordering::Relaxed));
1531    }
1532}