From e1ba7618a2ed83dcbccbf2b3bad8463f6fce866f Mon Sep 17 00:00:00 2001 From: Abhinav Vedmala Date: Mon, 25 May 2026 10:55:31 -0700 Subject: [PATCH] Fix MCP startup config reload race --- .../tests/suite/v2/mcp_startup_config.rs | 274 ++++++++++++++++++ codex-rs/app-server/tests/suite/v2/mod.rs | 1 + codex-rs/core/src/session/mod.rs | 20 ++ codex-rs/core/src/session/session.rs | 2 + codex-rs/core/src/session/tests.rs | 13 + codex-rs/core/src/session/turn_context.rs | 35 +++ 6 files changed, 345 insertions(+) create mode 100644 codex-rs/app-server/tests/suite/v2/mcp_startup_config.rs diff --git a/codex-rs/app-server/tests/suite/v2/mcp_startup_config.rs b/codex-rs/app-server/tests/suite/v2/mcp_startup_config.rs new file mode 100644 index 0000000000..27ab6b9cfc --- /dev/null +++ b/codex-rs/app-server/tests/suite/v2/mcp_startup_config.rs @@ -0,0 +1,274 @@ +use std::borrow::Cow; +use std::collections::BTreeMap; +use std::path::Path; +use std::path::PathBuf; +use std::sync::Arc; +use std::sync::atomic::AtomicBool; +use std::sync::atomic::Ordering; +use std::time::Duration; + +use anyhow::Result; +use app_test_support::McpProcess; +use app_test_support::create_final_assistant_message_sse_response; +use app_test_support::create_mock_responses_server_sequence_unchecked; +use app_test_support::to_response; +use app_test_support::write_mock_responses_config_toml; +use axum::Router; +use codex_app_server_protocol::ItemCompletedNotification; +use codex_app_server_protocol::JSONRPCResponse; +use codex_app_server_protocol::RequestId; +use codex_app_server_protocol::ThreadItem; +use codex_app_server_protocol::ThreadStartParams; +use codex_app_server_protocol::ThreadStartResponse; +use codex_app_server_protocol::TurnStartParams; +use codex_app_server_protocol::TurnStartResponse; +use codex_app_server_protocol::UserInput as V2UserInput; +use codex_core::shell::default_user_shell; +use core_test_support::responses; +use pretty_assertions::assert_eq; +use rmcp::handler::server::ServerHandler; +use rmcp::model::JsonObject; +use rmcp::model::ListToolsResult; +use rmcp::model::PaginatedRequestParams; +use rmcp::model::ServerCapabilities; +use rmcp::model::ServerInfo; +use rmcp::model::Tool; +use rmcp::model::ToolAnnotations; +use rmcp::service::RequestContext; +use rmcp::transport::StreamableHttpServerConfig; +use rmcp::transport::StreamableHttpService; +use rmcp::transport::streamable_http_server::session::local::LocalSessionManager; +use serde_json::json; +use tempfile::TempDir; +use tokio::net::TcpListener; +use tokio::task::JoinHandle; +use tokio::time::timeout; + +const DEFAULT_READ_TIMEOUT: Duration = Duration::from_secs(10); +const MCP_STARTUP_ENV_VAR: &str = "CODEX_MCP_STARTUP_CONFIG_REPRO"; +const MCP_STARTUP_ENV_VALUE: &str = "loaded-during-mcp-startup"; + +#[tokio::test] +async fn first_turn_uses_config_written_during_mcp_startup() -> Result<()> { + let tmp = TempDir::new()?; + let codex_home = tmp.path().join("codex_home"); + std::fs::create_dir(&codex_home)?; + let workspace = tmp.path().join("workspace"); + std::fs::create_dir(&workspace)?; + + let (command, expected_output) = read_mcp_startup_env_command(); + let responses_server = create_mock_responses_server_sequence_unchecked(vec![ + create_exact_shell_command_sse_response(command, "call-env")?, + create_final_assistant_message_sse_response("done")?, + ]) + .await; + write_mock_responses_config_toml( + codex_home.as_path(), + &responses_server.uri(), + &BTreeMap::new(), + /*auto_compact_limit*/ 1024, + /*requires_openai_auth*/ None, + "mock_provider", + "compact", + )?; + + let config_path = codex_home.join("config.toml"); + let config_toml = std::fs::read_to_string(&config_path)?.replace( + "sandbox_mode = \"read-only\"", + "sandbox_mode = \"danger-full-access\"", + ); + std::fs::write(&config_path, config_toml)?; + let (mcp_server_url, mcp_server_handle) = + start_config_writing_mcp_server(config_path.clone()).await?; + let mut config_toml = std::fs::read_to_string(&config_path)?; + config_toml.push_str(&format!( + r#" +[mcp_servers.env-writer] +url = "{mcp_server_url}/mcp" +"# + )); + std::fs::write(&config_path, config_toml)?; + + let mut mcp = McpProcess::new(codex_home.as_path()).await?; + timeout(DEFAULT_READ_TIMEOUT, mcp.initialize()).await??; + + let start_id = mcp + .send_thread_start_request(ThreadStartParams { + cwd: Some(workspace.to_string_lossy().into_owned()), + ..Default::default() + }) + .await?; + let start_resp: JSONRPCResponse = timeout( + DEFAULT_READ_TIMEOUT, + mcp.read_stream_until_response_message(RequestId::Integer(start_id)), + ) + .await??; + let ThreadStartResponse { thread, .. } = to_response::(start_resp)?; + + let turn_id = mcp + .send_turn_start_request(TurnStartParams { + thread_id: thread.id.clone(), + input: vec![V2UserInput::Text { + text: "read the MCP-provided env var".to_string(), + text_elements: Vec::new(), + }], + cwd: Some(workspace), + ..Default::default() + }) + .await?; + let turn_resp: JSONRPCResponse = timeout( + DEFAULT_READ_TIMEOUT, + mcp.read_stream_until_response_message(RequestId::Integer(turn_id)), + ) + .await??; + let _: TurnStartResponse = to_response::(turn_resp)?; + + let completed = wait_for_command_execution_completed(&mut mcp).await?; + let ThreadItem::CommandExecution { + aggregated_output, .. + } = completed.item + else { + unreachable!("helper returns command execution item"); + }; + assert!( + std::fs::read_to_string(&config_path)?.contains(MCP_STARTUP_ENV_VAR), + "MCP tool discovery should have written the shell env policy during the first turn" + ); + assert_eq!(aggregated_output.as_deref(), Some(expected_output.as_str())); + + mcp_server_handle.abort(); + let _ = mcp_server_handle.await; + + Ok(()) +} + +#[derive(Clone)] +struct ConfigWritingMcpServer { + config_path: Arc, + wrote_config: Arc, +} + +impl ServerHandler for ConfigWritingMcpServer { + fn get_info(&self) -> ServerInfo { + ServerInfo { + capabilities: ServerCapabilities::builder().enable_tools().build(), + ..ServerInfo::default() + } + } + + async fn list_tools( + &self, + _request: Option, + _context: RequestContext, + ) -> std::result::Result { + if !self.wrote_config.swap(true, Ordering::SeqCst) { + append_shell_environment_policy(&self.config_path) + .map_err(|err| rmcp::ErrorData::internal_error(err.to_string(), None))?; + } + + let input_schema: JsonObject = serde_json::from_value(json!({ + "type": "object", + "additionalProperties": false + })) + .map_err(|err| rmcp::ErrorData::internal_error(err.to_string(), None))?; + + let mut tool = Tool::new( + Cow::Borrowed("env_writer_probe"), + Cow::Borrowed("Probe tool for config refresh tests."), + Arc::new(input_schema), + ); + tool.annotations = Some(ToolAnnotations::new().read_only(true)); + + Ok(ListToolsResult { + tools: vec![tool], + next_cursor: None, + meta: None, + }) + } +} + +async fn start_config_writing_mcp_server(config_path: PathBuf) -> Result<(String, JoinHandle<()>)> { + let listener = TcpListener::bind("127.0.0.1:0").await?; + let addr = listener.local_addr()?; + let config_path = Arc::new(config_path); + let wrote_config = Arc::new(AtomicBool::new(false)); + let mcp_service = StreamableHttpService::new( + move || { + Ok(ConfigWritingMcpServer { + config_path: Arc::clone(&config_path), + wrote_config: Arc::clone(&wrote_config), + }) + }, + Arc::new(LocalSessionManager::default()), + StreamableHttpServerConfig::default(), + ); + let router = Router::new().nest_service("/mcp", mcp_service); + + let handle = tokio::spawn(async move { + let _ = axum::serve(listener, router).await; + }); + + Ok((format!("http://{addr}"), handle)) +} + +fn append_shell_environment_policy(config_path: &Path) -> Result<()> { + let mut config_toml = std::fs::read_to_string(config_path)?; + if !config_toml.contains(MCP_STARTUP_ENV_VAR) { + config_toml.push_str(&format!( + r#" +[shell_environment_policy.set] +{MCP_STARTUP_ENV_VAR} = "{MCP_STARTUP_ENV_VALUE}" +"# + )); + std::fs::write(config_path, config_toml)?; + } + Ok(()) +} + +fn read_mcp_startup_env_command() -> (String, String) { + match default_user_shell().name() { + "powershell" => ( + format!("Write-Output $env:{MCP_STARTUP_ENV_VAR}"), + format!("{MCP_STARTUP_ENV_VALUE}\r\n"), + ), + "cmd" => ( + format!("echo %{MCP_STARTUP_ENV_VAR}%"), + format!("{MCP_STARTUP_ENV_VALUE}\r\n"), + ), + _ => ( + format!("printf '%s\\n' \"${MCP_STARTUP_ENV_VAR}\""), + format!("{MCP_STARTUP_ENV_VALUE}\n"), + ), + } +} + +fn create_exact_shell_command_sse_response(command: String, call_id: &str) -> Result { + let tool_call_arguments = serde_json::to_string(&json!({ + "command": command, + "workdir": null, + "timeout_ms": 5000 + }))?; + Ok(responses::sse(vec![ + responses::ev_response_created("resp-1"), + responses::ev_function_call(call_id, "shell_command", &tool_call_arguments), + responses::ev_completed("resp-1"), + ])) +} + +async fn wait_for_command_execution_completed( + mcp: &mut McpProcess, +) -> Result { + loop { + let notif = mcp + .read_stream_until_notification_message("item/completed") + .await?; + let completed: ItemCompletedNotification = serde_json::from_value( + notif + .params + .ok_or_else(|| anyhow::anyhow!("missing item/completed params"))?, + )?; + if matches!(completed.item, ThreadItem::CommandExecution { .. }) { + return Ok(completed); + } + } +} diff --git a/codex-rs/app-server/tests/suite/v2/mod.rs b/codex-rs/app-server/tests/suite/v2/mod.rs index 92e0f126f3..d7ad4cf38b 100644 --- a/codex-rs/app-server/tests/suite/v2/mod.rs +++ b/codex-rs/app-server/tests/suite/v2/mod.rs @@ -24,6 +24,7 @@ mod marketplace_upgrade; mod mcp_resource; mod mcp_server_elicitation; mod mcp_server_status; +mod mcp_startup_config; mod mcp_tool; mod memory_reset; mod model_list; diff --git a/codex-rs/core/src/session/mod.rs b/codex-rs/core/src/session/mod.rs index 675e794aee..b97a588f68 100644 --- a/codex-rs/core/src/session/mod.rs +++ b/codex-rs/core/src/session/mod.rs @@ -4,6 +4,7 @@ use std::fmt::Debug; use std::path::Path; use std::path::PathBuf; use std::sync::Arc; +use std::sync::atomic::AtomicBool; use std::sync::atomic::AtomicU64; use std::time::SystemTime; use std::time::UNIX_EPOCH; @@ -1461,6 +1462,25 @@ impl Session { config.config_layer_stack = config .config_layer_stack .with_user_layer_from(&next_config.config_layer_stack); + match config + .config_layer_stack + .effective_config() + .as_table() + .and_then(|table| table.get("shell_environment_policy")) + .cloned() + { + Some(value) => { + match value.try_into::() { + Ok(policy) => config.permissions.shell_environment_policy = policy.into(), + Err(err) => warn!( + "failed to parse shell_environment_policy while refreshing runtime config: {err}" + ), + } + } + None => { + config.permissions.shell_environment_policy = ShellEnvironmentPolicy::default(); + } + } config.tool_suggest = resolve_tool_suggest_config_from_layer_stack(&config.config_layer_stack); let config = Arc::new(config); diff --git a/codex-rs/core/src/session/session.rs b/codex-rs/core/src/session/session.rs index e430202ae1..f319dc7019 100644 --- a/codex-rs/core/src/session/session.rs +++ b/codex-rs/core/src/session/session.rs @@ -30,6 +30,7 @@ pub(crate) struct Session { /// session. pub(super) features: ManagedFeatures, pub(super) pending_mcp_server_refresh_config: Mutex>, + pub(super) mcp_startup_config_reload_checked: AtomicBool, pub(crate) conversation: Arc, pub(crate) active_turn: Mutex>, pub(crate) input_queue: InputQueue, @@ -1048,6 +1049,7 @@ impl Session { managed_network_proxy_refresh_lock: Semaphore::new(/*permits*/ 1), features: config.features.clone(), pending_mcp_server_refresh_config: Mutex::new(None), + mcp_startup_config_reload_checked: AtomicBool::new(false), conversation: Arc::new(RealtimeConversationManager::new()), active_turn: Mutex::new(None), input_queue: InputQueue::new(), diff --git a/codex-rs/core/src/session/tests.rs b/codex-rs/core/src/session/tests.rs index ac62a3482c..9502364e46 100644 --- a/codex-rs/core/src/session/tests.rs +++ b/codex-rs/core/src/session/tests.rs @@ -1487,6 +1487,9 @@ async fn refresh_runtime_config_updates_runtime_refreshable_fields_and_keeps_ses enabled = false destructive_enabled = false +[shell_environment_policy.set] +CODEX_REFRESH_RUNTIME_CONFIG_TEST = "updated" + [tool_suggest] disabled_tools = [ { type = "connector", id = " calendar " }, @@ -1522,6 +1525,14 @@ disabled_tools = [ assert_eq!(app.destructive_enabled, Some(false)); assert_eq!(config.model, original.model); assert_eq!(config.notify, original.notify); + assert_eq!( + config + .permissions + .shell_environment_policy + .r#set + .get("CODEX_REFRESH_RUNTIME_CONFIG_TEST"), + Some(&"updated".to_string()) + ); assert_eq!( config.tool_suggest.disabled_tools, vec![ @@ -4631,6 +4642,7 @@ pub(crate) async fn make_session_and_context() -> (Session, TurnContext) { managed_network_proxy_refresh_lock: Semaphore::new(/*permits*/ 1), features: config.features.clone(), pending_mcp_server_refresh_config: Mutex::new(None), + mcp_startup_config_reload_checked: AtomicBool::new(false), conversation: Arc::new(RealtimeConversationManager::new()), active_turn: Mutex::new(None), input_queue: super::input_queue::InputQueue::new(), @@ -6460,6 +6472,7 @@ where managed_network_proxy_refresh_lock: Semaphore::new(/*permits*/ 1), features: config.features.clone(), pending_mcp_server_refresh_config: Mutex::new(None), + mcp_startup_config_reload_checked: AtomicBool::new(false), conversation: Arc::new(RealtimeConversationManager::new()), active_turn: Mutex::new(None), input_queue: super::input_queue::InputQueue::new(), diff --git a/codex-rs/core/src/session/turn_context.rs b/codex-rs/core/src/session/turn_context.rs index de38083135..4f36b9717d 100644 --- a/codex-rs/core/src/session/turn_context.rs +++ b/codex-rs/core/src/session/turn_context.rs @@ -375,6 +375,39 @@ fn local_time_context() -> (String, String) { } impl Session { + #[expect( + clippy::await_holding_invalid_type, + reason = "initial MCP discovery reads through the session-owned manager guard" + )] + async fn reload_config_after_mcp_startup_once(&self) { + if self + .mcp_startup_config_reload_checked + .load(Ordering::SeqCst) + { + return; + } + + { + let mcp_connection_manager = self.services.mcp_connection_manager.read().await; + if !mcp_connection_manager.has_servers() { + return; + } + } + + if self + .mcp_startup_config_reload_checked + .swap(true, Ordering::SeqCst) + { + return; + } + + { + let mcp_connection_manager = self.services.mcp_connection_manager.read().await; + let _ = mcp_connection_manager.list_all_tools().await; + } + self.reload_user_config_layer().await; + } + /// Don't expand the number of mutated arguments on config. We are in the process of getting rid of it. pub(crate) fn build_per_turn_config( session_configuration: &SessionConfiguration, @@ -544,6 +577,7 @@ impl Session { sub_id: String, updates: SessionSettingsUpdate, ) -> CodexResult> { + self.reload_config_after_mcp_startup_once().await; let notify_config_contributors = !self.services.extensions.config_contributors().is_empty(); let update_result: CodexResult<_> = { let mut state = self.state.lock().await; @@ -751,6 +785,7 @@ impl Session { } pub(crate) async fn new_default_turn_with_sub_id(&self, sub_id: String) -> Arc { + self.reload_config_after_mcp_startup_once().await; let session_configuration = { let state = self.state.lock().await; state.session_configuration.clone()