diff --git a/codex-rs/app-server/src/message_processor.rs b/codex-rs/app-server/src/message_processor.rs index 276f14f0f3..8071e73bdb 100644 --- a/codex-rs/app-server/src/message_processor.rs +++ b/codex-rs/app-server/src/message_processor.rs @@ -94,6 +94,7 @@ use codex_feedback::CodexFeedback; use codex_goal_extension::GoalService; use codex_home::CodexHomeUserInstructionsProvider; use codex_login::AuthManager; +use codex_mcp::ParentMcpBindings; use codex_models_manager::manager::ModelCatalogSettings; use codex_otel::auth_storage::AuthStorageOriginator; use codex_protocol::ThreadId; @@ -424,6 +425,12 @@ impl MessageProcessor { None, ) .with_guardian_policy_loader(Arc::new(config_manager.clone())); + let manager = match rpc_transport { + AppServerRpcTransport::Stdio => { + manager.with_parent_mcp_bindings(ParentMcpBindings::from_launcher()) + } + AppServerRpcTransport::Websocket | AppServerRpcTransport::InProcess => manager, + }; match code_mode_session_provider { Some(provider) => manager.with_code_mode_session_provider(provider), None => manager, diff --git a/codex-rs/codex-mcp/src/lib.rs b/codex-rs/codex-mcp/src/lib.rs index 9bd5bc49db..798982b017 100644 --- a/codex-rs/codex-mcp/src/lib.rs +++ b/codex-rs/codex-mcp/src/lib.rs @@ -18,6 +18,7 @@ pub use elicitation::ElicitationReviewer; pub use elicitation::ElicitationReviewerHandle; pub use ema_auth::ema_auth_scope; pub use event_stream::McpEventStreamOpener; +pub use parent_socket::ParentMcpBindings; pub use resource_client::CodexAppsResourceListParams; pub use resource_client::McpEventCatalogSnapshot; pub use resource_client::McpEventDefinition; @@ -142,6 +143,7 @@ mod executor_environment_http_client; pub(crate) mod mcp; mod openai_docs_source_attribution; mod pagination; +mod parent_socket; mod plugin_config; mod resource_client; mod resource_origin; diff --git a/codex-rs/codex-mcp/src/mcp/mod.rs b/codex-rs/codex-mcp/src/mcp/mod.rs index e7cbe2b9ac..5ed78804d3 100644 --- a/codex-rs/codex-mcp/src/mcp/mod.rs +++ b/codex-rs/codex-mcp/src/mcp/mod.rs @@ -57,6 +57,7 @@ use crate::McpPermissionSource; use crate::McpProtocolMode; use crate::McpServerKey; use crate::McpServerSource; +use crate::ParentMcpBindings; use crate::ResolvedMcpCatalog; use crate::ResolvedMcpServer; use crate::connection_manager::McpConnectionSet; @@ -154,6 +155,8 @@ pub struct McpClientConfig { pub struct McpConfig { /// Shared settings that shape client initialization and tool discovery. pub client: McpClientConfig, + /// Runtime-only launcher bindings for local plugin declarations. + pub parent_bindings: ParentMcpBindings, /// Optional product SKU forwarded to the host-owned apps MCP server. pub apps_mcp_product_sku: Option, /// Codex home directory used for MCP OAuth state and app-tool cache files. @@ -481,6 +484,7 @@ pub(crate) fn effective_mcp_server( } Some( EffectiveMcpServer::from_config_with_policy(server, registration.credential_policy()) + .with_parent_socket(config.parent_bindings.for_registration(registration)) .with_agent_plugin(registration.source().is_agent_plugin()) .with_request_auth_provider(request_auth_provider.cloned()), ) diff --git a/codex-rs/codex-mcp/src/mcp/mod_tests.rs b/codex-rs/codex-mcp/src/mcp/mod_tests.rs index 673f9f93b4..87626530f2 100644 --- a/codex-rs/codex-mcp/src/mcp/mod_tests.rs +++ b/codex-rs/codex-mcp/src/mcp/mod_tests.rs @@ -226,6 +226,7 @@ pub(crate) fn test_mcp_config(codex_home: PathBuf) -> McpConfig { codex_home, mcp_enterprise_managed_auth: None, ema_state: Default::default(), + parent_bindings: Default::default(), mcp_ema_cancellation: codex_config::McpEmaCancellation::default(), xaa_enabled: false, mcp_oauth_credentials_store_mode: OAuthCredentialsStoreMode::default(), diff --git a/codex-rs/codex-mcp/src/parent_socket.rs b/codex-rs/codex-mcp/src/parent_socket.rs new file mode 100644 index 0000000000..3ba43394a4 --- /dev/null +++ b/codex-rs/codex-mcp/src/parent_socket.rs @@ -0,0 +1,86 @@ +//! Match launcher-supplied MCP endpoints to host plugins' stdio declarations. +//! +//! The launcher supplies one binding object or an array in `CODEX_MCP_PARENT_BINDING`. +//! Each resolved registration needs exactly one matching endpoint. Policy operates +//! on the original stdio declaration, including the launch command identity. + +use std::sync::Arc; + +use codex_config::McpServerTransportConfig; +use codex_rmcp_client::ParentSocket; +use serde::Deserialize; +#[cfg(any(unix, test))] +use serde_json::Value; + +use crate::McpServerSource; +use crate::ResolvedMcpServer; + +#[derive(Debug, Deserialize)] +struct Binding { + plugin_id: String, + server_name: String, + id: String, + #[serde(flatten)] + socket: ParentSocket, +} + +/// Host plugin endpoints captured once by a stdio app-server. Other runtimes default to none. +#[derive(Debug, Clone, Default)] +pub struct ParentMcpBindings(Arc<[Binding]>); + +impl ParentMcpBindings { + /// Ignore inherited bindings unless the process that advertised them is our immediate parent. + pub fn from_launcher() -> Self { + #[cfg(unix)] + if let Ok(pid) = std::env::var("CODEX_MCP_PARENT_PID") + && pid.parse::().ok() == Some(std::os::unix::process::parent_id()) + && let Ok(json) = std::env::var("CODEX_MCP_PARENT_BINDING") + && let Ok(value) = serde_json::from_str(&json) + { + return Self::from_value(value); + } + Self::default() + } + + #[cfg(any(unix, test))] + fn from_value(value: Value) -> Self { + let entries = match value { + Value::Array(entries) => entries, + single => vec![single], + }; + Self( + entries + .into_iter() + .filter_map(|entry| serde_json::from_value(entry).ok()) + .collect(), + ) + } + + pub(crate) fn for_registration( + &self, + registration: &ResolvedMcpServer, + ) -> Option { + let McpServerSource::Plugin(plugin) = registration.source() else { + return None; + }; + let config = registration.config(); + let McpServerTransportConfig::Stdio { env: Some(env), .. } = &config.transport else { + return None; + }; + if !config.is_local_environment() { + return None; + } + let id = env.get("CODEX_MCP_PARENT_BINDING_ID")?; + let mut matches = self.0.iter().filter(|binding| { + plugin.plugin_id() == binding.plugin_id + && registration.name() == binding.server_name + && *id == binding.id + }); + let binding = matches.next()?; + matches.next().is_none().then(|| binding.socket.clone()) + } +} + +#[cfg(test)] +#[path = "parent_socket_tests.rs"] +mod tests; diff --git a/codex-rs/codex-mcp/src/parent_socket_tests.rs b/codex-rs/codex-mcp/src/parent_socket_tests.rs new file mode 100644 index 0000000000..e11f51110d --- /dev/null +++ b/codex-rs/codex-mcp/src/parent_socket_tests.rs @@ -0,0 +1,116 @@ +#![cfg(test)] + +use super::*; +use crate::McpPluginAttribution; +use crate::McpServerRegistration; +use crate::ResolvedMcpCatalog; +use crate::mcp::effective_mcp_server; +use crate::mcp::tests::test_mcp_config; +use codex_config::McpServerConfig; +use pretty_assertions::assert_eq; +use serde_json::json; + +#[test] +fn parent_binding_is_scoped_to_the_runtime_and_resolved_plugin_declaration() { + let endpoint = json!({ + "plugin_id": "plugin@marketplace", + "server_name": "server", + "id": "v1", + "path": "/tmp/socket", + "pid": 1 + }); + let isolated = test_mcp_config(std::env::temp_dir()); + let mut host = isolated.clone(); + host.parent_bindings = ParentMcpBindings::from_value(endpoint.clone()); + let config: McpServerConfig = serde_json::from_value(json!({ + "command": "launcher", + "env": {"CODEX_MCP_PARENT_BINDING_ID":"v1"} + })) + .unwrap(); + let plugin = |id: &str, config| { + McpServerRegistration::from_plugin( + "server".to_string(), + McpPluginAttribution::new(id.to_string(), "Plugin".to_string()), + /*plugin_order*/ 0, + config, + ) + }; + let resolve = |runtime: &crate::McpConfig, registrations: Vec| { + let mut builder = ResolvedMcpCatalog::builder(); + for registration in registrations { + builder.register(registration); + } + let catalog = builder.build(); + effective_mcp_server( + runtime, + /*auth*/ None, + catalog.server_by_name("server").unwrap(), + ) + .unwrap() + .parent_socket + }; + let original = plugin("plugin@marketplace", config.clone()); + assert_eq!( + resolve(&host, vec![original.clone()]), + Some(serde_json::from_value(endpoint).unwrap()) + ); + assert_eq!(resolve(&isolated, vec![original.clone()]), None); + assert_eq!( + resolve(&host, vec![plugin("plugin@other", config.clone())]), + None + ); + let mut old = config.clone(); + if let McpServerTransportConfig::Stdio { env, .. } = &mut old.transport { + *env = None; + } + assert_eq!( + resolve(&host, vec![plugin("plugin@marketplace", old)]), + None + ); + let shadow = McpServerRegistration::from_config("server".to_string(), config); + assert_eq!(resolve(&host, vec![original, shadow]), None); +} + +#[test] +fn each_registration_requires_its_own_unique_match() { + let endpoint = |plugin, server, id, path| json!({"plugin_id": plugin, "server_name": server, "id": id, "path": path, "pid": 1}); + let first = endpoint("plugin@market", "first", "v1", "/first"); + let second = endpoint("plugin@market", "second", "v1", "/second"); + let mut builder = ResolvedMcpCatalog::builder(); + for name in ["first", "second"] { + let config = serde_json::from_value(json!({ + "command": "launcher", + "env": {"CODEX_MCP_PARENT_BINDING_ID": "v1"} + })) + .unwrap(); + builder.register(McpServerRegistration::from_plugin( + name.to_string(), + McpPluginAttribution::new("plugin@market".to_string(), "Plugin".to_string()), + /*plugin_order*/ 0, + config, + )); + } + let catalog = builder.build(); + let resolve = |bindings: &ParentMcpBindings, name| { + bindings.for_registration(catalog.server_by_name(name).unwrap()) + }; + let bindings = ParentMcpBindings::from_value(json!([ + second, + endpoint("other@market", "first", "v1", "/other-plugin"), + endpoint("plugin@market", "first", "v2", "/other-version"), + {"plugin_id": "malformed"}, + first, + ])); + let first_socket = Some(serde_json::from_value(first.clone()).unwrap()); + let second_socket = Some(serde_json::from_value(second.clone()).unwrap()); + assert_eq!(resolve(&bindings, "first"), first_socket); + assert_eq!(resolve(&bindings, "second"), second_socket); + + let bindings = ParentMcpBindings::from_value(json!([ + first, + second, + endpoint("plugin@market", "first", "v1", "/ambiguous"), + ])); + assert_eq!(resolve(&bindings, "first"), None); + assert_eq!(resolve(&bindings, "second"), second_socket); +} diff --git a/codex-rs/codex-mcp/src/rmcp_client.rs b/codex-rs/codex-mcp/src/rmcp_client.rs index 261be309bb..0a3e3932bb 100644 --- a/codex-rs/codex-mcp/src/rmcp_client.rs +++ b/codex-rs/codex-mcp/src/rmcp_client.rs @@ -1641,6 +1641,14 @@ pub(crate) async fn make_rmcp_client( env_vars, cwd, } => { + if let Some(socket) = server.parent_socket.as_ref() { + let mode = server.stdio_protocol_mode(protocol_mode).ok_or_else(|| { + StartupOutcomeError::from(anyhow!("invalid parent socket protocol mode")) + })?; + return RmcpClient::new_parent_socket_client(socket.clone(), mode) + .await + .map_err(|err| StartupOutcomeError::from(anyhow!(err))); + } let command_os: OsString = command.into(); let args_os: Vec = args.into_iter().map(Into::into).collect(); let env_os = env.map(|env| { diff --git a/codex-rs/codex-mcp/src/server.rs b/codex-rs/codex-mcp/src/server.rs index 52a5c53165..7e0b8526dc 100644 --- a/codex-rs/codex-mcp/src/server.rs +++ b/codex-rs/codex-mcp/src/server.rs @@ -42,6 +42,7 @@ pub(crate) enum McpCredentialPolicy { /// MCP server after runtime additions have been applied. #[derive(Debug, Clone)] pub struct EffectiveMcpServer { + pub(crate) parent_socket: Option, config: McpServerConfig, request_auth_provider: Option, credential_policy: McpCredentialPolicy, @@ -63,6 +64,7 @@ impl EffectiveMcpServer { config, request_auth_provider: None, credential_policy, + parent_socket: None, agent_plugin: false, requires_read_only_mcp_tools: false, } @@ -131,6 +133,14 @@ impl EffectiveMcpServer { mode.stdio_mode(version.map(OsStr::new)).ok() } + pub(crate) fn with_parent_socket( + mut self, + socket: Option, + ) -> Self { + self.parent_socket = socket; + self + } + pub fn enabled(&self) -> bool { self.config.enabled } @@ -185,6 +195,7 @@ pub(crate) struct McpServerConnectionIdentity { transport: McpServerTransportConfig, environment_id: String, host_plugin_root: Option, + parent_socket: Option, oauth_store: Option<(OAuthCredentialsStoreMode, AuthKeyringBackendKind)>, oauth_refresh_mode: Option, oauth_config: Option, @@ -319,6 +330,7 @@ impl McpServerConnectionIdentity { transport: config.transport.clone(), environment_id: config.environment_id.clone(), host_plugin_root: host_plugin_root.cloned(), + parent_socket: server.parent_socket.clone(), oauth_store: stored_oauth_url .is_some() .then_some((store_mode, keyring_backend_kind)), @@ -366,6 +378,7 @@ impl McpServerConnectionIdentity { && self.transport == other.transport && self.environment_id == other.environment_id && self.host_plugin_root == other.host_plugin_root + && self.parent_socket == other.parent_socket && self.oauth_store == other.oauth_store && self.oauth_refresh_mode == other.oauth_refresh_mode // Callback settings only affect a future login, not the live connection. diff --git a/codex-rs/core/src/config/mod.rs b/codex-rs/core/src/config/mod.rs index 2c2cd24ffe..f85bff7a7d 100644 --- a/codex-rs/core/src/config/mod.rs +++ b/codex-rs/core/src/config/mod.rs @@ -2137,6 +2137,7 @@ impl Config { } McpConfig { + parent_bindings: Default::default(), executor_discovery_v2: None, client: McpClientConfig { chatgpt_base_url: self.chatgpt_base_url.clone(), diff --git a/codex-rs/core/src/mcp.rs b/codex-rs/core/src/mcp.rs index 5d30d98934..7b5a692fbf 100644 --- a/codex-rs/core/src/mcp.rs +++ b/codex-rs/core/src/mcp.rs @@ -32,6 +32,7 @@ use codex_mcp::McpEnvironmentAuthority; use codex_mcp::McpPluginAttribution; use codex_mcp::McpServerRegistration; use codex_mcp::McpToolCatalogCache; +use codex_mcp::ParentMcpBindings; use codex_mcp::ToolInfo; use codex_mcp::codex_apps_mcp_server_config; use codex_mcp::configured_mcp_servers; @@ -112,6 +113,7 @@ enum OrderedMcpOverlay { #[derive(Clone)] pub struct McpManager { + pub(crate) parent_bindings: ParentMcpBindings, connection_pool: codex_mcp::McpConnectionPool, plugins_manager: Arc, extensions: Arc>, @@ -137,6 +139,7 @@ impl McpManager { codex_apps_tools_cache: ConnectorRuntimeManager, ) -> Self { Self { + parent_bindings: Default::default(), connection_pool: codex_mcp::McpConnectionPool::default(), plugins_manager, extensions, @@ -153,6 +156,7 @@ impl McpManager { Arc::clone(&self.extensions), ConnectorRuntimeManager::default(), ); + manager.parent_bindings = self.parent_bindings.clone(); manager.connection_pool = self.connection_pool.clone(); manager } @@ -537,6 +541,7 @@ impl McpManager { !selected_plugins.is_empty() || !loaded_plugins.capability_summaries().is_empty(); let mut mcp_config = config .to_mcp_config_with_loaded_plugins(&loaded_plugins, selected_plugin_registrations); + mcp_config.parent_bindings = self.parent_bindings.clone(); mcp_config.ema_state = Arc::clone(&self.ema_state); let mut catalog = mcp_config.mcp_server_catalog.to_builder(); // Isolated sessions do not inherit the implicit Apps connection. diff --git a/codex-rs/core/src/thread_manager.rs b/codex-rs/core/src/thread_manager.rs index 31ab2663b7..9f6d69e155 100644 --- a/codex-rs/core/src/thread_manager.rs +++ b/codex-rs/core/src/thread_manager.rs @@ -77,6 +77,7 @@ use codex_login::AuthManager; use codex_login::CodexAuth; use codex_login::default_client::CODEX_INTERNAL_ORIGINATOR_OVERRIDE_ENV_VAR; use codex_login::default_client::originator; +use codex_mcp::ParentMcpBindings; use codex_model_provider::ModelCatalogFactory; use codex_model_provider::ProviderAuthContext; use codex_model_provider_info::ModelProviderInfo; @@ -787,6 +788,15 @@ impl ThreadManager { self } + /// Attach launcher endpoints before sharing the manager. Isolated sessions use their own manager. + pub fn with_parent_mcp_bindings(mut self, bindings: ParentMcpBindings) -> Self { + let Some(state) = Arc::get_mut(&mut self.state) else { + unreachable!("MCP bindings must be set before the thread manager is shared"); + }; + Arc::make_mut(&mut state.mcp_manager).parent_bindings = bindings; + self + } + /// Samples host metrics without creating a Codex thread or code-mode session. /// Process-owned providers observe existing children; custom providers retain /// their transport's connection policy. diff --git a/codex-rs/rmcp-client/src/lib.rs b/codex-rs/rmcp-client/src/lib.rs index eed03d2518..9ab0433bf9 100644 --- a/codex-rs/rmcp-client/src/lib.rs +++ b/codex-rs/rmcp-client/src/lib.rs @@ -27,6 +27,7 @@ mod oauth_discovery; mod oauth_http_client; mod oauth_refresh_mode; mod ordered_byte_transport; +mod parent_socket; mod perform_oauth_login; mod program_resolver; mod protocol_mode; @@ -94,6 +95,7 @@ pub use oauth_callback::resolve_mcp_oauth_callback_url; pub use oauth_client_registration::McpOAuthClientRegistration; pub use oauth_discovery::discover_authorization_metadata; pub use oauth_refresh_mode::McpOAuthRefreshMode; +pub use parent_socket::ParentSocket; pub use perform_oauth_login::OAuthProviderError; pub use perform_oauth_login::OauthLoginHandle; pub use perform_oauth_login::perform_oauth_login; diff --git a/codex-rs/rmcp-client/src/parent_socket.rs b/codex-rs/rmcp-client/src/parent_socket.rs new file mode 100644 index 0000000000..aade6568c9 --- /dev/null +++ b/codex-rs/rmcp-client/src/parent_socket.rs @@ -0,0 +1,58 @@ +//! Require a private socket directory and authenticate the MCP listener before sending data. + +use std::io; +use std::path::PathBuf; + +use serde::Deserialize; + +use crate::rmcp_client::ByteStream; + +/// A socket address supplied by the host process, never by the MCP declaration. +#[derive(Debug, Clone, PartialEq, Eq, Deserialize)] +pub struct ParentSocket { + path: PathBuf, + pid: i32, +} + +impl ParentSocket { + /// Check the containing directory and the host's identity on every connection. + #[cfg(unix)] + pub(crate) async fn connect(&self) -> io::Result> { + use std::os::unix::fs::MetadataExt; + + if !self.path.is_absolute() || self.pid <= 0 { + return Err(io::Error::new( + io::ErrorKind::InvalidInput, + "MCP socket requires an absolute path and positive host PID", + )); + } + // SAFETY: geteuid has no preconditions. + let uid = unsafe { libc::geteuid() }; + let parent = self.path.parent().ok_or(io::ErrorKind::InvalidInput)?; + let dir = tokio::fs::symlink_metadata(parent).await?; + if !dir.is_dir() || dir.uid() != uid || dir.mode() & 0o777 != 0o700 { + return Err(io::Error::new( + io::ErrorKind::PermissionDenied, + "MCP socket requires a user-owned directory with mode 0700", + )); + } + let stream = tokio::net::UnixStream::connect(&self.path).await?; + let peer = stream.peer_cred()?; + if peer.pid() != Some(self.pid) || peer.uid() != uid { + return Err(io::Error::new( + io::ErrorKind::PermissionDenied, + "MCP socket owner differs from launch host", + )); + } + Ok(Box::new(stream)) + } + + #[cfg(not(unix))] + pub(crate) async fn connect(&self) -> io::Result> { + Err(io::ErrorKind::Unsupported.into()) + } +} + +#[cfg(all(test, any(target_os = "linux", target_os = "macos")))] +#[path = "parent_socket_tests.rs"] +mod tests; diff --git a/codex-rs/rmcp-client/src/parent_socket_tests.rs b/codex-rs/rmcp-client/src/parent_socket_tests.rs new file mode 100644 index 0000000000..1595efa4e1 --- /dev/null +++ b/codex-rs/rmcp-client/src/parent_socket_tests.rs @@ -0,0 +1,86 @@ +#![cfg(test)] + +use super::*; +use pretty_assertions::assert_eq; +use std::fs; +use std::os::unix::fs::PermissionsExt; +use tokio::io::AsyncReadExt; +use tokio::net::UnixListener; + +fn private_dir() -> io::Result { + tempfile::Builder::new() + .permissions(fs::Permissions::from_mode(0o700)) + .tempdir() +} + +#[tokio::test] +async fn only_the_expected_listener_receives_an_mcp_stream() -> io::Result<()> { + let dir = private_dir()?; + let path = dir.path().join("mcp"); + let listener = UnixListener::bind(&path)?; + let pid = std::process::id().cast_signed(); + let mut socket = ParentSocket { path, pid: pid + 1 }; + assert_eq!( + socket.connect().await.err().map(|error| error.kind()), + Some(io::ErrorKind::PermissionDenied) + ); + let (mut peer, _) = listener.accept().await?; + assert_eq!(peer.read(&mut [0]).await?, 0); + + socket.pid = pid; + socket.connect().await?; + Ok(()) +} + +#[tokio::test] +async fn rechecks_directory_permissions_before_connecting() -> io::Result<()> { + let dir = private_dir()?; + let socket = ParentSocket { + path: dir.path().join("mcp"), + pid: std::process::id().cast_signed(), + }; + let listener = std::os::unix::net::UnixListener::bind(&socket.path)?; + listener.set_nonblocking(true)?; + socket.connect().await?; + listener.accept()?; + + fs::set_permissions(dir.path(), fs::Permissions::from_mode(0o750))?; + assert_eq!( + socket.connect().await.err().map(|error| error.kind()), + Some(io::ErrorKind::PermissionDenied) + ); + assert_eq!( + listener.accept().unwrap_err().kind(), + io::ErrorKind::WouldBlock + ); + Ok(()) +} + +#[tokio::test] +async fn rejects_a_symlink_as_the_socket_directory() -> io::Result<()> { + let dir = private_dir()?; + let _listener = UnixListener::bind(dir.path().join("mcp"))?; + let link = dir.path().join("alias"); + std::os::unix::fs::symlink(dir.path(), &link)?; + let socket = ParentSocket { + path: link.join("mcp"), + pid: std::process::id().cast_signed(), + }; + assert_eq!( + socket.connect().await.err().map(|error| error.kind()), + Some(io::ErrorKind::PermissionDenied) + ); + Ok(()) +} + +#[tokio::test] +async fn rejects_relative_socket_path() { + let socket = ParentSocket { + path: "mcp".into(), + pid: std::process::id().cast_signed(), + }; + assert_eq!( + socket.connect().await.err().map(|error| error.kind()), + Some(io::ErrorKind::InvalidInput) + ); +} diff --git a/codex-rs/rmcp-client/src/rmcp_client.rs b/codex-rs/rmcp-client/src/rmcp_client.rs index 6be27cad11..cef4191129 100644 --- a/codex-rs/rmcp-client/src/rmcp_client.rs +++ b/codex-rs/rmcp-client/src/rmcp_client.rs @@ -153,9 +153,16 @@ impl InitializeMode { } } +/// Streams that carry MCP without an associated child process. +pub(crate) trait ByteStream: + tokio::io::AsyncRead + tokio::io::AsyncWrite + Send + Unpin +{ +} +impl ByteStream for T {} + enum PendingTransport { - InProcess { - transport: tokio::io::DuplexStream, + ByteStream { + transport: Box, }, Stdio { transport: Box, @@ -210,6 +217,7 @@ pub enum StreamableHttpBearerToken { #[derive(Clone)] enum TransportRecipe { + ParentSocket(crate::ParentSocket), InProcess { factory: Arc, }, @@ -553,7 +561,25 @@ impl RmcpClient { pub async fn new_in_process_client( factory: Arc, ) -> io::Result { - let transport_recipe = TransportRecipe::InProcess { factory }; + 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::new_byte_stream_client(TransportRecipe::ParentSocket(socket), protocol_mode).await + } + + async fn new_byte_stream_client( + transport_recipe: TransportRecipe, + protocol_mode: McpProtocolMode, + ) -> io::Result { let transport = Self::create_pending_transport(&transport_recipe) .await .map_err(io::Error::other)?; @@ -564,7 +590,7 @@ impl RmcpClient { }), stdio_process: None, transport_recipe, - protocol_mode: McpProtocolMode::Legacy, + protocol_mode, requires_read_only_tools: false, initialize_context: Mutex::new(None), session_recovery_lock: Semaphore::new(/*permits*/ 1), @@ -628,7 +654,7 @@ impl RmcpClient { .map_err(io::Error::other)?; let stdio_process = match &transport { PendingTransport::Stdio { transport } => Some(transport.process_slot()), - PendingTransport::InProcess { .. } + PendingTransport::ByteStream { .. } | PendingTransport::StreamableHttp { .. } | PendingTransport::StreamableHttpWithOAuth { .. } | PendingTransport::StreamableHttpWithAccessTokenOnly { .. } => None, @@ -1517,8 +1543,13 @@ impl RmcpClient { match transport_recipe { TransportRecipe::InProcess { factory } => { let transport = factory.open().await?; - Ok(PendingTransport::InProcess { transport }) + 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 { @@ -1740,7 +1771,9 @@ impl RmcpClient { deadline: Arc::clone(initialize_deadline), }) } - TransportRecipe::InProcess { .. } | TransportRecipe::Stdio { .. } => None, + TransportRecipe::InProcess { .. } + | TransportRecipe::ParentSocket(_) + | TransportRecipe::Stdio { .. } => None, }; let lifecycle = self.protocol_mode.client_lifecycle(); let session_expired = CancellationToken::new(); @@ -1757,7 +1790,7 @@ impl RmcpClient { }; let mut discovery = None; let (transport, oauth_runtime, handshake_cleanup) = match pending_transport { - PendingTransport::InProcess { transport } => ( + PendingTransport::ByteStream { transport } => ( client_service() .serve_with_lifecycle( track_tool_list_changes( diff --git a/codex-rs/rmcp-client/src/streamable_http_retry.rs b/codex-rs/rmcp-client/src/streamable_http_retry.rs index 2e5e142d88..4e600e79b3 100644 --- a/codex-rs/rmcp-client/src/streamable_http_retry.rs +++ b/codex-rs/rmcp-client/src/streamable_http_retry.rs @@ -41,7 +41,7 @@ impl RmcpClient { ) -> Result> { let timeout = initialize_context.timeout; let should_retry = match &initial_transport { - PendingTransport::InProcess { .. } | PendingTransport::Stdio { .. } => false, + PendingTransport::ByteStream { .. } | PendingTransport::Stdio { .. } => false, PendingTransport::StreamableHttp { .. } | PendingTransport::StreamableHttpWithOAuth { .. } | PendingTransport::StreamableHttpWithAccessTokenOnly { .. } => true,