use std::collections::HashMap; use std::ffi::OsStr; use std::ffi::OsString; use std::future::Future; use std::io; use std::sync::Arc; use std::sync::Mutex as StdMutex; use std::sync::OnceLock; use std::sync::PoisonError; use std::sync::atomic::AtomicBool; use std::sync::atomic::AtomicU64; use std::sync::atomic::AtomicUsize; use std::sync::atomic::Ordering; use std::time::Duration; use std::time::Instant; use crate::AuthProviderResolver; use akode_config::McpServerOAuthConfig; use akode_config::types::AuthKeyringBackendKind; use akode_config::types::McpServerEnvVar; use akode_exec_server::HttpClient; use akode_keyring_store::DefaultKeyringStore; use akode_otel::auth_storage::AuthStorageOriginator; use anyhow::Context; use anyhow::Result; use anyhow::anyhow; use futures::FutureExt; use futures::future::BoxFuture; use http::HeaderMap; use http::header::AUTHORIZATION; use oauth2::TokenResponse; use rmcp::model::CallToolRequestParams; use rmcp::model::CallToolResult; use rmcp::model::ClientNotification; use rmcp::model::ClientRequest; use rmcp::model::ContentBlock; use rmcp::model::CustomNotification; use rmcp::model::ElicitRequestParams; use rmcp::model::ElicitResult; use rmcp::model::ElicitationAction; use rmcp::model::Extensions; use rmcp::model::InitializeRequestParams; use rmcp::model::ListResourceTemplatesRequest; use rmcp::model::ListResourceTemplatesResult; use rmcp::model::ListResourcesRequest; use rmcp::model::ListResourcesResult; use rmcp::model::ListToolsRequest; use rmcp::model::ListToolsResult; use rmcp::model::MetaObject; use rmcp::model::PaginatedRequestParams; use rmcp::model::ProtocolVersion; use rmcp::model::ReadResourceRequestParams; use rmcp::model::ReadResourceResult; use rmcp::model::RequestId; use rmcp::model::RequestMetaObject; use rmcp::model::RequestParamsMeta; use rmcp::model::ServerPeerInfo; use rmcp::model::ServerResult; use rmcp::model::Tool; use rmcp::service::ClientCacheConfig; use rmcp::service::ClientServiceExt; use rmcp::service::RequestHandle; use rmcp::service::RoleClient; use rmcp::service::RunningService; use rmcp::service::ServiceError; use rmcp::transport::AuthorizationManager; use rmcp::transport::IntoTransport; use rmcp::transport::StreamableHttpClientTransport; use rmcp::transport::auth::AuthClient; use rmcp::transport::auth::AuthError; use rmcp::transport::streamable_http_client::StreamableHttpClientTransportConfig; use rmcp::transport::streamable_http_client::StreamableHttpError; use serde::Deserialize; use serde::Serialize; use serde_json::Value; use tokio::sync::Mutex; use tokio::sync::Semaphore; use tokio::sync::watch; use tokio::time; use tracing::instrument; use tracing::warn; use crate::elicitation_client_service::ElicitationClientService; use crate::event_notification_transport::capture_event_notifications; use crate::event_notification_transport::event_notification_channel; use crate::http_client_adapter::StreamableHttpClientAdapter; use crate::http_client_adapter::StreamableHttpClientAdapterError; use crate::http_client_adapter::StreamableHttpRedirectMode; use crate::in_process_transport::InProcessTransportFactory; use crate::oauth::OAuthCredentialStore; use crate::oauth::OAuthPersistor; use crate::oauth::OAuthRuntime; use crate::oauth::ResolvedOAuthCredentialStore; use crate::oauth::ResolvedOAuthTokens; use crate::oauth::StoredOAuthTokens; use crate::oauth::install_tokens_in_manager; use crate::oauth::resolve_oauth_tokens_from_store_policy; use crate::oauth::validate_refresh_token_issuer; use crate::oauth_client_credentials::OAuthClientCredentials; use crate::oauth_http_client::OAuthHttpClientAdapter; use crate::oauth_refresh_mode::McpOAuthRefreshMode; use crate::ordered_byte_transport::OrderedByteTransport; use crate::protocol_mode::McpProtocolMode; use crate::request_cancellation::RequestCancellation; use crate::startup_error::is_authentication_required_error; use crate::stdio_server_launcher::StdioProcessSlot; use crate::stdio_server_launcher::StdioServerCommand; use crate::stdio_server_launcher::StdioServerLauncher; use crate::stdio_server_launcher::StdioServerTransport; use crate::stdio_server_launcher::StdioTermination; use crate::tool_list_changes::track_tool_list_changes; use crate::utils::build_default_headers; use akode_config::types::OAuthCredentialsStoreMode; #[path = "stdio_handshake.rs"] mod stdio_handshake; #[path = "streamable_http_retry.rs"] mod streamable_http_retry; use self::streamable_http_retry::HandshakeError; use self::streamable_http_retry::STREAMABLE_HTTP_RETRY_DELAYS_MS; use self::streamable_http_retry::sleep_with_retry_deadline; const READ_ONLY_TOOLS_META_KEY: &str = "openai/readOnly"; enum PendingTransport { InProcess { transport: tokio::io::DuplexStream, }, Stdio { transport: Box, }, StreamableHttp { transport: StreamableHttpClientTransport, }, StreamableHttpWithOAuth { transport: StreamableHttpClientTransport>, oauth_runtime: OAuthRuntime, }, StreamableHttpWithAccessTokenOnly { transport: StreamableHttpClientTransport>, }, } enum ClientState { Connecting { transport: Option, }, Ready { service: Arc>, oauth: Option, }, Closed, } /// Bearer authentication applied directly or by the selected HTTP transport. #[derive(Clone)] pub enum StreamableHttpBearerToken { /// A token already resolved in the current process. Resolved(String), /// The HTTP client attaches credentials when it sends each request. ProvidedByHttpClient, } #[derive(Clone)] enum TransportRecipe { InProcess { factory: Arc, }, Stdio { command: StdioServerCommand, launcher: Arc, }, StreamableHttp { server_name: String, url: String, bearer_token: Option, http_headers: Option>, env_http_headers: Option>, oauth_config: Option>, store_mode: OAuthCredentialsStoreMode, keyring_backend_kind: AuthKeyringBackendKind, pinned_credential_store: Arc>, originator: AuthStorageOriginator, http_client: Arc, auth_provider: Option>, redirect_mode: StreamableHttpRedirectMode, oauth_refresh_mode: McpOAuthRefreshMode, initialize_deadline: Arc>>, }, } struct InitializeDeadlineGuard { deadline: Arc>>, } impl Drop for InitializeDeadlineGuard { fn drop(&mut self) { *self.deadline.lock().unwrap_or_else(PoisonError::into_inner) = None; } } #[derive(Clone)] struct InitializeContext { timeout: Option, client_info: InitializeRequestParams, send_elicitation: Arc, } #[derive(Clone)] pub(crate) struct ElicitationPauseState { active_count: Arc, paused: watch::Sender, } impl ElicitationPauseState { pub(crate) fn new() -> Self { let (paused, _rx) = watch::channel(false); Self { active_count: Arc::new(AtomicUsize::new(0)), paused, } } pub(crate) fn enter(&self) -> ElicitationPauseGuard { if self.active_count.fetch_add(1, Ordering::AcqRel) == 0 { self.paused.send_replace(true); } ElicitationPauseGuard { pause_state: self.clone(), } } fn subscribe(&self) -> watch::Receiver { self.paused.subscribe() } } pub(crate) struct ElicitationPauseGuard { pause_state: ElicitationPauseState, } impl Drop for ElicitationPauseGuard { fn drop(&mut self) { if self.pause_state.active_count.fetch_sub(1, Ordering::AcqRel) == 1 { self.pause_state.paused.send_replace(false); } } } async fn active_time_timeout( duration: Duration, mut pause_state: watch::Receiver, operation: Fut, ) -> std::result::Result where Fut: Future, { let mut remaining = duration; tokio::pin!(operation); loop { if *pause_state.borrow_and_update() { tokio::select! { result = &mut operation => return Ok(result), changed = pause_state.changed() => { if changed.is_err() { return time::timeout(remaining, operation).await.map_err(|_| ()); } let _paused = *pause_state.borrow_and_update(); } } continue; } let active_start = Instant::now(); tokio::select! { result = &mut operation => return Ok(result), _ = time::sleep(remaining) => { return Err(()); } changed = pause_state.changed() => { if changed.is_err() { return time::timeout(remaining, operation).await.map_err(|_| ()); } if *pause_state.borrow_and_update() { remaining = remaining.saturating_sub(active_start.elapsed()); if remaining.is_zero() { return Err(()); } } } } } } #[derive(Debug, thiserror::Error)] pub(crate) enum ClientOperationError { #[error(transparent)] Service(#[from] rmcp::service::ServiceError), #[error("timed out awaiting {label} after {duration:.0?}")] Timeout { label: String, duration: Duration }, } fn remaining_operation_timeout( label: &str, timeout: Option, deadline: Option, ) -> std::result::Result, ClientOperationError> { let Some(deadline) = deadline else { return Ok(None); }; let remaining = deadline.saturating_duration_since(Instant::now()); if remaining.is_zero() { Err(ClientOperationError::Timeout { label: label.to_string(), duration: timeout.unwrap_or(remaining), }) } else { Ok(Some(remaining)) } } #[derive(Debug, Clone, PartialEq)] pub enum Elicitation { Mcp(ElicitRequestParams), OpenAiForm { meta: Option, message: String, requested_schema: serde_json::Value, }, OpenAiElicitationForm { meta: Option, message: String, requested_schema: serde_json::Value, }, UserVerification { meta: Option, title: String, description: String, challenge: String, }, } impl Elicitation { pub fn meta(&self) -> Option<&serde_json::Map> { match self { Self::Mcp(request) => request.meta().map(|meta| &meta.0.0), Self::OpenAiForm { meta, .. } | Self::OpenAiElicitationForm { meta, .. } | Self::UserVerification { meta, .. } => { meta.as_ref().and_then(serde_json::Value::as_object) } } } } #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct ElicitationResponse { pub action: ElicitationAction, pub content: Option, #[serde(rename = "_meta")] pub meta: Option, } impl From for ElicitationResponse { fn from(value: ElicitResult) -> Self { Self { action: value.action, content: value.content, meta: value.meta.map(|meta| Value::Object(meta.0)), } } } impl From for ElicitResult { fn from(value: ElicitationResponse) -> Self { let mut result = Self::new(value.action); result.content = value.content; result.meta = value.meta.and_then(|meta| match meta { Value::Object(meta) => Some(rmcp::model::MetaObject::from(meta)), _ => None, }); result } } /// Interface for sending elicitation requests to the UI and awaiting a response. pub type SendElicitation = Box< dyn Fn(RequestId, Elicitation) -> BoxFuture<'static, Result> + Send + Sync, >; pub struct ToolWithConnectorId { pub tool: Tool, pub connector_id: Option, pub connector_name: Option, pub connector_description: Option, } pub struct ListToolsWithConnectorIdResult { pub meta: Option, pub next_cursor: Option, pub tools: Vec, } /// An active Plugin Runtime event request and its request-scoped notifications. pub struct CancellableEventStreamRequest { pub handle: RequestHandle, pub notifications: crate::EventNotificationReceiver, } /// MCP client implemented on top of the official `rmcp` SDK. /// https://github.com/modelcontextprotocol/rust-sdk pub struct RmcpClient { // Drop our interest in retrying before the SDK transport uses its ordinary shutdown grace. stdio_process: Option, state: Mutex, transport_recipe: TransportRecipe, protocol_mode: McpProtocolMode, requires_read_only_tools: bool, initialize_context: Mutex>, session_recovery_lock: Semaphore, elicitation_pause_state: ElicitationPauseState, tool_list_revision: Arc, cancel_requests_on_drop: AtomicBool, } impl RmcpClient { /// Extend tool-call cancellation to catalog, resource, and custom requests on a shared connection. pub fn enable_request_cancellation(&self) { self.cancel_requests_on_drop.store(true, Ordering::Relaxed); } fn request_cancellation(&self) -> RequestCancellation { if self.cancel_requests_on_drop.load(Ordering::Relaxed) { RequestCancellation::OnDrop } else { RequestCancellation::Disabled } } /// Tool catalog invalidation sequence, ordered before subsequent responses. pub fn tool_list_revision(&self) -> crate::ToolListRevision { crate::ToolListRevision(Arc::clone(&self.tool_list_revision)) } /// Requests server-side read-only filtering and invocation checks for every tool request. pub fn with_read_only_tools(mut self, requires_read_only_tools: bool) -> Self { self.requires_read_only_tools = requires_read_only_tools; self } fn apply_read_only_tools_meta(&self, meta: &mut Option) { if self.requires_read_only_tools { meta.get_or_insert_default() .insert(READ_ONLY_TOOLS_META_KEY.to_string(), Value::Bool(true)); } } /// Returns the protocol compatibility policy captured when this client was created. pub fn protocol_mode(&self) -> McpProtocolMode { self.protocol_mode } pub async fn new_in_process_client( factory: Arc, ) -> io::Result { let transport_recipe = TransportRecipe::InProcess { factory }; let transport = Self::create_pending_transport(&transport_recipe) .await .map_err(io::Error::other)?; Ok(Self { state: Mutex::new(ClientState::Connecting { transport: Some(transport), }), stdio_process: None, transport_recipe, protocol_mode: McpProtocolMode::Legacy, requires_read_only_tools: false, initialize_context: Mutex::new(None), session_recovery_lock: Semaphore::new(/*permits*/ 1), elicitation_pause_state: ElicitationPauseState::new(), tool_list_revision: Arc::default(), cancel_requests_on_drop: AtomicBool::new(false), }) } pub async fn new_stdio_client( program: OsString, args: Vec, env: Option>, env_vars: &[McpServerEnvVar], cwd: Option, launcher: Arc, ) -> io::Result { Self::new_stdio_client_with_protocol_mode( program, args, env, env_vars, cwd, launcher, McpProtocolMode::Legacy, ) .await } /// Constructs a stdio client with an explicitly selected compatibility policy. #[allow(clippy::too_many_arguments)] pub async fn new_stdio_client_with_protocol_mode( program: OsString, args: Vec, mut env: Option>, env_vars: &[McpServerEnvVar], cwd: Option, launcher: Arc, protocol_mode: McpProtocolMode, ) -> io::Result { let requested_stdio_version = match protocol_mode { McpProtocolMode::Legacy => None, McpProtocolMode::V20260728 | McpProtocolMode::DiscoverLocalStdio => env .as_mut() .and_then(|env| env.remove(OsStr::new("AKODE_MCP_PROTOCOL_VERSION"))), }; let protocol_mode = protocol_mode.stdio_mode(requested_stdio_version.as_deref())?; let transport_recipe = TransportRecipe::Stdio { command: StdioServerCommand::new( program, args, env, env_vars.to_vec(), cwd, protocol_mode, ), launcher, }; let transport = Self::create_pending_transport(&transport_recipe) .await .map_err(io::Error::other)?; let stdio_process = match &transport { PendingTransport::Stdio { transport } => Some(transport.process_slot()), PendingTransport::InProcess { .. } | PendingTransport::StreamableHttp { .. } | PendingTransport::StreamableHttpWithOAuth { .. } | PendingTransport::StreamableHttpWithAccessTokenOnly { .. } => None, }; Ok(Self { state: Mutex::new(ClientState::Connecting { transport: Some(transport), }), stdio_process, transport_recipe, protocol_mode, initialize_context: Mutex::new(None), requires_read_only_tools: false, session_recovery_lock: Semaphore::new(/*permits*/ 1), elicitation_pause_state: ElicitationPauseState::new(), tool_list_revision: Arc::default(), cancel_requests_on_drop: AtomicBool::new(false), }) } #[allow(clippy::too_many_arguments)] pub async fn new_streamable_http_client( server_name: &str, url: &str, bearer_token: Option, http_headers: Option>, env_http_headers: Option>, store_mode: OAuthCredentialsStoreMode, keyring_backend_kind: AuthKeyringBackendKind, http_client: Arc, auth_provider: Option>, ) -> Result { Self::new_streamable_http_client_with_protocol_mode( server_name, url, bearer_token, http_headers, env_http_headers, store_mode, keyring_backend_kind, http_client, auth_provider, McpProtocolMode::Legacy, ) .await } /// Constructs a streamable HTTP client with an explicitly selected compatibility policy. #[allow(clippy::too_many_arguments)] pub async fn new_streamable_http_client_with_protocol_mode( server_name: &str, url: &str, bearer_token: Option, http_headers: Option>, env_http_headers: Option>, store_mode: OAuthCredentialsStoreMode, keyring_backend_kind: AuthKeyringBackendKind, http_client: Arc, auth_provider: Option>, protocol_mode: McpProtocolMode, ) -> Result { Self::new_streamable_http_client_with_protocol_mode_and_redirect_mode( server_name, url, bearer_token.map(StreamableHttpBearerToken::Resolved), http_headers, env_http_headers, /*oauth_config*/ None, store_mode, keyring_backend_kind, http_client, auth_provider, protocol_mode, StreamableHttpRedirectMode::Legacy, McpOAuthRefreshMode::Legacy, ) .await } #[allow(clippy::too_many_arguments)] pub async fn new_streamable_http_client_with_protocol_mode_and_redirect_mode( server_name: &str, url: &str, bearer_token: Option, http_headers: Option>, env_http_headers: Option>, oauth_config: Option, store_mode: OAuthCredentialsStoreMode, keyring_backend_kind: AuthKeyringBackendKind, http_client: Arc, auth_provider: Option>, protocol_mode: McpProtocolMode, redirect_mode: StreamableHttpRedirectMode, oauth_refresh_mode: McpOAuthRefreshMode, ) -> Result { let transport_recipe = TransportRecipe::StreamableHttp { server_name: server_name.to_string(), url: url.to_string(), bearer_token, http_headers, env_http_headers, oauth_config: oauth_config.map(Arc::new), store_mode, keyring_backend_kind, pinned_credential_store: Arc::new(OnceLock::new()), originator: AuthStorageOriginator::current(), http_client, auth_provider, redirect_mode, oauth_refresh_mode, initialize_deadline: Arc::new(StdMutex::new(None)), }; let transport = Self::create_pending_transport(&transport_recipe).await?; Ok(Self { state: Mutex::new(ClientState::Connecting { transport: Some(transport), }), stdio_process: None, transport_recipe, protocol_mode, initialize_context: Mutex::new(None), requires_read_only_tools: false, session_recovery_lock: Semaphore::new(/*permits*/ 1), elicitation_pause_state: ElicitationPauseState::new(), tool_list_revision: Arc::default(), cancel_requests_on_drop: AtomicBool::new(false), }) } /// Perform the initialization handshake with the MCP server. /// https://modelcontextprotocol.io/specification/2025-06-18/basic/lifecycle#initialization #[instrument(level = "trace", skip_all)] pub async fn initialize( &self, params: InitializeRequestParams, timeout: Option, send_elicitation: SendElicitation, ) -> Result { let context = InitializeContext { timeout, client_info: params, send_elicitation: Arc::new(send_elicitation), }; let pending_transport = { let mut guard = self.state.lock().await; match &mut *guard { ClientState::Connecting { transport } => match transport.take() { Some(transport) => transport, None => return Err(anyhow!("client already initializing")), }, ClientState::Ready { .. } => return Err(anyhow!("client already initialized")), ClientState::Closed => return Err(anyhow!("MCP client is shut down")), } }; let (service, oauth_runtime) = self .connect_pending_transport_with_initialize_retries(pending_transport, &context) .await?; let initialize_result_rmcp = service .peer() .peer_info() .ok_or_else(|| anyhow!("handshake succeeded but server info was missing"))?; let initialize_result = initialize_result_rmcp.as_ref().clone(); { let mut initialize_context = self.initialize_context.lock().await; *initialize_context = Some(context); } { let mut guard = self.state.lock().await; if matches!(*guard, ClientState::Closed) { return Err(anyhow!("MCP client is shut down")); } *guard = ClientState::Ready { service, oauth: oauth_runtime.clone(), }; } if let Some(OAuthRuntime::Legacy(runtime)) = oauth_runtime && let Err(error) = runtime.persist_if_needed().await { warn!("failed to persist OAuth tokens after initialize: {error}"); } Ok(initialize_result) } pub async fn list_tools( &self, params: Option, timeout: Option, ) -> Result { let mut params = crate::trace_context::traced_pagination(params); self.refresh_oauth_if_needed().await?; if self.requires_read_only_tools { self.apply_read_only_tools_meta(&mut params.get_or_insert_default().meta); } let cancellation = self.request_cancellation(); let result = self .run_service_operation("tools/list", timeout, move |service| { let params = params.clone(); async move { if matches!(cancellation, RequestCancellation::Disabled) { return service.list_tools(params).await; } let result = cancellation .send( service.peer(), ClientRequest::ListToolsRequest(ListToolsRequest { method: Default::default(), params, extensions: Default::default(), }), rmcp::service::PeerRequestOptions::no_options(), ) .await?; match result { ServerResult::ListToolsResult(result) => Ok(result), _ => Err(ServiceError::UnexpectedResponse), } } .boxed() }) .await?; self.persist_oauth_tokens().await; Ok(result) } #[instrument(level = "trace", skip_all)] pub async fn list_tools_with_connector_ids( &self, params: Option, timeout: Option, ) -> Result { let result = self.list_tools(params, timeout).await?; let tools = result .tools .into_iter() .map(|tool| { let meta = tool.meta.as_ref(); let connector_id = Self::meta_string(meta, "connector_id"); let connector_name = Self::meta_string(meta, "connector_name") .or_else(|| Self::meta_string(meta, "connector_display_name")); let connector_description = Self::meta_string(meta, "connector_description") .or_else(|| Self::meta_string(meta, "connectorDescription")); Ok(ToolWithConnectorId { tool, connector_id, connector_name, connector_description, }) }) .collect::>>()?; Ok(ListToolsWithConnectorIdResult { meta: result.meta.map(|meta| serde_json::json!(meta)), next_cursor: result.next_cursor, tools, }) } fn meta_string(meta: Option<&rmcp::model::MetaObject>, key: &str) -> Option { meta.and_then(|meta| meta.get(key)) .and_then(Value::as_str) .map(str::trim) .filter(|value| !value.is_empty()) .map(str::to_string) } pub async fn list_resources( &self, params: Option, timeout: Option, ) -> Result { let params = crate::trace_context::traced_pagination(params); self.refresh_oauth_if_needed().await?; let cancellation = self.request_cancellation(); let result = self .run_service_operation("resources/list", timeout, move |service| { let params = params.clone(); async move { if matches!(cancellation, RequestCancellation::Disabled) { return service.list_resources(params).await; } let result = cancellation .send( service.peer(), ClientRequest::ListResourcesRequest(ListResourcesRequest { method: Default::default(), params, extensions: Default::default(), }), rmcp::service::PeerRequestOptions::no_options(), ) .await?; match result { ServerResult::ListResourcesResult(result) => Ok(result), _ => Err(ServiceError::UnexpectedResponse), } } .boxed() }) .await?; self.persist_oauth_tokens().await; Ok(result) } pub async fn list_resource_templates( &self, params: Option, timeout: Option, ) -> Result { let params = crate::trace_context::traced_pagination(params); self.refresh_oauth_if_needed().await?; let cancellation = self.request_cancellation(); let result = self .run_service_operation("resources/templates/list", timeout, move |service| { let params = params.clone(); async move { if matches!(cancellation, RequestCancellation::Disabled) { return service.list_resource_templates(params).await; } let result = cancellation .send( service.peer(), ClientRequest::ListResourceTemplatesRequest( ListResourceTemplatesRequest { method: Default::default(), params, extensions: Default::default(), }, ), rmcp::service::PeerRequestOptions::no_options(), ) .await?; match result { ServerResult::ListResourceTemplatesResult(result) => Ok(result), _ => Err(ServiceError::UnexpectedResponse), } } .boxed() }) .await?; self.persist_oauth_tokens().await; Ok(result) } pub async fn read_resource( &self, params: ReadResourceRequestParams, timeout: Option, ) -> Result { let mut params = params; params.meta = crate::trace_context::with_current_trace(params.meta); self.refresh_oauth_if_needed().await?; let cancellation = self.request_cancellation(); let requested_modern = self.protocol_mode != McpProtocolMode::Legacy; let result = self .run_service_operation("resources/read", timeout, move |service| { let params = params.clone(); async move { if matches!(cancellation, RequestCancellation::OnDrop) { return crate::request_input::read_resource( &service, service.service(), params, cancellation, ) .await; } let modern_session = requested_modern && service.peer().peer_info().is_some_and(|info| { info.protocol_version == ProtocolVersion::V_2026_07_28 }); if modern_session { service.read_resource(params).await } else { service.peer().read_resource(params).await } } .boxed() }) .await?; self.persist_oauth_tokens().await; Ok(result) } /// Reads a resource with inputs and timeout pauses owned by the calling chat. pub async fn read_resource_with_elicitation( &self, mut params: ReadResourceRequestParams, timeout: Option, send_elicitation: Arc, ) -> Result { params.meta = crate::trace_context::with_current_trace(params.meta); self.refresh_oauth_if_needed().await?; let cancellation = self.request_cancellation(); let pause_state = ElicitationPauseState::new(); let result = self .run_service_operation_with_pause_state( "resources/read", timeout, pause_state.clone(), move |service| { let params = params.clone(); let input_service = service .service() .for_request(Arc::clone(&send_elicitation), pause_state.clone()); async move { if !service.peer().peer_info().is_some_and(|info| { info.protocol_version == ProtocolVersion::V_2026_07_28 }) { return Err(ServiceError::McpError(rmcp::ErrorData::invalid_request( "request-scoped MCP inputs require protocol 2026-07-28", /*data*/ None, ))); } crate::request_input::read_resource( &service, &input_service, params, cancellation, ) .await } .boxed() }, ) .await?; self.persist_oauth_tokens().await; Ok(result) } /// Builds metadata against the session that sends each attempt, including a recovery retry. /// The resolver must be safe to invoke again and must retain the call's captured authority. pub async fn call_tool( &self, name: String, arguments: Option, meta_for_session: F, timeout: Option, ) -> Result where F: Fn(&rmcp::model::ServerCapabilities) -> Result> + Send + Sync, { self.call_tool_inner( name, arguments, meta_for_session, timeout, /*send_elicitation*/ None, ) .await } /// Routes modern tool inputs and timeout pauses to this caller on a shared connection. /// Legacy connections are rejected because their callbacks belong to connection startup. pub async fn call_tool_with_elicitation( &self, name: String, arguments: Option, meta_for_session: F, timeout: Option, send_elicitation: Arc, ) -> Result where F: Fn(&rmcp::model::ServerCapabilities) -> Result> + Send + Sync, { self.call_tool_inner( name, arguments, meta_for_session, timeout, Some(send_elicitation), ) .await } async fn call_tool_inner( &self, name: String, arguments: Option, meta_for_session: F, timeout: Option, send_elicitation: Option>, ) -> Result where F: Fn(&rmcp::model::ServerCapabilities) -> Result> + Send + Sync, { let authentication_required_result = |error| { if !is_authentication_required_error(&error) { return Err(error); } // Local expiry and server rejection use the same reconnect signal without // exposing token-endpoint or transport details in the tool result. let mut result = CallToolResult::error(vec![ContentBlock::text( "MCP authentication required. Reconnect to continue using this server.", )]); result.meta = Some( serde_json::Map::from_iter([( "mcp/www_authenticate".to_string(), Value::String("Bearer error=\"invalid_token\"".to_string()), )]) .into(), ); Ok(result) }; if let Err(error) = self.refresh_oauth_if_needed().await { return authentication_required_result(error); } let arguments = match arguments { Some(Value::Object(map)) => Some(map), Some(other) => { return Err(anyhow!( "MCP tool arguments must be a JSON object, got {other}" )); } None => None, }; let mut rmcp_params = CallToolRequestParams::new(name); rmcp_params.arguments = arguments; let requested_modern = self.protocol_mode != McpProtocolMode::Legacy; let meta_for_session = &meta_for_session; let pause_state = if send_elicitation.is_some() { ElicitationPauseState::new() } else { self.elicitation_pause_state.clone() }; match self .run_service_operation_with_pause_state( "tools/call", timeout, pause_state.clone(), move |service| { let mut rmcp_params = rmcp_params.clone(); let send_elicitation = send_elicitation.clone(); let pause_state = pause_state.clone(); async move { // Resolve from this service, not a cached startup capability or another // service observed before recovery. Local policy failures never send a call. let meta = (|| { let info = service .peer() .peer_info() .context("MCP session has no negotiated server capabilities")?; let mut meta = match meta_for_session(&info.capabilities)? { Some(Value::Object(map)) => Some(RequestMetaObject::from(map)), Some(other) => { return Err(anyhow!( "MCP tool request _meta must be a JSON object, got {other}" )); } None => None, }; self.apply_read_only_tools_meta(&mut meta); Ok(crate::trace_context::with_current_trace(meta)) })(); let meta = match meta { Ok(meta) => meta, Err(error) => return Ok(Err(error)), }; let modern_session = requested_modern && service.peer().peer_info().is_some_and(|info| { info.protocol_version == ProtocolVersion::V_2026_07_28 }); if modern_session { rmcp_params.meta = meta; let input_service = send_elicitation .map(|sender| service.service().for_request(sender, pause_state)); return crate::request_input::call_tool( &service, input_service.as_ref().unwrap_or_else(|| service.service()), rmcp_params, ) .await .map(Ok); } if send_elicitation.is_some() { return Err(ServiceError::McpError(rmcp::ErrorData::invalid_request( "request-scoped MCP inputs require protocol 2026-07-28", /*data*/ None, ))); } let mut options = rmcp::service::PeerRequestOptions::no_options(); options.meta = meta; let result = RequestCancellation::OnDrop .send( service.peer(), ClientRequest::CallToolRequest(rmcp::model::CallToolRequest::new( rmcp_params, )), options, ) .await?; match result { ServerResult::CallToolResult(result) => Ok(Ok(result)), _ => Err(rmcp::service::ServiceError::UnexpectedResponse), } } .boxed() }, ) .await { Ok(Ok(result)) => { self.persist_oauth_tokens().await; Ok(result) } Ok(Err(error)) => Err(error), Err(error) => { let Some(ClientOperationError::Service(ServiceError::TransportSend(transport))) = error.downcast_ref() else { return authentication_required_result(error); }; let Some(StreamableHttpError::AuthRequired(challenge)) = transport .error .downcast_ref::>() else { return authentication_required_result(error); }; // The transport has already handled automatic refresh. Preserve the challenge // for interactive login without replaying the rejected tool call. let mut result = CallToolResult::error(vec![ContentBlock::text("Authentication required")]); result.meta = Some(MetaObject::from(serde_json::Map::from_iter([( "mcp/www_authenticate".to_string(), serde_json::json!([challenge.www_authenticate_header]), )]))); Ok(result) } } } pub async fn send_custom_notification( &self, method: &str, params: Option, ) -> Result<()> { self.refresh_oauth_if_needed().await?; self.run_service_operation( "notifications/custom", /*timeout*/ None, move |service| { let params = params.clone(); async move { service .send_notification(ClientNotification::CustomNotification( CustomNotification { method: method.to_string(), params, extensions: Extensions::new(), }, )) .await } .boxed() }, ) .await?; self.persist_oauth_tokens().await; Ok(()) } pub async fn send_custom_request( &self, method: &str, params: Option, ) -> Result { self.send_custom_request_with_timeout(method, params, /*timeout*/ None) .await } pub async fn send_custom_request_with_timeout( &self, method: &str, params: Option, timeout: Option, ) -> Result { self.refresh_oauth_if_needed().await?; let cancellation = self.request_cancellation(); let response = self .run_service_operation("requests/custom", timeout, move |service| { let params = params.clone(); async move { let request = crate::trace_context::traced_custom_request(method, params); cancellation .send( service.peer(), ClientRequest::CustomRequest(request), rmcp::service::PeerRequestOptions::no_options(), ) .await } .boxed() }) .await?; self.persist_oauth_tokens().await; Ok(response) } /// Starts a Plugin Runtime event stream without waiting for its final response. pub async fn send_event_stream_request( &self, params: Option, ) -> Result { let service = self.service().await?; let (sender, notifications) = event_notification_channel(); let mut request = crate::trace_context::traced_custom_request("events/stream", params); request.extensions.insert(sender); let handle = service .peer() .send_cancellable_request( ClientRequest::CustomRequest(request), rmcp::service::PeerRequestOptions::no_options(), ) .await?; Ok(CancellableEventStreamRequest { handle, notifications, }) } async fn service(&self) -> Result>> { let guard = self.state.lock().await; match &*guard { ClientState::Ready { service, .. } => Ok(Arc::clone(service)), ClientState::Connecting { .. } => Err(anyhow!("MCP client not initialized")), ClientState::Closed => Err(anyhow!("MCP client is shut down")), } } async fn oauth_runtime(&self) -> Option { let guard = self.state.lock().await; match &*guard { ClientState::Ready { oauth: Some(runtime), .. } => Some(runtime.clone()), _ => None, } } /// Returns `None` when this client does not manage stored OAuth credentials. pub async fn managed_oauth_credentials(&self) -> Option> { let runtime = self.oauth_runtime().await?; Some(match runtime { OAuthRuntime::Legacy(persistor) => persistor.stored_credentials().await, OAuthRuntime::Coordinated { store, .. } => store.stored_credentials().await, }) } /// Returns whether an initialized transport or its underlying service has stopped. pub async fn is_closed(&self) -> bool { let state = self.state.lock().await; match &*state { ClientState::Ready { service, .. } => { service.is_closed() || service.peer().is_transport_closed() } ClientState::Connecting { .. } => false, ClientState::Closed => true, } } /// Stop the MCP transport and any stdio server process owned by this client. pub async fn shutdown(&self) { if let Err(error) = self.shutdown_for(StdioTermination::Shutdown).await { warn!("failed to terminate MCP stdio server process: {error}"); } } /// Wait for a failed discovery process to release resources needed by a subsequent launch. pub async fn shutdown_before_retry(&self) -> io::Result<()> { self.shutdown_for(StdioTermination::Restart).await } async fn shutdown_for(&self, reason: StdioTermination) -> io::Result<()> { let previous_state = { let mut guard = self.state.lock().await; std::mem::replace(&mut *guard, ClientState::Closed) }; let process = match &self.stdio_process { Some(slot) => Some(slot.lock().await.close()), None => None, }; if matches!(reason, StdioTermination::Restart) { // Let the helper see EOF before escalating to process-group termination. drop(previous_state); } if let Some(process) = process { process.terminate(reason).await?; } Ok(()) } /// This should be called after every tool call so that if a given tool call triggered /// a refresh of the OAuth tokens, they are persisted. async fn persist_oauth_tokens(&self) { if let Some(OAuthRuntime::Legacy(runtime)) = self.oauth_runtime().await && let Err(error) = runtime.persist_if_needed().await { warn!("failed to persist OAuth tokens: {error}"); } } /// Prepares managed OAuth before the MCP operation timeout starts. async fn refresh_oauth_if_needed(&self) -> Result<()> { if let Some(runtime) = self.oauth_runtime().await { runtime.refresh_if_needed().await?; } Ok(()) } async fn create_pending_transport( transport_recipe: &TransportRecipe, ) -> Result { match transport_recipe { TransportRecipe::InProcess { factory } => { let transport = factory.open().await?; Ok(PendingTransport::InProcess { transport }) } TransportRecipe::Stdio { command, launcher } => { let transport = launcher.launch(command.clone()).await?; Ok(PendingTransport::Stdio { transport: Box::new(transport), }) } TransportRecipe::StreamableHttp { server_name, url, bearer_token, http_headers, env_http_headers, oauth_config, store_mode, keyring_backend_kind, pinned_credential_store, originator, http_client, auth_provider, redirect_mode, oauth_refresh_mode, initialize_deadline, } => { let has_configured_headers = matches!( bearer_token, Some(StreamableHttpBearerToken::ProvidedByHttpClient) ) || http_headers .as_ref() .is_some_and(|headers| !headers.is_empty()) || env_http_headers .as_ref() .is_some_and(|headers| !headers.is_empty()); let default_headers = build_default_headers(http_headers.clone(), env_http_headers.clone())?; let auth_provider = if bearer_token.is_some() || default_headers.contains_key(AUTHORIZATION) { None } else { auth_provider.clone() }; let resolved_oauth_tokens = if bearer_token.is_none() && auth_provider.is_none() && !default_headers.contains_key(AUTHORIZATION) { OAuthClientCredentials::resolve(oauth_config.as_deref())?; let oauth_server_name = server_name.clone(); let oauth_url = url.clone(); let oauth_store_mode = *store_mode; let oauth_keyring_backend_kind = *keyring_backend_kind; let pinned_credential_store = Arc::clone(pinned_credential_store); // Recovery can run after the startup scope ends, even when startup found // no credentials and therefore could not pin a store with this attribution. let originator = *originator; let load = move || -> Result> { if let Some(store) = pinned_credential_store.get().copied() { // Rebuilds reread the source selected during first construction. Only // initial construction below evaluates configured store policy. return store .load(&DefaultKeyringStore, &oauth_server_name, &oauth_url) .map(|tokens| { tokens.map(|tokens| ResolvedOAuthTokens { tokens, store }) }); } match resolve_oauth_tokens_from_store_policy( &DefaultKeyringStore, &oauth_server_name, &oauth_url, oauth_store_mode, oauth_keyring_backend_kind, ) { Ok(tokens) => { if let Some(resolved) = tokens.as_ref() { // Retries and session recovery rebuild this transport. Pin the // first concrete source so Auto is not reevaluated mid-client. pinned_credential_store.set(resolved.store).map_err(|_| { anyhow!( "OAuth credential store pinned concurrently for MCP server `{oauth_server_name}`" ) })?; } Ok(tokens) } Err(err) => { warn!( "failed to read tokens for server `{oauth_server_name}`: {err}" ); Ok(None) } } }; tokio::task::spawn_blocking(move || originator.sync_scope(load)) .await .map_err(|error| { anyhow!("OAuth credential loading task failed: {error}") })?? } else { None }; if let Some(ResolvedOAuthTokens { tokens: initial_tokens, store: credential_store, }) = resolved_oauth_tokens { match create_oauth_transport_and_runtime( server_name, url, initial_tokens.clone(), credential_store, default_headers.clone(), Arc::clone(http_client), has_configured_headers, *redirect_mode, *oauth_refresh_mode, Arc::clone(initialize_deadline), oauth_config.as_deref(), ) .await { Ok(pending_transport) => Ok(pending_transport), Err(err) if err.downcast_ref::().is_some_and(|auth_err| { matches!(auth_err, AuthError::NoAuthorizationSupport) }) => { let access_token = initial_tokens .token_response .0 .access_token() .secret() .to_string(); warn!( "OAuth metadata discovery is unavailable for MCP server `{server_name}`; falling back to stored bearer token authentication" ); let http_config = StreamableHttpClientTransportConfig::with_uri(url.clone()) .auth_header(access_token); let transport = StreamableHttpClientTransport::with_client( StreamableHttpClientAdapter::new( Arc::clone(http_client), default_headers, /*auth_provider*/ None, has_configured_headers, *redirect_mode, Arc::clone(initialize_deadline), ), http_config, ); Ok(PendingTransport::StreamableHttp { transport }) } Err(err) => Err(err), } } else { let mut http_config = StreamableHttpClientTransportConfig::with_uri(url.clone()); if let Some(StreamableHttpBearerToken::Resolved(bearer_token)) = bearer_token { http_config = http_config.auth_header(bearer_token.clone()); } let transport = StreamableHttpClientTransport::with_client( StreamableHttpClientAdapter::new( Arc::clone(http_client), default_headers, auth_provider, has_configured_headers, *redirect_mode, Arc::clone(initialize_deadline), ), http_config, ); Ok(PendingTransport::StreamableHttp { transport }) } } } } async fn connect_pending_transport( &self, pending_transport: PendingTransport, initialize_context: &InitializeContext, timeout: Option, ) -> Result<( Arc>, Option, )> { // Request IDs and remembered cancellations belong to this connection, including // when a failed initialization or expired HTTP session creates a new transport. let client_service = || { let send_elicitation = Arc::clone(&initialize_context.send_elicitation); let mut info = initialize_context.client_info.clone(); if self.protocol_mode == McpProtocolMode::DiscoverLocalStdio { info.protocol_version = McpProtocolMode::Legacy.preferred_protocol_version(); } ElicitationClientService::new( info, Box::new(move |id, request| send_elicitation(id, request)), self.elicitation_pause_state.clone(), ) }; let _initialize_deadline = match &self.transport_recipe { TransportRecipe::StreamableHttp { initialize_deadline, .. } => { *initialize_deadline .lock() .unwrap_or_else(PoisonError::into_inner) = timeout.and_then(|duration| Instant::now().checked_add(duration)); Some(InitializeDeadlineGuard { deadline: Arc::clone(initialize_deadline), }) } TransportRecipe::InProcess { .. } | TransportRecipe::Stdio { .. } => None, }; let lifecycle = self.protocol_mode.client_lifecycle(); let connect_stdio = |transport: StdioServerTransport, lifecycle| { client_service() .serve_with_lifecycle( track_tool_list_changes( OrderedByteTransport::new(transport), Arc::clone(&self.tool_list_revision), ), lifecycle, ) .boxed() }; let mut discovery = None; let (transport, oauth_runtime) = match pending_transport { PendingTransport::InProcess { transport } => ( client_service() .serve_with_lifecycle( track_tool_list_changes( OrderedByteTransport::new( IntoTransport::::into_transport(transport), ), Arc::clone(&self.tool_list_revision), ), lifecycle, ) .boxed(), None, ), PendingTransport::Stdio { mut transport } => { if transport.protocol_mode() == McpProtocolMode::DiscoverLocalStdio { discovery = transport .watch_discovery(timeout) .map(|reply| (reply, transport.process_ref())); } let lifecycle = transport.protocol_mode().client_lifecycle(); (connect_stdio(*transport, lifecycle), None) } PendingTransport::StreamableHttp { transport } => ( client_service() .serve_with_lifecycle( track_tool_list_changes( capture_event_notifications(transport), Arc::clone(&self.tool_list_revision), ), lifecycle, ) .boxed(), None, ), PendingTransport::StreamableHttpWithOAuth { transport, oauth_runtime, } => ( client_service() .serve_with_lifecycle( track_tool_list_changes(transport, Arc::clone(&self.tool_list_revision)), lifecycle, ) .boxed(), Some(oauth_runtime), ), PendingTransport::StreamableHttpWithAccessTokenOnly { transport } => ( client_service() .serve_with_lifecycle( track_tool_list_changes(transport, Arc::clone(&self.tool_list_revision)), lifecycle, ) .boxed(), None, ), }; let handshake = async { let mut result = transport.await; if let (Some((mut reply, process)), Err(error)) = (discovery, &result) && let Some(mode) = stdio_handshake::restart_mode(error, reply.try_recv().ok())? { process .terminate(StdioTermination::Restart) .await .context("stop stdio server before handshake restart")?; let fresh = self.launch_stdio_replacement(mode).await?; // A confirmed modern helper doesn't need another legacy probe timer. // Windows can still select initialize if it could not contain the new process. let lifecycle = match fresh.protocol_mode() { McpProtocolMode::DiscoverLocalStdio => { rmcp::service::ClientLifecycleMode::Discover { preferred_versions: vec![ProtocolVersion::V_2026_07_28], } } mode => mode.client_lifecycle(), }; result = connect_stdio(fresh, lifecycle).await; } result.map_err(|source| HandshakeError { source }.into()) }; let service_result = match timeout { Some(duration) => time::timeout(duration, handshake) .await .with_context(|| { format!("timed out handshaking with MCP server after {duration:?}") }) .flatten(), None => handshake.await, }; let service = match service_result { Ok(service) => service, Err(error) => { if let Some(OAuthRuntime::Legacy(runtime)) = oauth_runtime.as_ref() && let Err(persist_error) = runtime.persist_if_needed().await { warn!( "failed to persist OAuth tokens after failed initialize: {persist_error}" ); } return Err(error); } }; // Preserve Codex's existing snapshot and request-freshness behavior. rmcp 3 // enables response caching and stale-on-error fallback by default. service .peer() .set_response_cache_config(ClientCacheConfig::disabled()) .await; Ok((Arc::new(service), oauth_runtime)) } async fn launch_stdio_replacement( &self, mode: McpProtocolMode, ) -> Result { let TransportRecipe::Stdio { command, launcher } = &self.transport_recipe else { unreachable!("stdio discovery uses a stdio launch recipe"); }; let slot = self .stdio_process .as_ref() .context("missing stdio process")?; launcher .launch(command.for_restart(mode, Arc::clone(slot))) .await .context("restart stdio server") } async fn run_service_operation( &self, label: &str, timeout: Option, operation: F, ) -> Result where F: Fn(Arc>) -> Fut, Fut: std::future::Future>, { self.run_service_operation_with_pause_state( label, timeout, self.elicitation_pause_state.clone(), operation, ) .await } async fn run_service_operation_with_pause_state( &self, label: &str, timeout: Option, pause_state: ElicitationPauseState, operation: F, ) -> Result where F: Fn(Arc>) -> Fut, Fut: std::future::Future>, { let service = self.service().await?; match Self::run_service_operation_with_transient_retries( Arc::clone(&service), label, timeout, pause_state.clone(), &operation, ) .await { Ok(result) => Ok(result), Err(error) if Self::is_session_expired_404(&error) => { self.reinitialize_after_session_expiry(&service).await?; let recovered_service = self.service().await?; Self::run_service_operation_with_transient_retries( recovered_service, label, timeout, pause_state, &operation, ) .await .map_err(Into::into) } Err(error) => Err(error.into()), } } async fn run_service_operation_with_transient_retries( service: Arc>, label: &str, timeout: Option, pause_state: ElicitationPauseState, operation: &F, ) -> std::result::Result where F: Fn(Arc>) -> Fut, Fut: std::future::Future>, { let retry_deadline = timeout.map(|duration| Instant::now() + duration); for (attempt, retry_delay_ms) in STREAMABLE_HTTP_RETRY_DELAYS_MS .iter() .copied() .map(Some) .chain(std::iter::once(None)) .enumerate() { let attempt_timeout = remaining_operation_timeout(label, timeout, retry_deadline)?; match Self::run_service_operation_once( Arc::clone(&service), label, attempt_timeout, pause_state.clone(), operation, ) .await { Ok(result) => return Ok(result), Err(error) if label == "tools/list" && Self::is_retryable_transport_error(&error) => { let Some(retry_delay_ms) = retry_delay_ms else { return Err(error); }; let delay = Duration::from_millis(retry_delay_ms); warn!( attempt = attempt + 1, max_attempts = STREAMABLE_HTTP_RETRY_DELAYS_MS.len() + 1, delay_ms = delay.as_millis(), error = %error, "streamable HTTP MCP tools/list failed with a retryable error; retrying" ); if !sleep_with_retry_deadline(delay, retry_deadline).await { return Err(ClientOperationError::Timeout { label: label.to_string(), duration: timeout.unwrap_or(delay), }); } } Err(error) => return Err(error), } } unreachable!("service operation retry loop should return on success or final error") } async fn run_service_operation_once( service: Arc>, label: &str, timeout: Option, pause_state: ElicitationPauseState, operation: &F, ) -> std::result::Result where F: Fn(Arc>) -> Fut, Fut: std::future::Future>, { match timeout { Some(duration) => { active_time_timeout(duration, pause_state.subscribe(), operation(service)) .await .map_err(|_| ClientOperationError::Timeout { label: label.to_string(), duration, })? .map_err(ClientOperationError::from) } None => operation(service).await.map_err(ClientOperationError::from), } } pub(crate) fn is_retryable_transport_error(error: &ClientOperationError) -> bool { let ClientOperationError::Service(rmcp::service::ServiceError::TransportSend(error)) = error else { return false; }; error .error .downcast_ref::>() .is_some_and(Self::is_retryable_streamable_http_error) } fn is_session_expired_404(error: &ClientOperationError) -> bool { let ClientOperationError::Service(rmcp::service::ServiceError::TransportSend(error)) = error else { return false; }; error .error .downcast_ref::>() .is_some_and(|error| { matches!( error, StreamableHttpError::Client( StreamableHttpClientAdapterError::SessionExpired404 ) ) }) } async fn reinitialize_after_session_expiry( &self, failed_service: &Arc>, ) -> Result<()> { let _recovery_guard = self .session_recovery_lock .acquire() .await .map_err(|_| anyhow!("MCP client recovery semaphore closed"))?; { let guard = self.state.lock().await; match &*guard { ClientState::Ready { service, .. } if !Arc::ptr_eq(service, failed_service) => { return Ok(()); } ClientState::Ready { .. } => {} ClientState::Connecting { .. } => { return Err(anyhow!("MCP client not initialized")); } ClientState::Closed => { return Err(anyhow!("MCP client is shut down")); } } } let initialize_context = self .initialize_context .lock() .await .clone() .ok_or_else(|| anyhow!("MCP client cannot recover before initialize succeeds"))?; let pending_transport = Self::create_pending_transport(&self.transport_recipe).await?; let (service, oauth_runtime) = self .connect_pending_transport_with_initialize_retries( pending_transport, &initialize_context, ) .await?; service .peer() .peer_info() .ok_or_else(|| anyhow!("recovered handshake succeeded but server info was missing"))?; { let mut guard = self.state.lock().await; if matches!(*guard, ClientState::Closed) { return Err(anyhow!("MCP client is shut down")); } *guard = ClientState::Ready { service, oauth: oauth_runtime.clone(), }; } if let Some(OAuthRuntime::Legacy(runtime)) = oauth_runtime && let Err(error) = runtime.persist_if_needed().await { warn!("failed to persist OAuth tokens after session recovery: {error}"); } Ok(()) } } #[allow(clippy::too_many_arguments)] async fn create_oauth_transport_and_runtime( server_name: &str, url: &str, initial_tokens: StoredOAuthTokens, credential_store: ResolvedOAuthCredentialStore, default_headers: HeaderMap, http_client: Arc, has_configured_headers: bool, redirect_mode: StreamableHttpRedirectMode, oauth_refresh_mode: McpOAuthRefreshMode, initialize_deadline: Arc>>, oauth_config: Option<&McpServerOAuthConfig>, ) -> Result { OAuthClientCredentials::resolve(oauth_config)? .validate_stored_client_id(&initial_tokens.client_id)?; let oauth_http_client = Arc::new(OAuthHttpClientAdapter::new_with_redirect_mode( http_client.clone(), default_headers.clone(), url, has_configured_headers, redirect_mode, )?); let mut manager = AuthorizationManager::new_with_oauth_http_client(url.to_string(), oauth_http_client) .await?; manager.set_allow_missing_issuer(true); let metadata = manager .resolve_metadata() .await .context("failed to resolve OAuth metadata before using stored credentials")? .metadata; let use_stored_access_token_only = match validate_refresh_token_issuer(&metadata, &initial_tokens) { Ok(()) => false, Err(_error) if initial_tokens.access_token_is_usable_without_refresh() => true, Err(error) => return Err(error), }; manager.set_metadata(metadata); let mut runtime_tokens = initial_tokens.clone(); if use_stored_access_token_only { runtime_tokens.token_response.0.set_refresh_token(None); runtime_tokens.issuer = None; } install_tokens_in_manager(&mut manager, &runtime_tokens, oauth_config).await?; let coordinated_store = match oauth_refresh_mode { McpOAuthRefreshMode::Coordinated if !use_stored_access_token_only => { let store = OAuthCredentialStore::new( initial_tokens.clone(), credential_store, DefaultKeyringStore, oauth_config.cloned(), ); manager.set_credential_store(store.clone()); Some(store) } McpOAuthRefreshMode::Legacy | McpOAuthRefreshMode::Coordinated => None, }; let auth_client = AuthClient::new( StreamableHttpClientAdapter::new( http_client, default_headers, /*auth_provider*/ None, has_configured_headers, redirect_mode, initialize_deadline, ), manager, ); let auth_manager = auth_client.auth_manager.clone(); let transport = StreamableHttpClientTransport::with_client( auth_client, StreamableHttpClientTransportConfig::with_uri(url.to_string()), ); if use_stored_access_token_only { warn!( "stored OAuth refresh credentials could not be bound to their issuer for MCP server `{server_name}`; using the stored access token without refresh" ); return Ok(PendingTransport::StreamableHttpWithAccessTokenOnly { transport }); } let runtime = match coordinated_store { Some(store) => OAuthRuntime::Coordinated { auth_manager, store, }, None => OAuthRuntime::Legacy(OAuthPersistor::new( server_name.to_string(), url.to_string(), auth_manager, credential_store, Some(initial_tokens), oauth_config.cloned(), )), }; Ok(PendingTransport::StreamableHttpWithOAuth { transport, oauth_runtime: runtime, }) } #[cfg(test)] #[path = "tool_input_tests.rs"] mod tool_input_tests; #[cfg(test)] #[path = "user_verification_cancellation_tests.rs"] mod user_verification_cancellation_tests; #[cfg(test)] mod tests { use std::time::Duration; use pretty_assertions::assert_eq; use tokio::time; use super::*; #[test] fn client_operation_timeout_rounds_duration() { let error = ClientOperationError::Timeout { label: "tools/list".to_string(), duration: Duration::from_nanos(29_999_999_875), }; assert_eq!(error.to_string(), "timed out awaiting tools/list after 30s"); } #[tokio::test] async fn active_time_timeout_pauses_while_elicitation_is_pending() { let pause_state = ElicitationPauseState::new(); let pause = pause_state.enter(); tokio::spawn(async move { time::sleep(Duration::from_millis(75)).await; drop(pause); }); let result = active_time_timeout(Duration::from_millis(50), pause_state.subscribe(), async { time::sleep(Duration::from_millis(90)).await; "done" }) .await; assert_eq!(Ok("done"), result); } }