Skip to main content

adk_tool/mcp/
reconnect.rs

1// MCP Connection Refresher
2//
3// Provides automatic reconnection for MCP connections when they fail.
4// Based on adk-go's connectionRefresher pattern.
5//
6// Handles:
7// - A closed transport, as when a stdio server process exits
8// - A broken pipe, reset connection, or interrupted HTTP stream
9// - An expired Streamable HTTP session
10// - HTTP 401 rejections, so a factory can reconnect with fresh credentials
11// - Automatic retry with reconnection
12
13use super::discovery::{ListError, McpDiscoveryLimits, list_tools};
14use rmcp::{
15    RoleClient, ServiceError,
16    model::{CallToolRequestParams, CallToolResponse, Tool as McpTool},
17    service::RunningService,
18};
19use std::sync::Arc;
20use tokio::sync::{Mutex, RwLock};
21use tracing::{debug, info, warn};
22
23/// How a failed request relates to the connection that carried it.
24#[derive(Debug, Clone, Copy, PartialEq, Eq)]
25enum Failure {
26    /// The connection can no longer carry requests.
27    ConnectionLost,
28    /// The server rejected the request's credentials with HTTP 401 before running it.
29    AuthRejected,
30    /// The server answered, or the request failed for a reason a new connection does not fix.
31    Other,
32}
33
34/// Classifies `error` from its variant and the transport error it wraps.
35///
36/// Text the server chose, such as an HTTP error body, never decides the outcome.
37fn classify(error: &ServiceError) -> Failure {
38    match error {
39        ServiceError::TransportClosed => Failure::ConnectionLost,
40        ServiceError::TransportSend(error) => classify_transport(error.error.as_ref()),
41        // The server answered with a JSON-RPC error or an unexpected result, or the
42        // request ended on this side: none of these leaves the connection unusable.
43        _ => Failure::Other,
44    }
45}
46
47/// The error ADK's own Streamable HTTP client reports.
48#[cfg(feature = "http-transport")]
49type HttpError = rmcp::transport::streamable_http_client::StreamableHttpError<reqwest::Error>;
50
51fn classify_transport(error: &(dyn std::error::Error + 'static)) -> Failure {
52    #[cfg(feature = "http-transport")]
53    if let Some(error) = error.downcast_ref::<HttpError>() {
54        return classify_http(error);
55    }
56    let mut current = Some(error);
57    while let Some(error) = current {
58        #[cfg(feature = "http-transport")]
59        if error.is::<rmcp::transport::streamable_http_client::AuthRequiredError>() {
60            return Failure::AuthRejected;
61        }
62        if let Some(error) = error.downcast_ref::<std::io::Error>() {
63            return classify_io(error);
64        }
65        current = error.source();
66    }
67    Failure::Other
68}
69
70#[cfg(feature = "http-transport")]
71fn classify_http(error: &HttpError) -> Failure {
72    use rmcp::transport::streamable_http_client::{SseError, StreamableHttpError};
73    match error {
74        StreamableHttpError::AuthRequired(_) => Failure::AuthRejected,
75        // rmcp formats this as `HTTP {status}: {body}`, so the prefix is rmcp's, not the server's.
76        StreamableHttpError::UnexpectedServerResponse(message)
77            if message.starts_with("HTTP 401 ") =>
78        {
79            Failure::AuthRejected
80        }
81        StreamableHttpError::Client(error)
82            if error.status() == Some(reqwest::StatusCode::UNAUTHORIZED) =>
83        {
84            Failure::AuthRejected
85        }
86        StreamableHttpError::Io(error) => classify_io(error),
87        StreamableHttpError::Sse(SseError::Body(_))
88        | StreamableHttpError::UnexpectedEndOfStream
89        | StreamableHttpError::TransportChannelClosed
90        | StreamableHttpError::SessionExpired => Failure::ConnectionLost,
91        // A 5xx, an unparseable body, or any other answer the server sent on a live session.
92        _ => Failure::Other,
93    }
94}
95
96fn classify_io(error: &std::io::Error) -> Failure {
97    use std::io::ErrorKind;
98    match error.kind() {
99        ErrorKind::BrokenPipe
100        | ErrorKind::ConnectionReset
101        | ErrorKind::ConnectionAborted
102        | ErrorKind::NotConnected
103        | ErrorKind::UnexpectedEof => Failure::ConnectionLost,
104        _ => Failure::Other,
105    }
106}
107
108/// Returns `true` when `error` shows the connection is unusable, or that the server
109/// rejected the request's credentials, so a new connection may succeed.
110///
111/// The decision comes from the error's variant: a closed transport, a broken pipe or
112/// reset connection, an interrupted HTTP stream, an expired session, or an HTTP 401.
113/// An answer from the server, such as an HTTP 5xx or a JSON-RPC error, never
114/// triggers a refresh, whatever its body says.
115///
116/// # Example
117///
118/// ```
119/// use adk_tool::mcp::{rmcp::ServiceError, should_refresh_connection};
120///
121/// assert!(should_refresh_connection(&ServiceError::TransportClosed));
122/// assert!(!should_refresh_connection(&ServiceError::UnexpectedResponse));
123/// ```
124pub fn should_refresh_connection(error: &ServiceError) -> bool {
125    match classify(error) {
126        Failure::ConnectionLost | Failure::AuthRejected => true,
127        Failure::Other => false,
128    }
129}
130
131/// Returns `true` when the transport reports that the server rejected the
132/// request's credentials with HTTP 401.
133///
134/// rmcp reports a 401 that carries `WWW-Authenticate` as `AuthRequired`, and
135/// one without it as an `HTTP 401` server response or reqwest's status error. A
136/// JSON-RPC error whose message merely mentions authorization is not matched:
137/// that request reached the server.
138pub(crate) fn is_auth_rejection(error: &ServiceError) -> bool {
139    classify(error) == Failure::AuthRejected
140}
141
142/// Replay of `tools/call` after an ambiguous connection failure is opt-in.
143///
144/// A transport failure after the request was transmitted does not prove the call did not run.
145/// Flipping this to `true` silently re-enables duplicate external writes — a payment, message,
146/// or deletion executing more than once. See #504.
147pub(crate) const DEFAULT_RETRY_TOOL_CALLS: bool = false;
148
149/// A request rejected with HTTP 401 never ran, so it is retried after a
150/// reconnect even when replay is not allowed.
151pub(crate) fn should_retry_mcp_operation(
152    error: &ServiceError,
153    attempt: u32,
154    refresh_config: &RefreshConfig,
155    has_connection_factory: bool,
156    replay_allowed: bool,
157) -> bool {
158    let failure = classify(error);
159    (replay_allowed || failure == Failure::AuthRejected)
160        && has_connection_factory
161        && attempt < refresh_config.max_attempts
162        && failure != Failure::Other
163}
164
165/// Result of an operation with retry information
166#[derive(Debug, Clone)]
167pub struct RetryResult<T> {
168    /// The result value
169    pub value: T,
170    /// Whether a reconnection occurred
171    pub reconnected: bool,
172}
173
174impl<T> RetryResult<T> {
175    /// Create a new result without reconnection
176    pub fn ok(value: T) -> Self {
177        Self { value, reconnected: false }
178    }
179
180    /// Create a new result after reconnection
181    pub fn reconnected(value: T) -> Self {
182        Self { value, reconnected: true }
183    }
184}
185
186/// Configuration for connection refresh behavior
187#[derive(Debug, Clone)]
188pub struct RefreshConfig {
189    /// Maximum number of reconnection attempts
190    pub max_attempts: u32,
191    /// Delay between reconnection attempts in milliseconds
192    pub retry_delay_ms: u64,
193    /// Whether to log reconnection attempts
194    pub log_reconnections: bool,
195}
196
197impl Default for RefreshConfig {
198    fn default() -> Self {
199        Self { max_attempts: 3, retry_delay_ms: 1000, log_reconnections: true }
200    }
201}
202
203impl RefreshConfig {
204    /// Create a new config with custom max attempts
205    pub fn with_max_attempts(mut self, attempts: u32) -> Self {
206        self.max_attempts = attempts;
207        self
208    }
209
210    /// Create a new config with custom retry delay
211    pub fn with_retry_delay_ms(mut self, delay_ms: u64) -> Self {
212        self.retry_delay_ms = delay_ms;
213        self
214    }
215
216    /// Disable logging
217    pub fn without_logging(mut self) -> Self {
218        self.log_reconnections = false;
219        self
220    }
221}
222
223/// Factory trait for creating new MCP connections.
224///
225/// Implement this trait to provide reconnection capability to `ConnectionRefresher`.
226#[async_trait::async_trait]
227pub trait ConnectionFactory<S>: Send + Sync
228where
229    S: rmcp::service::Service<RoleClient> + Send + Sync + 'static,
230{
231    /// Create a new connection to the MCP server.
232    async fn create_connection(&self) -> Result<RunningService<RoleClient, S>, String>;
233}
234
235/// Connection refresher that wraps an MCP client and handles automatic reconnection.
236///
237/// This is similar to adk-go's `connectionRefresher` struct. It transparently
238/// retries operations after reconnecting when the underlying session fails.
239///
240/// Requests share the current connection and run concurrently: each one holds
241/// the connection only for its own lifetime, never a lock. A connection that
242/// has already closed, such as one to a stdio server process that exited, is
243/// replaced before the next request is sent, so that request is never a replay.
244/// Concurrent failures on one connection reconnect once.
245///
246/// # Type Parameters
247///
248/// * `S` - The service type for the MCP client
249/// * `F` - The factory type for creating new connections
250///
251/// # Example
252///
253/// ```rust,ignore
254/// use adk_tool::mcp::{ConnectionRefresher, ConnectionFactory};
255///
256/// struct MyFactory { /* ... */ }
257///
258/// #[async_trait::async_trait]
259/// impl ConnectionFactory<MyService> for MyFactory {
260///     async fn create_connection(&self) -> Result<RunningService<RoleClient, MyService>, String> {
261///         // Create and return a new connection
262///     }
263/// }
264///
265/// let refresher = ConnectionRefresher::new(initial_client, Arc::new(factory));
266///
267/// // Read-only discovery automatically retries on connection failure.
268/// let tools = refresher.list_tools().await?;
269///
270/// // Tool calls are not replayed unless the caller explicitly opts in.
271/// // The server chooses whether to answer inline or with a task, so the
272/// // caller reads the response to find out which happened.
273/// let response = refresher
274///     .with_tool_call_retries()
275///     .call_tool(params)
276///     .await?
277///     .value;
278/// match response {
279///     CallToolResponse::Complete(result) => println!("{result:?}"),
280///     other => println!("not a plain result: {other:?}"),
281/// }
282/// ```
283pub struct ConnectionRefresher<S, F>
284where
285    S: rmcp::service::Service<RoleClient> + Send + Sync + 'static,
286    F: ConnectionFactory<S>,
287{
288    /// The current connection. Requests clone the `Arc` and release the lock before sending.
289    client: RwLock<Option<Arc<RunningService<RoleClient, S>>>>,
290    /// Held while a connection is created, so concurrent failures replace a dead
291    /// connection once instead of once per caller.
292    connecting: Mutex<()>,
293    /// Factory for creating new connections
294    factory: Arc<F>,
295    /// Configuration for refresh behavior
296    config: RefreshConfig,
297    /// Whether ambiguous tool-call outcomes may be replayed after reconnection.
298    retry_tool_calls: bool,
299    /// Bounds on `list_tools`.
300    discovery_limits: McpDiscoveryLimits,
301}
302
303impl<S, F> ConnectionRefresher<S, F>
304where
305    S: rmcp::service::Service<RoleClient> + Send + Sync + 'static,
306    F: ConnectionFactory<S>,
307{
308    /// Create a new connection refresher with an initial client and factory.
309    ///
310    /// # Arguments
311    ///
312    /// * `client` - The initial MCP client connection
313    /// * `factory` - Factory for creating new connections when needed
314    pub fn new(client: RunningService<RoleClient, S>, factory: Arc<F>) -> Self {
315        Self {
316            client: RwLock::new(Some(Arc::new(client))),
317            connecting: Mutex::new(()),
318            factory,
319            config: RefreshConfig::default(),
320            retry_tool_calls: DEFAULT_RETRY_TOOL_CALLS,
321            discovery_limits: McpDiscoveryLimits::default(),
322        }
323    }
324
325    /// Create a new connection refresher without an initial connection.
326    ///
327    /// The first operation will trigger a connection.
328    pub fn lazy(factory: Arc<F>) -> Self {
329        Self {
330            client: RwLock::new(None),
331            connecting: Mutex::new(()),
332            factory,
333            config: RefreshConfig::default(),
334            retry_tool_calls: DEFAULT_RETRY_TOOL_CALLS,
335            discovery_limits: McpDiscoveryLimits::default(),
336        }
337    }
338
339    /// Set the refresh configuration.
340    pub fn with_config(mut self, config: RefreshConfig) -> Self {
341        self.config = config;
342        self
343    }
344
345    /// Set the maximum number of reconnection attempts.
346    pub fn with_max_attempts(mut self, attempts: u32) -> Self {
347        self.config.max_attempts = attempts;
348        self
349    }
350
351    /// Set the bounds on [`list_tools`](Self::list_tools).
352    ///
353    /// The timeout covers the whole listing, reconnect attempts included. See
354    /// [`McpDiscoveryLimits`] for the defaults.
355    ///
356    /// # Example
357    ///
358    /// ```rust,ignore
359    /// let refresher = ConnectionRefresher::new(client, Arc::new(factory))
360    ///     .with_discovery_limits(McpDiscoveryLimits::default().with_max_pages(8));
361    /// ```
362    pub fn with_discovery_limits(mut self, limits: McpDiscoveryLimits) -> Self {
363        self.discovery_limits = limits;
364        self
365    }
366
367    /// Allow `tools/call` to be replayed after reconnecting.
368    ///
369    /// A transport failure after request transmission is an ambiguous outcome:
370    /// a mutating tool may have completed its external effect before the
371    /// response was lost. Enable this only for read-only tools or operations
372    /// protected by a stable provider idempotency guarantee.
373    ///
374    /// # Example
375    ///
376    /// ```rust,ignore
377    /// let refresher = ConnectionRefresher::new(client, Arc::new(factory))
378    ///     .with_tool_call_retries();
379    /// ```
380    pub fn with_tool_call_retries(mut self) -> Self {
381        self.retry_tool_calls = true;
382        self
383    }
384
385    /// Returns a connection to send on: the current one, or a new one when there
386    /// is none or the current one has closed.
387    async fn connection(&self) -> Result<Arc<RunningService<RoleClient, S>>, String> {
388        if let Some(client) = self.client.read().await.as_ref()
389            && !is_connection_closed(client)
390        {
391            return Ok(Arc::clone(client));
392        }
393        self.replace(None).await
394    }
395
396    /// Installs a new connection unless another caller already replaced `failed`
397    /// with a live one, and returns the connection to use.
398    ///
399    /// With `failed` set to `None`, only a missing or closed connection is replaced.
400    async fn replace(
401        &self,
402        failed: Option<&Arc<RunningService<RoleClient, S>>>,
403    ) -> Result<Arc<RunningService<RoleClient, S>>, String> {
404        let _connecting = self.connecting.lock().await;
405        if let Some(current) = self.client.read().await.as_ref()
406            && !is_connection_closed(current)
407            && failed.is_none_or(|failed| !Arc::ptr_eq(current, failed))
408        {
409            return Ok(Arc::clone(current));
410        }
411
412        if self.config.log_reconnections {
413            info!("creating MCP connection");
414        }
415        // The old connection closes once the last in-flight request on it drops its `Arc`.
416        let created = Arc::new(self.factory.create_connection().await?);
417        *self.client.write().await = Some(Arc::clone(&created));
418        Ok(created)
419    }
420
421    /// Sends one request through `send`, reconnecting and resending after a
422    /// retryable connection failure when `replay_allowed` permits it.
423    async fn with_reconnect<T, Fut>(
424        &self,
425        operation: &str,
426        replay_allowed: bool,
427        mut send: impl FnMut(Arc<RunningService<RoleClient, S>>) -> Fut,
428    ) -> Result<RetryResult<T>, String>
429    where
430        Fut: std::future::Future<Output = Result<T, ListError>>,
431    {
432        let mut connection = self.connection().await?;
433        let mut attempt = 0u32;
434        loop {
435            let error = match send(Arc::clone(&connection)).await {
436                Ok(value) => return Ok(RetryResult { value, reconnected: attempt > 0 }),
437                Err(ListError::Service(error)) => error,
438                // A listing that ran past its bounds would do the same on a new connection.
439                Err(bound) => return Err(bound.to_string()),
440            };
441            if !should_retry_mcp_operation(&error, attempt, &self.config, true, replay_allowed) {
442                if !replay_allowed
443                    && should_refresh_connection(&error)
444                    && !is_auth_rejection(&error)
445                {
446                    return Err(format!(
447                        "MCP {operation} result is uncertain and was not replayed: {error}. \
448                         Enable tool-call retries only for replay-safe operations"
449                    ));
450                }
451                return Err(error.to_string());
452            }
453            if self.config.log_reconnections {
454                warn!(error = %error, operation, "MCP request failed, will retry with reconnection");
455            }
456
457            // A failed reconnect counts as an attempt, like a failed request.
458            loop {
459                attempt += 1;
460                if self.config.retry_delay_ms > 0 {
461                    tokio::time::sleep(tokio::time::Duration::from_millis(
462                        self.config.retry_delay_ms,
463                    ))
464                    .await;
465                }
466                match self.replace(Some(&connection)).await {
467                    Ok(replacement) => {
468                        if self.config.log_reconnections {
469                            debug!(attempt, operation, "reconnected MCP connection");
470                        }
471                        connection = replacement;
472                        break;
473                    }
474                    Err(refresh_error) if attempt < self.config.max_attempts => {
475                        if self.config.log_reconnections {
476                            warn!(error = %refresh_error, attempt, "MCP reconnection failed");
477                        }
478                    }
479                    Err(refresh_error) => {
480                        return Err(format!("{error}; reconnecting failed: {refresh_error}"));
481                    }
482                }
483            }
484        }
485    }
486
487    /// List all tools from the MCP server with automatic reconnection.
488    ///
489    /// Handles pagination internally and restarts from scratch if
490    /// reconnection occurs (per MCP spec, cursors don't persist across sessions).
491    /// The listing is bounded by the [discovery limits](Self::with_discovery_limits).
492    pub async fn list_tools(&self) -> Result<RetryResult<Vec<McpTool>>, String> {
493        let limits = self.discovery_limits;
494        let listing = self.with_reconnect("list_tools", true, |client| async move {
495            list_tools(client.peer(), limits.max_pages).await
496        });
497        tokio::time::timeout(limits.timeout, listing).await.unwrap_or_else(|_| {
498            Err(ListError::Timeout { method: "tools/list", timeout: limits.timeout }.to_string())
499        })
500    }
501
502    /// Call a tool on the MCP server.
503    ///
504    /// Tool calls are not replayed by default after an ambiguous connection
505    /// failure. Use [`Self::with_tool_call_retries`] only when the operation is
506    /// known to be replay-safe. A call rejected with HTTP 401 never ran, so it is
507    /// resent after a reconnect either way.
508    pub async fn call_tool(
509        &self,
510        params: CallToolRequestParams,
511    ) -> Result<RetryResult<CallToolResponse>, String> {
512        self.with_reconnect("tool call", self.retry_tool_calls, |client| {
513            let params = params.clone();
514            async move { Ok(client.call_tool_once(params).await?) }
515        })
516        .await
517    }
518
519    /// Get the cancellation token for the current connection.
520    pub async fn cancellation_token(
521        &self,
522    ) -> Option<rmcp::service::RunningServiceCancellationToken> {
523        self.client.read().await.as_ref().map(|client| client.cancellation_token())
524    }
525
526    /// Check if currently connected.
527    pub async fn is_connected(&self) -> bool {
528        self.client.read().await.is_some()
529    }
530
531    /// Force a reconnection.
532    ///
533    /// Requests already in flight finish on the old connection.
534    pub async fn reconnect(&self) -> Result<(), String> {
535        let current = self.client.read().await.clone();
536        match current {
537            Some(current) => self.replace(Some(&current)).await.map(drop),
538            None => self.replace(None).await.map(drop),
539        }
540    }
541
542    /// Close the connection.
543    pub async fn close(&self) {
544        if let Some(client) = self.client.write().await.take() {
545            client.cancellation_token().cancel();
546        }
547    }
548}
549
550/// Returns `true` when `client` can no longer carry requests: its service loop was
551/// cancelled, or its transport closed, as it does when a stdio server process exits.
552pub(crate) fn is_connection_closed<S>(client: &RunningService<RoleClient, S>) -> bool
553where
554    S: rmcp::service::Service<RoleClient>,
555{
556    client.is_closed() || client.peer().is_transport_closed()
557}
558
559/// Simple wrapper for MCP clients that don't support reconnection.
560///
561/// Use this for stdio-based MCP servers where reconnection isn't possible
562/// without restarting the server process. Requests share the connection and
563/// run concurrently.
564///
565/// # Example
566///
567/// ```rust,ignore
568/// use adk_tool::mcp::{SimpleClient, rmcp::{ServiceExt, transport::TokioChildProcess}};
569/// use tokio::process::Command;
570///
571/// let client = ().serve(TokioChildProcess::new(Command::new("my-mcp-server"))?).await?;
572/// let simple = SimpleClient::new(client);
573/// let (tools, peer_info) = tokio::join!(simple.list_tools(), async {
574///     simple.inner().peer_info()
575/// });
576/// ```
577pub struct SimpleClient<S>
578where
579    S: rmcp::service::Service<RoleClient> + Send + Sync + 'static,
580{
581    client: Arc<RunningService<RoleClient, S>>,
582    discovery_limits: McpDiscoveryLimits,
583}
584
585impl<S> SimpleClient<S>
586where
587    S: rmcp::service::Service<RoleClient> + Send + Sync + 'static,
588{
589    /// Create a new simple client wrapper.
590    pub fn new(client: RunningService<RoleClient, S>) -> Self {
591        Self { client: Arc::new(client), discovery_limits: McpDiscoveryLimits::default() }
592    }
593
594    /// Set the bounds on [`list_tools`](Self::list_tools). See [`McpDiscoveryLimits`]
595    /// for the defaults.
596    ///
597    /// # Example
598    ///
599    /// ```rust,ignore
600    /// let simple = SimpleClient::new(client)
601    ///     .with_discovery_limits(McpDiscoveryLimits::default().with_max_pages(8));
602    /// ```
603    pub fn with_discovery_limits(mut self, limits: McpDiscoveryLimits) -> Self {
604        self.discovery_limits = limits;
605        self
606    }
607
608    /// List all tools from the MCP server, within the [discovery limits](Self::with_discovery_limits).
609    pub async fn list_tools(&self) -> Result<Vec<McpTool>, String> {
610        let limits = self.discovery_limits;
611        super::discovery::within(
612            "tools/list",
613            limits.timeout,
614            list_tools(self.client.peer(), limits.max_pages),
615        )
616        .await
617        .map_err(|error| error.to_string())
618    }
619
620    /// Call a tool on the MCP server.
621    pub async fn call_tool(
622        &self,
623        params: CallToolRequestParams,
624    ) -> Result<CallToolResponse, String> {
625        self.client.call_tool_once(params).await.map_err(|e| e.to_string())
626    }
627
628    /// Get the cancellation token.
629    pub async fn cancellation_token(&self) -> rmcp::service::RunningServiceCancellationToken {
630        self.client.cancellation_token()
631    }
632
633    /// Get the shared connection.
634    ///
635    /// Clone the `Arc` to send requests directly; nothing serializes them.
636    pub fn inner(&self) -> &Arc<RunningService<RoleClient, S>> {
637        &self.client
638    }
639}
640
641#[cfg(test)]
642mod tests {
643    use super::*;
644
645    fn transport_error(error: impl std::error::Error + Send + Sync + 'static) -> ServiceError {
646        ServiceError::TransportSend(rmcp::transport::DynamicTransportError::from_parts(
647            "test",
648            std::any::TypeId::of::<()>(),
649            Box::new(error),
650        ))
651    }
652
653    fn io(kind: std::io::ErrorKind, message: &str) -> std::io::Error {
654        std::io::Error::new(kind, message.to_string())
655    }
656
657    #[test]
658    fn a_lost_connection_triggers_a_refresh() {
659        use std::io::ErrorKind;
660        // rmcp's `ServiceError::TransportClosed`, reported once a stdio server exits.
661        assert!(should_refresh_connection(&ServiceError::TransportClosed));
662        for kind in [
663            ErrorKind::BrokenPipe,
664            ErrorKind::ConnectionReset,
665            ErrorKind::ConnectionAborted,
666            ErrorKind::NotConnected,
667            ErrorKind::UnexpectedEof,
668        ] {
669            assert!(should_refresh_connection(&transport_error(io(kind, "lost"))), "{kind:?}");
670        }
671    }
672
673    /// An I/O error a transport wraps in its own error type is found through `source()`.
674    #[test]
675    fn a_wrapped_io_error_is_classified_by_its_kind() {
676        #[derive(Debug)]
677        struct Codec(std::io::Error);
678        impl std::fmt::Display for Codec {
679            fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
680                write!(f, "codec failed")
681            }
682        }
683        impl std::error::Error for Codec {
684            fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
685                Some(&self.0)
686            }
687        }
688        let broken = Codec(io(std::io::ErrorKind::BrokenPipe, "pipe"));
689        assert!(should_refresh_connection(&transport_error(broken)));
690    }
691
692    /// Server-chosen text that mentions a lost connection never triggers a refresh.
693    #[test]
694    fn error_text_does_not_trigger_a_refresh() {
695        let text = "upstream geoffrey: EOF, broken pipe, connection reset, transport closed, \
696                    session not found";
697        let errors = [
698            transport_error(io(std::io::ErrorKind::Other, text)),
699            ServiceError::McpError(rmcp::ErrorData::internal_error(text.to_string(), None)),
700            ServiceError::UnexpectedResponse,
701            ServiceError::Timeout { timeout: std::time::Duration::from_secs(1) },
702        ];
703        for error in errors {
704            assert!(!should_refresh_connection(&error), "{error}");
705            assert!(!is_auth_rejection(&error), "{error}");
706        }
707    }
708
709    #[test]
710    fn server_errors_that_mention_authorization_are_not_auth_rejections() {
711        let error = ServiceError::McpError(rmcp::ErrorData::new(
712            rmcp::model::ErrorCode(-32001),
713            "upstream returned 401 Unauthorized; auth required",
714            None,
715        ));
716        assert!(!is_auth_rejection(&error));
717        assert!(!should_refresh_connection(&error));
718    }
719
720    #[cfg(feature = "http-transport")]
721    mod http {
722        use super::*;
723        use rmcp::transport::streamable_http_client::AuthRequiredError;
724
725        fn http(error: HttpError) -> ServiceError {
726            transport_error(error)
727        }
728
729        #[test]
730        fn http_401_rejections_trigger_a_refresh() {
731            let with_challenge =
732                http(HttpError::AuthRequired(AuthRequiredError::new("Bearer".to_string())));
733            let without_challenge =
734                http(HttpError::UnexpectedServerResponse("HTTP 401 Unauthorized: ".into()));
735            for error in [with_challenge, without_challenge] {
736                assert!(is_auth_rejection(&error), "{error}");
737                assert!(should_refresh_connection(&error), "{error}");
738            }
739        }
740
741        #[test]
742        fn a_5xx_never_triggers_a_refresh_whatever_its_body_says() {
743            let error = http(HttpError::UnexpectedServerResponse(
744                "HTTP 500 Internal Server Error: upstream geoffrey: EOF; Transport closed; \
745                 connection reset; session not found; HTTP 401 Unauthorized"
746                    .into(),
747            ));
748            assert!(!should_refresh_connection(&error), "{error}");
749            assert!(!is_auth_rejection(&error), "{error}");
750        }
751
752        #[test]
753        fn an_interrupted_stream_or_expired_session_triggers_a_refresh() {
754            for error in [
755                HttpError::UnexpectedEndOfStream,
756                HttpError::TransportChannelClosed,
757                HttpError::SessionExpired,
758                HttpError::Io(io(std::io::ErrorKind::ConnectionReset, "reset")),
759            ] {
760                let error = http(error);
761                assert!(should_refresh_connection(&error), "{error}");
762                assert!(!is_auth_rejection(&error), "{error}");
763            }
764        }
765
766        #[test]
767        fn a_rejected_tool_call_is_retried_without_replay_opt_in() {
768            let config = RefreshConfig::default();
769            let rejected = http(HttpError::AuthRequired(AuthRequiredError::new("Bearer".into())));
770            assert!(should_retry_mcp_operation(&rejected, 0, &config, true, false));
771            assert!(!should_retry_mcp_operation(
772                &ServiceError::TransportClosed,
773                0,
774                &config,
775                true,
776                false
777            ));
778        }
779    }
780
781    #[test]
782    fn test_refresh_config_default() {
783        let config = RefreshConfig::default();
784        assert_eq!(config.max_attempts, 3);
785        assert_eq!(config.retry_delay_ms, 1000);
786        assert!(config.log_reconnections);
787    }
788
789    #[test]
790    fn test_refresh_config_builder() {
791        let config = RefreshConfig::default()
792            .with_max_attempts(5)
793            .with_retry_delay_ms(500)
794            .without_logging();
795
796        assert_eq!(config.max_attempts, 5);
797        assert_eq!(config.retry_delay_ms, 500);
798        assert!(!config.log_reconnections);
799    }
800
801    #[test]
802    fn test_retry_result() {
803        let ok_result = RetryResult::ok(42);
804        assert_eq!(ok_result.value, 42);
805        assert!(!ok_result.reconnected);
806
807        let reconnected_result = RetryResult::reconnected(42);
808        assert_eq!(reconnected_result.value, 42);
809        assert!(reconnected_result.reconnected);
810    }
811}