Skip to content

armgit / codex

Public Imported from GitHub
0

Lightweight coding agent that runs in your terminal

Rust

Bound remote MCP handshake HTTP requests (#37168)

jife244a9d94e2e
diff --git a/codex-rs/rmcp-client/src/http_client_adapter.rs b/codex-rs/rmcp-client/src/http_client_adapter.rs
index bde57a9d99..e1473001d9 100644
--- a/codex-rs/rmcp-client/src/http_client_adapter.rs
+++ b/codex-rs/rmcp-client/src/http_client_adapter.rs
@@ -10,6 +10,9 @@
use std::collections::HashMap;
use std::io;
use std::sync::Arc;
+use std::sync::Mutex;
+use std::sync::PoisonError;
+use std::time::Instant;
use bytes::Bytes;
use codex_api::SharedAuthProvider;
@@ -76,6 +79,7 @@ pub(crate) struct StreamableHttpClientAdapter {
auth_provider: Option<SharedAuthProvider>,
has_configured_headers: bool,
redirect_mode: StreamableHttpRedirectMode,
+ initialize_deadline: Arc<Mutex<Option<Instant>>>,
}
#[derive(Debug, thiserror::Error)]
@@ -97,6 +101,7 @@ impl StreamableHttpClientAdapter {
auth_provider: Option<SharedAuthProvider>,
has_configured_headers: bool,
redirect_mode: StreamableHttpRedirectMode,
+ initialize_deadline: Arc<Mutex<Option<Instant>>>,
) -> Self {
Self {
http_client,
@@ -104,6 +109,7 @@ impl StreamableHttpClientAdapter {
auth_provider,
has_configured_headers,
redirect_mode,
+ initialize_deadline,
}
}
@@ -168,6 +174,26 @@ impl StreamableHttpClient for StreamableHttpClientAdapter {
} else {
self.redirect_policy(&headers)
};
+ let timeout_ms = if matches!(
+ mcp_method.as_deref(),
+ Some("initialize" | "notifications/initialized")
+ ) || mcp_method.as_deref() == Some(DiscoverRequestMethod::VALUE)
+ {
+ self.initialize_deadline
+ .lock()
+ .unwrap_or_else(PoisonError::into_inner)
+ .map(|deadline| {
+ u64::try_from(
+ deadline
+ .saturating_duration_since(Instant::now())
+ .as_millis(),
+ )
+ .unwrap_or(u64::MAX)
+ .max(1)
+ })
+ } else {
+ None
+ };
let body = serde_json::to_vec(&message).map_err(StreamableHttpError::Deserialize)?;
let has_authorization_header = headers.contains_key(AUTHORIZATION);
@@ -178,7 +204,7 @@ impl StreamableHttpClient for StreamableHttpClientAdapter {
url: uri.to_string(),
headers: protocol_headers(&headers),
body: Some(body.into()),
- timeout_ms: None,
+ timeout_ms,
redirect_policy,
request_id: "buffered-request".to_string(),
stream_response: true,
diff --git a/codex-rs/rmcp-client/src/rmcp_client.rs b/codex-rs/rmcp-client/src/rmcp_client.rs
index 2f1501d596..6ce310c0a2 100644
--- a/codex-rs/rmcp-client/src/rmcp_client.rs
+++ b/codex-rs/rmcp-client/src/rmcp_client.rs
@@ -4,7 +4,9 @@ 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::AtomicUsize;
use std::sync::atomic::Ordering;
use std::time::Duration;
@@ -141,9 +143,20 @@ enum TransportRecipe {
http_client: Arc<dyn HttpClient>,
auth_provider: Option<SharedAuthProvider>,
redirect_mode: StreamableHttpRedirectMode,
+ 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>,
@@ -525,6 +538,7 @@ impl RmcpClient {
http_client,
auth_provider,
redirect_mode,
+ initialize_deadline: Arc::new(StdMutex::new(None)),
};
let transport = Self::create_pending_transport(&transport_recipe).await?;
Ok(Self {
@@ -948,6 +962,7 @@ impl RmcpClient {
http_client,
auth_provider,
redirect_mode,
+ initialize_deadline,
} => {
let has_configured_headers = http_headers
.as_ref()
@@ -1018,6 +1033,7 @@ impl RmcpClient {
Arc::clone(http_client),
has_configured_headers,
*redirect_mode,
+ Arc::clone(initialize_deadline),
)
.await
{
@@ -1051,6 +1067,7 @@ impl RmcpClient {
/*auth_provider*/ None,
has_configured_headers,
*redirect_mode,
+ Arc::clone(initialize_deadline),
),
http_config,
);
@@ -1072,6 +1089,7 @@ impl RmcpClient {
auth_provider,
has_configured_headers,
*redirect_mode,
+ Arc::clone(initialize_deadline),
),
http_config,
);
@@ -1090,6 +1108,21 @@ impl RmcpClient {
Arc<RunningService<RoleClient, ElicitationClientService>>,
Option<OAuthPersistor>,
)> {
+ 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 (transport, oauth_persistor) = match pending_transport {
PendingTransport::InProcess { transport } => (
@@ -1389,6 +1422,7 @@ async fn create_oauth_transport_and_runtime(
http_client: Arc<dyn HttpClient>,
has_configured_headers: bool,
redirect_mode: StreamableHttpRedirectMode,
+ initialize_deadline: Arc<StdMutex<Option<Instant>>>,
) -> Result<(
StreamableHttpClientTransport<AuthClient<StreamableHttpClientAdapter>>,
OAuthPersistor,
@@ -1427,6 +1461,7 @@ async fn create_oauth_transport_and_runtime(
/*auth_provider*/ None,
has_configured_headers,
redirect_mode,
+ initialize_deadline,
),
manager,
);
diff --git a/codex-rs/rmcp-client/tests/streamable_http_remote.rs b/codex-rs/rmcp-client/tests/streamable_http_remote.rs
index 0d4690a825..5cfdf4be86 100644
--- a/codex-rs/rmcp-client/tests/streamable_http_remote.rs
+++ b/codex-rs/rmcp-client/tests/streamable_http_remote.rs
@@ -6,7 +6,24 @@
mod streamable_http_test_support;
+use std::sync::Arc;
+use std::time::Duration;
+
+use codex_config::types::AuthKeyringBackendKind;
+use codex_config::types::OAuthCredentialsStoreMode;
+use codex_rmcp_client::ElicitationAction;
+use codex_rmcp_client::ElicitationResponse;
+use codex_rmcp_client::RmcpClient;
+use futures::FutureExt as _;
use pretty_assertions::assert_eq;
+use rmcp::model::ClientCapabilities;
+use rmcp::model::Implementation;
+use rmcp::model::InitializeRequestParams;
+use rmcp::model::ProtocolVersion;
+use wiremock::Mock;
+use wiremock::MockServer;
+use wiremock::ResponseTemplate;
+use wiremock::matchers::method;
use streamable_http_test_support::call_echo_tool;
use streamable_http_test_support::create_remote_client;
@@ -35,3 +52,60 @@ async fn streamable_http_remote_client_round_trips_through_exec_server() -> anyh
Ok(())
}
+
+/// A timed-out MCP handshake must release the remote executor for later requests.
+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
+async fn streamable_http_handshake_timeout_unblocks_remote_executor() -> anyhow::Result<()> {
+ let http_server = MockServer::start().await;
+ Mock::given(method("POST"))
+ .respond_with(ResponseTemplate::new(200).set_delay(Duration::from_secs(10)))
+ .mount(&http_server)
+ .await;
+ let exec_server = spawn_exec_server().await?;
+ let client = RmcpClient::new_streamable_http_client(
+ "stalled-remote-http",
+ &format!("{}/mcp", http_server.uri()),
+ Some("test-bearer".to_string()),
+ /*http_headers*/ None,
+ /*env_http_headers*/ None,
+ OAuthCredentialsStoreMode::File,
+ AuthKeyringBackendKind::default(),
+ Arc::new(exec_server.client.clone()),
+ /*auth_provider*/ None,
+ )
+ .await?;
+ let params = InitializeRequestParams::new(
+ ClientCapabilities::default(),
+ Implementation::new("codex-test", "0.0.0-test"),
+ )
+ .with_protocol_version(ProtocolVersion::V_2025_06_18);
+ let error = client
+ .initialize(
+ params,
+ Some(Duration::from_millis(500)),
+ Box::new(|_, _| {
+ async {
+ Ok(ElicitationResponse {
+ action: ElicitationAction::Accept,
+ content: None,
+ meta: None,
+ })
+ }
+ .boxed()
+ }),
+ )
+ .await
+ .expect_err("the stalled MCP handshake must time out");
+ assert!(
+ error.to_string().contains("timed out"),
+ "unexpected MCP handshake error: {error}"
+ );
+
+ tokio::time::timeout(
+ Duration::from_secs(2),
+ exec_server.client.environment_info(),
+ )
+ .await
+ .expect("a timed-out handshake must not leave the serial executor blocked")?;
+ Ok(())
+}