use super::discovery::{ListError, McpDiscoveryLimits, list_tools};
use rmcp::{
RoleClient, ServiceError,
model::{CallToolRequestParams, CallToolResponse, Tool as McpTool},
service::RunningService,
};
use std::sync::Arc;
use tokio::sync::{Mutex, RwLock};
use tracing::{debug, info, warn};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Failure {
ConnectionLost,
AuthRejected,
Other,
}
fn classify(error: &ServiceError) -> Failure {
match error {
ServiceError::TransportClosed => Failure::ConnectionLost,
ServiceError::TransportSend(error) => classify_transport(error.error.as_ref()),
_ => Failure::Other,
}
}
#[cfg(feature = "http-transport")]
type HttpError = rmcp::transport::streamable_http_client::StreamableHttpError<reqwest::Error>;
fn classify_transport(error: &(dyn std::error::Error + 'static)) -> Failure {
#[cfg(feature = "http-transport")]
if let Some(error) = error.downcast_ref::<HttpError>() {
return classify_http(error);
}
let mut current = Some(error);
while let Some(error) = current {
#[cfg(feature = "http-transport")]
if error.is::<rmcp::transport::streamable_http_client::AuthRequiredError>() {
return Failure::AuthRejected;
}
if let Some(error) = error.downcast_ref::<std::io::Error>() {
return classify_io(error);
}
current = error.source();
}
Failure::Other
}
#[cfg(feature = "http-transport")]
fn classify_http(error: &HttpError) -> Failure {
use rmcp::transport::streamable_http_client::{SseError, StreamableHttpError};
match error {
StreamableHttpError::AuthRequired(_) => Failure::AuthRejected,
StreamableHttpError::UnexpectedServerResponse(message)
if message.starts_with("HTTP 401 ") =>
{
Failure::AuthRejected
}
StreamableHttpError::Client(error)
if error.status() == Some(reqwest::StatusCode::UNAUTHORIZED) =>
{
Failure::AuthRejected
}
StreamableHttpError::Io(error) => classify_io(error),
StreamableHttpError::Sse(SseError::Body(_))
| StreamableHttpError::UnexpectedEndOfStream
| StreamableHttpError::TransportChannelClosed
| StreamableHttpError::SessionExpired => Failure::ConnectionLost,
_ => Failure::Other,
}
}
fn classify_io(error: &std::io::Error) -> Failure {
use std::io::ErrorKind;
match error.kind() {
ErrorKind::BrokenPipe
| ErrorKind::ConnectionReset
| ErrorKind::ConnectionAborted
| ErrorKind::NotConnected
| ErrorKind::UnexpectedEof => Failure::ConnectionLost,
_ => Failure::Other,
}
}
pub fn should_refresh_connection(error: &ServiceError) -> bool {
match classify(error) {
Failure::ConnectionLost | Failure::AuthRejected => true,
Failure::Other => false,
}
}
pub(crate) fn is_auth_rejection(error: &ServiceError) -> bool {
classify(error) == Failure::AuthRejected
}
pub(crate) const DEFAULT_RETRY_TOOL_CALLS: bool = false;
pub(crate) fn should_retry_mcp_operation(
error: &ServiceError,
attempt: u32,
refresh_config: &RefreshConfig,
has_connection_factory: bool,
replay_allowed: bool,
) -> bool {
let failure = classify(error);
(replay_allowed || failure == Failure::AuthRejected)
&& has_connection_factory
&& attempt < refresh_config.max_attempts
&& failure != Failure::Other
}
#[derive(Debug, Clone)]
pub struct RetryResult<T> {
pub value: T,
pub reconnected: bool,
}
impl<T> RetryResult<T> {
pub fn ok(value: T) -> Self {
Self { value, reconnected: false }
}
pub fn reconnected(value: T) -> Self {
Self { value, reconnected: true }
}
}
#[derive(Debug, Clone)]
pub struct RefreshConfig {
pub max_attempts: u32,
pub retry_delay_ms: u64,
pub log_reconnections: bool,
}
impl Default for RefreshConfig {
fn default() -> Self {
Self { max_attempts: 3, retry_delay_ms: 1000, log_reconnections: true }
}
}
impl RefreshConfig {
pub fn with_max_attempts(mut self, attempts: u32) -> Self {
self.max_attempts = attempts;
self
}
pub fn with_retry_delay_ms(mut self, delay_ms: u64) -> Self {
self.retry_delay_ms = delay_ms;
self
}
pub fn without_logging(mut self) -> Self {
self.log_reconnections = false;
self
}
}
#[async_trait::async_trait]
pub trait ConnectionFactory<S>: Send + Sync
where
S: rmcp::service::Service<RoleClient> + Send + Sync + 'static,
{
async fn create_connection(&self) -> Result<RunningService<RoleClient, S>, String>;
}
pub struct ConnectionRefresher<S, F>
where
S: rmcp::service::Service<RoleClient> + Send + Sync + 'static,
F: ConnectionFactory<S>,
{
client: RwLock<Option<Arc<RunningService<RoleClient, S>>>>,
connecting: Mutex<()>,
factory: Arc<F>,
config: RefreshConfig,
retry_tool_calls: bool,
discovery_limits: McpDiscoveryLimits,
}
impl<S, F> ConnectionRefresher<S, F>
where
S: rmcp::service::Service<RoleClient> + Send + Sync + 'static,
F: ConnectionFactory<S>,
{
pub fn new(client: RunningService<RoleClient, S>, factory: Arc<F>) -> Self {
Self {
client: RwLock::new(Some(Arc::new(client))),
connecting: Mutex::new(()),
factory,
config: RefreshConfig::default(),
retry_tool_calls: DEFAULT_RETRY_TOOL_CALLS,
discovery_limits: McpDiscoveryLimits::default(),
}
}
pub fn lazy(factory: Arc<F>) -> Self {
Self {
client: RwLock::new(None),
connecting: Mutex::new(()),
factory,
config: RefreshConfig::default(),
retry_tool_calls: DEFAULT_RETRY_TOOL_CALLS,
discovery_limits: McpDiscoveryLimits::default(),
}
}
pub fn with_config(mut self, config: RefreshConfig) -> Self {
self.config = config;
self
}
pub fn with_max_attempts(mut self, attempts: u32) -> Self {
self.config.max_attempts = attempts;
self
}
pub fn with_discovery_limits(mut self, limits: McpDiscoveryLimits) -> Self {
self.discovery_limits = limits;
self
}
pub fn with_tool_call_retries(mut self) -> Self {
self.retry_tool_calls = true;
self
}
async fn connection(&self) -> Result<Arc<RunningService<RoleClient, S>>, String> {
if let Some(client) = self.client.read().await.as_ref()
&& !is_connection_closed(client)
{
return Ok(Arc::clone(client));
}
self.replace(None).await
}
async fn replace(
&self,
failed: Option<&Arc<RunningService<RoleClient, S>>>,
) -> Result<Arc<RunningService<RoleClient, S>>, String> {
let _connecting = self.connecting.lock().await;
if let Some(current) = self.client.read().await.as_ref()
&& !is_connection_closed(current)
&& failed.is_none_or(|failed| !Arc::ptr_eq(current, failed))
{
return Ok(Arc::clone(current));
}
if self.config.log_reconnections {
info!("creating MCP connection");
}
let created = Arc::new(self.factory.create_connection().await?);
*self.client.write().await = Some(Arc::clone(&created));
Ok(created)
}
async fn with_reconnect<T, Fut>(
&self,
operation: &str,
replay_allowed: bool,
mut send: impl FnMut(Arc<RunningService<RoleClient, S>>) -> Fut,
) -> Result<RetryResult<T>, String>
where
Fut: std::future::Future<Output = Result<T, ListError>>,
{
let mut connection = self.connection().await?;
let mut attempt = 0u32;
loop {
let error = match send(Arc::clone(&connection)).await {
Ok(value) => return Ok(RetryResult { value, reconnected: attempt > 0 }),
Err(ListError::Service(error)) => error,
Err(bound) => return Err(bound.to_string()),
};
if !should_retry_mcp_operation(&error, attempt, &self.config, true, replay_allowed) {
if !replay_allowed
&& should_refresh_connection(&error)
&& !is_auth_rejection(&error)
{
return Err(format!(
"MCP {operation} result is uncertain and was not replayed: {error}. \
Enable tool-call retries only for replay-safe operations"
));
}
return Err(error.to_string());
}
if self.config.log_reconnections {
warn!(error = %error, operation, "MCP request failed, will retry with reconnection");
}
loop {
attempt += 1;
if self.config.retry_delay_ms > 0 {
tokio::time::sleep(tokio::time::Duration::from_millis(
self.config.retry_delay_ms,
))
.await;
}
match self.replace(Some(&connection)).await {
Ok(replacement) => {
if self.config.log_reconnections {
debug!(attempt, operation, "reconnected MCP connection");
}
connection = replacement;
break;
}
Err(refresh_error) if attempt < self.config.max_attempts => {
if self.config.log_reconnections {
warn!(error = %refresh_error, attempt, "MCP reconnection failed");
}
}
Err(refresh_error) => {
return Err(format!("{error}; reconnecting failed: {refresh_error}"));
}
}
}
}
}
pub async fn list_tools(&self) -> Result<RetryResult<Vec<McpTool>>, String> {
let limits = self.discovery_limits;
let listing = self.with_reconnect("list_tools", true, |client| async move {
list_tools(client.peer(), limits.max_pages).await
});
tokio::time::timeout(limits.timeout, listing).await.unwrap_or_else(|_| {
Err(ListError::Timeout { method: "tools/list", timeout: limits.timeout }.to_string())
})
}
pub async fn call_tool(
&self,
params: CallToolRequestParams,
) -> Result<RetryResult<CallToolResponse>, String> {
self.with_reconnect("tool call", self.retry_tool_calls, |client| {
let params = params.clone();
async move { Ok(client.call_tool_once(params).await?) }
})
.await
}
pub async fn cancellation_token(
&self,
) -> Option<rmcp::service::RunningServiceCancellationToken> {
self.client.read().await.as_ref().map(|client| client.cancellation_token())
}
pub async fn is_connected(&self) -> bool {
self.client.read().await.is_some()
}
pub async fn reconnect(&self) -> Result<(), String> {
let current = self.client.read().await.clone();
match current {
Some(current) => self.replace(Some(¤t)).await.map(drop),
None => self.replace(None).await.map(drop),
}
}
pub async fn close(&self) {
if let Some(client) = self.client.write().await.take() {
client.cancellation_token().cancel();
}
}
}
pub(crate) fn is_connection_closed<S>(client: &RunningService<RoleClient, S>) -> bool
where
S: rmcp::service::Service<RoleClient>,
{
client.is_closed() || client.peer().is_transport_closed()
}
pub struct SimpleClient<S>
where
S: rmcp::service::Service<RoleClient> + Send + Sync + 'static,
{
client: Arc<RunningService<RoleClient, S>>,
discovery_limits: McpDiscoveryLimits,
}
impl<S> SimpleClient<S>
where
S: rmcp::service::Service<RoleClient> + Send + Sync + 'static,
{
pub fn new(client: RunningService<RoleClient, S>) -> Self {
Self { client: Arc::new(client), discovery_limits: McpDiscoveryLimits::default() }
}
pub fn with_discovery_limits(mut self, limits: McpDiscoveryLimits) -> Self {
self.discovery_limits = limits;
self
}
pub async fn list_tools(&self) -> Result<Vec<McpTool>, String> {
let limits = self.discovery_limits;
super::discovery::within(
"tools/list",
limits.timeout,
list_tools(self.client.peer(), limits.max_pages),
)
.await
.map_err(|error| error.to_string())
}
pub async fn call_tool(
&self,
params: CallToolRequestParams,
) -> Result<CallToolResponse, String> {
self.client.call_tool_once(params).await.map_err(|e| e.to_string())
}
pub async fn cancellation_token(&self) -> rmcp::service::RunningServiceCancellationToken {
self.client.cancellation_token()
}
pub fn inner(&self) -> &Arc<RunningService<RoleClient, S>> {
&self.client
}
}
#[cfg(test)]
mod tests {
use super::*;
fn transport_error(error: impl std::error::Error + Send + Sync + 'static) -> ServiceError {
ServiceError::TransportSend(rmcp::transport::DynamicTransportError::from_parts(
"test",
std::any::TypeId::of::<()>(),
Box::new(error),
))
}
fn io(kind: std::io::ErrorKind, message: &str) -> std::io::Error {
std::io::Error::new(kind, message.to_string())
}
#[test]
fn a_lost_connection_triggers_a_refresh() {
use std::io::ErrorKind;
assert!(should_refresh_connection(&ServiceError::TransportClosed));
for kind in [
ErrorKind::BrokenPipe,
ErrorKind::ConnectionReset,
ErrorKind::ConnectionAborted,
ErrorKind::NotConnected,
ErrorKind::UnexpectedEof,
] {
assert!(should_refresh_connection(&transport_error(io(kind, "lost"))), "{kind:?}");
}
}
#[test]
fn a_wrapped_io_error_is_classified_by_its_kind() {
#[derive(Debug)]
struct Codec(std::io::Error);
impl std::fmt::Display for Codec {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "codec failed")
}
}
impl std::error::Error for Codec {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
Some(&self.0)
}
}
let broken = Codec(io(std::io::ErrorKind::BrokenPipe, "pipe"));
assert!(should_refresh_connection(&transport_error(broken)));
}
#[test]
fn error_text_does_not_trigger_a_refresh() {
let text = "upstream geoffrey: EOF, broken pipe, connection reset, transport closed, \
session not found";
let errors = [
transport_error(io(std::io::ErrorKind::Other, text)),
ServiceError::McpError(rmcp::ErrorData::internal_error(text.to_string(), None)),
ServiceError::UnexpectedResponse,
ServiceError::Timeout { timeout: std::time::Duration::from_secs(1) },
];
for error in errors {
assert!(!should_refresh_connection(&error), "{error}");
assert!(!is_auth_rejection(&error), "{error}");
}
}
#[test]
fn server_errors_that_mention_authorization_are_not_auth_rejections() {
let error = ServiceError::McpError(rmcp::ErrorData::new(
rmcp::model::ErrorCode(-32001),
"upstream returned 401 Unauthorized; auth required",
None,
));
assert!(!is_auth_rejection(&error));
assert!(!should_refresh_connection(&error));
}
#[cfg(feature = "http-transport")]
mod http {
use super::*;
use rmcp::transport::streamable_http_client::AuthRequiredError;
fn http(error: HttpError) -> ServiceError {
transport_error(error)
}
#[test]
fn http_401_rejections_trigger_a_refresh() {
let with_challenge =
http(HttpError::AuthRequired(AuthRequiredError::new("Bearer".to_string())));
let without_challenge =
http(HttpError::UnexpectedServerResponse("HTTP 401 Unauthorized: ".into()));
for error in [with_challenge, without_challenge] {
assert!(is_auth_rejection(&error), "{error}");
assert!(should_refresh_connection(&error), "{error}");
}
}
#[test]
fn a_5xx_never_triggers_a_refresh_whatever_its_body_says() {
let error = http(HttpError::UnexpectedServerResponse(
"HTTP 500 Internal Server Error: upstream geoffrey: EOF; Transport closed; \
connection reset; session not found; HTTP 401 Unauthorized"
.into(),
));
assert!(!should_refresh_connection(&error), "{error}");
assert!(!is_auth_rejection(&error), "{error}");
}
#[test]
fn an_interrupted_stream_or_expired_session_triggers_a_refresh() {
for error in [
HttpError::UnexpectedEndOfStream,
HttpError::TransportChannelClosed,
HttpError::SessionExpired,
HttpError::Io(io(std::io::ErrorKind::ConnectionReset, "reset")),
] {
let error = http(error);
assert!(should_refresh_connection(&error), "{error}");
assert!(!is_auth_rejection(&error), "{error}");
}
}
#[test]
fn a_rejected_tool_call_is_retried_without_replay_opt_in() {
let config = RefreshConfig::default();
let rejected = http(HttpError::AuthRequired(AuthRequiredError::new("Bearer".into())));
assert!(should_retry_mcp_operation(&rejected, 0, &config, true, false));
assert!(!should_retry_mcp_operation(
&ServiceError::TransportClosed,
0,
&config,
true,
false
));
}
}
#[test]
fn test_refresh_config_default() {
let config = RefreshConfig::default();
assert_eq!(config.max_attempts, 3);
assert_eq!(config.retry_delay_ms, 1000);
assert!(config.log_reconnections);
}
#[test]
fn test_refresh_config_builder() {
let config = RefreshConfig::default()
.with_max_attempts(5)
.with_retry_delay_ms(500)
.without_logging();
assert_eq!(config.max_attempts, 5);
assert_eq!(config.retry_delay_ms, 500);
assert!(!config.log_reconnections);
}
#[test]
fn test_retry_result() {
let ok_result = RetryResult::ok(42);
assert_eq!(ok_result.value, 42);
assert!(!ok_result.reconnected);
let reconnected_result = RetryResult::reconnected(42);
assert_eq!(reconnected_result.value, 42);
assert!(reconnected_result.reconnected);
}
}