Skip to content

armgit / codex

Public Imported from GitHub
0

Lightweight coding agent that runs in your terminal

Rust

Preserve executor MCP credential boundaries across reconnects (#48143)

rreichel3-oaic7e80f873f67
diff --git a/codex-rs/app-server/tests/suite/v2/executor_mcp.rs b/codex-rs/app-server/tests/suite/v2/executor_mcp.rs
index 2fddde479a..c7df4e6b17 100644
--- a/codex-rs/app-server/tests/suite/v2/executor_mcp.rs
+++ b/codex-rs/app-server/tests/suite/v2/executor_mcp.rs
@@ -1,6 +1,7 @@
use anyhow::Result;
use app_test_support::MockResponsesConfig;
use app_test_support::TestAppServer;
+use app_test_support::write_models_cache;
use axum::Json;
use axum::Router;
use axum::body::Bytes;
@@ -51,6 +52,7 @@ use std::collections::BTreeMap;
use std::process::Stdio;
use std::sync::Arc;
use std::sync::atomic::AtomicBool;
+use std::sync::atomic::AtomicUsize;
use std::sync::atomic::Ordering;
use std::time::Duration;
use tempfile::TempDir;
@@ -239,14 +241,18 @@ async fn selected_executor_discovers_browser_mcp_with_executor_only_bearer_token
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
-async fn legacy_executor_skips_required_browser_and_keeps_host_owned_mcp() -> Result<()> {
+async fn legacy_executor_blocks_plugin_host_credentials_and_keeps_host_owned_mcp() -> Result<()> {
+ const PLUGIN_ID: &str = "legacy-plugin@1";
+ const TOKEN_ENV: &str = "SELECTED_PLUGIN_CREDENTIAL_TEST_TOKEN";
+ const HOST_TOKEN: &str = "selected-plugin-host-credential-canary";
+ const EXECUTOR_TOKEN: &str = "selected-plugin-executor-credential-canary";
let responses_server = responses::start_mock_server().await;
let codex_home = TempDir::new()?;
let executor_home = TempDir::new()?;
+ let plugin = TempDir::new()?;
let http_listener = TcpListener::bind("127.0.0.1:0").await?;
let mcp_url = format!("http://{}/mcp", http_listener.local_addr()?);
- let expected_authorization = "Bearer host-only-token";
let service = StreamableHttpService::new(
|| Ok(ExecutorHttpMcpServer),
Arc::new(LocalSessionManager::default()),
@@ -256,12 +262,14 @@ async fn legacy_executor_skips_required_browser_and_keeps_host_owned_mcp() -> Re
.nest_service("/mcp", service)
.layer(axum::middleware::from_fn(
move |request: axum::extract::Request, next: axum::middleware::Next| async move {
- let authorized = request
+ let authorization = request
.headers()
.get(axum::http::header::AUTHORIZATION)
- .and_then(|value| value.to_str().ok())
- .is_some_and(|value| value == expected_authorization);
- if !authorized {
+ .and_then(|value| value.to_str().ok());
+ if !matches!(
+ authorization,
+ Some("Bearer host-only-token" | "Bearer plugin-public-token")
+ ) {
return axum::http::StatusCode::UNAUTHORIZED.into_response();
}
next.run(request).await
@@ -275,7 +283,7 @@ async fn legacy_executor_skips_required_browser_and_keeps_host_owned_mcp() -> Re
"[mcp_servers.host_remote]\nurl = \"{mcp_url}\"\nenvironment_id = \"{EXECUTOR_ID}\"\nbearer_token_env_var = \"HOST_MCP_TEST_TOKEN\"\nrequired = true\n"
);
MockResponsesConfig::new(&responses_server.uri())
- .with_sandbox_mode("danger-full-access")
+ .with_sandbox_mode("workspace-write")
.with_extra_config(&root_config)
.write(codex_home.path())?;
std::fs::write(
@@ -284,12 +292,34 @@ async fn legacy_executor_skips_required_browser_and_keeps_host_owned_mcp() -> Re
"[mcp_servers.node_repl]\nurl = \"http://127.0.0.1:9/mcp\"\nbearer_token_env_var = \"NODE_REPL_AUTH_TOKEN\"\nrequired = true\nstartup_timeout_sec = 1\n\n[mcp_servers.executor_public]\nurl = \"{mcp_url}\"\nhttp_headers = {{ Authorization = \"Bearer host-only-token\" }}\nrequired = true\n"
),
)?;
+ std::fs::create_dir_all(plugin.path().join(".codex-plugin"))?;
+ std::fs::write(
+ plugin.path().join(".codex-plugin/plugin.json"),
+ r#"{"name":"legacy-plugin"}"#,
+ )?;
+ std::fs::write(
+ plugin.path().join(".mcp.json"),
+ serde_json::to_vec(&json!({
+ "mcpServers": {
+ "plugin_public": {
+ "url": mcp_url,
+ "http_headers": {"Authorization": "Bearer plugin-public-token"},
+ },
+ "plugin_sensitive": {
+ "url": mcp_url,
+ "environment_id": "local",
+ "bearer_token_env_var": TOKEN_ENV,
+ }
+ }
+ }))?,
+ )?;
let mut executor = Command::new(codex_utils_cargo_bin::cargo_bin("codex")?)
.args(["exec-server", "--listen", "ws://127.0.0.1:0"])
.stdout(Stdio::piped())
.kill_on_drop(true)
.env("CODEX_HOME", executor_home.path())
+ .env(TOKEN_ENV, EXECUTOR_TOKEN)
.spawn()?;
let stdout = executor.stdout.take().expect("executor stdout is piped");
let mut lines = BufReader::new(stdout).lines();
@@ -299,6 +329,7 @@ async fn legacy_executor_skips_required_browser_and_keeps_host_owned_mcp() -> Re
let proxy_listener = TcpListener::bind("127.0.0.1:0").await?;
let proxy_url = format!("ws://{}", proxy_listener.local_addr()?);
+ let (http_requests_tx, mut http_requests_rx) = mpsc::unbounded_channel();
let legacy_executor = tokio::spawn(async move {
let (stream, _) = proxy_listener.accept().await?;
let downstream = accept_async(stream).await?;
@@ -311,15 +342,16 @@ async fn legacy_executor_skips_required_browser_and_keeps_host_owned_mcp() -> Re
let mut message = message?;
if let Message::Text(text) = &message {
let mut request: Value = serde_json::from_str(text)?;
- if request["method"] == "http/request"
- && let Some(headers) = request["params"]["headers"].as_array_mut()
- {
- for header in headers {
- if let Some(header) = header.as_object_mut() {
- header.remove("valueEnvVar");
+ if request["method"] == "http/request" {
+ http_requests_tx.send(request.clone())?;
+ if let Some(headers) = request["params"]["headers"].as_array_mut() {
+ for header in headers {
+ if let Some(header) = header.as_object_mut() {
+ header.remove("valueEnvVar");
+ }
}
+ message = Message::Text(request.to_string().into());
}
- message = Message::Text(request.to_string().into());
}
}
upstream_tx.send(message).await?;
@@ -364,11 +396,24 @@ async fn legacy_executor_skips_required_browser_and_keeps_host_owned_mcp() -> Re
let mut app_server = TestAppServer::builder()
.with_codex_home(codex_home.path())
- .with_env_overrides(&[("HOST_MCP_TEST_TOKEN", Some("host-only-token"))])
+ .with_env_overrides(&[
+ ("HOST_MCP_TEST_TOKEN", Some("host-only-token")),
+ (TOKEN_ENV, Some(HOST_TOKEN)),
+ ])
.without_auto_env()
.build_initialized_with_timeout(DEFAULT_READ_TIMEOUT)
.await?;
- let thread_id = start_thread(&mut app_server, /*selected_capability_roots*/ None).await?;
+ let thread_id = start_thread(
+ &mut app_server,
+ Some(vec![SelectedCapabilityRoot {
+ id: PLUGIN_ID.to_string(),
+ location: CapabilityRootLocation::Environment {
+ environment_id: EXECUTOR_ID.to_string(),
+ path: PathUri::from_host_native_path(plugin.path())?,
+ },
+ }]),
+ )
+ .await?;
let servers = mcp_server_statuses(&mut app_server, thread_id.clone()).await?;
assert!(servers.iter().any(|server| server.name == "host_remote"));
assert!(
@@ -377,6 +422,28 @@ async fn legacy_executor_skips_required_browser_and_keeps_host_owned_mcp() -> Re
.any(|server| server.name == "executor_public")
);
assert!(servers.iter().all(|server| server.name != "node_repl"));
+ let public_plugin = servers
+ .iter()
+ .find(|server| server.name == "plugin_public")
+ .expect("selected plugin public MCP should be discovered");
+ assert_eq!(public_plugin.plugin_id.as_deref(), Some(PLUGIN_ID));
+ assert!(public_plugin.tools.contains_key("echo"));
+ let sensitive_plugin = servers
+ .iter()
+ .find(|server| server.name == "plugin_sensitive")
+ .expect("selected plugin credential-bearing MCP should be discovered");
+ assert_eq!(sensitive_plugin.plugin_id.as_deref(), Some(PLUGIN_ID));
+ assert!(sensitive_plugin.tools.is_empty());
+ assert!(
+ sensitive_plugin
+ .tools_error
+ .as_deref()
+ .is_some_and(|error| {
+ error.contains("requires executor-side environment credential resolution")
+ }),
+ "legacy executor should reject the plugin's environment credential: {:?}",
+ sensitive_plugin.tools_error
+ );
let response = responses::mount_sse_once(
&responses_server,
@@ -410,12 +477,357 @@ async fn legacy_executor_skips_required_browser_and_keeps_host_owned_mcp() -> Re
.tool_by_name("mcp__host_remote", "echo")
.is_some()
);
+ assert!(
+ response
+ .single_request()
+ .tool_by_name("mcp__plugin_public", "echo")
+ .is_some()
+ );
+ let http_requests = std::iter::from_fn(|| http_requests_rx.try_recv().ok()).collect::<Vec<_>>();
+ for token in ["host-only-token", "plugin-public-token"] {
+ assert!(
+ http_requests
+ .iter()
+ .any(|request| request["params"]["headers"].to_string().contains(token)),
+ "expected a captured HTTP request using {token}"
+ );
+ }
+ assert!(
+ http_requests
+ .iter()
+ .all(|request| !request.to_string().contains(HOST_TOKEN)),
+ "the selected plugin sent the host credential to the legacy executor"
+ );
legacy_executor.abort();
http_server.abort();
Ok(())
}
+/// A cached executor declaration must retain its credential boundary after reconnecting.
+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
+async fn cached_executor_mcp_cannot_read_host_token_after_capability_downgrade() -> Result<()> {
+ const TOKEN_ENV: &str = "MCP_CREDENTIAL_BOUNDARY_TEST_TOKEN";
+ const HOST_TOKEN: &str = "host-only-credential-boundary-canary";
+ const EXECUTOR_TOKEN: &str = "executor-only-credential-boundary-canary";
+ const PARENT_PROMPT: &str = "spawn the credential boundary worker";
+ const CHILD_PROMPT: &str = "check cached credential boundary";
+ const DISCONNECT_MARKER: &str = "credential-boundary-disconnect";
+ const CALL_ID: &str = "cached-credential-call";
+
+ let responses_server = responses::start_mock_server().await;
+ let codex_home = TempDir::new()?;
+ let executor_home = TempDir::new()?;
+ MockResponsesConfig::new(&responses_server.uri())
+ .with_model("gpt-5.4")
+ .with_sandbox_mode("danger-full-access")
+ .with_approval_policy("never")
+ .with_extra_config("[features.multi_agent_v2]\nenabled = true\n")
+ .write(codex_home.path())?;
+ write_models_cache(codex_home.path()).await?;
+
+ let listener = TcpListener::bind("127.0.0.1:0").await?;
+ let mcp_url = format!("http://{}/mcp", listener.local_addr()?);
+ let initializations = Arc::new(AtomicUsize::new(0));
+ let service = StreamableHttpService::new(
+ || Ok(ExecutorHttpMcpServer),
+ Arc::new(LocalSessionManager::default()),
+ StreamableHttpServerConfig::default(),
+ );
+ let requests_seen = Arc::clone(&initializations);
+ let router = Router::new()
+ .nest_service("/mcp", service)
+ .layer(axum::middleware::from_fn(
+ move |request: axum::extract::Request, next: axum::middleware::Next| {
+ let requests_seen = Arc::clone(&requests_seen);
+ async move {
+ let expected_authorization = format!("Bearer {EXECUTOR_TOKEN}");
+ assert_eq!(
+ request
+ .headers()
+ .get(axum::http::header::AUTHORIZATION)
+ .and_then(|value| value.to_str().ok()),
+ Some(expected_authorization.as_str())
+ );
+ if request.method() == axum::http::Method::POST {
+ let (parts, body) = request.into_parts();
+ let body = axum::body::to_bytes(body, 1024 * 1024).await.unwrap();
+ let value: Value = serde_json::from_slice(&body).unwrap();
+ if value["method"] == "initialize" {
+ requests_seen.fetch_add(1, Ordering::SeqCst);
+ }
+ return next
+ .run(axum::extract::Request::from_parts(parts, body.into()))
+ .await;
+ }
+ next.run(request).await
+ }
+ },
+ ));
+ let http_server = tokio::spawn(async move { axum::serve(listener, router).await });
+ std::fs::write(
+ executor_home.path().join("config.toml"),
+ format!(
+ "[mcp_servers.cached_executor]\nurl = \"{mcp_url}\"\nbearer_token_env_var = \"{TOKEN_ENV}\"\nrequired = true\nstartup_timeout_sec = 3\n"
+ ),
+ )?;
+ let mut executor = Command::new(codex_utils_cargo_bin::cargo_bin("codex")?)
+ .args(["exec-server", "--listen", "ws://127.0.0.1:0"])
+ .stdout(Stdio::piped())
+ .kill_on_drop(true)
+ .env("CODEX_HOME", executor_home.path())
+ .env(TOKEN_ENV, EXECUTOR_TOKEN)
+ .spawn()?;
+ let mut lines = BufReader::new(executor.stdout.take().expect("executor stdout")).lines();
+ let executor_url = timeout(DEFAULT_READ_TIMEOUT, lines.next_line())
+ .await??
+ .expect("executor websocket URL");
+ let proxy_listener = TcpListener::bind("127.0.0.1:0").await?;
+ let proxy_url = format!("ws://{}", proxy_listener.local_addr()?);
+ let downgraded = Arc::new(AtomicBool::new(false));
+ let downgrade_seen = Arc::clone(&downgraded);
+ let fresh_connection = Arc::new(AtomicBool::new(false));
+ let fresh_connection_seen = Arc::clone(&fresh_connection);
+ let (http_requests_tx, mut http_requests_rx) = mpsc::unbounded_channel();
+ let proxy = tokio::spawn(async move {
+ while let Ok((stream, _)) = proxy_listener.accept().await {
+ let mut downstream = accept_async(stream).await?;
+ let initialize = downstream.next().await.expect("executor initialize")?;
+ let Message::Text(text) = &initialize else {
+ anyhow::bail!("expected text initialize request");
+ };
+ let request: Value = serde_json::from_str(text)?;
+ assert_eq!(request["method"], "initialize");
+ let legacy = downgrade_seen.load(Ordering::SeqCst);
+ if legacy && !request["params"]["resumeSessionId"].is_null() {
+ // Successful resume preserves cached metadata; retire the old logical session.
+ let response = json!({
+ "id": request["id"],
+ "error": {"code": -32602, "message": "test executor session retired"}
+ });
+ downstream
+ .send(Message::Text(response.to_string().into()))
+ .await?;
+ downstream.close(/*msg*/ None).await?;
+ continue;
+ }
+ fresh_connection_seen.fetch_or(legacy, Ordering::SeqCst);
+ let (mut upstream, _) = connect_async(&executor_url).await?;
+ upstream.send(initialize).await?;
+ let (mut downstream_tx, mut downstream_rx) = downstream.split();
+ let (mut upstream_tx, mut upstream_rx) = upstream.split();
+ let requests = async {
+ while let Some(message) = downstream_rx.next().await {
+ let message = message?;
+ if let Message::Text(text) = &message {
+ let request: Value = serde_json::from_str(text)?;
+ if request["method"] == "http/request" {
+ http_requests_tx.send(request.clone())?;
+ }
+ if request["method"] == "process/start"
+ && request["params"]["argv"]
+ .to_string()
+ .contains(DISCONNECT_MARKER)
+ {
+ // The child's first tool forces reconnect before its cached MCP starts.
+ assert_eq!(initializations.load(Ordering::SeqCst), 1);
+ downgrade_seen.store(true, Ordering::SeqCst);
+ break;
+ }
+ }
+ upstream_tx.send(message).await?;
+ }
+ Ok::<_, anyhow::Error>(())
+ };
+ let responses = async {
+ while let Some(message) = upstream_rx.next().await {
+ let mut message = message?;
+ if legacy && let Message::Text(text) = &message {
+ let mut response: Value = serde_json::from_str(text)?;
+ if let Some(result) =
+ response.get_mut("result").and_then(Value::as_object_mut)
+ {
+ result.remove("environmentInfo");
+ }
+ if let Some(capabilities) = response
+ .pointer_mut("/result/capabilities")
+ .and_then(Value::as_object_mut)
+ {
+ capabilities.remove("httpHeaderEnvVars");
+ }
+ message = Message::Text(response.to_string().into());
+ }
+ downstream_tx.send(message).await?;
+ }
+ Ok::<_, anyhow::Error>(())
+ };
+ tokio::select! {
+ result = requests => result?,
+ result = responses => result?,
+ }
+ }
+ Ok::<_, anyhow::Error>(())
+ });
+ std::fs::write(
+ codex_home.path().join("environments.toml"),
+ format!(
+ "default = \"{EXECUTOR_ID}\"\ninclude_local = false\n\n[[environments]]\nid = \"{EXECUTOR_ID}\"\nurl = \"{proxy_url}\"\n"
+ ),
+ )?;
+ let mut app_server = TestAppServer::builder()
+ .with_codex_home(codex_home.path())
+ .with_env_overrides(&[(TOKEN_ENV, Some(HOST_TOKEN))])
+ .without_auto_env()
+ .build_initialized_with_timeout(DEFAULT_READ_TIMEOUT)
+ .await?;
+ let request_id = app_server
+ .send_thread_start_request(ThreadStartParams {
+ model: Some("gpt-5.4".to_string()),
+ ..Default::default()
+ })
+ .await?;
+ let ThreadStartResponse { thread, .. } =
+ timeout(DEFAULT_READ_TIMEOUT, app_server.read_response(request_id)).await??;
+ timeout(
+ DEFAULT_READ_TIMEOUT,
+ app_server.read_stream_until_matching_notification("executor MCP ready", |notification| {
+ notification.method == "mcpServer/startupStatus/updated"
+ && notification.params.as_ref().is_some_and(|params| {
+ params["name"] == "cached_executor" && params["status"] == "ready"
+ })
+ }),
+ )
+ .await??;
+
+ for (marker, events) in [
+ (
+ PARENT_PROMPT,
+ vec![responses::ev_function_call_with_namespace(
+ "spawn-credential-worker",
+ "collaboration",
+ "spawn_agent",
+ &json!({"task_name": "worker", "message": CHILD_PROMPT, "fork_turns": "none"})
+ .to_string(),
+ )],
+ ),
+ (
+ CHILD_PROMPT,
+ vec![responses::ev_exec_command_call(
+ "disconnect-call",
+ &format!("echo {DISCONNECT_MARKER}"),
+ )],
+ ),
+ (
+ "disconnect-call",
+ // A process RPC waits for terminal recovery before the MCP credential lookup.
+ vec![responses::ev_exec_command_call(
+ "reconnect-barrier",
+ "echo credential-boundary-ready",
+ )],
+ ),
+ (
+ "reconnect-barrier",
+ vec![responses::ev_function_call_with_namespace(
+ CALL_ID,
+ "mcp__cached_executor",
+ "echo",
+ r#"{"message":"test credential boundary"}"#,
+ )],
+ ),
+ (
+ "spawn-credential-worker",
+ vec![responses::ev_assistant_message("parent-done", "Done")],
+ ),
+ ] {
+ responses::mount_sse_once_match(
+ &responses_server,
+ move |request: &wiremock::Request| {
+ let body = String::from_utf8_lossy(&request.body);
+ body.contains(marker)
+ && (marker != CHILD_PROMPT || !body.contains("spawn-credential-worker"))
+ },
+ responses::sse(
+ events
+ .into_iter()
+ .chain([responses::ev_completed(marker)])
+ .collect(),
+ ),
+ )
+ .await;
+ }
+ let child_done = responses::mount_sse_once_match(
+ &responses_server,
+ |request: &wiremock::Request| String::from_utf8_lossy(&request.body).contains(CALL_ID),
+ responses::sse(vec![
+ responses::ev_assistant_message("child-done", "Done"),
+ responses::ev_completed("child-done"),
+ ]),
+ )
+ .await;
+ let request_id = app_server
+ .send_turn_start_request(TurnStartParams {
+ thread_id: thread.id,
+ input: vec![UserInput::Text {
+ text: PARENT_PROMPT.to_string(),
+ text_elements: Vec::new(),
+ }],
+ ..Default::default()
+ })
+ .await?;
+ let _: TurnStartResponse =
+ timeout(DEFAULT_READ_TIMEOUT, app_server.read_response(request_id)).await??;
+ let request = timeout(DEFAULT_READ_TIMEOUT, async {
+ loop {
+ if let Some(request) = child_done.requests().into_iter().next() {
+ break request;
+ }
+ tokio::time::sleep(Duration::from_millis(/*millis*/ 10)).await;
+ }
+ })
+ .await?;
+ assert!(downgraded.load(Ordering::SeqCst));
+ assert!(fresh_connection.load(Ordering::SeqCst));
+ let (barrier_output, barrier_success) = request
+ .function_call_output_content_and_success("reconnect-barrier")
+ .expect("reconnect barrier should have an output");
+ let barrier_output = barrier_output.expect("reconnect barrier output should contain text");
+ assert_ne!(barrier_success, Some(false));
+ assert!(
+ barrier_output.contains("Process exited with code 0")
+ && barrier_output.contains("credential-boundary-ready"),
+ "reconnect barrier did not complete successfully: {barrier_output}"
+ );
+ let mut http_requests = Vec::new();
+ while let Ok(request) = http_requests_rx.try_recv() {
+ http_requests.push(request);
+ }
+ assert!(
+ http_requests
+ .iter()
+ .any(|request| request["params"]["headers"].to_string().contains(TOKEN_ENV))
+ );
+ assert!(
+ http_requests
+ .iter()
+ .all(|request| !request.to_string().contains(HOST_TOKEN)),
+ "worker credentials reached executor HTTP requests"
+ );
+ let output = request.function_call_output(CALL_ID);
+ assert!(
+ output["output"]
+ .as_array()
+ .is_some_and(|items| items.iter().any(|item| {
+ item["type"] == "input_text"
+ && item["text"]
+ == "MCP tool `cached_executor/echo` is not available to the model"
+ })),
+ "expected the failed MCP server to be unavailable: {output}"
+ );
+ proxy.abort();
+ http_server.abort();
+ Ok(())
+}
+
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn guardian_review_does_not_discover_executor_mcp() -> Result<()> {
let responses_server = responses::start_mock_server().await;
diff --git a/codex-rs/codex-mcp/src/catalog.rs b/codex-rs/codex-mcp/src/catalog.rs
index 486b7a9480..00a08c51ba 100644
--- a/codex-rs/codex-mcp/src/catalog.rs
+++ b/codex-rs/codex-mcp/src/catalog.rs
@@ -3,15 +3,18 @@ use std::collections::BTreeMap;
use std::collections::BTreeSet;
use std::collections::HashMap;
+use codex_config::DEFAULT_MCP_SERVER_ENVIRONMENT_ID;
use codex_config::McpServerConfig;
use codex_config::McpServerDisabledReason;
use codex_config::McpServerIdpOAuthConfig;
+use codex_config::McpServerTransportConfig;
use codex_config::RequirementSource;
use codex_protocol::mcp_policy::EnvironmentMcpPolicy;
use codex_utils_path_uri::PathUri;
use crate::CODEX_APPS_MCP_SERVER_NAME;
use crate::McpProtocolMode;
+use crate::server::McpCredentialPolicy;
/// Plugin identity retained with an MCP registration for tool attribution.
#[derive(Clone, Debug, PartialEq, Eq)]
@@ -139,20 +142,36 @@ pub struct McpServerRegistration {
name: String,
source: McpServerSource,
config: McpServerConfig,
+ credential_policy: McpCredentialPolicy,
protocol_mode: Option<McpProtocolMode>,
precedence: RegistrationPrecedence,
}
impl McpServerRegistration {
+ /// Registers host-owned configuration, which may resolve credentials on the host.
pub fn from_config(name: String, config: McpServerConfig) -> Self {
Self::new(
name,
McpServerSource::Config,
config,
RegistrationPrecedence::Config,
+ McpCredentialPolicy::HostFallbackAllowed,
)
}
+ /// Registers executor-discovered configuration without authority to read
+ /// host environment credentials.
+ pub fn from_executor_config(name: String, config: McpServerConfig) -> Self {
+ Self::new(
+ name,
+ McpServerSource::Config,
+ config,
+ RegistrationPrecedence::Config,
+ McpCredentialPolicy::ExecutorOnly,
+ )
+ }
+
+ /// Registers a plugin discovered by the host's process-wide plugin manager.
pub fn from_plugin(
name: String,
attribution: McpPluginAttribution,
@@ -164,21 +183,34 @@ impl McpServerRegistration {
McpServerSource::Plugin(attribution),
config,
RegistrationPrecedence::Plugin(Reverse(plugin_order)),
+ McpCredentialPolicy::HostFallbackAllowed,
)
}
/// Registers a thread-selected plugin above discovered plugins and below config.
+ /// HTTP credential authority comes from the selected root, not the server's execution environment.
pub fn from_selected_plugin(
name: String,
attribution: McpPluginAttribution,
selection_order: usize,
+ source_environment_id: &str,
config: McpServerConfig,
) -> Self {
+ let credential_policy = if source_environment_id != DEFAULT_MCP_SERVER_ENVIRONMENT_ID
+ && matches!(
+ &config.transport,
+ McpServerTransportConfig::StreamableHttp { .. }
+ ) {
+ McpCredentialPolicy::ExecutorOnly
+ } else {
+ McpCredentialPolicy::HostFallbackAllowed
+ };
Self::new(
name,
McpServerSource::SelectedPlugin(attribution),
config,
RegistrationPrecedence::SelectedPlugin(Reverse(selection_order)),
+ credential_policy,
)
}
@@ -192,6 +224,7 @@ impl McpServerRegistration {
McpServerSource::Compatibility { id: id.into() },
config,
RegistrationPrecedence::Compatibility,
+ McpCredentialPolicy::HostFallbackAllowed,
)
}
@@ -209,6 +242,7 @@ impl McpServerRegistration {
},
config,
RegistrationPrecedence::Extension(contribution_order),
+ McpCredentialPolicy::HostFallbackAllowed,
)
}
@@ -233,6 +267,7 @@ impl McpServerRegistration {
},
config,
RegistrationPrecedence::Extension(contribution_order),
+ McpCredentialPolicy::HostFallbackAllowed,
)
}
@@ -241,11 +276,13 @@ impl McpServerRegistration {
source: McpServerSource,
config: McpServerConfig,
precedence: RegistrationPrecedence,
+ credential_policy: McpCredentialPolicy,
) -> Self {
Self {
name,
source,
config,
+ credential_policy,
protocol_mode: None,
precedence,
}
@@ -511,6 +548,7 @@ impl McpCatalogBuilder {
ResolvedMcpServer {
source: registration.source,
config: registration.config,
+ credential_policy: registration.credential_policy,
protocol_mode: registration.protocol_mode,
},
))
@@ -534,6 +572,7 @@ impl McpCatalogBuilder {
pub struct ResolvedMcpServer {
source: McpServerSource,
config: McpServerConfig,
+ credential_policy: McpCredentialPolicy,
protocol_mode: Option<McpProtocolMode>,
}
@@ -546,6 +585,10 @@ impl ResolvedMcpServer {
&self.config
}
+ pub(crate) fn credential_policy(&self) -> McpCredentialPolicy {
+ self.credential_policy
+ }
+
pub fn protocol_mode(&self) -> Option<McpProtocolMode> {
self.protocol_mode
}
@@ -592,17 +635,23 @@ impl ResolvedMcpCatalog {
/// Replaces the resolved server set while preserving known sources and EMA policy.
///
- /// Names not present in the existing catalog are treated as config-owned.
+ /// # Panics
+ ///
+ /// Panics if a materialized server is missing from the catalog.
pub fn with_materialized_servers(&self, servers: HashMap<String, McpServerConfig>) -> Self {
let mut builder = McpCatalogBuilder {
ema_idp: self.ema_idp.clone(),
..Default::default()
};
for (name, config) in servers {
- let previous = self.server(&name);
- let source = previous
- .map(|server| server.source.clone())
- .unwrap_or(McpServerSource::Config);
+ #[expect(
+ clippy::expect_used,
+ reason = "materialized servers must have catalog registrations"
+ )]
+ let previous = self
+ .server(&name)
+ .expect("materialized MCP server must have a catalog registration");
+ let source = previous.source.clone();
let precedence = match &source {
McpServerSource::Plugin(_) => RegistrationPrecedence::Plugin(Reverse(0)),
McpServerSource::SelectedPlugin(_) => {
@@ -612,8 +661,10 @@ impl ResolvedMcpCatalog {
McpServerSource::Compatibility { .. } => RegistrationPrecedence::Compatibility,
McpServerSource::Extension { .. } => RegistrationPrecedence::Extension(0),
};
- let mut registration = McpServerRegistration::new(name, source, config, precedence);
- registration.protocol_mode = previous.and_then(ResolvedMcpServer::protocol_mode);
+ let credential_policy = previous.credential_policy();
+ let mut registration =
+ McpServerRegistration::new(name, source, config, precedence, credential_policy);
+ registration.protocol_mode = previous.protocol_mode();
builder.register(registration);
}
builder.build()
diff --git a/codex-rs/codex-mcp/src/catalog_tests.rs b/codex-rs/codex-mcp/src/catalog_tests.rs
index c9a1bc6706..ed791c4963 100644
--- a/codex-rs/codex-mcp/src/catalog_tests.rs
+++ b/codex-rs/codex-mcp/src/catalog_tests.rs
@@ -18,6 +18,7 @@ use pretty_assertions::assert_eq;
use crate::CODEX_APPS_MCP_SERVER_NAME;
use crate::McpProtocolMode;
+use crate::server::McpCredentialPolicy;
use super::McpEnvironmentAuthority;
use super::McpPluginAttribution;
@@ -95,6 +96,107 @@ fn remove(source: McpServerSource) -> McpServerConflictAction {
McpServerConflictAction::Remove(source)
}
+#[test]
+fn executor_credential_policy_survives_catalog_rebuilds_and_materialization() {
+ let mut config = server("https://executor.example/mcp");
+ config.environment_id = "remote".to_string();
+ let mut executor = ResolvedMcpCatalog::builder();
+ executor.register(McpServerRegistration::from_executor_config(
+ "docs".to_string(),
+ config.clone(),
+ ));
+ let executor = executor.build();
+ let mut host = ResolvedMcpCatalog::builder();
+ host.register(McpServerRegistration::from_config(
+ "docs".to_string(),
+ config,
+ ));
+ let host = host.build();
+
+ for catalog in [
+ executor.to_builder().build(),
+ executor.with_materialized_servers(executor.configured_servers()),
+ ] {
+ assert_eq!(
+ catalog.server("docs").unwrap(),
+ executor.server("docs").unwrap(),
+ );
+ assert_eq!(
+ catalog.server("docs").unwrap().credential_policy(),
+ McpCredentialPolicy::ExecutorOnly,
+ );
+ assert!(!catalog.has_same_servers(&host));
+ }
+ assert_eq!(
+ host.server("docs").unwrap().credential_policy(),
+ McpCredentialPolicy::HostFallbackAllowed,
+ );
+}
+
+#[test]
+#[should_panic(expected = "materialized MCP server must have a catalog registration")]
+fn materialized_server_requires_catalog_registration() {
+ let catalog = ResolvedMcpCatalog::default();
+ let server: McpServerConfig = serde_json::from_value(serde_json::json!({
+ "url": "https://executor.example/mcp",
+ "environment_id": "remote",
+ "bearer_token_env_var": "MCP_EXECUTOR_CREDENTIAL_CANARY",
+ }))
+ .expect("valid MCP server config");
+
+ catalog.with_materialized_servers(HashMap::from([("unregistered".to_string(), server)]));
+}
+
+#[test]
+fn selected_plugin_credential_policy_follows_origin_and_survives_catalog_rebuild() {
+ let mut remote_stdio: McpServerConfig =
+ serde_json::from_value(serde_json::json!({ "command": "remote-server" }))
+ .expect("valid stdio server");
+ remote_stdio.environment_id = "executor-1".to_string();
+ let mut remote_destination = server("https://executor.example/mcp");
+ remote_destination.environment_id = "executor-1".to_string();
+
+ for (source_environment_id, config, expected_policy) in [
+ (
+ "executor-1",
+ server("https://executor.example/mcp"),
+ McpCredentialPolicy::ExecutorOnly,
+ ),
+ (
+ DEFAULT_MCP_SERVER_ENVIRONMENT_ID,
+ remote_destination,
+ McpCredentialPolicy::HostFallbackAllowed,
+ ),
+ (
+ "executor-1",
+ remote_stdio,
+ McpCredentialPolicy::HostFallbackAllowed,
+ ),
+ ] {
+ let mut builder = ResolvedMcpCatalog::builder();
+ builder.register(McpServerRegistration::from_selected_plugin(
+ "docs".to_string(),
+ plugin("selected-root"),
+ /*selection_order*/ 0,
+ source_environment_id,
+ config,
+ ));
+ let catalog = builder.build();
+ for rebuilt in [
+ catalog.to_builder().build(),
+ catalog.with_materialized_servers(catalog.configured_servers()),
+ ] {
+ let registration = rebuilt.server("docs").unwrap();
+ assert_eq!(
+ registration.source(),
+ &selected_plugin_source("selected-root")
+ );
+ assert_eq!(registration.credential_policy(), expected_policy);
+ assert_eq!(registration, catalog.server("docs").unwrap());
+ }
+ }
+}
+
#[test]
fn plugin_host_root_is_retained_in_catalog_identity() {
let original_root = PathUri::parse("file:///plugins/original").expect("valid plugin root URI");
@@ -246,6 +348,7 @@ fn rejected_plugin_ema_registration_does_not_veto_hosted_apps() {
host_owned_apps: true,
},
config: expected,
+ credential_policy: McpCredentialPolicy::HostFallbackAllowed,
protocol_mode: None,
}),
);
@@ -363,6 +466,7 @@ fn disabled_winner_remains_a_veto_when_the_catalog_is_extended() {
Some(&super::ResolvedMcpServer {
source: extension_source("hosted"),
config: expected,
+ credential_policy: McpCredentialPolicy::HostFallbackAllowed,
protocol_mode: None,
})
);
@@ -396,6 +500,7 @@ fn disabled_discovered_plugin_remains_a_veto_for_runtime_overlays() {
Some(&super::ResolvedMcpServer {
source: extension_source("hosted"),
config: expected,
+ credential_policy: McpCredentialPolicy::HostFallbackAllowed,
protocol_mode: None,
})
);
@@ -453,12 +558,14 @@ fn selected_plugins_override_discovered_plugins_but_not_config() {
"docs".to_string(),
plugin("selected-beta"),
/*selection_order*/ 1,
+ DEFAULT_MCP_SERVER_ENVIRONMENT_ID,
server("https://selected-beta.example/mcp"),
));
builder.register(McpServerRegistration::from_selected_plugin(
"docs".to_string(),
plugin("selected-alpha"),
/*selection_order*/ 0,
+ DEFAULT_MCP_SERVER_ENVIRONMENT_ID,
selected.clone(),
));
@@ -469,6 +576,7 @@ fn selected_plugins_override_discovered_plugins_but_not_config() {
Some(&super::ResolvedMcpServer {
source: selected_plugin_source("selected-alpha"),
config: selected,
+ credential_policy: McpCredentialPolicy::HostFallbackAllowed,
protocol_mode: None,
})
);
@@ -496,6 +604,7 @@ fn selected_plugins_override_discovered_plugins_but_not_config() {
Some(&super::ResolvedMcpServer {
source: selected_plugin_source("selected-alpha"),
config: refreshed,
+ credential_policy: McpCredentialPolicy::HostFallbackAllowed,
protocol_mode: None,
})
);
@@ -513,6 +622,7 @@ fn selected_plugins_override_discovered_plugins_but_not_config() {
Some(&super::ResolvedMcpServer {
source: McpServerSource::Config,
config: configured,
+ credential_policy: McpCredentialPolicy::HostFallbackAllowed,
protocol_mode: None,
})
);
@@ -528,6 +638,7 @@ fn disabled_selected_plugin_does_not_veto_runtime_overlays() {
"docs".to_string(),
plugin("selected"),
/*selection_order*/ 0,
+ DEFAULT_MCP_SERVER_ENVIRONMENT_ID,
disabled,
));
let mut builder = builder.build().to_builder();
@@ -545,6 +656,7 @@ fn disabled_selected_plugin_does_not_veto_runtime_overlays() {
Some(&super::ResolvedMcpServer {
source: extension_source("hosted"),
config: extension,
+ credential_policy: McpCredentialPolicy::HostFallbackAllowed,
protocol_mode: None,
})
);
@@ -571,6 +683,7 @@ fn equal_precedence_uses_insertion_order_not_source_identity() {
Some(&super::ResolvedMcpServer {
source: compatibility_source("a-second"),
config: server("https://second.example/mcp"),
+ credential_policy: McpCredentialPolicy::HostFallbackAllowed,
protocol_mode: None,
})
);
@@ -642,6 +755,7 @@ fn extension_protocol_mode_follows_the_winner_through_materialization() {
Some(&ResolvedMcpServer {
source: extension_source("winner"),
config: refreshed,
+ credential_policy: McpCredentialPolicy::HostFallbackAllowed,
protocol_mode: Some(McpProtocolMode::Legacy),
})
);
@@ -694,6 +808,7 @@ fn environment_policy_preserves_selected_plugin_and_empty_server_allowlist_seman
"selected".to_string(),
plugin("selected-plugin"),
/*selection_order*/ 0,
+ DEFAULT_MCP_SERVER_ENVIRONMENT_ID,
server("https://plugin.example/mcp"),
));
let metadata_only_policy = EnvironmentMcpPolicy {
diff --git a/codex-rs/codex-mcp/src/connection_manager_tests.rs b/codex-rs/codex-mcp/src/connection_manager_tests.rs
index ff1494db3c..cbf368936c 100644
--- a/codex-rs/codex-mcp/src/connection_manager_tests.rs
+++ b/codex-rs/codex-mcp/src/connection_manager_tests.rs
@@ -2034,7 +2034,7 @@ async fn read_only_apps_discovery_never_uses_a_shared_writable_catalog() -> anyh
ready_selected_capability_roots: Vec::new(),
mcp_servers: HashMap::from([(
CODEX_APPS_MCP_SERVER_NAME.to_string(),
- EffectiveMcpServer::configured(server_config.clone()),
+ EffectiveMcpServer::from_host_config(server_config.clone()),
)]),
submit_id: "test".to_string(),
tx_event: None,
@@ -2108,11 +2108,11 @@ async fn hosted_apps_protocol_mode_is_independent_of_generic_mode() -> anyhow::R
mcp_servers: HashMap::from([
(
CODEX_APPS_MCP_SERVER_NAME.to_string(),
- EffectiveMcpServer::configured(server_config.clone()),
+ EffectiveMcpServer::from_host_config(server_config.clone()),
),
(
"third_party".to_string(),
- EffectiveMcpServer::configured(server_config.clone()),
+ EffectiveMcpServer::from_host_config(server_config.clone()),
),
]),
submit_id: "protocol-mode-scope".to_string(),
@@ -2213,7 +2213,7 @@ async fn codex_apps_extension_does_not_share_host_owned_tools_cache() -> anyhow:
ready_selected_capability_roots: Vec::new(),
mcp_servers: HashMap::from([(
CODEX_APPS_MCP_SERVER_NAME.to_string(),
- EffectiveMcpServer::configured(server_config.clone()),
+ EffectiveMcpServer::from_host_config(server_config.clone()),
)]),
submit_id: "cache-ownership-test".to_string(),
tx_event: None,
@@ -2890,6 +2890,7 @@ async fn capture_binding_skips_pending_optional_servers_after_configured_shared_
"pending-selected".to_string(),
crate::McpPluginAttribution::new("selected-plugin".to_string(), "Selected".to_string()),
/*selection_order*/ 0,
+ codex_config::DEFAULT_MCP_SERVER_ENVIRONMENT_ID,
serde_json::from_value(serde_json::json!({ "command": "selected-plugin" }))
.expect("selected plugin MCP config"),
));
@@ -4385,7 +4386,7 @@ fn server_metadata_preserves_tool_approval_policy() {
..Default::default()
},
);
- let metadata = McpServerMetadata::from(&EffectiveMcpServer::configured(config));
+ let metadata = McpServerMetadata::from(&EffectiveMcpServer::from_host_config(config));
assert_eq!(metadata.environment_id, "remote");
assert_eq!(metadata.tool_approval_mode("read"), AppToolApproval::Prompt);
@@ -4416,7 +4417,7 @@ fn hosted_actor_credentials_are_only_available_to_host_owned_mcp_servers() {
);
local_config.auth = McpServerAuth::ChatGpt;
- let local_server = EffectiveMcpServer::configured(local_config.clone());
+ let local_server = EffectiveMcpServer::from_host_config(local_config.clone());
let local_provider =
chatgpt_auth_provider_for_server(&local_server, Some(Arc::clone(&provider)))
.expect("host-owned Codex Apps must retain hosted authentication");
@@ -4430,7 +4431,7 @@ fn hosted_actor_credentials_are_only_available_to_host_owned_mcp_servers() {
let mut remote_config = local_config;
remote_config.environment_id = "customer-executor".to_string();
- let remote_server = EffectiveMcpServer::configured(remote_config);
+ let remote_server = EffectiveMcpServer::from_host_config(remote_config);
assert!(
chatgpt_auth_provider_for_server(&remote_server, Some(provider)).is_none(),
"customer-owned executors must never receive hosted actor credentials"
@@ -4531,6 +4532,13 @@ async fn executor_owned_chatgpt_mcp_accepts_only_safe_explicit_authorization() -
server_json["env_http_headers"] = serde_json::json!({ name: value });
}
let server_config = serde_json::from_value::<McpServerConfig>(server_json)?;
+ let mut runtime_config = runtime_config.clone();
+ let mut catalog = crate::ResolvedMcpCatalog::builder();
+ catalog.register(crate::McpServerRegistration::from_config(
+ "fake-first-party".to_string(),
+ server_config.clone(),
+ ));
+ runtime_config.mcp_server_catalog = catalog.build();
let mcp_servers = crate::effective_mcp_servers_from_configured(
HashMap::from([("fake-first-party".to_string(), server_config)]),
&runtime_config,
@@ -4657,7 +4665,7 @@ async fn no_local_runtime_fails_local_stdio_but_keeps_local_http_server() {
let mcp_servers = HashMap::from([
(
"stdio".to_string(),
- EffectiveMcpServer::configured(McpServerConfig {
+ EffectiveMcpServer::from_host_config(McpServerConfig {
auth: Default::default(),
transport: McpServerTransportConfig::Stdio {
command: "echo".to_string(),
@@ -4687,7 +4695,7 @@ async fn no_local_runtime_fails_local_stdio_but_keeps_local_http_server() {
),
(
"http".to_string(),
- EffectiveMcpServer::configured(McpServerConfig {
+ EffectiveMcpServer::from_host_config(McpServerConfig {
auth: Default::default(),
transport: McpServerTransportConfig::StreamableHttp {
url: "http://127.0.0.1:1".to_string(),
@@ -5084,7 +5092,7 @@ fn reusable_server_identity(
config: &McpServerConfig,
runtime_context: &McpRuntimeContext,
) -> McpServerConnectionIdentity {
- let server = EffectiveMcpServer::configured(config.clone());
+ let server = EffectiveMcpServer::from_host_config(config.clone());
let resolved_environment = runtime_context.resolve_server_environment(server_name, config);
McpServerConnectionIdentity::new(
server_name,
@@ -5116,7 +5124,7 @@ async fn manager_with_reusable_ready_server(
&permission_profile,
/*prefix_mcp_tool_names*/ true,
);
- let server = EffectiveMcpServer::configured(config.clone());
+ let server = EffectiveMcpServer::from_host_config(config.clone());
manager.servers.insert(
"docs".to_string(),
McpServerView {
@@ -5174,7 +5182,7 @@ async fn reconcile_reusable_server_with_mcp_config(
ready_selected_capability_roots: Vec::new(),
mcp_servers: HashMap::from([(
server_name.to_string(),
- EffectiveMcpServer::configured(config),
+ EffectiveMcpServer::from_host_config(config),
)]),
submit_id: "refresh".to_string(),
tx_event: Some(tx_event),
@@ -5542,7 +5550,7 @@ async fn reconciliation_reuses_connection_without_relisting_regular_tools() -> a
&permission_profile,
/*prefix_mcp_tool_names*/ true,
);
- let server = EffectiveMcpServer::configured(config.clone());
+ let server = EffectiveMcpServer::from_host_config(config.clone());
previous.servers.insert(
"docs".to_string(),
McpServerView {
@@ -5767,7 +5775,7 @@ fn connection_identity_tracks_only_oauth_credentials_when_oauth_is_active() {
assert!(!debug.contains("new-secret"));
McpServerConnectionIdentity::new(
"docs",
- &EffectiveMcpServer::configured(config),
+ &EffectiveMcpServer::from_host_config(config),
/*host_plugin_root*/ None,
OAuthCredentialsStoreMode::File,
AuthKeyringBackendKind::Direct,
@@ -5845,7 +5853,7 @@ fn connection_identity_uses_effective_authorization_headers() {
.map(|value| HashMap::from([("aUtHoRiZaTiOn".to_string(), value.to_string())])),
http_headers_helper: None,
};
- let server = EffectiveMcpServer::configured(config);
+ let server = EffectiveMcpServer::from_host_config(config);
let identity = |keyring_backend_kind, oauth_refresh_mode| {
McpServerConnectionIdentity::new(
"docs",
@@ -5928,6 +5936,13 @@ async fn reconciliation_replaces_connection_when_auth_mode_changes() -> anyhow::
let mut config = reusable_server_config("https://chatgpt.com/backend-api/ps/mcp");
config.environment_id = "customer-executor".to_string();
config.auth = auth;
+ let mut mcp_config = mcp_config.clone();
+ let mut catalog = crate::ResolvedMcpCatalog::builder();
+ catalog.register(crate::McpServerRegistration::from_config(
+ "docs".to_string(),
+ config.clone(),
+ ));
+ mcp_config.mcp_server_catalog = catalog.build();
crate::effective_mcp_servers_from_configured(
HashMap::from([("docs".to_string(), config)]),
&mcp_config,
@@ -5999,7 +6014,7 @@ async fn reconciliation_replaces_connection_when_protocol_mode_changes() {
ready_selected_capability_roots: Vec::new(),
mcp_servers: HashMap::from([(
"docs".to_string(),
- EffectiveMcpServer::configured(config),
+ EffectiveMcpServer::from_host_config(config),
)]),
submit_id: "refresh".to_string(),
tx_event: None,
@@ -6057,7 +6072,7 @@ async fn reconciliation_reuses_legacy_stdio_server_when_modern_protocol_is_enabl
ready_selected_capability_roots: Vec::new(),
mcp_servers: HashMap::from([(
"docs".to_string(),
- EffectiveMcpServer::configured(config),
+ EffectiveMcpServer::from_host_config(config),
)]),
submit_id: "refresh".to_string(),
tx_event: None,
@@ -6316,7 +6331,7 @@ async fn reconciliation_reconnects_when_host_plugin_root_changes() {
vec![create_test_tool("docs", "search")],
)
.await;
- let server = EffectiveMcpServer::configured(server_config.clone());
+ let server = EffectiveMcpServer::from_host_config(server_config.clone());
let resolved_environment = runtime_context.resolve_server_environment("docs", &server_config);
let original_identity = McpServerConnectionIdentity::new(
"docs",
@@ -6385,7 +6400,7 @@ async fn reconciliation_reconnects_when_host_plugin_root_changes() {
async fn connection_identity_distinguishes_accounts_with_the_same_token() -> anyhow::Result<()> {
let runtime_context = reusable_server_runtime_context();
let config = reusable_server_config("http://127.0.0.1:1");
- let server = EffectiveMcpServer::configured(config);
+ let server = EffectiveMcpServer::from_host_config(config);
let access_token = "header.e30.same";
let previous_auth = CodexAuth::from_external_chatgpt_tokens(
access_token,
@@ -6430,7 +6445,7 @@ async fn connection_identity_distinguishes_accounts_with_the_same_token() -> any
async fn connection_identity_distinguishes_agent_account_runtime_and_task() -> anyhow::Result<()> {
let runtime_context = reusable_server_runtime_context();
let config = reusable_server_config("http://127.0.0.1:1");
- let server = EffectiveMcpServer::configured(config);
+ let server = EffectiveMcpServer::from_host_config(config);
let record = codex_login::auth::AgentIdentityAuthRecord {
agent_runtime_id: "agent-a".to_string(),
agent_private_key: "MC4CAQAwBQYDK2VwBCIEIJ7kFBaOujmoz1gvBNEC+BeM2IX87FFB0xmISOZ/XO0c"
diff --git a/codex-rs/codex-mcp/src/mcp/mod.rs b/codex-rs/codex-mcp/src/mcp/mod.rs
index 0830a1a56b..7dfd637c23 100644
--- a/codex-rs/codex-mcp/src/mcp/mod.rs
+++ b/codex-rs/codex-mcp/src/mcp/mod.rs
@@ -390,6 +390,10 @@ fn is_trusted_chatgpt_mcp_server(
///
/// Compatibility built-ins and extension overlays must already be reflected in
/// `configured_servers`; this function does not synthesize missing servers.
+///
+/// # Panics
+///
+/// Panics if a materialized server is missing from the catalog.
pub fn effective_mcp_servers_from_configured(
configured_servers: HashMap<String, McpServerConfig>,
config: &McpConfig,
@@ -398,6 +402,14 @@ pub fn effective_mcp_servers_from_configured(
let mut servers = configured_servers
.into_iter()
.map(|(name, mut server)| {
+ #[expect(
+ clippy::expect_used,
+ reason = "materialized servers must have catalog registrations"
+ )]
+ let registration = config
+ .mcp_server_catalog
+ .server(&name)
+ .expect("materialized MCP server must have a catalog registration");
match server.auth.clone() {
McpServerAuth::ChatGpt => {
if !is_trusted_chatgpt_mcp_server(&server.transport, &config.chatgpt_base_url) {
@@ -406,13 +418,13 @@ pub fn effective_mcp_servers_from_configured(
}
McpServerAuth::OAuth | McpServerAuth::EmaAuth => {}
}
- let agent_plugin = config
- .mcp_server_catalog
- .server(&name)
- .is_some_and(|server| server.source().is_agent_plugin());
(
name,
- EffectiveMcpServer::configured(server).with_agent_plugin(agent_plugin),
+ EffectiveMcpServer::from_config_with_policy(
+ server,
+ registration.credential_policy(),
+ )
+ .with_agent_plugin(registration.source().is_agent_plugin()),
)
})
.collect::<HashMap<_, _>>();
diff --git a/codex-rs/codex-mcp/src/mcp/mod_tests.rs b/codex-rs/codex-mcp/src/mcp/mod_tests.rs
index 50e7cedc33..c90d39eb68 100644
--- a/codex-rs/codex-mcp/src/mcp/mod_tests.rs
+++ b/codex-rs/codex-mcp/src/mcp/mod_tests.rs
@@ -4,6 +4,7 @@ use crate::McpServerRegistration;
use crate::connection_manager::tests::create_ready_async_managed_client;
use crate::mcp::auth::McpAuthStatusEntry;
use crate::rmcp_client::StartupOutcomeError;
+use crate::server::McpCredentialPolicy;
use codex_config::Constrained;
use codex_config::types::AppToolApproval;
use codex_config::types::AuthKeyringBackendKind;
@@ -152,6 +153,7 @@ fn ema_catalog_supports_configured_installed_and_selected_plugins_without_wideni
"selected".into(),
plugin,
/*selection_order*/ 0,
+ codex_config::DEFAULT_MCP_SERVER_ENVIRONMENT_ID,
server,
));
let mut config = test_mcp_config(PathBuf::new());
@@ -216,6 +218,7 @@ fn mcp_server_permissions_handle_unattached_and_threadless_servers() {
"selected".to_string(),
McpPluginAttribution::new("selected@test".to_string(), "Selected".to_string()),
/*selection_order*/ 0,
+ codex_config::DEFAULT_MCP_SERVER_ENVIRONMENT_ID,
selected_server,
));
config.mcp_server_catalog = catalog.build();
@@ -394,6 +397,7 @@ fn selected_mcp_attribution_does_not_join_an_unrelated_local_summary() {
"Executor GitHub".to_string(),
),
/*selection_order*/ 0,
+ "executor-1",
codex_apps_mcp_server_config(
"https://github.example",
/*apps_mcp_product_sku*/ None,
@@ -551,6 +555,55 @@ fn codex_apps_server_config_forwards_originator_and_configured_product_sku_heade
}
}
+#[test]
+fn effective_mcp_servers_preserve_executor_credential_policy() {
+ let mut config = test_mcp_config(PathBuf::new());
+ let server: McpServerConfig = serde_json::from_value(serde_json::json!({
+ "url": "https://executor.example/mcp",
+ "environment_id": "remote",
+ "bearer_token_env_var": "MCP_EXECUTOR_CREDENTIAL_CANARY",
+ }))
+ .expect("valid MCP server config");
+ let mut catalog = ResolvedMcpCatalog::builder();
+ catalog.register(McpServerRegistration::from_executor_config(
+ "executor".to_string(),
+ server.clone(),
+ ));
+ catalog.register(McpServerRegistration::from_config(
+ "host".to_string(),
+ server,
+ ));
+ config.mcp_server_catalog = catalog.build();
+ let effective = effective_mcp_servers(&config, /*auth*/ None);
+
+ assert_eq!(
+ effective["executor"].credential_policy(),
+ McpCredentialPolicy::ExecutorOnly,
+ );
+ assert_eq!(
+ effective["host"].credential_policy(),
+ McpCredentialPolicy::HostFallbackAllowed,
+ );
+}
+
+#[test]
+#[should_panic(expected = "materialized MCP server must have a catalog registration")]
+fn effective_mcp_servers_require_catalog_registration() {
+ let config = test_mcp_config(PathBuf::new());
+ let server: McpServerConfig = serde_json::from_value(serde_json::json!({
+ "url": "https://executor.example/mcp",
+ "environment_id": "remote",
+ "bearer_token_env_var": "MCP_EXECUTOR_CREDENTIAL_CANARY",
+ }))
+ .expect("valid MCP server config");
+
+ effective_mcp_servers_from_configured(
+ HashMap::from([("unregistered".to_string(), server)]),
+ &config,
+ /*auth*/ None,
+ );
+}
+
#[test]
fn effective_mcp_servers_preserve_chatgpt_auth_for_staging() {
for url in [
@@ -562,6 +615,12 @@ fn effective_mcp_servers_preserve_chatgpt_auth_for_staging() {
let server = codex_apps_mcp_server_config(
url, /*apps_mcp_product_sku*/ None, /*originator*/ None,
);
+ let mut catalog = ResolvedMcpCatalog::builder();
+ catalog.register(McpServerRegistration::from_config(
+ "staging".to_string(),
+ server.clone(),
+ ));
+ config.mcp_server_catalog = catalog.build();
let configured = HashMap::from([("staging".to_string(), server)]);
let effective =
effective_mcp_servers_from_configured(configured, &config, /*auth*/ None);
diff --git a/codex-rs/codex-mcp/src/rmcp_client.rs b/codex-rs/codex-mcp/src/rmcp_client.rs
index 2844a61979..f40ca17224 100644
--- a/codex-rs/codex-mcp/src/rmcp_client.rs
+++ b/codex-rs/codex-mcp/src/rmcp_client.rs
@@ -4,6 +4,7 @@
//! initializing the server, listing raw tools, applying per-server tool filters,
//! and exposing cached Codex Apps tools while a client is still connecting.
//! Initialization capabilities survive tool-discovery failures and reset on a new attempt.
+//! Executor-discovered environment credentials remain executor-bound across those attempts.
//! Higher-level aggregation and resource/tool APIs live in
//! [`crate::connection_manager`].
@@ -36,6 +37,7 @@ use crate::pagination::collect_paginated_with_limit;
use crate::runtime::McpRuntimeContext;
use crate::runtime::emit_duration;
use crate::server::EffectiveMcpServer;
+use crate::server::McpCredentialPolicy;
use crate::server::has_explicit_http_authorization;
use crate::tool_catalog_cache::McpToolCatalogCacheContext;
use crate::tool_catalog_cache::McpToolCatalogFetchTicket;
@@ -870,11 +872,18 @@ fn is_untrusted_connector_meta_key(key: &str) -> bool {
fn resolve_bearer_token(
server_name: &str,
bearer_token_env_var: Option<&str>,
+ credential_policy: McpCredentialPolicy,
) -> Result<Option<String>> {
let Some(env_var) = bearer_token_env_var else {
return Ok(None);
};
+ if credential_policy == McpCredentialPolicy::ExecutorOnly {
+ return Err(anyhow!(
+ "MCP server '{server_name}' requires executor-side environment credential resolution; update the executor to a version that supports it (host fallback is disabled)"
+ ));
+ }
+
match env::var(env_var) {
Ok(value) => {
if value.is_empty() {
@@ -1167,6 +1176,23 @@ pub(crate) async fn make_rmcp_client(
protocol_mode: McpProtocolMode,
) -> Result<RmcpClient, StartupOutcomeError> {
let config = server.config().clone();
+ if server.credential_policy() == McpCredentialPolicy::ExecutorOnly {
+ // Executor HTTP declarations cannot acquire host header helpers through
+ // cached registration materialization.
+ let valid_transport = matches!(
+ &config.transport,
+ McpServerTransportConfig::StreamableHttp {
+ env_http_headers,
+ http_headers_helper: None,
+ ..
+ } if env_http_headers.as_ref().is_none_or(HashMap::is_empty)
+ );
+ if config.is_local_environment() || !valid_transport {
+ return Err(StartupOutcomeError::from(anyhow!(
+ "executor-discovered MCP server '{server_name}' requires a remote HTTP transport without host environment headers or helpers"
+ )));
+ }
+ }
if matches!(config.auth, McpServerAuth::EmaAuth) {
return Err(StartupOutcomeError::from(anyhow!(
"EMA MCP connections are not enabled in this version"
@@ -1271,9 +1297,13 @@ pub(crate) async fn make_rmcp_client(
Some(StreamableHttpBearerToken::ProvidedByHttpClient),
)
} else {
- let token = resolve_bearer_token(server_name, bearer_token_env_var.as_deref())
- .map_err(StartupOutcomeError::from)?
- .map(StreamableHttpBearerToken::Resolved);
+ let token = resolve_bearer_token(
+ server_name,
+ bearer_token_env_var.as_deref(),
+ server.credential_policy(),
+ )
+ .map_err(StartupOutcomeError::from)?
+ .map(StreamableHttpBearerToken::Resolved);
(http_client, token)
};
let redirect_mode = if server.is_agent_plugin() {
@@ -1476,3 +1506,7 @@ mod tests {
);
}
}
+
+#[cfg(test)]
+#[path = "rmcp_client_credential_policy_tests.rs"]
+mod credential_policy_tests;
diff --git a/codex-rs/codex-mcp/src/rmcp_client_credential_policy_tests.rs b/codex-rs/codex-mcp/src/rmcp_client_credential_policy_tests.rs
new file mode 100644
index 0000000000..09f922eeaf
--- /dev/null
+++ b/codex-rs/codex-mcp/src/rmcp_client_credential_policy_tests.rs
@@ -0,0 +1,59 @@
+//! Credential resolution must retain executor provenance when host fallback is considered.
+
+use super::resolve_bearer_token;
+use crate::server::McpCredentialPolicy;
+use pretty_assertions::assert_eq;
+
+#[test]
+fn executor_credentials_reject_host_fallback_for_arbitrary_environment_names() {
+ for env_var in ["PATH", "MCP_UNPROTECTED_TEST_TOKEN"] {
+ let error = resolve_bearer_token("docs", Some(env_var), McpCredentialPolicy::ExecutorOnly)
+ .expect_err("executor credential names must never resolve on the host");
+
+ assert_eq!(
+ error.to_string(),
+ "MCP server 'docs' requires executor-side environment credential resolution; update the executor to a version that supports it (host fallback is disabled)",
+ );
+ }
+}
+
+#[test]
+fn servers_without_environment_credentials_do_not_require_host_fallback() {
+ for policy in [
+ McpCredentialPolicy::ExecutorOnly,
+ McpCredentialPolicy::HostFallbackAllowed,
+ ] {
+ assert_eq!(
+ resolve_bearer_token("docs", /*bearer_token_env_var*/ None, policy)
+ .expect("a server without an environment credential needs no resolution"),
+ None,
+ );
+ }
+}
+
+#[test]
+fn configured_credentials_retain_host_environment_resolution() {
+ // PATH is nonsecret and read without changing the process environment.
+ let expected = match std::env::var("PATH") {
+ Ok(value) if value.is_empty() => {
+ Err("Environment variable PATH for MCP server 'docs' is empty".to_string())
+ }
+ Ok(value) => Ok(Some(value)),
+ Err(std::env::VarError::NotPresent) => {
+ Err("Environment variable PATH for MCP server 'docs' is not set".to_string())
+ }
+ Err(std::env::VarError::NotUnicode(_)) => Err(
+ "Environment variable PATH for MCP server 'docs' contains invalid Unicode".to_string(),
+ ),
+ };
+
+ assert_eq!(
+ resolve_bearer_token(
+ "docs",
+ Some("PATH"),
+ McpCredentialPolicy::HostFallbackAllowed
+ )
+ .map_err(|error| error.to_string()),
+ expected,
+ );
+}
diff --git a/codex-rs/codex-mcp/src/server.rs b/codex-rs/codex-mcp/src/server.rs
index d052418957..df532ee1ea 100644
--- a/codex-rs/codex-mcp/src/server.rs
+++ b/codex-rs/codex-mcp/src/server.rs
@@ -23,23 +23,47 @@ use codex_utils_path_uri::PathUri;
use rmcp::model::ElicitationCapability;
use tracing::warn;
+/// Authority to resolve environment-variable credentials, retained independently of
+/// executor capabilities so a reconnect cannot promote guest configuration to host access.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
+pub(crate) enum McpCredentialPolicy {
+ /// Host-configured servers retain local and legacy remote credential resolution.
+ HostFallbackAllowed,
+ /// Executor-discovered names must never be looked up in the host environment.
+ ExecutorOnly,
+}
+
/// MCP server after runtime additions have been applied.
#[derive(Debug, Clone)]
pub struct EffectiveMcpServer {
config: McpServerConfig,
+ credential_policy: McpCredentialPolicy,
agent_plugin: bool,
requires_read_only_mcp_tools: bool,
}
impl EffectiveMcpServer {
- pub fn configured(config: McpServerConfig) -> Self {
+ /// Constructs an effective server from host-owned configuration.
+ pub fn from_host_config(config: McpServerConfig) -> Self {
+ Self::from_config_with_policy(config, McpCredentialPolicy::HostFallbackAllowed)
+ }
+
+ pub(crate) fn from_config_with_policy(
+ config: McpServerConfig,
+ credential_policy: McpCredentialPolicy,
+ ) -> Self {
Self {
config,
+ credential_policy,
agent_plugin: false,
requires_read_only_mcp_tools: false,
}
}
+ pub(crate) fn credential_policy(&self) -> McpCredentialPolicy {
+ self.credential_policy
+ }
+
pub fn with_agent_plugin(mut self, agent_plugin: bool) -> Self {
self.agent_plugin = agent_plugin;
self
@@ -108,6 +132,7 @@ pub(crate) fn has_explicit_http_authorization(config: &McpServerConfig) -> bool
#[derive(Clone)]
pub(crate) struct McpServerConnectionIdentity {
auth: McpServerAuth,
+ pub(crate) credential_policy: McpCredentialPolicy,
transport: McpServerTransportConfig,
environment_id: String,
host_plugin_root: Option<PathUri>,
@@ -168,12 +193,13 @@ impl McpServerConnectionIdentity {
name.eq_ignore_ascii_case("authorization") && valid_http_header_value(value)
})
}) && !env_http_headers.as_ref().is_some_and(|headers| {
- headers.iter().any(|(name, env_var)| {
- name.eq_ignore_ascii_case("authorization")
- && std::env::var(env_var).is_ok_and(|value| {
- !value.trim().is_empty() && valid_http_header_value(&value)
- })
- })
+ server.credential_policy() == McpCredentialPolicy::HostFallbackAllowed
+ && headers.iter().any(|(name, env_var)| {
+ name.eq_ignore_ascii_case("authorization")
+ && std::env::var(env_var).is_ok_and(|value| {
+ !value.trim().is_empty() && valid_http_header_value(&value)
+ })
+ })
}) =>
{
Some(url)
@@ -218,7 +244,10 @@ impl McpServerConnectionIdentity {
}
))
.then(|| runtime_context.local_process_cwd());
- let referenced_environment_variables = referenced_environment_variables(config);
+ let referenced_environment_variables = match server.credential_policy() {
+ McpCredentialPolicy::HostFallbackAllowed => referenced_environment_variables(config),
+ McpCredentialPolicy::ExecutorOnly => Vec::new(),
+ };
let runtime_auth = runtime_auth_provider.and(auth).cloned();
let runtime_auth_token = runtime_auth.as_ref().and_then(|auth| auth.get_token().ok());
let oauth_store_was_contended = oauth_credentials
@@ -229,6 +258,7 @@ impl McpServerConnectionIdentity {
Self {
auth: config.auth.clone(),
+ credential_policy: server.credential_policy(),
transport: config.transport.clone(),
environment_id: config.environment_id.clone(),
host_plugin_root: host_plugin_root.cloned(),
@@ -267,6 +297,7 @@ impl McpServerConnectionIdentity {
(Some(_), None) | (None, Some(_)) => false,
};
self.auth == other.auth
+ && self.credential_policy == other.credential_policy
&& self.transport == other.transport
&& self.environment_id == other.environment_id
&& self.host_plugin_root == other.host_plugin_root
diff --git a/codex-rs/codex-mcp/src/server_tests.rs b/codex-rs/codex-mcp/src/server_tests.rs
index 7365f75573..1cbe2f122e 100644
--- a/codex-rs/codex-mcp/src/server_tests.rs
+++ b/codex-rs/codex-mcp/src/server_tests.rs
@@ -1,7 +1,20 @@
+use super::EffectiveMcpServer;
+use super::McpCredentialPolicy;
+use super::McpServerConnectionIdentity;
use super::referenced_environment_variables;
+use crate::McpProtocolMode;
+use crate::runtime::McpRuntimeContext;
+use crate::tool_catalog_cache::McpToolCatalogCache;
use codex_config::DEFAULT_MCP_SERVER_ENVIRONMENT_ID;
use codex_config::McpServerConfig;
+use codex_config::types::AuthKeyringBackendKind;
+use codex_config::types::OAuthCredentialsStoreMode;
+use codex_exec_server_test_support::environment_manager_without_environments;
+use codex_protocol::mcp::ClientMcpExtensions;
+use codex_rmcp_client::McpOAuthRefreshMode;
use pretty_assertions::assert_eq;
+use rmcp::model::ElicitationCapability;
+use std::sync::Arc;
#[test]
fn remote_http_connections_track_host_headers_but_not_executor_bearer_tokens() {
@@ -41,3 +54,125 @@ fn remote_http_connections_track_host_headers_but_not_executor_bearer_tokens() {
],
);
}
+
+fn runtime_context() -> McpRuntimeContext {
+ McpRuntimeContext::new(
+ Arc::new(environment_manager_without_environments()),
+ std::env::temp_dir(),
+ )
+}
+
+fn connection_identity(
+ server: &EffectiveMcpServer,
+ runtime_context: &McpRuntimeContext,
+) -> McpServerConnectionIdentity {
+ McpServerConnectionIdentity::new(
+ "docs",
+ server,
+ /*host_plugin_root*/ None,
+ OAuthCredentialsStoreMode::default(),
+ AuthKeyringBackendKind::default(),
+ McpOAuthRefreshMode::Legacy,
+ &Ok(None),
+ runtime_context,
+ /*runtime_auth_provider*/ None,
+ /*auth*/ None,
+ /*codex_apps_cache_identity*/ None,
+ ElicitationCapability::default(),
+ ClientMcpExtensions::default(),
+ /*previous_identity*/ None,
+ )
+}
+
+fn explicit_authorization_server() -> EffectiveMcpServer {
+ EffectiveMcpServer::from_host_config(
+ serde_json::from_value(serde_json::json!({
+ "url": "https://example.com/mcp",
+ "environment_id": "executor-1",
+ "http_headers": {"Authorization": "Bearer test-canary"},
+ }))
+ .expect("remote MCP configuration should deserialize"),
+ )
+}
+
+#[test]
+fn connection_identity_does_not_reuse_connections_across_credential_policies() {
+ let runtime_context = runtime_context();
+ let host_server = explicit_authorization_server();
+ let executor_server = EffectiveMcpServer::from_config_with_policy(
+ host_server.config().clone(),
+ McpCredentialPolicy::ExecutorOnly,
+ );
+ let host_identity = connection_identity(&host_server, &runtime_context);
+ let executor_identity = connection_identity(&executor_server, &runtime_context);
+
+ assert!(
+ host_identity
+ .has_same_connection_config(&connection_identity(&host_server, &runtime_context,))
+ );
+ assert!(
+ executor_identity
+ .has_same_connection_config(&connection_identity(&executor_server, &runtime_context,))
+ );
+ assert!(!host_identity.has_same_connection_config(&executor_identity));
+ assert!(!executor_identity.has_same_connection_config(&host_identity));
+}
+
+#[test]
+fn executor_connection_identity_does_not_capture_host_environment_values() {
+ let runtime_context = runtime_context();
+ let host_server = EffectiveMcpServer::from_host_config(
+ serde_json::from_value(serde_json::json!({
+ "url": "https://example.com/mcp",
+ "environment_id": "executor-1",
+ "bearer_token_env_var": "PATH",
+ }))
+ .expect("remote MCP configuration should deserialize"),
+ );
+ let executor_server = EffectiveMcpServer::from_config_with_policy(
+ host_server.config().clone(),
+ McpCredentialPolicy::ExecutorOnly,
+ );
+
+ assert_eq!(
+ connection_identity(&host_server, &runtime_context).referenced_environment_variables,
+ vec![("PATH".to_string(), std::env::var_os("PATH"))],
+ );
+ assert_eq!(
+ connection_identity(&executor_server, &runtime_context).referenced_environment_variables,
+ Vec::new(),
+ );
+}
+
+#[test]
+fn tool_catalog_cache_does_not_reuse_catalogs_across_credential_policies() {
+ let runtime_context = runtime_context();
+ let host_server = explicit_authorization_server();
+ let executor_server = EffectiveMcpServer::from_config_with_policy(
+ host_server.config().clone(),
+ McpCredentialPolicy::ExecutorOnly,
+ );
+ let host_identity = connection_identity(&host_server, &runtime_context);
+ let executor_identity = connection_identity(&executor_server, &runtime_context);
+ let cache = McpToolCatalogCache::default();
+ let context = |identity| {
+ cache
+ .context(
+ "docs",
+ host_server.config(),
+ &runtime_context,
+ /*resolved_environment*/ None,
+ (
+ &ElicitationCapability::default(),
+ &ClientMcpExtensions::default(),
+ ),
+ Some((identity, McpProtocolMode::Legacy, false)),
+ )
+ .expect("explicit authorization permits catalog caching")
+ };
+ let host_context = context(&host_identity);
+ host_context.publish_if_newest(host_context.begin_fetch(), &[]);
+
+ assert_eq!(context(&host_identity).current_tools(), Some(Vec::new()));
+ assert_eq!(context(&executor_identity).current_tools(), None);
+}
diff --git a/codex-rs/codex-mcp/src/tool_catalog_cache.rs b/codex-rs/codex-mcp/src/tool_catalog_cache.rs
index c08c203b60..d3608afe98 100644
--- a/codex-rs/codex-mcp/src/tool_catalog_cache.rs
+++ b/codex-rs/codex-mcp/src/tool_catalog_cache.rs
@@ -26,6 +26,7 @@ use tokio::time::Instant;
use crate::McpProtocolMode;
use crate::McpRuntimeContext;
use crate::ToolInfo;
+use crate::server::McpCredentialPolicy;
use crate::server::McpServerConnectionIdentity;
use crate::server::has_explicit_http_authorization;
@@ -324,6 +325,10 @@ impl ToolCatalogTransportIdentity {
}
let mut hasher = Sha1::new();
+ hasher.update(match connection_identity.credential_policy {
+ McpCredentialPolicy::HostFallbackAllowed => b"host-fallback".as_slice(),
+ McpCredentialPolicy::ExecutorOnly => b"executor-only".as_slice(),
+ });
hasher.update(
serde_json::to_vec(&(
url,
@@ -351,9 +356,12 @@ impl ToolCatalogTransportIdentity {
env_vars.dedup();
for name in env_vars {
hasher.update(name.as_bytes());
- let mut value_hasher = DefaultHasher::new();
- std::env::var_os(name).hash(&mut value_hasher);
- hasher.update(value_hasher.finish().to_le_bytes());
+ if connection_identity.credential_policy == McpCredentialPolicy::HostFallbackAllowed
+ {
+ let mut value_hasher = DefaultHasher::new();
+ std::env::var_os(name).hash(&mut value_hasher);
+ hasher.update(value_hasher.finish().to_le_bytes());
+ }
}
return Some(Self::StreamableHttp {
fingerprint: hasher.finalize().into(),
diff --git a/codex-rs/core/src/config/config_tests.rs b/codex-rs/core/src/config/config_tests.rs
index 05e984e688..fbf31a0940 100644
--- a/codex-rs/core/src/config/config_tests.rs
+++ b/codex-rs/core/src/config/config_tests.rs
@@ -5923,6 +5923,7 @@ url = "https://sample.example/mcp"
"Selected Plugin".to_string(),
),
/*selection_order*/ 0,
+ codex_config::DEFAULT_MCP_SERVER_ENVIRONMENT_ID,
selected.clone(),
)],
)
diff --git a/codex-rs/core/src/mcp.rs b/codex-rs/core/src/mcp.rs
index 7c5928cc26..7bf01ce299 100644
--- a/codex-rs/core/src/mcp.rs
+++ b/codex-rs/core/src/mcp.rs
@@ -230,6 +230,7 @@ impl McpManager {
contribution.plugin_display_name.clone(),
),
selection_order,
+ &contribution.source_environment_id,
server,
),
);
diff --git a/codex-rs/core/src/session/mcp_runtime.rs b/codex-rs/core/src/session/mcp_runtime.rs
index e40ba8c6dd..800527900f 100644
--- a/codex-rs/core/src/session/mcp_runtime.rs
+++ b/codex-rs/core/src/session/mcp_runtime.rs
@@ -262,7 +262,7 @@ impl Session {
registered.insert(name.clone());
catalog
.get_or_insert_with(|| projection.config.mcp_server_catalog.to_builder())
- .register(McpServerRegistration::from_config(name, server));
+ .register(McpServerRegistration::from_executor_config(name, server));
}
}
diff --git a/codex-rs/core/src/thread_manager_tests.rs b/codex-rs/core/src/thread_manager_tests.rs
index 49a8ab8650..79f635244c 100644
--- a/codex-rs/core/src/thread_manager_tests.rs
+++ b/codex-rs/core/src/thread_manager_tests.rs
@@ -1625,7 +1625,8 @@ async fn start_thread_seeds_extension_data_for_mcp_and_lifecycle_contributors()
);
let CapabilityRootLocation::Environment { environment_id, .. } =
&selected_root.location;
- server.environment_id = environment_id.clone();
+ let source_environment_id = environment_id.clone();
+ server.environment_id = source_environment_id.clone();
server.enabled = false;
let plugin_id = format!("plugin-{}", selected_root.id);
vec![codex_extension_api::SelectedPlugin {
@@ -1634,6 +1635,7 @@ async fn start_thread_seeds_extension_data_for_mcp_and_lifecycle_contributors()
mcp: Box::pin(async move {
codex_extension_api::SelectedPluginContribution {
plugin_display_name: plugin_id,
+ source_environment_id,
connector_ids: vec![format!("{}-connector", selected_root.id)],
servers: vec![(selected_root.id, server)],
}
@@ -1799,6 +1801,25 @@ async fn start_thread_seeds_extension_data_for_mcp_and_lifecycle_contributors()
selected_servers(&second_resolved.config),
std::collections::BTreeMap::from([("selected-b".to_string(), "env-b".to_string())])
);
+ for (config, name, source_environment_id) in [
+ (&first_resolved.config, "selected-a", "env-a"),
+ (&second_resolved.config, "selected-b", "env-b"),
+ ] {
+ let server = config
+ .mcp_server_catalog
+ .server(name)
+ .expect("selected plugin server should be registered");
+ let plugin_id = format!("plugin-{name}");
+ let mut expected = codex_mcp::ResolvedMcpCatalog::builder();
+ expected.register(codex_mcp::McpServerRegistration::from_selected_plugin(
+ name.to_string(),
+ codex_mcp::McpPluginAttribution::new(plugin_id.clone(), plugin_id),
+ /*selection_order*/ 0,
+ source_environment_id,
+ server.config().clone(),
+ ));
+ assert_eq!(Some(server), expected.build().server(name));
+ }
let codex_apps_server = codex_mcp::configured_mcp_servers(&first_resolved.config)
.remove(codex_mcp::CODEX_APPS_MCP_SERVER_NAME)
.expect("Codex Apps server should be configured");
diff --git a/codex-rs/core/tests/suite/mcp_auth_refresh.rs b/codex-rs/core/tests/suite/mcp_auth_refresh.rs
index 6a9f3ec62c..67bfe7f09b 100644
--- a/codex-rs/core/tests/suite/mcp_auth_refresh.rs
+++ b/codex-rs/core/tests/suite/mcp_auth_refresh.rs
@@ -81,7 +81,7 @@ async fn hosted_plugin_runtime_ps_mcp_tool_calls_use_current_auth_manager_token(
*bearer_token_env_var = None;
let mcp_servers = HashMap::from([(
CODEX_APPS_MCP_SERVER_NAME.to_string(),
- EffectiveMcpServer::configured(hosted_plugin_runtime_config),
+ EffectiveMcpServer::from_host_config(hosted_plugin_runtime_config),
)]);
let mut config = ConfigBuilder::default()
.codex_home(home.path().to_path_buf())
diff --git a/codex-rs/ext/extension-api/src/contributors/mcp.rs b/codex-rs/ext/extension-api/src/contributors/mcp.rs
index ba1631ceb9..138005a5af 100644
--- a/codex-rs/ext/extension-api/src/contributors/mcp.rs
+++ b/codex-rs/ext/extension-api/src/contributors/mcp.rs
@@ -157,6 +157,8 @@ pub struct SelectedPlugin<'a> {
#[derive(Clone)]
pub struct SelectedPluginContribution {
pub plugin_display_name: String,
+ /// Environment that supplied the plugin, independent of where its MCP servers run.
+ pub source_environment_id: String,
pub connector_ids: Vec<String>,
pub servers: Vec<(String, McpServerConfig)>,
}
diff --git a/codex-rs/ext/mcp/src/event_stream_tests.rs b/codex-rs/ext/mcp/src/event_stream_tests.rs
index 30ffcd5f6d..a6403cbb32 100644
--- a/codex-rs/ext/mcp/src/event_stream_tests.rs
+++ b/codex-rs/ext/mcp/src/event_stream_tests.rs
@@ -161,7 +161,7 @@ impl Fixture {
ready_selected_capability_roots: Vec::new(),
mcp_servers: HashMap::from([(
CODEX_APPS_MCP_SERVER_NAME.into(),
- EffectiveMcpServer::configured(server_config.clone()),
+ EffectiveMcpServer::from_host_config(server_config.clone()),
)]),
submit_id: "test".into(),
tx_event: None,
diff --git a/codex-rs/ext/mcp/src/plugin.rs b/codex-rs/ext/mcp/src/plugin.rs
index d3ba5d4e52..b5586c3373 100644
--- a/codex-rs/ext/mcp/src/plugin.rs
+++ b/codex-rs/ext/mcp/src/plugin.rs
@@ -10,6 +10,7 @@ use codex_extension_api::McpServerContributor;
use codex_extension_api::SelectedPlugin;
use codex_extension_api::SelectedPluginContribution;
use codex_features::Feature;
+use codex_protocol::capabilities::CapabilityRootLocation;
use codex_protocol::capabilities::SelectedCapabilityRoot;
use std::collections::HashMap;
use std::sync::Arc;
@@ -85,8 +86,11 @@ impl PluginContributor {
.into_iter()
.map(|declaration| declaration.connector_id.0)
.collect();
+ let CapabilityRootLocation::Environment { environment_id, .. } =
+ &selected_root.location;
Some(SelectedPluginContribution {
plugin_display_name: plugin.plugin().manifest().display_name().to_string(),
+ source_environment_id: environment_id.clone(),
servers,
connector_ids,
})
diff --git a/codex-rs/ext/mcp/src/plugin/discovery.rs b/codex-rs/ext/mcp/src/plugin/discovery.rs
index d556755e16..bdd6f585a1 100644
--- a/codex-rs/ext/mcp/src/plugin/discovery.rs
+++ b/codex-rs/ext/mcp/src/plugin/discovery.rs
@@ -128,6 +128,7 @@ pub(super) fn metadata_from_discovery(
SelectedPluginContribution {
plugin_display_name: manifest.display_name().to_string(),
+ source_environment_id: environment_id.clone(),
servers,
connector_ids,
}
diff --git a/codex-rs/ext/mcp/tests/plugin_mcp.rs b/codex-rs/ext/mcp/tests/plugin_mcp.rs
index 9da77e4d76..f3bf0c57f8 100644
--- a/codex-rs/ext/mcp/tests/plugin_mcp.rs
+++ b/codex-rs/ext/mcp/tests/plugin_mcp.rs
@@ -60,6 +60,7 @@ struct ContributionSummary {
name: String,
plugin_id: String,
plugin_display_name: String,
+ source_environment_id: String,
selection_order: usize,
enabled: bool,
}
@@ -68,6 +69,7 @@ struct ContributionSummary {
struct PackageSummary {
plugin_id: String,
plugin_display_name: String,
+ source_environment_id: String,
connector_ids: Vec<String>,
}
@@ -120,6 +122,7 @@ command = "expected-command"
name: "allowed".to_string(),
plugin_id: "selected-root".to_string(),
plugin_display_name: "Selected Demo".to_string(),
+ source_environment_id: LOCAL_ENVIRONMENT_ID.to_string(),
selection_order: 0,
enabled: true,
},
@@ -127,6 +130,7 @@ command = "expected-command"
name: "mismatched".to_string(),
plugin_id: "selected-root".to_string(),
plugin_display_name: "Selected Demo".to_string(),
+ source_environment_id: LOCAL_ENVIRONMENT_ID.to_string(),
selection_order: 0,
enabled: false,
},
@@ -134,6 +138,7 @@ command = "expected-command"
name: "unlisted".to_string(),
plugin_id: "selected-root".to_string(),
plugin_display_name: "Selected Demo".to_string(),
+ source_environment_id: LOCAL_ENVIRONMENT_ID.to_string(),
selection_order: 0,
enabled: false,
},
@@ -169,6 +174,7 @@ async fn selected_plugin_package_is_contributed_without_servers_or_connectors()
.map(|(_, plugin_id, contribution)| PackageSummary {
plugin_id,
plugin_display_name: contribution.plugin_display_name,
+ source_environment_id: contribution.source_environment_id,
connector_ids: contribution.connector_ids,
});
@@ -177,6 +183,7 @@ async fn selected_plugin_package_is_contributed_without_servers_or_connectors()
Some(PackageSummary {
plugin_id: "selected-root".to_string(),
plugin_display_name: "Skill Only".to_string(),
+ source_environment_id: LOCAL_ENVIRONMENT_ID.to_string(),
connector_ids: Vec::new(),
})
);
@@ -216,7 +223,9 @@ plugins = false
matches!(
direct.as_slice(),
[(selected_root_id, _, contribution)]
- if selected_root_id == "selected-root" && contribution.servers.is_empty()
+ if selected_root_id == "selected-root"
+ && contribution.source_environment_id == LOCAL_ENVIRONMENT_ID
+ && contribution.servers.is_empty()
),
"managed Plugins disable should preserve only the direct selected-root identity"
);
@@ -230,7 +239,9 @@ plugins = false
matches!(
discovered.as_slice(),
[(selected_root_id, _, contribution)]
- if selected_root_id == "selected-root" && contribution.servers.is_empty()
+ if selected_root_id == "selected-root"
+ && contribution.source_environment_id == LOCAL_ENVIRONMENT_ID
+ && contribution.servers.is_empty()
),
"managed Plugins disable should preserve only the discovered selected-root identity"
);
@@ -362,6 +373,13 @@ default_tools_approval_mode = "auto"
.expect("test config should allow feature update");
let high_level = selected_plugin_contributions(&config, plugin_root.path()).await?;
+ assert_eq!(
+ existing
+ .iter()
+ .map(|contribution| contribution.source_environment_id.as_str())
+ .collect::<Vec<_>>(),
+ vec![LOCAL_ENVIRONMENT_ID, LOCAL_ENVIRONMENT_ID]
+ );
assert_eq!(high_level, existing);
Ok(())
}
@@ -382,6 +400,7 @@ async fn selected_plugin_contributions(
name,
plugin_id: plugin_id.clone(),
plugin_display_name: contribution.plugin_display_name.clone(),
+ source_environment_id: contribution.source_environment_id.clone(),
selection_order,
enabled: config.enabled,
})