mirror of
https://github.com/openai/codex.git
synced 2026-12-05 01:00:54 +00:00
## Why A tool-list page can take multiple attempts. Tracing the whole page keeps retry warnings tied to the page that triggered them. ## What changed Wrap each `tools/list` page request in an `mcp.tools.list_page` span that covers the retry loop. Record whether the request has a cursor via `mcp.has_cursor`. ## Testing Extend the trace propagation test in both MCP protocol modes. Return HTTP 503 on the first request for the second page and verify that the requests carry the page span context, the cursor flag reflects the request, and the retry warning appears on the page span. GitOrigin-RevId: e4b695731d037f71c15660a826c9f2e59d02e55f
2439 lines
92 KiB
Rust
2439 lines
92 KiB
Rust
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 crate::local_stdio_transport::DiscoveryOutcome;
|
|
use anyhow::Context;
|
|
use anyhow::Result;
|
|
use anyhow::anyhow;
|
|
use codex_config::McpServerOAuthConfig;
|
|
use codex_config::types::AuthKeyringBackendKind;
|
|
use codex_config::types::McpServerEnvVar;
|
|
use codex_exec_server::HttpClient;
|
|
use codex_keyring_store::DefaultKeyringStore;
|
|
use codex_otel::auth_storage::AuthStorageOriginator;
|
|
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 tokio_util::sync::CancellationToken;
|
|
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::RecoveryHandshakeGuard;
|
|
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::OAuthStreamableHttpClient;
|
|
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 codex_config::types::OAuthCredentialsStoreMode;
|
|
|
|
#[path = "session_expiry_transport.rs"]
|
|
mod session_expiry_transport;
|
|
#[path = "stdio_handshake.rs"]
|
|
mod stdio_handshake;
|
|
#[path = "streamable_http_retry.rs"]
|
|
mod streamable_http_retry;
|
|
|
|
use self::session_expiry_transport::serve_http_transport;
|
|
use self::session_expiry_transport::spawn_http_transport;
|
|
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";
|
|
|
|
#[derive(Clone, Copy)]
|
|
enum InitializeMode {
|
|
Normal,
|
|
ExpiredReplyRecovery(Option<Instant>),
|
|
}
|
|
|
|
impl InitializeMode {
|
|
fn cancellation(
|
|
self,
|
|
adapter: &mut StreamableHttpClientAdapter,
|
|
) -> (Option<CancellationToken>, Option<RecoveryHandshakeGuard>) {
|
|
match self {
|
|
Self::Normal => (None, None),
|
|
Self::ExpiredReplyRecovery(_) => {
|
|
let guard = RecoveryHandshakeGuard::new();
|
|
let cancellation = adapter.enable_recovery_cancellation(guard.handle());
|
|
(Some(cancellation), Some(guard))
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
/// Streams that carry MCP without an associated child process.
|
|
pub(crate) trait ByteStream:
|
|
tokio::io::AsyncRead + tokio::io::AsyncWrite + Send + Unpin
|
|
{
|
|
}
|
|
impl<T: tokio::io::AsyncRead + tokio::io::AsyncWrite + Send + Unpin> ByteStream for T {}
|
|
|
|
enum PendingTransport {
|
|
ByteStream {
|
|
transport: Box<dyn ByteStream>,
|
|
},
|
|
Stdio {
|
|
transport: Box<StdioServerTransport>,
|
|
},
|
|
StreamableHttp {
|
|
transport: StreamableHttpClientTransport<StreamableHttpClientAdapter>,
|
|
handshake_cleanup: Option<RecoveryHandshakeGuard>,
|
|
},
|
|
StreamableHttpWithOAuth {
|
|
transport: StreamableHttpClientTransport<OAuthStreamableHttpClient>,
|
|
oauth_runtime: OAuthRuntime,
|
|
handshake_cleanup: Option<RecoveryHandshakeGuard>,
|
|
},
|
|
StreamableHttpWithAccessTokenOnly {
|
|
transport: StreamableHttpClientTransport<AuthClient<StreamableHttpClientAdapter>>,
|
|
handshake_cleanup: Option<RecoveryHandshakeGuard>,
|
|
},
|
|
}
|
|
|
|
enum ClientState {
|
|
Connecting { transport: Option<PendingTransport> },
|
|
Ready(Arc<ReadySession>),
|
|
Closed,
|
|
}
|
|
|
|
/// One initialized connection generation, including its OAuth state and expiry signal.
|
|
struct ReadySession {
|
|
service: Arc<RunningService<RoleClient, ElicitationClientService>>,
|
|
oauth: Option<OAuthRuntime>,
|
|
session_expired: CancellationToken,
|
|
}
|
|
|
|
impl ReadySession {
|
|
fn is_expired(&self) -> bool {
|
|
self.session_expired.is_cancelled()
|
|
}
|
|
|
|
fn expire(&self) {
|
|
self.session_expired.cancel();
|
|
self.service.cancellation_token().cancel();
|
|
}
|
|
}
|
|
|
|
/// 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 {
|
|
ParentSocket(crate::ParentSocket),
|
|
InProcess {
|
|
factory: Arc<dyn InProcessTransportFactory>,
|
|
},
|
|
Stdio {
|
|
command: StdioServerCommand,
|
|
launcher: Arc<dyn StdioServerLauncher>,
|
|
},
|
|
StreamableHttp {
|
|
server_name: String,
|
|
url: String,
|
|
bearer_token: Option<StreamableHttpBearerToken>,
|
|
http_headers: Option<HashMap<String, String>>,
|
|
env_http_headers: Option<HashMap<String, String>>,
|
|
oauth_config: Option<Arc<McpServerOAuthConfig>>,
|
|
store_mode: OAuthCredentialsStoreMode,
|
|
keyring_backend_kind: AuthKeyringBackendKind,
|
|
pinned_credential_store: Arc<OnceLock<ResolvedOAuthCredentialStore>>,
|
|
originator: AuthStorageOriginator,
|
|
http_client: Arc<dyn HttpClient>,
|
|
auth_provider: Option<Arc<dyn AuthProviderResolver>>,
|
|
redirect_mode: StreamableHttpRedirectMode,
|
|
oauth_refresh_mode: McpOAuthRefreshMode,
|
|
initialize_deadline: Arc<StdMutex<Option<Instant>>>,
|
|
},
|
|
}
|
|
|
|
struct InitializeDeadlineGuard {
|
|
deadline: Arc<StdMutex<Option<Instant>>>,
|
|
}
|
|
|
|
impl Drop for InitializeDeadlineGuard {
|
|
fn drop(&mut self) {
|
|
*self.deadline.lock().unwrap_or_else(PoisonError::into_inner) = None;
|
|
}
|
|
}
|
|
|
|
#[derive(Clone)]
|
|
struct InitializeContext {
|
|
timeout: Option<Duration>,
|
|
client_info: InitializeRequestParams,
|
|
send_elicitation: Arc<SendElicitation>,
|
|
}
|
|
|
|
#[derive(Clone)]
|
|
pub(crate) struct ElicitationPauseState {
|
|
active_count: Arc<AtomicUsize>,
|
|
paused: watch::Sender<bool>,
|
|
}
|
|
|
|
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<bool> {
|
|
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);
|
|
}
|
|
}
|
|
}
|
|
|
|
/// Bounds one handshake attempt, or leaves it unbounded when no timeout was configured.
|
|
async fn handshake_timeout<T>(
|
|
timeout: Option<Duration>,
|
|
handshake: impl Future<Output = T>,
|
|
) -> Result<T> {
|
|
match timeout {
|
|
Some(duration) => time::timeout(duration, handshake)
|
|
.await
|
|
.with_context(|| format!("timed out handshaking with MCP server after {duration:?}")),
|
|
None => Ok(handshake.await),
|
|
}
|
|
}
|
|
|
|
async fn active_time_timeout<T, Fut>(
|
|
duration: Duration,
|
|
mut pause_state: watch::Receiver<bool>,
|
|
operation: Fut,
|
|
) -> std::result::Result<T, ()>
|
|
where
|
|
Fut: Future<Output = T>,
|
|
{
|
|
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<Duration>,
|
|
deadline: Option<Instant>,
|
|
) -> std::result::Result<Option<Duration>, 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<serde_json::Value>,
|
|
message: String,
|
|
requested_schema: serde_json::Value,
|
|
},
|
|
OpenAiElicitationForm {
|
|
meta: Option<serde_json::Value>,
|
|
message: String,
|
|
requested_schema: serde_json::Value,
|
|
},
|
|
UserVerification {
|
|
meta: Option<serde_json::Value>,
|
|
title: String,
|
|
description: String,
|
|
challenge: String,
|
|
},
|
|
}
|
|
|
|
impl Elicitation {
|
|
pub fn meta(&self) -> Option<&serde_json::Map<String, serde_json::Value>> {
|
|
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_json::Value>,
|
|
#[serde(rename = "_meta")]
|
|
pub meta: Option<serde_json::Value>,
|
|
}
|
|
|
|
impl From<ElicitResult> 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<ElicitationResponse> 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<ElicitationResponse>> + Send + Sync,
|
|
>;
|
|
|
|
pub struct ToolWithConnectorId {
|
|
pub tool: Tool,
|
|
pub connector_id: Option<String>,
|
|
pub connector_name: Option<String>,
|
|
pub connector_description: Option<String>,
|
|
}
|
|
|
|
pub struct ListToolsWithConnectorIdResult {
|
|
pub meta: Option<serde_json::Value>,
|
|
pub next_cursor: Option<String>,
|
|
pub tools: Vec<ToolWithConnectorId>,
|
|
}
|
|
|
|
/// An active Plugin Runtime event request and its request-scoped notifications.
|
|
pub struct CancellableEventStreamRequest {
|
|
pub handle: RequestHandle<RoleClient>,
|
|
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<StdioProcessSlot>,
|
|
state: Mutex<ClientState>,
|
|
transport_recipe: TransportRecipe,
|
|
protocol_mode: McpProtocolMode,
|
|
requires_read_only_tools: bool,
|
|
initialize_context: Mutex<Option<InitializeContext>>,
|
|
session_recovery_lock: Semaphore,
|
|
elicitation_pause_state: ElicitationPauseState,
|
|
tool_list_revision: Arc<AtomicU64>,
|
|
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<RequestMetaObject>) {
|
|
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
|
|
}
|
|
|
|
/// Matches the registered HTTP route and header configuration after dispatch.
|
|
/// A client that selected stored OAuth during session recovery no longer qualifies.
|
|
pub fn matches_result_body_source(
|
|
&self,
|
|
require_runtime_auth: bool,
|
|
expected_url: &str,
|
|
expected_headers: Option<&HashMap<String, String>>,
|
|
expected_env_headers: Option<&HashMap<String, String>>,
|
|
) -> bool {
|
|
let TransportRecipe::StreamableHttp {
|
|
url,
|
|
auth_provider,
|
|
bearer_token: None,
|
|
http_headers,
|
|
env_http_headers,
|
|
pinned_credential_store,
|
|
..
|
|
} = &self.transport_recipe
|
|
else {
|
|
return false;
|
|
};
|
|
(!require_runtime_auth || auth_provider.is_some())
|
|
&& pinned_credential_store.get().is_none()
|
|
&& url == expected_url
|
|
&& http_headers.as_ref() == expected_headers
|
|
&& env_http_headers.as_ref() == expected_env_headers
|
|
}
|
|
|
|
pub async fn new_in_process_client(
|
|
factory: Arc<dyn InProcessTransportFactory>,
|
|
) -> io::Result<Self> {
|
|
Self::new_byte_stream_client(
|
|
TransportRecipe::InProcess { factory },
|
|
McpProtocolMode::Legacy,
|
|
)
|
|
.await
|
|
}
|
|
|
|
/// Opens the launch host's socket using the same MCP wire protocol as stdio.
|
|
pub async fn new_parent_socket_client(
|
|
socket: crate::ParentSocket,
|
|
protocol_mode: McpProtocolMode,
|
|
) -> io::Result<Self> {
|
|
Self::new_byte_stream_client(TransportRecipe::ParentSocket(socket), protocol_mode).await
|
|
}
|
|
|
|
async fn new_byte_stream_client(
|
|
transport_recipe: TransportRecipe,
|
|
protocol_mode: McpProtocolMode,
|
|
) -> io::Result<Self> {
|
|
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,
|
|
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<OsString>,
|
|
env: Option<HashMap<OsString, OsString>>,
|
|
env_vars: &[McpServerEnvVar],
|
|
cwd: Option<String>,
|
|
launcher: Arc<dyn StdioServerLauncher>,
|
|
) -> io::Result<Self> {
|
|
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<OsString>,
|
|
mut env: Option<HashMap<OsString, OsString>>,
|
|
env_vars: &[McpServerEnvVar],
|
|
cwd: Option<String>,
|
|
launcher: Arc<dyn StdioServerLauncher>,
|
|
protocol_mode: McpProtocolMode,
|
|
) -> io::Result<Self> {
|
|
let requested_stdio_version = match protocol_mode {
|
|
McpProtocolMode::Legacy => None,
|
|
McpProtocolMode::V20260728 | McpProtocolMode::DiscoverLocalStdio => env
|
|
.as_mut()
|
|
.and_then(|env| env.remove(OsStr::new("CODEX_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::ByteStream { .. }
|
|
| 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<String>,
|
|
http_headers: Option<HashMap<String, String>>,
|
|
env_http_headers: Option<HashMap<String, String>>,
|
|
store_mode: OAuthCredentialsStoreMode,
|
|
keyring_backend_kind: AuthKeyringBackendKind,
|
|
http_client: Arc<dyn HttpClient>,
|
|
auth_provider: Option<Arc<dyn AuthProviderResolver>>,
|
|
) -> Result<Self> {
|
|
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<String>,
|
|
http_headers: Option<HashMap<String, String>>,
|
|
env_http_headers: Option<HashMap<String, String>>,
|
|
store_mode: OAuthCredentialsStoreMode,
|
|
keyring_backend_kind: AuthKeyringBackendKind,
|
|
http_client: Arc<dyn HttpClient>,
|
|
auth_provider: Option<Arc<dyn AuthProviderResolver>>,
|
|
protocol_mode: McpProtocolMode,
|
|
) -> Result<Self> {
|
|
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<StreamableHttpBearerToken>,
|
|
http_headers: Option<HashMap<String, String>>,
|
|
env_http_headers: Option<HashMap<String, String>>,
|
|
oauth_config: Option<McpServerOAuthConfig>,
|
|
store_mode: OAuthCredentialsStoreMode,
|
|
keyring_backend_kind: AuthKeyringBackendKind,
|
|
http_client: Arc<dyn HttpClient>,
|
|
auth_provider: Option<Arc<dyn AuthProviderResolver>>,
|
|
protocol_mode: McpProtocolMode,
|
|
redirect_mode: StreamableHttpRedirectMode,
|
|
oauth_refresh_mode: McpOAuthRefreshMode,
|
|
) -> Result<Self> {
|
|
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<Duration>,
|
|
send_elicitation: SendElicitation,
|
|
) -> Result<ServerPeerInfo> {
|
|
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 session = self
|
|
.connect_pending_transport_with_initialize_retries(
|
|
pending_transport,
|
|
&context,
|
|
InitializeMode::Normal,
|
|
)
|
|
.await?;
|
|
|
|
let initialize_result_rmcp = session
|
|
.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 oauth_runtime = self.install_ready_session(session).await?;
|
|
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)
|
|
}
|
|
|
|
#[instrument(
|
|
name = "mcp.tools.list_page",
|
|
skip_all,
|
|
fields(mcp.has_cursor = params.as_ref().is_some_and(|params| params.cursor.is_some()))
|
|
)]
|
|
pub async fn list_tools(
|
|
&self,
|
|
params: Option<PaginatedRequestParams>,
|
|
timeout: Option<Duration>,
|
|
) -> Result<ListToolsResult> {
|
|
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),
|
|
}
|
|
}
|
|
})
|
|
// Box the retry loop once per page to bound the instrumented future's layout.
|
|
.boxed()
|
|
.await?;
|
|
self.persist_oauth_tokens().await;
|
|
Ok(result)
|
|
}
|
|
|
|
/// List a page of Codex Apps tools and restore any shared connector metadata.
|
|
#[instrument(level = "trace", skip_all)]
|
|
pub async fn list_tools_with_connector_ids(
|
|
&self,
|
|
params: Option<PaginatedRequestParams>,
|
|
timeout: Option<Duration>,
|
|
) -> Result<ListToolsWithConnectorIdResult> {
|
|
let result = self.list_tools(params, timeout).await?;
|
|
let apps: HashMap<_, _> = result
|
|
.meta
|
|
.as_ref()
|
|
.and_then(|meta| meta.get("openai/apps"))
|
|
.and_then(Value::as_array)
|
|
.into_iter()
|
|
.flatten()
|
|
.filter_map(|app| Some((app["connectorId"].as_str()?, app)))
|
|
.collect();
|
|
let tools = result
|
|
.tools
|
|
.into_iter()
|
|
.map(|mut tool| {
|
|
let connector_id = Self::meta_string(tool.meta.as_ref(), "connector_id");
|
|
if let Some(app) = connector_id.as_deref().and_then(|id| apps.get(id))
|
|
&& let Some(meta) = &mut tool.meta
|
|
{
|
|
// Preserve the wire strings for callers that read the raw tool metadata.
|
|
for (shared_key, tool_key) in [
|
|
("connectorName", "connector_name"),
|
|
("connectorDescription", "connector_description"),
|
|
] {
|
|
if let Some(value) = app[shared_key]
|
|
.as_str()
|
|
.filter(|value| !value.trim().is_empty())
|
|
{
|
|
meta.insert(tool_key.into(), Value::from(value));
|
|
}
|
|
}
|
|
}
|
|
let meta = tool.meta.as_ref();
|
|
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"));
|
|
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<String> {
|
|
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<PaginatedRequestParams>,
|
|
timeout: Option<Duration>,
|
|
) -> Result<ListResourcesResult> {
|
|
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<PaginatedRequestParams>,
|
|
timeout: Option<Duration>,
|
|
) -> Result<ListResourceTemplatesResult> {
|
|
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<Duration>,
|
|
) -> Result<ReadResourceResult> {
|
|
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<Duration>,
|
|
send_elicitation: Arc<SendElicitation>,
|
|
) -> Result<ReadResourceResult> {
|
|
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<F>(
|
|
&self,
|
|
name: String,
|
|
arguments: Option<Value>,
|
|
meta_for_session: F,
|
|
timeout: Option<Duration>,
|
|
) -> Result<CallToolResult>
|
|
where
|
|
F: Fn(&rmcp::model::ServerCapabilities) -> Result<Option<Value>> + 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<F>(
|
|
&self,
|
|
name: String,
|
|
arguments: Option<Value>,
|
|
meta_for_session: F,
|
|
timeout: Option<Duration>,
|
|
send_elicitation: Arc<SendElicitation>,
|
|
) -> Result<CallToolResult>
|
|
where
|
|
F: Fn(&rmcp::model::ServerCapabilities) -> Result<Option<Value>> + Send + Sync,
|
|
{
|
|
self.call_tool_inner(
|
|
name,
|
|
arguments,
|
|
meta_for_session,
|
|
timeout,
|
|
Some(send_elicitation),
|
|
)
|
|
.await
|
|
}
|
|
|
|
async fn call_tool_inner<F>(
|
|
&self,
|
|
name: String,
|
|
arguments: Option<Value>,
|
|
meta_for_session: F,
|
|
timeout: Option<Duration>,
|
|
send_elicitation: Option<Arc<SendElicitation>>,
|
|
) -> Result<CallToolResult>
|
|
where
|
|
F: Fn(&rmcp::model::ServerCapabilities) -> Result<Option<Value>> + 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::<StreamableHttpError<StreamableHttpClientAdapterError>>()
|
|
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<serde_json::Value>,
|
|
) -> 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<serde_json::Value>,
|
|
) -> Result<ServerResult> {
|
|
self.send_custom_request_with_timeout(method, params, /*timeout*/ None)
|
|
.await
|
|
}
|
|
|
|
pub async fn send_custom_request_with_timeout(
|
|
&self,
|
|
method: &str,
|
|
params: Option<serde_json::Value>,
|
|
timeout: Option<Duration>,
|
|
) -> Result<ServerResult> {
|
|
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<serde_json::Value>,
|
|
) -> Result<CancellableEventStreamRequest> {
|
|
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 install_ready_session(
|
|
&self,
|
|
session: Arc<ReadySession>,
|
|
) -> Result<Option<OAuthRuntime>> {
|
|
let oauth_runtime = session.oauth.clone();
|
|
let mut guard = self.state.lock().await;
|
|
if matches!(*guard, ClientState::Closed) {
|
|
return Err(anyhow!("MCP client is shut down"));
|
|
}
|
|
*guard = ClientState::Ready(session);
|
|
Ok(oauth_runtime)
|
|
}
|
|
|
|
async fn current_session(&self) -> Result<Arc<ReadySession>> {
|
|
let guard = self.state.lock().await;
|
|
match &*guard {
|
|
ClientState::Ready(session) => Ok(Arc::clone(session)),
|
|
ClientState::Connecting { .. } => Err(anyhow!("MCP client not initialized")),
|
|
ClientState::Closed => Err(anyhow!("MCP client is shut down")),
|
|
}
|
|
}
|
|
|
|
async fn service(&self) -> Result<Arc<RunningService<RoleClient, ElicitationClientService>>> {
|
|
let session = self.current_session().await?;
|
|
if !session.is_expired() {
|
|
return Ok(Arc::clone(&session.service));
|
|
}
|
|
let session = self.reinitialize_after_session_expiry(&session).await?;
|
|
if session.is_expired() {
|
|
return Err(ClientOperationError::Service(
|
|
rmcp::service::ServiceError::TransportClosed,
|
|
)
|
|
.into());
|
|
}
|
|
Ok(Arc::clone(&session.service))
|
|
}
|
|
|
|
async fn oauth_runtime(&self) -> Option<OAuthRuntime> {
|
|
let guard = self.state.lock().await;
|
|
match &*guard {
|
|
ClientState::Ready(session) => session.oauth.clone(),
|
|
_ => None,
|
|
}
|
|
}
|
|
|
|
/// Returns `None` when this client does not manage stored OAuth credentials.
|
|
pub async fn managed_oauth_credentials(&self) -> Option<Option<StoredOAuthTokens>> {
|
|
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(session) => {
|
|
session.is_expired()
|
|
|| session.service.is_closed()
|
|
|| session.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(())
|
|
}
|
|
|
|
// Keep the transport future's polling code in this crate for both startup and recovery.
|
|
fn create_pending_transport(
|
|
transport_recipe: &TransportRecipe,
|
|
) -> BoxFuture<'_, Result<PendingTransport>> {
|
|
Self::pending_transport_for(transport_recipe, InitializeMode::Normal)
|
|
}
|
|
|
|
fn pending_transport_for(
|
|
transport_recipe: &TransportRecipe,
|
|
mode: InitializeMode,
|
|
) -> BoxFuture<'_, Result<PendingTransport>> {
|
|
Box::pin(Self::create_pending_transport_inner(transport_recipe, mode))
|
|
}
|
|
|
|
async fn create_pending_transport_inner(
|
|
transport_recipe: &TransportRecipe,
|
|
mode: InitializeMode,
|
|
) -> Result<PendingTransport> {
|
|
match transport_recipe {
|
|
TransportRecipe::InProcess { factory } => {
|
|
let transport = factory.open().await?;
|
|
Ok(PendingTransport::ByteStream {
|
|
transport: Box::new(transport),
|
|
})
|
|
}
|
|
TransportRecipe::ParentSocket(socket) => Ok(PendingTransport::ByteStream {
|
|
transport: socket.connect().await?,
|
|
}),
|
|
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<Option<ResolvedOAuthTokens>> {
|
|
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(),
|
|
mode,
|
|
)
|
|
.await
|
|
{
|
|
Ok(pending_transport) => Ok(pending_transport),
|
|
Err(err)
|
|
if err.downcast_ref::<AuthError>().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 mut adapter = StreamableHttpClientAdapter::new(
|
|
Arc::clone(http_client),
|
|
default_headers,
|
|
/*auth_provider*/ None,
|
|
has_configured_headers,
|
|
*redirect_mode,
|
|
Arc::clone(initialize_deadline),
|
|
);
|
|
let (initialize_cancellation, handshake_cleanup) =
|
|
mode.cancellation(&mut adapter);
|
|
let transport =
|
|
spawn_http_transport(adapter, http_config, initialize_cancellation);
|
|
Ok(PendingTransport::StreamableHttp {
|
|
transport,
|
|
handshake_cleanup,
|
|
})
|
|
}
|
|
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 mut adapter = StreamableHttpClientAdapter::new(
|
|
Arc::clone(http_client),
|
|
default_headers,
|
|
auth_provider,
|
|
has_configured_headers,
|
|
*redirect_mode,
|
|
Arc::clone(initialize_deadline),
|
|
);
|
|
let (initialize_cancellation, handshake_cleanup) =
|
|
mode.cancellation(&mut adapter);
|
|
let transport =
|
|
spawn_http_transport(adapter, http_config, initialize_cancellation);
|
|
Ok(PendingTransport::StreamableHttp {
|
|
transport,
|
|
handshake_cleanup,
|
|
})
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
async fn connect_pending_transport(
|
|
&self,
|
|
pending_transport: PendingTransport,
|
|
initialize_context: &InitializeContext,
|
|
timeout: Option<Duration>,
|
|
) -> Result<Arc<ReadySession>> {
|
|
// 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::ParentSocket(_)
|
|
| TransportRecipe::Stdio { .. } => None,
|
|
};
|
|
let lifecycle = self.protocol_mode.client_lifecycle();
|
|
let session_expired = CancellationToken::new();
|
|
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, handshake_cleanup) = match pending_transport {
|
|
PendingTransport::ByteStream { transport } => (
|
|
client_service()
|
|
.serve_with_lifecycle(
|
|
track_tool_list_changes(
|
|
OrderedByteTransport::new(
|
|
IntoTransport::<RoleClient, _, _>::into_transport(transport),
|
|
),
|
|
Arc::clone(&self.tool_list_revision),
|
|
),
|
|
lifecycle,
|
|
)
|
|
.boxed(),
|
|
None,
|
|
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, None)
|
|
}
|
|
PendingTransport::StreamableHttp {
|
|
transport,
|
|
handshake_cleanup,
|
|
} => (
|
|
serve_http_transport(
|
|
client_service(),
|
|
capture_event_notifications(transport),
|
|
Arc::clone(&self.tool_list_revision),
|
|
lifecycle,
|
|
session_expired.clone(),
|
|
)
|
|
.boxed(),
|
|
None,
|
|
handshake_cleanup,
|
|
),
|
|
PendingTransport::StreamableHttpWithOAuth {
|
|
transport,
|
|
oauth_runtime,
|
|
handshake_cleanup,
|
|
} => (
|
|
serve_http_transport(
|
|
client_service(),
|
|
transport,
|
|
Arc::clone(&self.tool_list_revision),
|
|
lifecycle,
|
|
session_expired.clone(),
|
|
)
|
|
.boxed(),
|
|
Some(oauth_runtime),
|
|
handshake_cleanup,
|
|
),
|
|
PendingTransport::StreamableHttpWithAccessTokenOnly {
|
|
transport,
|
|
handshake_cleanup,
|
|
} => (
|
|
serve_http_transport(
|
|
client_service(),
|
|
transport,
|
|
Arc::clone(&self.tool_list_revision),
|
|
lifecycle,
|
|
session_expired.clone(),
|
|
)
|
|
.boxed(),
|
|
None,
|
|
handshake_cleanup,
|
|
),
|
|
};
|
|
|
|
let started = time::Instant::now();
|
|
let handshake = async {
|
|
let initial = handshake_timeout(timeout, transport).await;
|
|
let mode = if let Some((reply, _)) = discovery.as_mut() {
|
|
let outcome = reply.try_recv();
|
|
match &initial {
|
|
Ok(Err(error)) => stdio_handshake::restart_mode(error, outcome.ok())?,
|
|
Err(_)
|
|
if matches!(
|
|
outcome,
|
|
Ok(DiscoveryOutcome::RetryLegacy)
|
|
| Err(tokio::sync::oneshot::error::TryRecvError::Closed)
|
|
) =>
|
|
{
|
|
Some(McpProtocolMode::Legacy)
|
|
}
|
|
_ => None,
|
|
}
|
|
} else {
|
|
None
|
|
};
|
|
let (Some(mode), Some((_, process))) = (mode, discovery) else {
|
|
return initial?.map_err(|source| HandshakeError { source }.into());
|
|
};
|
|
let retry_timeout = if mode == McpProtocolMode::Legacy {
|
|
timeout
|
|
} else {
|
|
// A modern version re-offer stays within the original deadline.
|
|
timeout.map(|limit| limit.saturating_sub(started.elapsed()))
|
|
};
|
|
handshake_timeout(retry_timeout, async {
|
|
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(),
|
|
};
|
|
connect_stdio(fresh, lifecycle)
|
|
.await
|
|
.map_err(|source| HandshakeError { source }.into())
|
|
})
|
|
.await?
|
|
};
|
|
let service_result = 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}"
|
|
);
|
|
}
|
|
if let Some(handshake_cleanup) = handshake_cleanup {
|
|
let cleanup = handshake_cleanup.handle();
|
|
drop(handshake_cleanup);
|
|
match timeout.map(|limit| limit.saturating_sub(started.elapsed())) {
|
|
Some(remaining) if !remaining.is_zero() => {
|
|
let _ = time::timeout(remaining, cleanup.wait_after_failure()).await;
|
|
}
|
|
Some(_) => {}
|
|
None => cleanup.wait_after_failure().await,
|
|
}
|
|
}
|
|
return Err(error);
|
|
}
|
|
};
|
|
if let Some(handshake_cleanup) = handshake_cleanup {
|
|
handshake_cleanup.complete();
|
|
}
|
|
|
|
// 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(ReadySession {
|
|
service: Arc::new(service),
|
|
oauth: oauth_runtime,
|
|
session_expired,
|
|
}))
|
|
}
|
|
|
|
async fn launch_stdio_replacement(
|
|
&self,
|
|
mode: McpProtocolMode,
|
|
) -> Result<StdioServerTransport> {
|
|
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<T, F, Fut>(
|
|
&self,
|
|
label: &str,
|
|
timeout: Option<Duration>,
|
|
operation: F,
|
|
) -> Result<T>
|
|
where
|
|
F: Fn(Arc<RunningService<RoleClient, ElicitationClientService>>) -> Fut,
|
|
Fut: std::future::Future<Output = std::result::Result<T, rmcp::service::ServiceError>>,
|
|
{
|
|
self.run_service_operation_with_pause_state(
|
|
label,
|
|
timeout,
|
|
self.elicitation_pause_state.clone(),
|
|
operation,
|
|
)
|
|
.await
|
|
}
|
|
|
|
async fn run_service_operation_with_pause_state<T, F, Fut>(
|
|
&self,
|
|
label: &str,
|
|
timeout: Option<Duration>,
|
|
pause_state: ElicitationPauseState,
|
|
operation: F,
|
|
) -> Result<T>
|
|
where
|
|
F: Fn(Arc<RunningService<RoleClient, ElicitationClientService>>) -> Fut,
|
|
Fut: std::future::Future<Output = std::result::Result<T, rmcp::service::ServiceError>>,
|
|
{
|
|
let mut session = self.current_session().await?;
|
|
let reply_expired = session.is_expired();
|
|
let operation_timeout = if reply_expired {
|
|
let deadline = timeout.map(|duration| Instant::now() + duration);
|
|
let _remaining = remaining_operation_timeout(label, timeout, deadline)?;
|
|
let recovery = self.reinitialize_after_session_expiry_inner(&session, deadline);
|
|
let recovered = match timeout {
|
|
Some(duration) => time::timeout(duration, recovery).await.map_err(|_| {
|
|
ClientOperationError::Timeout {
|
|
label: label.to_string(),
|
|
duration,
|
|
}
|
|
})?,
|
|
None => recovery.await,
|
|
};
|
|
let recovered = match recovered {
|
|
Ok(recovered) => recovered,
|
|
Err(error) => {
|
|
if let Some(duration) = timeout
|
|
&& deadline.is_some_and(|deadline| Instant::now() >= deadline)
|
|
{
|
|
return Err(ClientOperationError::Timeout {
|
|
label: label.to_string(),
|
|
duration,
|
|
}
|
|
.into());
|
|
}
|
|
return Err(error);
|
|
}
|
|
};
|
|
if recovered.is_expired() {
|
|
return Err(ClientOperationError::Service(
|
|
rmcp::service::ServiceError::TransportClosed,
|
|
)
|
|
.into());
|
|
}
|
|
session = recovered;
|
|
remaining_operation_timeout(label, timeout, deadline)?
|
|
} else {
|
|
timeout
|
|
};
|
|
|
|
match Self::run_service_operation_with_transient_retries(
|
|
Arc::clone(&session.service),
|
|
label,
|
|
operation_timeout,
|
|
pause_state.clone(),
|
|
&operation,
|
|
)
|
|
.await
|
|
{
|
|
Ok(result) => Ok(result),
|
|
Err(error) if Self::is_session_expired_404(&error) => {
|
|
if reply_expired {
|
|
session.expire();
|
|
return Err(error.into());
|
|
}
|
|
let recovered = self.reinitialize_after_session_expiry(&session)
|
|
.await
|
|
.inspect_err(|_| {
|
|
if let TransportRecipe::StreamableHttp { server_name, .. } = &self.transport_recipe {
|
|
tracing::error!(server = ?server_name, operation = label, "MCP operation failed during session recovery");
|
|
}
|
|
})?;
|
|
Self::run_service_operation_with_transient_retries(
|
|
Arc::clone(&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<T, F, Fut>(
|
|
service: Arc<RunningService<RoleClient, ElicitationClientService>>,
|
|
label: &str,
|
|
timeout: Option<Duration>,
|
|
pause_state: ElicitationPauseState,
|
|
operation: &F,
|
|
) -> std::result::Result<T, ClientOperationError>
|
|
where
|
|
F: Fn(Arc<RunningService<RoleClient, ElicitationClientService>>) -> Fut,
|
|
Fut: std::future::Future<Output = std::result::Result<T, rmcp::service::ServiceError>>,
|
|
{
|
|
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 Self::is_retryable_tools_list_error(label, &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<T, F, Fut>(
|
|
service: Arc<RunningService<RoleClient, ElicitationClientService>>,
|
|
label: &str,
|
|
timeout: Option<Duration>,
|
|
pause_state: ElicitationPauseState,
|
|
operation: &F,
|
|
) -> std::result::Result<T, ClientOperationError>
|
|
where
|
|
F: Fn(Arc<RunningService<RoleClient, ElicitationClientService>>) -> Fut,
|
|
Fut: std::future::Future<Output = std::result::Result<T, rmcp::service::ServiceError>>,
|
|
{
|
|
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),
|
|
}
|
|
}
|
|
|
|
fn is_retryable_tools_list_error(label: &str, error: &ClientOperationError) -> bool {
|
|
if label != "tools/list" {
|
|
return false;
|
|
}
|
|
let ClientOperationError::Service(rmcp::service::ServiceError::TransportSend(error)) =
|
|
error
|
|
else {
|
|
return false;
|
|
};
|
|
|
|
error
|
|
.error
|
|
.downcast_ref::<StreamableHttpError<StreamableHttpClientAdapterError>>()
|
|
.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::<StreamableHttpError<StreamableHttpClientAdapterError>>()
|
|
.is_some_and(|error| {
|
|
matches!(
|
|
error,
|
|
StreamableHttpError::Client(
|
|
StreamableHttpClientAdapterError::SessionExpired404
|
|
)
|
|
)
|
|
})
|
|
}
|
|
|
|
fn reinitialize_after_session_expiry<'a>(
|
|
&'a self,
|
|
failed_session: &'a Arc<ReadySession>,
|
|
) -> BoxFuture<'a, Result<Arc<ReadySession>>> {
|
|
Box::pin(self.reinitialize_after_session_expiry_inner(failed_session, /*deadline*/ None))
|
|
}
|
|
|
|
async fn reinitialize_after_session_expiry_inner(
|
|
&self,
|
|
failed_session: &Arc<ReadySession>,
|
|
deadline: Option<Instant>,
|
|
) -> Result<Arc<ReadySession>> {
|
|
let recovery_guard = self
|
|
.session_recovery_lock
|
|
.acquire()
|
|
.await
|
|
.map_err(|_| anyhow!("MCP client recovery semaphore closed"))?;
|
|
|
|
let mode = {
|
|
let guard = self.state.lock().await;
|
|
match &*guard {
|
|
ClientState::Ready(session) if !Arc::ptr_eq(session, failed_session) => None,
|
|
ClientState::Ready(session) if session.is_expired() => {
|
|
Some(InitializeMode::ExpiredReplyRecovery(deadline))
|
|
}
|
|
ClientState::Ready(_) => Some(InitializeMode::Normal),
|
|
ClientState::Connecting { .. } => {
|
|
return Err(anyhow!("MCP client not initialized"));
|
|
}
|
|
ClientState::Closed => {
|
|
return Err(anyhow!("MCP client is shut down"));
|
|
}
|
|
}
|
|
};
|
|
let Some(mode) = mode else {
|
|
drop(recovery_guard);
|
|
return self.current_session().await;
|
|
};
|
|
|
|
let initialize_context = self
|
|
.initialize_context
|
|
.lock()
|
|
.await
|
|
.clone()
|
|
.ok_or_else(|| anyhow!("MCP client cannot recover before initialize succeeds"))?;
|
|
let pending_transport = Self::pending_transport_for(&self.transport_recipe, mode).await?;
|
|
let session = self
|
|
.connect_pending_transport_with_initialize_retries(
|
|
pending_transport,
|
|
&initialize_context,
|
|
mode,
|
|
)
|
|
.await?;
|
|
session
|
|
.service
|
|
.peer()
|
|
.peer_info()
|
|
.ok_or_else(|| anyhow!("recovered handshake succeeded but server info was missing"))?;
|
|
|
|
let oauth_runtime = self.install_ready_session(session).await?;
|
|
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}");
|
|
}
|
|
|
|
// Match the original ordering: release recovery before selecting the current
|
|
// generation, so shutdown or another recovery can still win the race.
|
|
drop(recovery_guard);
|
|
self.current_session().await
|
|
}
|
|
}
|
|
|
|
#[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<dyn HttpClient>,
|
|
has_configured_headers: bool,
|
|
redirect_mode: StreamableHttpRedirectMode,
|
|
oauth_refresh_mode: McpOAuthRefreshMode,
|
|
initialize_deadline: Arc<StdMutex<Option<Instant>>>,
|
|
oauth_config: Option<&McpServerOAuthConfig>,
|
|
mode: InitializeMode,
|
|
) -> Result<PendingTransport> {
|
|
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 mut http_client = StreamableHttpClientAdapter::new(
|
|
http_client,
|
|
default_headers,
|
|
/*auth_provider*/ None,
|
|
has_configured_headers,
|
|
redirect_mode,
|
|
initialize_deadline,
|
|
);
|
|
|
|
let (initialize_cancellation, handshake_cleanup) = mode.cancellation(&mut http_client);
|
|
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: spawn_http_transport(
|
|
AuthClient::new(http_client, manager),
|
|
StreamableHttpClientTransportConfig::with_uri(url.to_string()),
|
|
initialize_cancellation,
|
|
),
|
|
handshake_cleanup,
|
|
});
|
|
}
|
|
|
|
let auth_manager = Arc::new(Mutex::new(manager));
|
|
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(),
|
|
)),
|
|
};
|
|
let transport = spawn_http_transport(
|
|
OAuthStreamableHttpClient::new(http_client, runtime.clone()),
|
|
StreamableHttpClientTransportConfig::with_uri(url.to_string()),
|
|
initialize_cancellation,
|
|
);
|
|
|
|
Ok(PendingTransport::StreamableHttpWithOAuth {
|
|
transport,
|
|
oauth_runtime: runtime,
|
|
handshake_cleanup,
|
|
})
|
|
}
|
|
|
|
#[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);
|
|
}
|
|
}
|