1use 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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
25enum Failure {
26 ConnectionLost,
28 AuthRejected,
30 Other,
32}
33
34fn classify(error: &ServiceError) -> Failure {
38 match error {
39 ServiceError::TransportClosed => Failure::ConnectionLost,
40 ServiceError::TransportSend(error) => classify_transport(error.error.as_ref()),
41 _ => Failure::Other,
44 }
45}
46
47#[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 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 _ => 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
108pub fn should_refresh_connection(error: &ServiceError) -> bool {
125 match classify(error) {
126 Failure::ConnectionLost | Failure::AuthRejected => true,
127 Failure::Other => false,
128 }
129}
130
131pub(crate) fn is_auth_rejection(error: &ServiceError) -> bool {
139 classify(error) == Failure::AuthRejected
140}
141
142pub(crate) const DEFAULT_RETRY_TOOL_CALLS: bool = false;
148
149pub(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#[derive(Debug, Clone)]
167pub struct RetryResult<T> {
168 pub value: T,
170 pub reconnected: bool,
172}
173
174impl<T> RetryResult<T> {
175 pub fn ok(value: T) -> Self {
177 Self { value, reconnected: false }
178 }
179
180 pub fn reconnected(value: T) -> Self {
182 Self { value, reconnected: true }
183 }
184}
185
186#[derive(Debug, Clone)]
188pub struct RefreshConfig {
189 pub max_attempts: u32,
191 pub retry_delay_ms: u64,
193 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 pub fn with_max_attempts(mut self, attempts: u32) -> Self {
206 self.max_attempts = attempts;
207 self
208 }
209
210 pub fn with_retry_delay_ms(mut self, delay_ms: u64) -> Self {
212 self.retry_delay_ms = delay_ms;
213 self
214 }
215
216 pub fn without_logging(mut self) -> Self {
218 self.log_reconnections = false;
219 self
220 }
221}
222
223#[async_trait::async_trait]
227pub trait ConnectionFactory<S>: Send + Sync
228where
229 S: rmcp::service::Service<RoleClient> + Send + Sync + 'static,
230{
231 async fn create_connection(&self) -> Result<RunningService<RoleClient, S>, String>;
233}
234
235pub struct ConnectionRefresher<S, F>
284where
285 S: rmcp::service::Service<RoleClient> + Send + Sync + 'static,
286 F: ConnectionFactory<S>,
287{
288 client: RwLock<Option<Arc<RunningService<RoleClient, S>>>>,
290 connecting: Mutex<()>,
293 factory: Arc<F>,
295 config: RefreshConfig,
297 retry_tool_calls: bool,
299 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 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 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 pub fn with_config(mut self, config: RefreshConfig) -> Self {
341 self.config = config;
342 self
343 }
344
345 pub fn with_max_attempts(mut self, attempts: u32) -> Self {
347 self.config.max_attempts = attempts;
348 self
349 }
350
351 pub fn with_discovery_limits(mut self, limits: McpDiscoveryLimits) -> Self {
363 self.discovery_limits = limits;
364 self
365 }
366
367 pub fn with_tool_call_retries(mut self) -> Self {
381 self.retry_tool_calls = true;
382 self
383 }
384
385 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 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 let created = Arc::new(self.factory.create_connection().await?);
417 *self.client.write().await = Some(Arc::clone(&created));
418 Ok(created)
419 }
420
421 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 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 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 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 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 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 pub async fn is_connected(&self) -> bool {
528 self.client.read().await.is_some()
529 }
530
531 pub async fn reconnect(&self) -> Result<(), String> {
535 let current = self.client.read().await.clone();
536 match current {
537 Some(current) => self.replace(Some(¤t)).await.map(drop),
538 None => self.replace(None).await.map(drop),
539 }
540 }
541
542 pub async fn close(&self) {
544 if let Some(client) = self.client.write().await.take() {
545 client.cancellation_token().cancel();
546 }
547 }
548}
549
550pub(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
559pub 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 pub fn new(client: RunningService<RoleClient, S>) -> Self {
591 Self { client: Arc::new(client), discovery_limits: McpDiscoveryLimits::default() }
592 }
593
594 pub fn with_discovery_limits(mut self, limits: McpDiscoveryLimits) -> Self {
604 self.discovery_limits = limits;
605 self
606 }
607
608 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 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 pub async fn cancellation_token(&self) -> rmcp::service::RunningServiceCancellationToken {
630 self.client.cancellation_token()
631 }
632
633 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 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 #[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 #[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}