From f88701f5c883d4a594ac4fda88b462d58dd9488d Mon Sep 17 00:00:00 2001 From: Matthew Zeng Date: Fri, 1 May 2026 21:22:12 -0700 Subject: [PATCH 01/12] [tool_suggest] More prompt polishes. (#20566) Tool suggest still misfires when model needs tool_search, updating the prompts to further disambiguate it: - [x] rename it from `tool_suggest` to `request_plugin_install` - [x] rephrase "suggestion" to "install" in the tool descriptions. - [x] disambiguate "the tool" vs "the plugin/connector". Tested with the Codex App and verified it still works. --- codex-rs/core/src/session/turn.rs | 4 +- codex-rs/core/src/tools/handlers/mod.rs | 4 +- ...l_suggest.rs => request_plugin_install.rs} | 91 ++++++++++--------- ...sts.rs => request_plugin_install_tests.rs} | 56 ++++++------ codex-rs/core/src/tools/spec.rs | 8 +- codex-rs/core/src/tools/spec_tests.rs | 6 +- .../request_plugin_install_description.md | 29 ++++++ .../search_tool/tool_suggest_description.md | 29 ------ codex-rs/core/tests/suite/mod.rs | 2 +- ...l_suggest.rs => request_plugin_install.rs} | 16 +++- codex-rs/tools/README.md | 2 +- codex-rs/tools/src/lib.rs | 30 +++--- ...l_suggest.rs => request_plugin_install.rs} | 36 ++++---- ...sts.rs => request_plugin_install_tests.rs} | 46 +++++----- codex-rs/tools/src/tool_discovery.rs | 30 +++--- codex-rs/tools/src/tool_discovery_tests.rs | 41 +++++---- codex-rs/tools/src/tool_registry_plan.rs | 15 ++- .../tools/src/tool_registry_plan_tests.rs | 38 ++++---- .../tools/src/tool_registry_plan_types.rs | 2 +- 19 files changed, 253 insertions(+), 232 deletions(-) rename codex-rs/core/src/tools/handlers/{tool_suggest.rs => request_plugin_install.rs} (75%) rename codex-rs/core/src/tools/handlers/{tool_suggest_tests.rs => request_plugin_install_tests.rs} (79%) create mode 100644 codex-rs/core/templates/search_tool/request_plugin_install_description.md delete mode 100644 codex-rs/core/templates/search_tool/tool_suggest_description.md rename codex-rs/core/tests/suite/{tool_suggest.rs => request_plugin_install.rs} (89%) rename codex-rs/tools/src/{tool_suggest.rs => request_plugin_install.rs} (76%) rename codex-rs/tools/src/{tool_suggest_tests.rs => request_plugin_install_tests.rs} (81%) diff --git a/codex-rs/core/src/session/turn.rs b/codex-rs/core/src/session/turn.rs index 5a1049c4a0..2b37372a33 100644 --- a/codex-rs/core/src/session/turn.rs +++ b/codex-rs/core/src/session/turn.rs @@ -97,7 +97,7 @@ use codex_protocol::protocol::TurnDiffEvent; use codex_protocol::protocol::WarningEvent; use codex_protocol::user_input::UserInput; use codex_tools::ToolName; -use codex_tools::filter_tool_suggest_discoverable_tools_for_client; +use codex_tools::filter_request_plugin_install_discoverable_tools_for_client; use codex_utils_stream_parser::AssistantTextChunk; use codex_utils_stream_parser::AssistantTextStreamParser; use codex_utils_stream_parser::ProposedPlanSegment; @@ -1170,7 +1170,7 @@ pub(crate) async fn built_tools( ) .await .map(|discoverable_tools| { - filter_tool_suggest_discoverable_tools_for_client( + filter_request_plugin_install_discoverable_tools_for_client( discoverable_tools, turn_context.app_server_client_name.as_deref(), ) diff --git a/codex-rs/core/src/tools/handlers/mod.rs b/codex-rs/core/src/tools/handlers/mod.rs index 0ddd1e5062..f7ad4f7e67 100644 --- a/codex-rs/core/src/tools/handlers/mod.rs +++ b/codex-rs/core/src/tools/handlers/mod.rs @@ -10,11 +10,11 @@ pub(crate) mod multi_agents_common; pub(crate) mod multi_agents_v2; mod plan; mod request_permissions; +mod request_plugin_install; mod request_user_input; mod shell; mod test_sync; mod tool_search; -mod tool_suggest; mod unavailable_tool; pub(crate) mod unified_exec; mod view_image; @@ -43,12 +43,12 @@ pub use mcp::McpHandler; pub use mcp_resource::McpResourceHandler; pub use plan::PlanHandler; pub use request_permissions::RequestPermissionsHandler; +pub use request_plugin_install::RequestPluginInstallHandler; pub use request_user_input::RequestUserInputHandler; pub use shell::ShellCommandHandler; pub use shell::ShellHandler; pub use test_sync::TestSyncHandler; pub use tool_search::ToolSearchHandler; -pub use tool_suggest::ToolSuggestHandler; pub use unavailable_tool::UnavailableToolHandler; pub(crate) use unavailable_tool::unavailable_tool_message; pub use unified_exec::UnifiedExecHandler; diff --git a/codex-rs/core/src/tools/handlers/tool_suggest.rs b/codex-rs/core/src/tools/handlers/request_plugin_install.rs similarity index 75% rename from codex-rs/core/src/tools/handlers/tool_suggest.rs rename to codex-rs/core/src/tools/handlers/request_plugin_install.rs index 7f74703ef1..673a73bfb7 100644 --- a/codex-rs/core/src/tools/handlers/tool_suggest.rs +++ b/codex-rs/core/src/tools/handlers/request_plugin_install.rs @@ -8,15 +8,15 @@ use codex_rmcp_client::ElicitationResponse; use codex_tools::DiscoverableTool; use codex_tools::DiscoverableToolAction; use codex_tools::DiscoverableToolType; -use codex_tools::TOOL_SUGGEST_PERSIST_ALWAYS_VALUE; -use codex_tools::TOOL_SUGGEST_PERSIST_KEY; -use codex_tools::TOOL_SUGGEST_TOOL_NAME; -use codex_tools::ToolSuggestArgs; -use codex_tools::ToolSuggestResult; -use codex_tools::all_suggested_connectors_picked_up; -use codex_tools::build_tool_suggestion_elicitation_request; -use codex_tools::filter_tool_suggest_discoverable_tools_for_client; -use codex_tools::verified_connector_suggestion_completed; +use codex_tools::REQUEST_PLUGIN_INSTALL_PERSIST_ALWAYS_VALUE; +use codex_tools::REQUEST_PLUGIN_INSTALL_PERSIST_KEY; +use codex_tools::REQUEST_PLUGIN_INSTALL_TOOL_NAME; +use codex_tools::RequestPluginInstallArgs; +use codex_tools::RequestPluginInstallResult; +use codex_tools::all_requested_connectors_picked_up; +use codex_tools::build_request_plugin_install_elicitation_request; +use codex_tools::filter_request_plugin_install_discoverable_tools_for_client; +use codex_tools::verified_connector_install_completed; use rmcp::model::RequestId; use serde_json::Value; use tracing::warn; @@ -32,9 +32,9 @@ use crate::tools::handlers::parse_arguments; use crate::tools::registry::ToolHandler; use crate::tools::registry::ToolKind; -pub struct ToolSuggestHandler; +pub struct RequestPluginInstallHandler; -impl ToolHandler for ToolSuggestHandler { +impl ToolHandler for RequestPluginInstallHandler { type Output = FunctionToolOutput; fn kind(&self) -> ToolKind { @@ -43,7 +43,7 @@ impl ToolHandler for ToolSuggestHandler { #[expect( clippy::await_holding_invalid_type, - reason = "tool suggestion discovery reads through the session-owned manager guard" + reason = "plugin install discovery reads through the session-owned manager guard" )] async fn handle(&self, invocation: ToolInvocation) -> Result { let ToolInvocation { @@ -58,12 +58,12 @@ impl ToolHandler for ToolSuggestHandler { ToolPayload::Function { arguments } => arguments, _ => { return Err(FunctionCallError::Fatal(format!( - "{TOOL_SUGGEST_TOOL_NAME} handler received unsupported payload" + "{REQUEST_PLUGIN_INSTALL_TOOL_NAME} handler received unsupported payload" ))); } }; - let args: ToolSuggestArgs = parse_arguments(&arguments)?; + let args: RequestPluginInstallArgs = parse_arguments(&arguments)?; let suggest_reason = args.suggest_reason.trim(); if suggest_reason.is_empty() { return Err(FunctionCallError::RespondToModel( @@ -72,14 +72,15 @@ impl ToolHandler for ToolSuggestHandler { } if args.action_type != DiscoverableToolAction::Install { return Err(FunctionCallError::RespondToModel( - "tool suggestions currently support only action_type=\"install\"".to_string(), + "plugin install requests currently support only action_type=\"install\"" + .to_string(), )); } if args.tool_type == DiscoverableToolType::Plugin && turn.app_server_client_name.as_deref() == Some("codex-tui") { return Err(FunctionCallError::RespondToModel( - "plugin tool suggestions are not available in codex-tui yet".to_string(), + "plugin install requests are not available in codex-tui yet".to_string(), )); } @@ -98,14 +99,14 @@ impl ToolHandler for ToolSuggestHandler { ) .await .map(|discoverable_tools| { - filter_tool_suggest_discoverable_tools_for_client( + filter_request_plugin_install_discoverable_tools_for_client( discoverable_tools, turn.app_server_client_name.as_deref(), ) }) .map_err(|err| { FunctionCallError::RespondToModel(format!( - "tool suggestions are unavailable right now: {err}" + "plugin install requests are unavailable right now: {err}" )) })?; @@ -114,12 +115,12 @@ impl ToolHandler for ToolSuggestHandler { .find(|tool| tool.tool_type() == args.tool_type && tool.id() == args.tool_id) .ok_or_else(|| { FunctionCallError::RespondToModel(format!( - "tool_id must match one of the discoverable tools exposed by {TOOL_SUGGEST_TOOL_NAME}" + "tool_id must match one of the discoverable tools exposed by {REQUEST_PLUGIN_INSTALL_TOOL_NAME}" )) })?; - let request_id = RequestId::String(format!("tool_suggestion_{call_id}").into()); - let params = build_tool_suggestion_elicitation_request( + let request_id = RequestId::String(format!("request_plugin_install_{call_id}").into()); + let params = build_request_plugin_install_elicitation_request( CODEX_APPS_MCP_SERVER_NAME, session.conversation_id.to_string(), turn.sub_id.clone(), @@ -131,14 +132,14 @@ impl ToolHandler for ToolSuggestHandler { .request_mcp_server_elicitation(turn.as_ref(), request_id, params) .await; if let Some(response) = response.as_ref() { - maybe_persist_tool_suggest_disable(&session, &turn, &tool, response).await; + maybe_persist_disabled_install_request(&session, &turn, &tool, response).await; } let user_confirmed = response .as_ref() .is_some_and(|response| response.action == ElicitationAction::Accept); let completed = if user_confirmed { - verify_tool_suggestion_completed(&session, &turn, &tool, auth.as_ref()).await + verify_request_plugin_install_completed(&session, &turn, &tool, auth.as_ref()).await } else { false }; @@ -149,7 +150,7 @@ impl ToolHandler for ToolSuggestHandler { .await; } - let content = serde_json::to_string(&ToolSuggestResult { + let content = serde_json::to_string(&RequestPluginInstallResult { completed, user_confirmed, tool_type: args.tool_type, @@ -160,7 +161,7 @@ impl ToolHandler for ToolSuggestHandler { }) .map_err(|err| { FunctionCallError::Fatal(format!( - "failed to serialize {TOOL_SUGGEST_TOOL_NAME} response: {err}" + "failed to serialize {REQUEST_PLUGIN_INSTALL_TOOL_NAME} response: {err}" )) })?; @@ -168,17 +169,17 @@ impl ToolHandler for ToolSuggestHandler { } } -async fn maybe_persist_tool_suggest_disable( +async fn maybe_persist_disabled_install_request( session: &crate::session::session::Session, turn: &crate::session::turn_context::TurnContext, tool: &DiscoverableTool, response: &ElicitationResponse, ) { - if !tool_suggest_response_requests_persistent_disable(response) { + if !request_plugin_install_response_requests_persistent_disable(response) { return; } - if let Err(err) = persist_tool_suggest_disable(&turn.config.codex_home, tool).await { + if let Err(err) = persist_disabled_install_request(&turn.config.codex_home, tool).await { warn!( error = %err, tool_id = tool.id(), @@ -190,7 +191,9 @@ async fn maybe_persist_tool_suggest_disable( session.reload_user_config_layer().await; } -fn tool_suggest_response_requests_persistent_disable(response: &ElicitationResponse) -> bool { +fn request_plugin_install_response_requests_persistent_disable( + response: &ElicitationResponse, +) -> bool { if response.action != ElicitationAction::Decline { return false; } @@ -199,24 +202,24 @@ fn tool_suggest_response_requests_persistent_disable(response: &ElicitationRespo .meta .as_ref() .and_then(Value::as_object) - .and_then(|meta| meta.get(TOOL_SUGGEST_PERSIST_KEY)) + .and_then(|meta| meta.get(REQUEST_PLUGIN_INSTALL_PERSIST_KEY)) .and_then(Value::as_str) - == Some(TOOL_SUGGEST_PERSIST_ALWAYS_VALUE) + == Some(REQUEST_PLUGIN_INSTALL_PERSIST_ALWAYS_VALUE) } -async fn persist_tool_suggest_disable( +async fn persist_disabled_install_request( codex_home: &codex_utils_absolute_path::AbsolutePathBuf, tool: &DiscoverableTool, ) -> anyhow::Result<()> { ConfigEditsBuilder::new(codex_home) .with_edits([ConfigEdit::AddToolSuggestDisabledTool( - disabled_tool_suggestion(tool), + disabled_install_request(tool), )]) .apply() .await } -fn disabled_tool_suggestion(tool: &DiscoverableTool) -> ToolSuggestDisabledTool { +fn disabled_install_request(tool: &DiscoverableTool) -> ToolSuggestDisabledTool { match tool { DiscoverableTool::Connector(connector) => { ToolSuggestDisabledTool::connector(connector.id.as_str()) @@ -225,14 +228,14 @@ fn disabled_tool_suggestion(tool: &DiscoverableTool) -> ToolSuggestDisabledTool } } -async fn verify_tool_suggestion_completed( +async fn verify_request_plugin_install_completed( session: &crate::session::session::Session, turn: &crate::session::turn_context::TurnContext, tool: &DiscoverableTool, auth: Option<&codex_login::CodexAuth>, ) -> bool { match tool { - DiscoverableTool::Connector(connector) => refresh_missing_suggested_connectors( + DiscoverableTool::Connector(connector) => refresh_missing_requested_connectors( session, turn, auth, @@ -241,17 +244,17 @@ async fn verify_tool_suggestion_completed( ) .await .is_some_and(|accessible_connectors| { - verified_connector_suggestion_completed(connector.id.as_str(), &accessible_connectors) + verified_connector_install_completed(connector.id.as_str(), &accessible_connectors) }), DiscoverableTool::Plugin(plugin) => { session.reload_user_config_layer().await; let config = session.get_config().await; - let completed = verified_plugin_suggestion_completed( + let completed = verified_plugin_install_completed( plugin.id.as_str(), config.as_ref(), session.services.plugins_manager.as_ref(), ); - let _ = refresh_missing_suggested_connectors( + let _ = refresh_missing_requested_connectors( session, turn, auth, @@ -268,7 +271,7 @@ async fn verify_tool_suggestion_completed( clippy::await_holding_invalid_type, reason = "connector cache refresh reads through the session-owned manager guard" )] -async fn refresh_missing_suggested_connectors( +async fn refresh_missing_requested_connectors( session: &crate::session::session::Session, turn: &crate::session::turn_context::TurnContext, auth: Option<&codex_login::CodexAuth>, @@ -285,7 +288,7 @@ async fn refresh_missing_suggested_connectors( connectors::accessible_connectors_from_mcp_tools(&mcp_tools), &turn.config, ); - if all_suggested_connectors_picked_up(expected_connector_ids, &accessible_connectors) { + if all_requested_connectors_picked_up(expected_connector_ids, &accessible_connectors) { return Some(accessible_connectors); } @@ -304,14 +307,14 @@ async fn refresh_missing_suggested_connectors( } Err(err) => { warn!( - "failed to refresh codex apps tools cache after tool suggestion for {tool_id}: {err:#}" + "failed to refresh codex apps tools cache after plugin install request for {tool_id}: {err:#}" ); None } } } -fn verified_plugin_suggestion_completed( +fn verified_plugin_install_completed( tool_id: &str, config: &crate::config::Config, plugins_manager: &codex_core_plugins::PluginsManager, @@ -327,5 +330,5 @@ fn verified_plugin_suggestion_completed( } #[cfg(test)] -#[path = "tool_suggest_tests.rs"] +#[path = "request_plugin_install_tests.rs"] mod tests; diff --git a/codex-rs/core/src/tools/handlers/tool_suggest_tests.rs b/codex-rs/core/src/tools/handlers/request_plugin_install_tests.rs similarity index 79% rename from codex-rs/core/src/tools/handlers/tool_suggest_tests.rs rename to codex-rs/core/src/tools/handlers/request_plugin_install_tests.rs index 65fd2f3a22..1a8caf0dce 100644 --- a/codex-rs/core/src/tools/handlers/tool_suggest_tests.rs +++ b/codex-rs/core/src/tools/handlers/request_plugin_install_tests.rs @@ -22,7 +22,7 @@ use serde_json::json; use tempfile::tempdir; #[tokio::test] -async fn verified_plugin_suggestion_completed_requires_installed_plugin() { +async fn verified_plugin_install_completed_requires_installed_plugin() { let codex_home = tempdir().expect("tempdir should succeed"); let curated_root = curated_plugins_repo_path(codex_home.path()); write_openai_curated_marketplace(&curated_root, &["sample"]); @@ -32,7 +32,7 @@ async fn verified_plugin_suggestion_completed_requires_installed_plugin() { let config = load_plugins_config(codex_home.path()).await; let plugins_manager = PluginsManager::new(codex_home.path().to_path_buf()); - assert!(!verified_plugin_suggestion_completed( + assert!(!verified_plugin_install_completed( "sample@openai-curated", &config, &plugins_manager, @@ -50,7 +50,7 @@ async fn verified_plugin_suggestion_completed_requires_installed_plugin() { .expect("plugin should install"); let refreshed_config = load_plugins_config(codex_home.path()).await; - assert!(verified_plugin_suggestion_completed( + assert!(verified_plugin_install_completed( "sample@openai-curated", &refreshed_config, &plugins_manager, @@ -58,43 +58,47 @@ async fn verified_plugin_suggestion_completed_requires_installed_plugin() { } #[test] -fn tool_suggest_response_persists_only_decline_always_mode() { - assert!(tool_suggest_response_requests_persistent_disable( +fn request_plugin_install_response_persists_only_decline_always_mode() { + assert!(request_plugin_install_response_requests_persistent_disable( &ElicitationResponse { action: ElicitationAction::Decline, content: None, - meta: Some(json!({ TOOL_SUGGEST_PERSIST_KEY: TOOL_SUGGEST_PERSIST_ALWAYS_VALUE })), + meta: Some(json!({ + REQUEST_PLUGIN_INSTALL_PERSIST_KEY: REQUEST_PLUGIN_INSTALL_PERSIST_ALWAYS_VALUE + })), } )); - assert!(!tool_suggest_response_requests_persistent_disable( - &ElicitationResponse { + assert!( + !request_plugin_install_response_requests_persistent_disable(&ElicitationResponse { action: ElicitationAction::Accept, content: None, - meta: Some(json!({ TOOL_SUGGEST_PERSIST_KEY: TOOL_SUGGEST_PERSIST_ALWAYS_VALUE })), - } - )); - assert!(!tool_suggest_response_requests_persistent_disable( - &ElicitationResponse { + meta: Some(json!({ + REQUEST_PLUGIN_INSTALL_PERSIST_KEY: REQUEST_PLUGIN_INSTALL_PERSIST_ALWAYS_VALUE + })), + }) + ); + assert!( + !request_plugin_install_response_requests_persistent_disable(&ElicitationResponse { action: ElicitationAction::Decline, content: None, - meta: Some(json!({ TOOL_SUGGEST_PERSIST_KEY: "session" })), - } - )); - assert!(!tool_suggest_response_requests_persistent_disable( - &ElicitationResponse { + meta: Some(json!({ REQUEST_PLUGIN_INSTALL_PERSIST_KEY: "session" })), + }) + ); + assert!( + !request_plugin_install_response_requests_persistent_disable(&ElicitationResponse { action: ElicitationAction::Decline, content: None, meta: None, - } - )); + }) + ); } #[tokio::test] -async fn persist_tool_suggest_disable_writes_connector_config() { +async fn persist_disabled_install_request_writes_connector_config() { let codex_home = tempdir().expect("tempdir should succeed"); let tool = connector_tool("connector_calendar", "Google Calendar"); - persist_tool_suggest_disable(&codex_home.path().abs(), &tool) + persist_disabled_install_request(&codex_home.path().abs(), &tool) .await .expect("persist connector disable"); @@ -111,7 +115,7 @@ async fn persist_tool_suggest_disable_writes_connector_config() { } #[tokio::test] -async fn persist_tool_suggest_disable_writes_plugin_config() { +async fn persist_disabled_install_request_writes_plugin_config() { let codex_home = tempdir().expect("tempdir should succeed"); let tool = DiscoverableTool::Plugin(Box::new(DiscoverablePluginInfo { id: "slack@openai-curated".to_string(), @@ -122,7 +126,7 @@ async fn persist_tool_suggest_disable_writes_plugin_config() { app_connector_ids: Vec::new(), })); - persist_tool_suggest_disable(&codex_home.path().abs(), &tool) + persist_disabled_install_request(&codex_home.path().abs(), &tool) .await .expect("persist plugin disable"); @@ -139,7 +143,7 @@ async fn persist_tool_suggest_disable_writes_plugin_config() { } #[tokio::test] -async fn persist_tool_suggest_disable_dedupes_existing_disabled_tools() { +async fn persist_disabled_install_request_dedupes_existing_disabled_tools() { let codex_home = tempdir().expect("tempdir should succeed"); let tool = connector_tool("connector_calendar", "Google Calendar"); std::fs::write( @@ -169,7 +173,7 @@ id = "slack@openai-curated" ) .expect("write config"); - persist_tool_suggest_disable(&codex_home.path().abs(), &tool) + persist_disabled_install_request(&codex_home.path().abs(), &tool) .await .expect("persist connector disable"); diff --git a/codex-rs/core/src/tools/spec.rs b/codex-rs/core/src/tools/spec.rs index 308d8c46f7..479dcc382f 100644 --- a/codex-rs/core/src/tools/spec.rs +++ b/codex-rs/core/src/tools/spec.rs @@ -86,12 +86,12 @@ pub(crate) fn build_specs_with_discoverable_tools( use crate::tools::handlers::McpResourceHandler; use crate::tools::handlers::PlanHandler; use crate::tools::handlers::RequestPermissionsHandler; + use crate::tools::handlers::RequestPluginInstallHandler; use crate::tools::handlers::RequestUserInputHandler; use crate::tools::handlers::ShellCommandHandler; use crate::tools::handlers::ShellHandler; use crate::tools::handlers::TestSyncHandler; use crate::tools::handlers::ToolSearchHandler; - use crate::tools::handlers::ToolSuggestHandler; use crate::tools::handlers::UnavailableToolHandler; use crate::tools::handlers::UnifiedExecHandler; use crate::tools::handlers::ViewImageHandler; @@ -174,7 +174,7 @@ pub(crate) fn build_specs_with_discoverable_tools( .cloned() .collect::>(); let mut tool_search_handler = None; - let tool_suggest_handler = Arc::new(ToolSuggestHandler); + let request_plugin_install_handler = Arc::new(RequestPluginInstallHandler); let code_mode_handler = Arc::new(CodeModeExecuteHandler); let code_mode_wait_handler = Arc::new(CodeModeWaitHandler); let unavailable_tool_handler = Arc::new(UnavailableToolHandler); @@ -281,8 +281,8 @@ pub(crate) fn build_specs_with_discoverable_tools( builder.register_handler(handler.name, tool_search_handler.clone()); } } - ToolHandlerKind::ToolSuggest => { - builder.register_handler(handler.name, tool_suggest_handler.clone()); + ToolHandlerKind::RequestPluginInstall => { + builder.register_handler(handler.name, request_plugin_install_handler.clone()); } ToolHandlerKind::UnifiedExec => { builder.register_handler(handler.name, unified_exec_handler.clone()); diff --git a/codex-rs/core/src/tools/spec_tests.rs b/codex-rs/core/src/tools/spec_tests.rs index afa586dc62..33cbb2718d 100644 --- a/codex-rs/core/src/tools/spec_tests.rs +++ b/codex-rs/core/src/tools/spec_tests.rs @@ -21,11 +21,11 @@ use codex_tools::ConfiguredToolSpec; use codex_tools::DiscoverableTool; use codex_tools::JsonSchema; use codex_tools::LoadableToolSpec; +use codex_tools::REQUEST_PLUGIN_INSTALL_TOOL_NAME; use codex_tools::ResponsesApiNamespaceTool; use codex_tools::ResponsesApiTool; use codex_tools::ShellCommandBackendConfig; use codex_tools::TOOL_SEARCH_TOOL_NAME; -use codex_tools::TOOL_SUGGEST_TOOL_NAME; use codex_tools::ToolName; use codex_tools::ToolSpec; use codex_tools::ToolsConfig; @@ -791,7 +791,7 @@ async fn multi_agent_v2_wait_agent_schema_uses_configured_min_timeout() { } #[tokio::test] -async fn tool_suggest_requires_apps_and_plugins_features() { +async fn request_plugin_install_requires_apps_and_plugins_features() { let model_info = search_capable_model_info().await; let discoverable_tools = Some(vec![discoverable_connector( "connector_2128aebfecb84f64a069897515042a44", @@ -831,7 +831,7 @@ async fn tool_suggest_requires_apps_and_plugins_features() { assert!( !tools .iter() - .any(|tool| tool.name() == TOOL_SUGGEST_TOOL_NAME), + .any(|tool| tool.name() == REQUEST_PLUGIN_INSTALL_TOOL_NAME), "tool_suggest should be absent when {disabled_feature:?} is disabled" ); } diff --git a/codex-rs/core/templates/search_tool/request_plugin_install_description.md b/codex-rs/core/templates/search_tool/request_plugin_install_description.md new file mode 100644 index 0000000000..437c8651e8 --- /dev/null +++ b/codex-rs/core/templates/search_tool/request_plugin_install_description.md @@ -0,0 +1,29 @@ +# Request plugin/connector install + +Use this tool only to ask the user to install one known plugin or connector from the list below. The list contains known candidates that are not currently installed. + +Use this ONLY when all of the following are true: +- The user explicitly asks to use a specific plugin or connector that is not already available in the current context or active `tools` list. +- `tool_search` is not available, or it has already been called and did not find or make the requested tool callable. +- The plugin or connector is one of the known installable plugins or connectors listed below. Only ask to install plugins or connectors from this list. + +Do not use this tool for adjacent capabilities, broad recommendations, or tools that merely seem useful. Only use when the user explicitly asks to use that exact listed plugin or connector. + +Known plugins/connectors available to install: +{{discoverable_tools}} + +Workflow: + +1. Check the current context and active `tools` list first. If current active tools aren't relevant and `tool_search` is available, only call this tool after `tool_search` has already been tried and found no relevant tool. +2. Match the user's explicit request against the known plugin/connector list above. Only proceed when one listed plugin or connector exactly fits. +3. If we found both connectors and plugins to install, use plugins first, only use connectors if the corresponding plugin is installed but the connector is not. +4. If one plugin or connector clearly fits, call `request_plugin_install` with: + - `tool_type`: `connector` or `plugin` + - `action_type`: `install` + - `tool_id`: exact id from the known plugin/connector list above + - `suggest_reason`: concise one-line user-facing reason this plugin or connector can help with the current request +5. After the request flow completes: + - if the user finished the install flow, continue by searching again or using the newly available plugin or connector + - if the user did not finish, continue without that plugin or connector, and don't request it again unless the user explicitly asks for it. + +IMPORTANT: DO NOT call this tool in parallel with other tools. diff --git a/codex-rs/core/templates/search_tool/tool_suggest_description.md b/codex-rs/core/templates/search_tool/tool_suggest_description.md deleted file mode 100644 index 9bed2d9d7b..0000000000 --- a/codex-rs/core/templates/search_tool/tool_suggest_description.md +++ /dev/null @@ -1,29 +0,0 @@ -# Tool suggestion discovery - -Use this tool only to ask the user to install one known plugin or connector from the list below. The list contains known candidates that are not currently installed. - -Use this ONLY when all of the following are true: -- The user explicitly wants a specific plugin or connector that is not already available in the current context or active `tools` list. -- `tool_search` is not available, or it has already been called and did not find or make the requested tool callable. -- The tool is one of the known installable plugins or connectors listed below. Only ask to install tools from this list. - -Do not use tool suggestion for adjacent capabilities, broad recommendations, or tools that merely seem useful. The user's intent must clearly match one listed tool. - -Known plugins/connectors available to install: -{{discoverable_tools}} - -Workflow: - -1. Check the current context and active `tools` list first. If `tool_search` is available, call `tool_search` before calling `tool_suggest`. Do not use tool suggestion if the needed tool is already available, found through `tool_search`, or callable after discovery. -2. Match the user's explicit request against the known plugin/connector list above. Only proceed when one listed plugin or connector exactly fits. -3. If we found both connectors and plugins to suggest, use plugins first, only use connectors if the corresponding plugin is installed but the connector is not. -4. If one tool clearly fits, call `tool_suggest` with: - - `tool_type`: `connector` or `plugin` - - `action_type`: `install` - - `tool_id`: exact id from the known plugin/connector list above - - `suggest_reason`: concise one-line user-facing reason this tool can help with the current request -5. After the suggestion flow completes: - - if the user finished the install flow, continue by searching again or using the newly available tool - - if the user did not finish, continue without that tool, and don't suggest that tool again unless the user explicitly asks for it. - -IMPORTANT: DO NOT call this tool in parallel with other tools. diff --git a/codex-rs/core/tests/suite/mod.rs b/codex-rs/core/tests/suite/mod.rs index fb96e23c8b..2f9478f3db 100644 --- a/codex-rs/core/tests/suite/mod.rs +++ b/codex-rs/core/tests/suite/mod.rs @@ -77,6 +77,7 @@ mod request_compression; mod request_permissions; #[cfg(not(target_os = "windows"))] mod request_permissions_tool; +mod request_plugin_install; mod request_user_input; mod responses_api_proxy_headers; mod resume; @@ -98,7 +99,6 @@ mod stream_no_completed; mod subagent_notifications; mod tool_harness; mod tool_parallelism; -mod tool_suggest; mod tools; mod truncation; mod turn_state; diff --git a/codex-rs/core/tests/suite/tool_suggest.rs b/codex-rs/core/tests/suite/request_plugin_install.rs similarity index 89% rename from codex-rs/core/tests/suite/tool_suggest.rs rename to codex-rs/core/tests/suite/request_plugin_install.rs index 6cb19d01a5..443ec7495f 100644 --- a/codex-rs/core/tests/suite/tool_suggest.rs +++ b/codex-rs/core/tests/suite/request_plugin_install.rs @@ -22,7 +22,7 @@ use core_test_support::test_codex::test_codex; use serde_json::Value; const TOOL_SEARCH_TOOL_NAME: &str = "tool_search"; -const TOOL_SUGGEST_TOOL_NAME: &str = "tool_suggest"; +const REQUEST_PLUGIN_INSTALL_TOOL_NAME: &str = "request_plugin_install"; const DISCOVERABLE_GMAIL_ID: &str = "connector_68df038e0ba48191908c8434991bbac2"; fn tool_names(body: &Value) -> Vec { @@ -89,7 +89,8 @@ fn configure_apps_without_search_tool(config: &mut Config, apps_base_url: &str) } #[tokio::test(flavor = "multi_thread", worker_threads = 2)] -async fn tool_suggest_is_available_without_search_tool_after_discovery_attempts() -> Result<()> { +async fn request_plugin_install_is_available_without_search_tool_after_discovery_attempts() +-> Result<()> { skip_if_no_network!(Ok(())); let server = start_mock_server().await; @@ -125,18 +126,23 @@ async fn tool_suggest_is_available_without_search_tool_after_discovery_attempts( "tools list should not include {TOOL_SEARCH_TOOL_NAME}: {tools:?}" ); assert!( - tools.iter().any(|name| name == TOOL_SUGGEST_TOOL_NAME), - "tools list should include {TOOL_SUGGEST_TOOL_NAME}: {tools:?}" + tools + .iter() + .any(|name| name == REQUEST_PLUGIN_INSTALL_TOOL_NAME), + "tools list should include {REQUEST_PLUGIN_INSTALL_TOOL_NAME}: {tools:?}" ); let description = - function_tool_description(&body, TOOL_SUGGEST_TOOL_NAME).expect("description"); + function_tool_description(&body, REQUEST_PLUGIN_INSTALL_TOOL_NAME).expect("description"); assert!(description.contains( "Use this tool only to ask the user to install one known plugin or connector from the list below" )); assert!(description.contains( "`tool_search` is not available, or it has already been called and did not find or make the requested tool callable." )); + assert!(description.contains( + "Only use when the user explicitly asks to use that exact listed plugin or connector." + )); assert!(description.contains("IMPORTANT: DO NOT call this tool in parallel with other tools.")); assert!(!description.contains("tool_search fails to find a good match")); diff --git a/codex-rs/tools/README.md b/codex-rs/tools/README.md index ac6bba853b..b85f8b2198 100644 --- a/codex-rs/tools/README.md +++ b/codex-rs/tools/README.md @@ -27,7 +27,7 @@ schema and Responses API tool primitives that no longer need to live in - collaboration and agent-job `ToolSpec` builders for spawn/send/wait/close, `request_user_input`, and CSV fanout/reporting - discoverable-tool models, client filtering, and `ToolSpec` builders for - `tool_search` and `tool_suggest` + `tool_search` and `request_plugin_install` - `parse_tool_input_schema()` - `parse_dynamic_tool()` - `parse_mcp_tool()` diff --git a/codex-rs/tools/src/lib.rs b/codex-rs/tools/src/lib.rs index 64b47f2fee..40e5b03468 100644 --- a/codex-rs/tools/src/lib.rs +++ b/codex-rs/tools/src/lib.rs @@ -13,6 +13,7 @@ mod local_tool; mod mcp_resource_tool; mod mcp_tool; mod plan_tool; +mod request_plugin_install; mod request_user_input_tool; mod responses_api; mod tool_config; @@ -21,7 +22,6 @@ mod tool_discovery; mod tool_registry_plan; mod tool_registry_plan_types; mod tool_spec; -mod tool_suggest; mod utility_tool; mod view_image; @@ -80,6 +80,15 @@ pub use mcp_resource_tool::create_read_mcp_resource_tool; pub use mcp_tool::mcp_call_tool_result_output_schema; pub use mcp_tool::parse_mcp_tool; pub use plan_tool::create_update_plan_tool; +pub use request_plugin_install::REQUEST_PLUGIN_INSTALL_APPROVAL_KIND_VALUE; +pub use request_plugin_install::REQUEST_PLUGIN_INSTALL_PERSIST_ALWAYS_VALUE; +pub use request_plugin_install::REQUEST_PLUGIN_INSTALL_PERSIST_KEY; +pub use request_plugin_install::RequestPluginInstallArgs; +pub use request_plugin_install::RequestPluginInstallMeta; +pub use request_plugin_install::RequestPluginInstallResult; +pub use request_plugin_install::all_requested_connectors_picked_up; +pub use request_plugin_install::build_request_plugin_install_elicitation_request; +pub use request_plugin_install::verified_connector_install_completed; pub use request_user_input_tool::REQUEST_USER_INPUT_TOOL_NAME; pub use request_user_input_tool::create_request_user_input_tool; pub use request_user_input_tool::normalize_request_user_input_args; @@ -110,18 +119,18 @@ pub use tool_discovery::DiscoverablePluginInfo; pub use tool_discovery::DiscoverableTool; pub use tool_discovery::DiscoverableToolAction; pub use tool_discovery::DiscoverableToolType; +pub use tool_discovery::REQUEST_PLUGIN_INSTALL_TOOL_NAME; +pub use tool_discovery::RequestPluginInstallEntry; pub use tool_discovery::TOOL_SEARCH_DEFAULT_LIMIT; pub use tool_discovery::TOOL_SEARCH_TOOL_NAME; -pub use tool_discovery::TOOL_SUGGEST_TOOL_NAME; pub use tool_discovery::ToolSearchResultSource; pub use tool_discovery::ToolSearchSource; pub use tool_discovery::ToolSearchSourceInfo; -pub use tool_discovery::ToolSuggestEntry; +pub use tool_discovery::collect_request_plugin_install_entries; pub use tool_discovery::collect_tool_search_source_infos; -pub use tool_discovery::collect_tool_suggest_entries; +pub use tool_discovery::create_request_plugin_install_tool; pub use tool_discovery::create_tool_search_tool; -pub use tool_discovery::create_tool_suggest_tool; -pub use tool_discovery::filter_tool_suggest_discoverable_tools_for_client; +pub use tool_discovery::filter_request_plugin_install_discoverable_tools_for_client; pub use tool_discovery::tool_search_result_source_to_loadable_tool_spec; pub use tool_registry_plan::build_tool_registry_plan; pub use tool_registry_plan_types::ToolHandlerKind; @@ -140,15 +149,6 @@ pub use tool_spec::create_image_generation_tool; pub use tool_spec::create_local_shell_tool; pub use tool_spec::create_tools_json_for_responses_api; pub use tool_spec::create_web_search_tool; -pub use tool_suggest::TOOL_SUGGEST_APPROVAL_KIND_VALUE; -pub use tool_suggest::TOOL_SUGGEST_PERSIST_ALWAYS_VALUE; -pub use tool_suggest::TOOL_SUGGEST_PERSIST_KEY; -pub use tool_suggest::ToolSuggestArgs; -pub use tool_suggest::ToolSuggestMeta; -pub use tool_suggest::ToolSuggestResult; -pub use tool_suggest::all_suggested_connectors_picked_up; -pub use tool_suggest::build_tool_suggestion_elicitation_request; -pub use tool_suggest::verified_connector_suggestion_completed; pub use utility_tool::create_list_dir_tool; pub use utility_tool::create_test_sync_tool; pub use view_image::ViewImageToolOptions; diff --git a/codex-rs/tools/src/tool_suggest.rs b/codex-rs/tools/src/request_plugin_install.rs similarity index 76% rename from codex-rs/tools/src/tool_suggest.rs rename to codex-rs/tools/src/request_plugin_install.rs index 86e81dbbfe..70e9cb093d 100644 --- a/codex-rs/tools/src/tool_suggest.rs +++ b/codex-rs/tools/src/request_plugin_install.rs @@ -13,12 +13,12 @@ use crate::DiscoverableTool; use crate::DiscoverableToolAction; use crate::DiscoverableToolType; -pub const TOOL_SUGGEST_APPROVAL_KIND_VALUE: &str = "tool_suggestion"; -pub const TOOL_SUGGEST_PERSIST_KEY: &str = "persist"; -pub const TOOL_SUGGEST_PERSIST_ALWAYS_VALUE: &str = "always"; +pub const REQUEST_PLUGIN_INSTALL_APPROVAL_KIND_VALUE: &str = "tool_suggestion"; +pub const REQUEST_PLUGIN_INSTALL_PERSIST_KEY: &str = "persist"; +pub const REQUEST_PLUGIN_INSTALL_PERSIST_ALWAYS_VALUE: &str = "always"; #[derive(Debug, Deserialize)] -pub struct ToolSuggestArgs { +pub struct RequestPluginInstallArgs { pub tool_type: DiscoverableToolType, pub action_type: DiscoverableToolAction, pub tool_id: String, @@ -26,7 +26,7 @@ pub struct ToolSuggestArgs { } #[derive(Debug, Serialize, PartialEq, Eq)] -pub struct ToolSuggestResult { +pub struct RequestPluginInstallResult { pub completed: bool, pub user_confirmed: bool, pub tool_type: DiscoverableToolType, @@ -37,7 +37,7 @@ pub struct ToolSuggestResult { } #[derive(Debug, Serialize, PartialEq, Eq)] -pub struct ToolSuggestMeta<'a> { +pub struct RequestPluginInstallMeta<'a> { pub codex_approval_kind: &'static str, pub persist: &'static str, pub tool_type: DiscoverableToolType, @@ -49,11 +49,11 @@ pub struct ToolSuggestMeta<'a> { pub install_url: Option<&'a str>, } -pub fn build_tool_suggestion_elicitation_request( +pub fn build_request_plugin_install_elicitation_request( server_name: &str, thread_id: String, turn_id: String, - args: &ToolSuggestArgs, + args: &RequestPluginInstallArgs, suggest_reason: &str, tool: &DiscoverableTool, ) -> McpServerElicitationRequestParams { @@ -66,7 +66,7 @@ pub fn build_tool_suggestion_elicitation_request( turn_id: Some(turn_id), server_name: server_name.to_string(), request: McpServerElicitationRequest::Form { - meta: Some(json!(build_tool_suggestion_meta( + meta: Some(json!(build_request_plugin_install_meta( args.tool_type, args.action_type, suggest_reason, @@ -85,16 +85,16 @@ pub fn build_tool_suggestion_elicitation_request( } } -pub fn all_suggested_connectors_picked_up( +pub fn all_requested_connectors_picked_up( expected_connector_ids: &[String], accessible_connectors: &[AppInfo], ) -> bool { expected_connector_ids.iter().all(|connector_id| { - verified_connector_suggestion_completed(connector_id, accessible_connectors) + verified_connector_install_completed(connector_id, accessible_connectors) }) } -pub fn verified_connector_suggestion_completed( +pub fn verified_connector_install_completed( tool_id: &str, accessible_connectors: &[AppInfo], ) -> bool { @@ -104,17 +104,17 @@ pub fn verified_connector_suggestion_completed( .is_some_and(|connector| connector.is_accessible) } -fn build_tool_suggestion_meta<'a>( +fn build_request_plugin_install_meta<'a>( tool_type: DiscoverableToolType, action_type: DiscoverableToolAction, suggest_reason: &'a str, tool_id: &'a str, tool_name: &'a str, install_url: Option<&'a str>, -) -> ToolSuggestMeta<'a> { - ToolSuggestMeta { - codex_approval_kind: TOOL_SUGGEST_APPROVAL_KIND_VALUE, - persist: TOOL_SUGGEST_PERSIST_ALWAYS_VALUE, +) -> RequestPluginInstallMeta<'a> { + RequestPluginInstallMeta { + codex_approval_kind: REQUEST_PLUGIN_INSTALL_APPROVAL_KIND_VALUE, + persist: REQUEST_PLUGIN_INSTALL_PERSIST_ALWAYS_VALUE, tool_type, suggest_type: action_type, suggest_reason, @@ -125,5 +125,5 @@ fn build_tool_suggestion_meta<'a>( } #[cfg(test)] -#[path = "tool_suggest_tests.rs"] +#[path = "request_plugin_install_tests.rs"] mod tests; diff --git a/codex-rs/tools/src/tool_suggest_tests.rs b/codex-rs/tools/src/request_plugin_install_tests.rs similarity index 81% rename from codex-rs/tools/src/tool_suggest_tests.rs rename to codex-rs/tools/src/request_plugin_install_tests.rs index 056ef70151..ff2370ade7 100644 --- a/codex-rs/tools/src/tool_suggest_tests.rs +++ b/codex-rs/tools/src/request_plugin_install_tests.rs @@ -4,8 +4,8 @@ use pretty_assertions::assert_eq; use serde_json::json; #[test] -fn build_tool_suggestion_elicitation_request_uses_expected_shape() { - let args = ToolSuggestArgs { +fn build_request_plugin_install_elicitation_request_uses_expected_shape() { + let args = RequestPluginInstallArgs { tool_type: DiscoverableToolType::Connector, action_type: DiscoverableToolAction::Install, tool_id: "connector_2128aebfecb84f64a069897515042a44".to_string(), @@ -30,7 +30,7 @@ fn build_tool_suggestion_elicitation_request_uses_expected_shape() { plugin_display_names: Vec::new(), })); - let request = build_tool_suggestion_elicitation_request( + let request = build_request_plugin_install_elicitation_request( "codex-apps", "thread-1".to_string(), "turn-1".to_string(), @@ -46,9 +46,9 @@ fn build_tool_suggestion_elicitation_request_uses_expected_shape() { turn_id: Some("turn-1".to_string()), server_name: "codex-apps".to_string(), request: McpServerElicitationRequest::Form { - meta: Some(json!(ToolSuggestMeta { - codex_approval_kind: TOOL_SUGGEST_APPROVAL_KIND_VALUE, - persist: TOOL_SUGGEST_PERSIST_ALWAYS_VALUE, + meta: Some(json!(RequestPluginInstallMeta { + codex_approval_kind: REQUEST_PLUGIN_INSTALL_APPROVAL_KIND_VALUE, + persist: REQUEST_PLUGIN_INSTALL_PERSIST_ALWAYS_VALUE, tool_type: DiscoverableToolType::Connector, suggest_type: DiscoverableToolAction::Install, suggest_reason: "Plan and reference events from your calendar", @@ -71,8 +71,8 @@ fn build_tool_suggestion_elicitation_request_uses_expected_shape() { } #[test] -fn build_tool_suggestion_elicitation_request_for_plugin_omits_install_url() { - let args = ToolSuggestArgs { +fn build_request_plugin_install_elicitation_request_for_plugin_omits_install_url() { + let args = RequestPluginInstallArgs { tool_type: DiscoverableToolType::Plugin, action_type: DiscoverableToolAction::Install, tool_id: "sample@openai-curated".to_string(), @@ -87,7 +87,7 @@ fn build_tool_suggestion_elicitation_request_for_plugin_omits_install_url() { app_connector_ids: vec!["connector_calendar".to_string()], })); - let request = build_tool_suggestion_elicitation_request( + let request = build_request_plugin_install_elicitation_request( "codex-apps", "thread-1".to_string(), "turn-1".to_string(), @@ -103,9 +103,9 @@ fn build_tool_suggestion_elicitation_request_for_plugin_omits_install_url() { turn_id: Some("turn-1".to_string()), server_name: "codex-apps".to_string(), request: McpServerElicitationRequest::Form { - meta: Some(json!(ToolSuggestMeta { - codex_approval_kind: TOOL_SUGGEST_APPROVAL_KIND_VALUE, - persist: TOOL_SUGGEST_PERSIST_ALWAYS_VALUE, + meta: Some(json!(RequestPluginInstallMeta { + codex_approval_kind: REQUEST_PLUGIN_INSTALL_APPROVAL_KIND_VALUE, + persist: REQUEST_PLUGIN_INSTALL_PERSIST_ALWAYS_VALUE, tool_type: DiscoverableToolType::Plugin, suggest_type: DiscoverableToolAction::Install, suggest_reason: "Use the sample plugin's skills and MCP server", @@ -126,8 +126,8 @@ fn build_tool_suggestion_elicitation_request_for_plugin_omits_install_url() { } #[test] -fn build_tool_suggestion_meta_uses_expected_shape() { - let meta = build_tool_suggestion_meta( +fn build_request_plugin_install_meta_uses_expected_shape() { + let meta = build_request_plugin_install_meta( DiscoverableToolType::Connector, DiscoverableToolAction::Install, "Find and reference emails from your inbox", @@ -138,9 +138,9 @@ fn build_tool_suggestion_meta_uses_expected_shape() { assert_eq!( meta, - ToolSuggestMeta { - codex_approval_kind: TOOL_SUGGEST_APPROVAL_KIND_VALUE, - persist: TOOL_SUGGEST_PERSIST_ALWAYS_VALUE, + RequestPluginInstallMeta { + codex_approval_kind: REQUEST_PLUGIN_INSTALL_APPROVAL_KIND_VALUE, + persist: REQUEST_PLUGIN_INSTALL_PERSIST_ALWAYS_VALUE, tool_type: DiscoverableToolType::Connector, suggest_type: DiscoverableToolAction::Install, suggest_reason: "Find and reference emails from your inbox", @@ -154,7 +154,7 @@ fn build_tool_suggestion_meta_uses_expected_shape() { } #[test] -fn verified_connector_suggestion_completed_requires_accessible_connector() { +fn verified_connector_install_completed_requires_accessible_connector() { let accessible_connectors = vec![AppInfo { id: "calendar".to_string(), name: "Google Calendar".to_string(), @@ -171,18 +171,18 @@ fn verified_connector_suggestion_completed_requires_accessible_connector() { plugin_display_names: Vec::new(), }]; - assert!(verified_connector_suggestion_completed( + assert!(verified_connector_install_completed( "calendar", &accessible_connectors, )); - assert!(!verified_connector_suggestion_completed( + assert!(!verified_connector_install_completed( "gmail", &accessible_connectors, )); } #[test] -fn all_suggested_connectors_picked_up_requires_every_expected_connector() { +fn all_requested_connectors_picked_up_requires_every_expected_connector() { let accessible_connectors = vec![AppInfo { id: "calendar".to_string(), name: "Google Calendar".to_string(), @@ -199,11 +199,11 @@ fn all_suggested_connectors_picked_up_requires_every_expected_connector() { plugin_display_names: Vec::new(), }]; - assert!(all_suggested_connectors_picked_up( + assert!(all_requested_connectors_picked_up( &["calendar".to_string()], &accessible_connectors, )); - assert!(!all_suggested_connectors_picked_up( + assert!(!all_requested_connectors_picked_up( &["calendar".to_string(), "gmail".to_string()], &accessible_connectors, )); diff --git a/codex-rs/tools/src/tool_discovery.rs b/codex-rs/tools/src/tool_discovery.rs index 74977dce38..9b3dd5df9f 100644 --- a/codex-rs/tools/src/tool_discovery.rs +++ b/codex-rs/tools/src/tool_discovery.rs @@ -15,7 +15,7 @@ use std::collections::BTreeMap; const TUI_CLIENT_NAME: &str = "codex-tui"; pub const TOOL_SEARCH_TOOL_NAME: &str = "tool_search"; pub const TOOL_SEARCH_DEFAULT_LIMIT: usize = 8; -pub const TOOL_SUGGEST_TOOL_NAME: &str = "tool_suggest"; +pub const REQUEST_PLUGIN_INSTALL_TOOL_NAME: &str = "request_plugin_install"; #[derive(Clone, Debug, PartialEq, Eq)] pub struct ToolSearchSourceInfo { @@ -111,7 +111,7 @@ impl From for DiscoverableTool { } } -pub fn filter_tool_suggest_discoverable_tools_for_client( +pub fn filter_request_plugin_install_discoverable_tools_for_client( discoverable_tools: Vec, app_server_client_name: Option<&str>, ) -> Vec { @@ -136,7 +136,7 @@ pub struct DiscoverablePluginInfo { } #[derive(Clone, Debug, PartialEq, Eq)] -pub struct ToolSuggestEntry { +pub struct RequestPluginInstallEntry { pub id: String, pub name: String, pub description: Option, @@ -271,7 +271,9 @@ pub fn collect_tool_search_source_infos<'a>( .collect() } -pub fn create_tool_suggest_tool(discoverable_tools: &[ToolSuggestEntry]) -> ToolSpec { +pub fn create_request_plugin_install_tool( + discoverable_tools: &[RequestPluginInstallEntry], +) -> ToolSpec { let properties = BTreeMap::from([ ( "tool_type".to_string(), @@ -291,7 +293,7 @@ pub fn create_tool_suggest_tool(discoverable_tools: &[ToolSuggestEntry]) -> Tool ( "suggest_reason".to_string(), JsonSchema::string(Some( - "Concise one-line user-facing reason why this tool can help with the current request." + "Concise one-line user-facing reason why this plugin or connector can help with the current request." .to_string(), )), ), @@ -299,11 +301,11 @@ pub fn create_tool_suggest_tool(discoverable_tools: &[ToolSuggestEntry]) -> Tool let discoverable_tools = format_discoverable_tools(discoverable_tools); let description = format!( - "# Tool suggestion discovery\n\nUse this tool only to ask the user to install one known plugin or connector from the list below. The list contains known candidates that are not currently installed.\n\nUse this ONLY when all of the following are true:\n- The user explicitly wants a specific plugin or connector that is not already available in the current context or active `tools` list.\n- `{TOOL_SEARCH_TOOL_NAME}` is not available, or it has already been called and did not find or make the requested tool callable.\n- The tool is one of the known installable plugins or connectors listed below. Only ask to install tools from this list.\n\nDo not use tool suggestion for adjacent capabilities, broad recommendations, or tools that merely seem useful. The user's intent must clearly match one listed tool.\n\nKnown plugins/connectors available to install:\n{discoverable_tools}\n\nWorkflow:\n\n1. Check the current context and active `tools` list first. If `{TOOL_SEARCH_TOOL_NAME}` is available, call `{TOOL_SEARCH_TOOL_NAME}` before calling `{TOOL_SUGGEST_TOOL_NAME}`. Do not use tool suggestion if the needed tool is already available, found through `{TOOL_SEARCH_TOOL_NAME}`, or callable after discovery.\n2. Match the user's explicit request against the known plugin/connector list above. Only proceed when one listed plugin or connector exactly fits.\n3. If we found both connectors and plugins to suggest, use plugins first, only use connectors if the corresponding plugin is installed but the connector is not.\n4. If one tool clearly fits, call `{TOOL_SUGGEST_TOOL_NAME}` with:\n - `tool_type`: `connector` or `plugin`\n - `action_type`: `install`\n - `tool_id`: exact id from the known plugin/connector list above\n - `suggest_reason`: concise one-line user-facing reason this tool can help with the current request\n5. After the suggestion flow completes:\n - if the user finished the install flow, continue by searching again or using the newly available tool\n - if the user did not finish, continue without that tool, and don't suggest that tool again unless the user explicitly asks for it.\n\nIMPORTANT: DO NOT call this tool in parallel with other tools." + "# Request plugin/connector install\n\nUse this tool only to ask the user to install one known plugin or connector from the list below. The list contains known candidates that are not currently installed.\n\nUse this ONLY when all of the following are true:\n- The user explicitly asks to use a specific plugin or connector that is not already available in the current context or active `tools` list.\n- `{TOOL_SEARCH_TOOL_NAME}` is not available, or it has already been called and did not find or make the requested tool callable.\n- The plugin or connector is one of the known installable plugins or connectors listed below. Only ask to install plugins or connectors from this list.\n\nDo not use this tool for adjacent capabilities, broad recommendations, or tools that merely seem useful. Only use when the user explicitly asks to use that exact listed plugin or connector.\n\nKnown plugins/connectors available to install:\n{discoverable_tools}\n\nWorkflow:\n\n1. Check the current context and active `tools` list first. If current active tools aren't relevant and `{TOOL_SEARCH_TOOL_NAME}` is available, only call this tool after `{TOOL_SEARCH_TOOL_NAME}` has already been tried and found no relevant tool.\n2. Match the user's explicit request against the known plugin/connector list above. Only proceed when one listed plugin or connector exactly fits.\n3. If we found both connectors and plugins to install, use plugins first, only use connectors if the corresponding plugin is installed but the connector is not.\n4. If one plugin or connector clearly fits, call `{REQUEST_PLUGIN_INSTALL_TOOL_NAME}` with:\n - `tool_type`: `connector` or `plugin`\n - `action_type`: `install`\n - `tool_id`: exact id from the known plugin/connector list above\n - `suggest_reason`: concise one-line user-facing reason this plugin or connector can help with the current request\n5. After the request flow completes:\n - if the user finished the install flow, continue by searching again or using the newly available plugin or connector\n - if the user did not finish, continue without that plugin or connector, and don't request it again unless the user explicitly asks for it.\n\nIMPORTANT: DO NOT call this tool in parallel with other tools." ); ToolSpec::Function(ResponsesApiTool { - name: TOOL_SUGGEST_TOOL_NAME.to_string(), + name: REQUEST_PLUGIN_INSTALL_TOOL_NAME.to_string(), description, strict: false, defer_loading: None, @@ -321,13 +323,13 @@ pub fn create_tool_suggest_tool(discoverable_tools: &[ToolSuggestEntry]) -> Tool }) } -pub fn collect_tool_suggest_entries( +pub fn collect_request_plugin_install_entries( discoverable_tools: &[DiscoverableTool], -) -> Vec { +) -> Vec { discoverable_tools .iter() .map(|tool| match tool { - DiscoverableTool::Connector(connector) => ToolSuggestEntry { + DiscoverableTool::Connector(connector) => RequestPluginInstallEntry { id: connector.id.clone(), name: connector.name.clone(), description: connector.description.clone(), @@ -336,7 +338,7 @@ pub fn collect_tool_suggest_entries( mcp_server_names: Vec::new(), app_connector_ids: Vec::new(), }, - DiscoverableTool::Plugin(plugin) => ToolSuggestEntry { + DiscoverableTool::Plugin(plugin) => RequestPluginInstallEntry { id: plugin.id.clone(), name: plugin.name.clone(), description: plugin.description.clone(), @@ -349,7 +351,7 @@ pub fn collect_tool_suggest_entries( .collect() } -fn format_discoverable_tools(discoverable_tools: &[ToolSuggestEntry]) -> String { +fn format_discoverable_tools(discoverable_tools: &[RequestPluginInstallEntry]) -> String { let mut discoverable_tools = discoverable_tools.to_vec(); discoverable_tools.sort_by(|left, right| { left.name @@ -373,7 +375,7 @@ fn format_discoverable_tools(discoverable_tools: &[ToolSuggestEntry]) -> String .join("\n") } -fn tool_description_or_fallback(tool: &ToolSuggestEntry) -> String { +fn tool_description_or_fallback(tool: &RequestPluginInstallEntry) -> String { if let Some(description) = tool .description .as_deref() @@ -389,7 +391,7 @@ fn tool_description_or_fallback(tool: &ToolSuggestEntry) -> String { } } -fn plugin_summary(tool: &ToolSuggestEntry) -> String { +fn plugin_summary(tool: &RequestPluginInstallEntry) -> String { let mut details = Vec::new(); if tool.has_skills { details.push("skills".to_string()); diff --git a/codex-rs/tools/src/tool_discovery_tests.rs b/codex-rs/tools/src/tool_discovery_tests.rs index 9edbccffaa..7a08ec100e 100644 --- a/codex-rs/tools/src/tool_discovery_tests.rs +++ b/codex-rs/tools/src/tool_discovery_tests.rs @@ -49,36 +49,36 @@ fn create_tool_search_tool_deduplicates_and_renders_enabled_sources() { } #[test] -fn create_tool_suggest_tool_uses_plugin_summary_fallback() { +fn create_request_plugin_install_tool_uses_plugin_summary_fallback() { let expected_description = concat!( - "# Tool suggestion discovery\n\n", + "# Request plugin/connector install\n\n", "Use this tool only to ask the user to install one known plugin or connector from the list below. The list contains known candidates that are not currently installed.\n\n", "Use this ONLY when all of the following are true:\n", - "- The user explicitly wants a specific plugin or connector that is not already available in the current context or active `tools` list.\n", + "- The user explicitly asks to use a specific plugin or connector that is not already available in the current context or active `tools` list.\n", "- `tool_search` is not available, or it has already been called and did not find or make the requested tool callable.\n", - "- The tool is one of the known installable plugins or connectors listed below. Only ask to install tools from this list.\n\n", - "Do not use tool suggestion for adjacent capabilities, broad recommendations, or tools that merely seem useful. The user's intent must clearly match one listed tool.\n\n", + "- The plugin or connector is one of the known installable plugins or connectors listed below. Only ask to install plugins or connectors from this list.\n\n", + "Do not use this tool for adjacent capabilities, broad recommendations, or tools that merely seem useful. Only use when the user explicitly asks to use that exact listed plugin or connector.\n\n", "Known plugins/connectors available to install:\n", "- GitHub (id: `github`, type: plugin, action: install): skills; MCP servers: github-mcp; app connectors: github-app\n", "- Slack (id: `slack@openai-curated`, type: connector, action: install): No description provided.\n\n", "Workflow:\n\n", - "1. Check the current context and active `tools` list first. If `tool_search` is available, call `tool_search` before calling `tool_suggest`. Do not use tool suggestion if the needed tool is already available, found through `tool_search`, or callable after discovery.\n", + "1. Check the current context and active `tools` list first. If current active tools aren't relevant and `tool_search` is available, only call this tool after `tool_search` has already been tried and found no relevant tool.\n", "2. Match the user's explicit request against the known plugin/connector list above. Only proceed when one listed plugin or connector exactly fits.\n", - "3. If we found both connectors and plugins to suggest, use plugins first, only use connectors if the corresponding plugin is installed but the connector is not.\n", - "4. If one tool clearly fits, call `tool_suggest` with:\n", + "3. If we found both connectors and plugins to install, use plugins first, only use connectors if the corresponding plugin is installed but the connector is not.\n", + "4. If one plugin or connector clearly fits, call `request_plugin_install` with:\n", " - `tool_type`: `connector` or `plugin`\n", " - `action_type`: `install`\n", " - `tool_id`: exact id from the known plugin/connector list above\n", - " - `suggest_reason`: concise one-line user-facing reason this tool can help with the current request\n", - "5. After the suggestion flow completes:\n", - " - if the user finished the install flow, continue by searching again or using the newly available tool\n", - " - if the user did not finish, continue without that tool, and don't suggest that tool again unless the user explicitly asks for it.\n\n", + " - `suggest_reason`: concise one-line user-facing reason this plugin or connector can help with the current request\n", + "5. After the request flow completes:\n", + " - if the user finished the install flow, continue by searching again or using the newly available plugin or connector\n", + " - if the user did not finish, continue without that plugin or connector, and don't request it again unless the user explicitly asks for it.\n\n", "IMPORTANT: DO NOT call this tool in parallel with other tools.", ); assert_eq!( - create_tool_suggest_tool(&[ - ToolSuggestEntry { + create_request_plugin_install_tool(&[ + RequestPluginInstallEntry { id: "slack@openai-curated".to_string(), name: "Slack".to_string(), description: None, @@ -87,7 +87,7 @@ fn create_tool_suggest_tool_uses_plugin_summary_fallback() { mcp_server_names: Vec::new(), app_connector_ids: Vec::new(), }, - ToolSuggestEntry { + RequestPluginInstallEntry { id: "github".to_string(), name: "GitHub".to_string(), description: None, @@ -98,7 +98,7 @@ fn create_tool_suggest_tool_uses_plugin_summary_fallback() { }, ]), ToolSpec::Function(ResponsesApiTool { - name: "tool_suggest".to_string(), + name: "request_plugin_install".to_string(), description: expected_description.to_string(), strict: false, defer_loading: None, @@ -113,7 +113,7 @@ fn create_tool_suggest_tool_uses_plugin_summary_fallback() { ( "suggest_reason".to_string(), JsonSchema::string(Some( - "Concise one-line user-facing reason why this tool can help with the current request." + "Concise one-line user-facing reason why this plugin or connector can help with the current request." .to_string(), ),), ), @@ -157,7 +157,7 @@ fn discoverable_tool_enums_use_expected_wire_names() { } #[test] -fn filter_tool_suggest_discoverable_tools_for_codex_tui_omits_plugins() { +fn filter_request_plugin_install_discoverable_tools_for_codex_tui_omits_plugins() { let discoverable_tools = vec![ DiscoverableTool::Connector(Box::new(AppInfo { id: "connector_google_calendar".to_string(), @@ -185,7 +185,10 @@ fn filter_tool_suggest_discoverable_tools_for_codex_tui_omits_plugins() { ]; assert_eq!( - filter_tool_suggest_discoverable_tools_for_client(discoverable_tools, Some("codex-tui"),), + filter_request_plugin_install_discoverable_tools_for_client( + discoverable_tools, + Some("codex-tui"), + ), vec![DiscoverableTool::Connector(Box::new(AppInfo { id: "connector_google_calendar".to_string(), name: "Google Calendar".to_string(), diff --git a/codex-rs/tools/src/tool_registry_plan.rs b/codex-rs/tools/src/tool_registry_plan.rs index 1da71ab04a..c00c7c8b13 100644 --- a/codex-rs/tools/src/tool_registry_plan.rs +++ b/codex-rs/tools/src/tool_registry_plan.rs @@ -1,4 +1,5 @@ use crate::CommandToolOptions; +use crate::REQUEST_PLUGIN_INSTALL_TOOL_NAME; use crate::REQUEST_USER_INPUT_TOOL_NAME; use crate::ResponsesApiNamespace; use crate::ResponsesApiNamespaceTool; @@ -6,7 +7,6 @@ use crate::ShellToolOptions; use crate::SpawnAgentToolOptions; use crate::TOOL_SEARCH_DEFAULT_LIMIT; use crate::TOOL_SEARCH_TOOL_NAME; -use crate::TOOL_SUGGEST_TOOL_NAME; use crate::ToolHandlerKind; use crate::ToolName; use crate::ToolRegistryPlan; @@ -19,8 +19,8 @@ use crate::ViewImageToolOptions; use crate::WebSearchToolOptions; use crate::coalesce_loadable_tool_specs; use crate::collect_code_mode_exec_prompt_tool_definitions; +use crate::collect_request_plugin_install_entries; use crate::collect_tool_search_source_infos; -use crate::collect_tool_suggest_entries; use crate::create_apply_patch_freeform_tool; use crate::create_apply_patch_json_tool; use crate::create_close_agent_tool_v1; @@ -39,6 +39,7 @@ use crate::create_local_shell_tool; use crate::create_read_mcp_resource_tool; use crate::create_report_agent_job_result_tool; use crate::create_request_permissions_tool; +use crate::create_request_plugin_install_tool; use crate::create_request_user_input_tool; use crate::create_resume_agent_tool; use crate::create_send_input_tool_v1; @@ -50,7 +51,6 @@ use crate::create_spawn_agent_tool_v2; use crate::create_spawn_agents_on_csv_tool; use crate::create_test_sync_tool; use crate::create_tool_search_tool; -use crate::create_tool_suggest_tool; use crate::create_update_goal_tool; use crate::create_update_plan_tool; use crate::create_view_image_tool; @@ -312,11 +312,16 @@ pub fn build_tool_registry_plan( params.discoverable_tools.filter(|tools| !tools.is_empty()) { plan.push_spec( - create_tool_suggest_tool(&collect_tool_suggest_entries(discoverable_tools)), + create_request_plugin_install_tool(&collect_request_plugin_install_entries( + discoverable_tools, + )), /*supports_parallel_tool_calls*/ true, /*code_mode_enabled*/ false, ); - plan.register_handler(TOOL_SUGGEST_TOOL_NAME, ToolHandlerKind::ToolSuggest); + plan.register_handler( + REQUEST_PLUGIN_INSTALL_TOOL_NAME, + ToolHandlerKind::RequestPluginInstall, + ); } if config.has_environment diff --git a/codex-rs/tools/src/tool_registry_plan_tests.rs b/codex-rs/tools/src/tool_registry_plan_tests.rs index 9564c3eb86..71aef8b1a7 100644 --- a/codex-rs/tools/src/tool_registry_plan_tests.rs +++ b/codex-rs/tools/src/tool_registry_plan_tests.rs @@ -1692,7 +1692,7 @@ fn search_tool_keeps_plain_deferred_dynamic_tools_when_namespace_tools_are_disab } #[test] -fn tool_suggest_is_not_registered_without_feature_flag() { +fn request_plugin_install_is_not_registered_without_feature_flag() { let model_info = search_capable_model_info(); let mut features = Features::with_defaults(); features.enable(Feature::ToolSearch); @@ -1725,12 +1725,12 @@ fn tool_suggest_is_not_registered_without_feature_flag() { assert!( !tools .iter() - .any(|tool| tool.name() == TOOL_SUGGEST_TOOL_NAME) + .any(|tool| tool.name() == REQUEST_PLUGIN_INSTALL_TOOL_NAME) ); } #[test] -fn tool_suggest_can_be_registered_without_search_tool() { +fn request_plugin_install_can_be_registered_without_search_tool() { let model_info = ModelInfo { supports_search_tool: false, ..search_capable_model_info() @@ -1762,12 +1762,13 @@ fn tool_suggest_can_be_registered_without_search_tool() { &[], ); - assert_contains_tool_names(&tools, &[TOOL_SUGGEST_TOOL_NAME]); - let tool_suggest = find_tool(&tools, TOOL_SUGGEST_TOOL_NAME); - assert!(tool_suggest.supports_parallel_tool_calls); + assert_contains_tool_names(&tools, &[REQUEST_PLUGIN_INSTALL_TOOL_NAME]); + let request_plugin_install = find_tool(&tools, REQUEST_PLUGIN_INSTALL_TOOL_NAME); + assert!(request_plugin_install.supports_parallel_tool_calls); assert_lacks_tool_name(&tools, TOOL_SEARCH_TOOL_NAME); - let ToolSpec::Function(ResponsesApiTool { description, .. }) = &tool_suggest.spec else { + let ToolSpec::Function(ResponsesApiTool { description, .. }) = &request_plugin_install.spec + else { panic!("expected function tool"); }; assert!(description.contains( @@ -1779,7 +1780,7 @@ fn tool_suggest_can_be_registered_without_search_tool() { } #[test] -fn tool_suggest_description_lists_discoverable_tools() { +fn request_plugin_install_description_lists_discoverable_tools() { let model_info = search_capable_model_info(); let mut features = Features::with_defaults(); features.enable(Feature::Apps); @@ -1827,16 +1828,16 @@ fn tool_suggest_description_lists_discoverable_tools() { &[], ); assert!(handlers.contains(&ToolHandlerSpec { - name: ToolName::plain(TOOL_SUGGEST_TOOL_NAME), - kind: ToolHandlerKind::ToolSuggest, + name: ToolName::plain(REQUEST_PLUGIN_INSTALL_TOOL_NAME), + kind: ToolHandlerKind::RequestPluginInstall, })); - let tool_suggest = find_tool(&tools, TOOL_SUGGEST_TOOL_NAME); + let request_plugin_install = find_tool(&tools, REQUEST_PLUGIN_INSTALL_TOOL_NAME); let ToolSpec::Function(ResponsesApiTool { description, parameters, .. - }) = &tool_suggest.spec + }) = &request_plugin_install.spec else { panic!("expected function tool"); }; @@ -1855,30 +1856,27 @@ fn tool_suggest_description_lists_discoverable_tools() { ); assert!( description.contains( - "The user explicitly wants a specific plugin or connector that is not already available in the current context or active `tools` list." + "The user explicitly asks to use a specific plugin or connector that is not already available in the current context or active `tools` list." ) ); assert!(description.contains( "`tool_search` is not available, or it has already been called and did not find or make the requested tool callable." )); assert!(description.contains( - "The tool is one of the known installable plugins or connectors listed below. Only ask to install tools from this list." + "The plugin or connector is one of the known installable plugins or connectors listed below. Only ask to install plugins or connectors from this list." )); assert!(description.contains( - "Do not use tool suggestion for adjacent capabilities, broad recommendations, or tools that merely seem useful." + "Do not use this tool for adjacent capabilities, broad recommendations, or tools that merely seem useful." )); assert!(description.contains("IMPORTANT: DO NOT call this tool in parallel with other tools.")); assert!(description.contains( - "Do not use tool suggestion if the needed tool is already available, found through `tool_search`, or callable after discovery." - )); - assert!(description.contains( - "If `tool_search` is available, call `tool_search` before calling `tool_suggest`." + "If current active tools aren't relevant and `tool_search` is available, only call this tool after `tool_search` has already been tried and found no relevant tool." )); assert!(!description.contains("targeted lookup")); assert!(!description.contains("broad or speculative searches")); assert!(description.contains("Only proceed when one listed plugin or connector exactly fits.")); assert!(description.contains( - "If we found both connectors and plugins to suggest, use plugins first, only use connectors if the corresponding plugin is installed but the connector is not." + "If we found both connectors and plugins to install, use plugins first, only use connectors if the corresponding plugin is installed but the connector is not." )); assert!(!description.contains("{{discoverable_tools}}")); assert!(!description.contains("tool_search fails to find a good match")); diff --git a/codex-rs/tools/src/tool_registry_plan_types.rs b/codex-rs/tools/src/tool_registry_plan_types.rs index d22335b614..f6ea215ac1 100644 --- a/codex-rs/tools/src/tool_registry_plan_types.rs +++ b/codex-rs/tools/src/tool_registry_plan_types.rs @@ -35,7 +35,7 @@ pub enum ToolHandlerKind { SpawnAgentV2, TestSync, ToolSearch, - ToolSuggest, + RequestPluginInstall, UnifiedExec, ViewImage, WaitAgentV1, From 35aaa5d9fcb606fb6f27dd5747ecab3f4ba0c07e Mon Sep 17 00:00:00 2001 From: pakrym-oai Date: Fri, 1 May 2026 23:33:32 -0700 Subject: [PATCH 02/12] Bound websocket request sends with idle timeout (#20751) ## Why We saw Responses websocket sessions recover only after a long quiet period when the server had already logged the websocket as disconnected. The normal connect path is already bounded by `websocket_connect_timeout_ms`, but the first request send on an established websocket reused only the receive-side idle timeout after the write completed. If the socket write/pump stalls, the client can sit in `ws_stream.send(...)` without reaching the existing receive timeout. --- .../codex-api/src/endpoint/responses_websocket.rs | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) diff --git a/codex-rs/codex-api/src/endpoint/responses_websocket.rs b/codex-rs/codex-api/src/endpoint/responses_websocket.rs index 4e97ecef9d..dd947a9dd7 100644 --- a/codex-rs/codex-api/src/endpoint/responses_websocket.rs +++ b/codex-rs/codex-api/src/endpoint/responses_websocket.rs @@ -556,10 +556,15 @@ async fn run_websocket_response_stream( trace!("websocket request: {request_text}"); let request_start = Instant::now(); - let result = ws_stream - .send(Message::Text(request_text.into())) - .await - .map_err(|err| ApiError::Stream(format!("failed to send websocket request: {err}"))); + let result = tokio::time::timeout( + idle_timeout, + ws_stream.send(Message::Text(request_text.into())), + ) + .await + .map_err(|_| ApiError::Stream("idle timeout sending websocket request".into())) + .and_then(|result| { + result.map_err(|err| ApiError::Stream(format!("failed to send websocket request: {err}"))) + }); if let Some(t) = telemetry.as_ref() { t.on_ws_request( From fd6644fd82abc94ec3046195cd03c80850615e41 Mon Sep 17 00:00:00 2001 From: Abhinav Vedmala Date: Fri, 1 May 2026 23:57:56 -0700 Subject: [PATCH 03/12] Fix approval prompt lint callsites --- .../core/src/guardian/approval_request.rs | 28 +++++++++++-------- codex-rs/core/src/mcp_tool_call_tests.rs | 16 +++++++++-- 2 files changed, 31 insertions(+), 13 deletions(-) diff --git a/codex-rs/core/src/guardian/approval_request.rs b/codex-rs/core/src/guardian/approval_request.rs index 391e240c9b..d3c37b7296 100644 --- a/codex-rs/core/src/guardian/approval_request.rs +++ b/codex-rs/core/src/guardian/approval_request.rs @@ -20,7 +20,6 @@ use codex_protocol::request_user_input::RequestUserInputAnswer; use codex_protocol::request_user_input::RequestUserInputQuestion; use codex_protocol::request_user_input::RequestUserInputQuestionOption; use codex_protocol::request_user_input::RequestUserInputResponse; -use codex_shell_command::parse_command::shlex_join; use codex_utils_absolute_path::AbsolutePathBuf; use serde::Serialize; use serde_json::Value; @@ -163,7 +162,10 @@ impl ApprovalRequest { if argv.len() > 1 { command.extend_from_slice(&argv[1..]); } - Some(PermissionRequestPayload::bash(shlex_join(&command), None)) + Some(PermissionRequestPayload::bash( + codex_shell_command::parse_command::shlex_join(&command), + /*description*/ None, + )) } Self::ApplyPatch { patch, .. } => Some(PermissionRequestPayload { tool_name: HookToolName::apply_patch(), @@ -1144,9 +1146,9 @@ mod tests { "turn-1".to_string(), Some("approval-1".to_string()), Some("retry".to_string()), - None, - None, - None, + /*network_approval_context*/ None, + /*proposed_execpolicy_amendment*/ None, + /*proposed_network_policy_amendments*/ None, Some(vec![ReviewDecision::Approved, ReviewDecision::Abort]), /*fallback_cwd*/ None, ) @@ -1181,7 +1183,11 @@ mod tests { }; let event = request - .apply_patch_approval_event("turn-1".to_string(), Some("needs write".to_string()), None) + .apply_patch_approval_event( + "turn-1".to_string(), + Some("needs write".to_string()), + /*grant_root*/ None, + ) .expect("apply_patch approval event"); assert_eq!(event.call_id, "call-1"); @@ -1248,12 +1254,12 @@ mod tests { let event = request .exec_approval_event( "ignored-turn".to_string(), - None, + /*approval_id*/ None, Some("need network".to_string()), - None, - None, - None, - None, + /*network_approval_context*/ None, + /*proposed_execpolicy_amendment*/ None, + /*proposed_network_policy_amendments*/ None, + /*available_decisions*/ None, Some(test_path_buf("/tmp").abs()), ) .expect("network exec approval event"); diff --git a/codex-rs/core/src/mcp_tool_call_tests.rs b/codex-rs/core/src/mcp_tool_call_tests.rs index 04418ca414..eb1457b6ea 100644 --- a/codex-rs/core/src/mcp_tool_call_tests.rs +++ b/codex-rs/core/src/mcp_tool_call_tests.rs @@ -682,7 +682,13 @@ fn codex_apps_tool_question_uses_fallback_app_label() { #[test] fn trusted_codex_apps_tool_question_offers_always_allow() { - let metadata = approval_metadata(Some("calendar"), Some("Calendar"), None, None, None); + let metadata = approval_metadata( + Some("calendar"), + Some("Calendar"), + /*connector_description*/ None, + /*tool_title*/ None, + /*tool_description*/ None, + ); let question = approval_prompt_request( CODEX_APPS_MCP_SERVER_NAME, "run_action", @@ -730,7 +736,13 @@ fn codex_apps_tool_question_without_elicitation_omits_always_allow() { tool_name: "run_action".to_string(), }; let persistent_key = session_key.clone(); - let metadata = approval_metadata(Some("calendar"), Some("Calendar"), None, None, None); + let metadata = approval_metadata( + Some("calendar"), + Some("Calendar"), + /*connector_description*/ None, + /*tool_title*/ None, + /*tool_description*/ None, + ); let question = approval_prompt_request( CODEX_APPS_MCP_SERVER_NAME, "run_action", From ad605dc791dff2becd54654a6d75f8ff780fd9ab Mon Sep 17 00:00:00 2001 From: Abhinav Vedmala Date: Sat, 2 May 2026 00:24:20 -0700 Subject: [PATCH 04/12] restore GuardianApprovalRequest name --- codex-rs/core/src/codex_delegate.rs | 6 +- .../core/src/guardian/approval_request.rs | 98 +++++++++---------- codex-rs/core/src/guardian/mod.rs | 2 +- codex-rs/core/src/guardian/prompt.rs | 6 +- codex-rs/core/src/guardian/review.rs | 12 +-- codex-rs/core/src/guardian/review_session.rs | 6 +- codex-rs/core/src/guardian/tests.rs | 52 +++++----- codex-rs/core/src/mcp_tool_call.rs | 8 +- codex-rs/core/src/mcp_tool_call_tests.rs | 8 +- codex-rs/core/src/session/mod.rs | 8 +- codex-rs/core/src/tools/network_approval.rs | 4 +- codex-rs/core/src/tools/orchestrator.rs | 2 +- .../core/src/tools/runtimes/apply_patch.rs | 8 +- .../src/tools/runtimes/apply_patch_tests.rs | 4 +- codex-rs/core/src/tools/runtimes/shell.rs | 8 +- .../tools/runtimes/shell/unix_escalation.rs | 4 +- .../core/src/tools/runtimes/unified_exec.rs | 11 ++- codex-rs/core/src/tools/sandboxing.rs | 8 +- 18 files changed, 131 insertions(+), 124 deletions(-) diff --git a/codex-rs/core/src/codex_delegate.rs b/codex-rs/core/src/codex_delegate.rs index ce66cbdd9e..e3c23ab859 100644 --- a/codex-rs/core/src/codex_delegate.rs +++ b/codex-rs/core/src/codex_delegate.rs @@ -31,7 +31,7 @@ use tokio_util::sync::CancellationToken; use crate::config::Config; use crate::environment_selection::ResolvedTurnEnvironments; -use crate::guardian::ApprovalRequest; +use crate::guardian::GuardianApprovalRequest; use crate::guardian::is_mcp_tool_approval_question_id; use crate::guardian::new_guardian_review_id; use crate::guardian::routes_approval_to_guardian; @@ -450,7 +450,7 @@ async fn handle_exec_approval( .. } = event; let hook_command = shlex_join(&command); - let approval_request = ApprovalRequest::Shell { + let approval_request = GuardianApprovalRequest::Shell { id: call_id.clone(), command, hook_command, @@ -555,7 +555,7 @@ async fn handle_patch_approval( }) .collect::>() .join("\n"); - let approval_request = ApprovalRequest::ApplyPatch { + let approval_request = GuardianApprovalRequest::ApplyPatch { id: approval_id.clone(), cwd: parent_ctx.cwd.clone(), files: changes diff --git a/codex-rs/core/src/guardian/approval_request.rs b/codex-rs/core/src/guardian/approval_request.rs index d3c37b7296..4002dc91ea 100644 --- a/codex-rs/core/src/guardian/approval_request.rs +++ b/codex-rs/core/src/guardian/approval_request.rs @@ -37,7 +37,7 @@ use crate::tools::sandboxing::PermissionRequestPayload; /// guardian review, approval hooks, and user-prompt transports deriving their /// own projections from it. #[derive(Debug, Clone, PartialEq)] -pub(crate) enum ApprovalRequest { +pub(crate) enum GuardianApprovalRequest { Shell { id: String, command: Vec, @@ -140,7 +140,7 @@ pub(crate) const MCP_TOOL_APPROVAL_TOOL_DESCRIPTION_KEY: &str = "tool_descriptio pub(crate) const MCP_TOOL_APPROVAL_TOOL_PARAMS_KEY: &str = "tool_params"; pub(crate) const MCP_TOOL_APPROVAL_TOOL_PARAMS_DISPLAY_KEY: &str = "tool_params_display"; -impl ApprovalRequest { +impl GuardianApprovalRequest { pub(crate) fn permission_request_payload(&self) -> Option { match self { Self::Shell { @@ -838,10 +838,10 @@ pub(crate) struct FormattedGuardianAction { } pub(crate) fn guardian_approval_request_to_json( - action: &ApprovalRequest, + action: &GuardianApprovalRequest, ) -> serde_json::Result { match action { - ApprovalRequest::Shell { + GuardianApprovalRequest::Shell { id: _, command, cwd, @@ -858,7 +858,7 @@ pub(crate) fn guardian_approval_request_to_json( justification.as_ref(), /*tty*/ None, ), - ApprovalRequest::ExecCommand { + GuardianApprovalRequest::ExecCommand { id: _, command, cwd, @@ -877,7 +877,7 @@ pub(crate) fn guardian_approval_request_to_json( Some(*tty), ), #[cfg(unix)] - ApprovalRequest::Execve { + GuardianApprovalRequest::Execve { id: _, source, program, @@ -891,7 +891,7 @@ pub(crate) fn guardian_approval_request_to_json( cwd, additional_permissions: additional_permissions.as_ref(), }), - ApprovalRequest::ApplyPatch { + GuardianApprovalRequest::ApplyPatch { id: _, cwd, files, @@ -903,7 +903,7 @@ pub(crate) fn guardian_approval_request_to_json( "files": files, "patch": patch, })), - ApprovalRequest::NetworkAccess { + GuardianApprovalRequest::NetworkAccess { id: _, turn_id: _, target, @@ -920,7 +920,7 @@ pub(crate) fn guardian_approval_request_to_json( port: *port, trigger: trigger.as_ref(), }), - ApprovalRequest::McpToolCall { + GuardianApprovalRequest::McpToolCall { id: _, server, tool_name, @@ -944,7 +944,7 @@ pub(crate) fn guardian_approval_request_to_json( tool_description: tool_description.as_ref(), annotations: annotations.as_ref(), }), - ApprovalRequest::RequestPermissions { + GuardianApprovalRequest::RequestPermissions { id: _, turn_id, reason, @@ -959,16 +959,16 @@ pub(crate) fn guardian_approval_request_to_json( } } -pub(crate) fn guardian_assessment_action(action: &ApprovalRequest) -> GuardianAssessmentAction { +pub(crate) fn guardian_assessment_action(action: &GuardianApprovalRequest) -> GuardianAssessmentAction { match action { - ApprovalRequest::Shell { command, cwd, .. } => { + GuardianApprovalRequest::Shell { command, cwd, .. } => { command_assessment_action(GuardianCommandSource::Shell, command, cwd) } - ApprovalRequest::ExecCommand { command, cwd, .. } => { + GuardianApprovalRequest::ExecCommand { command, cwd, .. } => { command_assessment_action(GuardianCommandSource::UnifiedExec, command, cwd) } #[cfg(unix)] - ApprovalRequest::Execve { + GuardianApprovalRequest::Execve { source, program, argv, @@ -980,11 +980,11 @@ pub(crate) fn guardian_assessment_action(action: &ApprovalRequest) -> GuardianAs argv: argv.clone(), cwd: cwd.clone(), }, - ApprovalRequest::ApplyPatch { cwd, files, .. } => GuardianAssessmentAction::ApplyPatch { + GuardianApprovalRequest::ApplyPatch { cwd, files, .. } => GuardianAssessmentAction::ApplyPatch { cwd: cwd.clone(), files: files.clone(), }, - ApprovalRequest::NetworkAccess { + GuardianApprovalRequest::NetworkAccess { id: _id, turn_id: _turn_id, target, @@ -999,7 +999,7 @@ pub(crate) fn guardian_assessment_action(action: &ApprovalRequest) -> GuardianAs protocol: *protocol, port: *port, }, - ApprovalRequest::McpToolCall { + GuardianApprovalRequest::McpToolCall { server, tool_name, connector_id, @@ -1013,7 +1013,7 @@ pub(crate) fn guardian_assessment_action(action: &ApprovalRequest) -> GuardianAs connector_name: connector_name.clone(), tool_title: tool_title.clone(), }, - ApprovalRequest::RequestPermissions { + GuardianApprovalRequest::RequestPermissions { reason, permissions, .. @@ -1024,9 +1024,9 @@ pub(crate) fn guardian_assessment_action(action: &ApprovalRequest) -> GuardianAs } } -pub(crate) fn guardian_reviewed_action(request: &ApprovalRequest) -> GuardianReviewedAction { +pub(crate) fn guardian_reviewed_action(request: &GuardianApprovalRequest) -> GuardianReviewedAction { match request { - ApprovalRequest::Shell { + GuardianApprovalRequest::Shell { sandbox_permissions, additional_permissions, .. @@ -1034,7 +1034,7 @@ pub(crate) fn guardian_reviewed_action(request: &ApprovalRequest) -> GuardianRev sandbox_permissions: *sandbox_permissions, additional_permissions: additional_permissions.clone(), }, - ApprovalRequest::ExecCommand { + GuardianApprovalRequest::ExecCommand { sandbox_permissions, additional_permissions, tty, @@ -1045,7 +1045,7 @@ pub(crate) fn guardian_reviewed_action(request: &ApprovalRequest) -> GuardianRev tty: *tty, }, #[cfg(unix)] - ApprovalRequest::Execve { + GuardianApprovalRequest::Execve { source, program, additional_permissions, @@ -1055,14 +1055,14 @@ pub(crate) fn guardian_reviewed_action(request: &ApprovalRequest) -> GuardianRev program: program.clone(), additional_permissions: additional_permissions.clone(), }, - ApprovalRequest::ApplyPatch { .. } => GuardianReviewedAction::ApplyPatch {}, - ApprovalRequest::NetworkAccess { protocol, port, .. } => { + GuardianApprovalRequest::ApplyPatch { .. } => GuardianReviewedAction::ApplyPatch {}, + GuardianApprovalRequest::NetworkAccess { protocol, port, .. } => { GuardianReviewedAction::NetworkAccess { protocol: *protocol, port: *port, } } - ApprovalRequest::McpToolCall { + GuardianApprovalRequest::McpToolCall { server, tool_name, connector_id, @@ -1076,41 +1076,41 @@ pub(crate) fn guardian_reviewed_action(request: &ApprovalRequest) -> GuardianRev connector_name: connector_name.clone(), tool_title: tool_title.clone(), }, - ApprovalRequest::RequestPermissions { .. } => GuardianReviewedAction::RequestPermissions {}, + GuardianApprovalRequest::RequestPermissions { .. } => GuardianReviewedAction::RequestPermissions {}, } } -pub(crate) fn guardian_request_target_item_id(request: &ApprovalRequest) -> Option<&str> { +pub(crate) fn guardian_request_target_item_id(request: &GuardianApprovalRequest) -> Option<&str> { match request { - ApprovalRequest::Shell { id, .. } - | ApprovalRequest::ExecCommand { id, .. } - | ApprovalRequest::ApplyPatch { id, .. } - | ApprovalRequest::McpToolCall { id, .. } - | ApprovalRequest::RequestPermissions { id, .. } => Some(id), - ApprovalRequest::NetworkAccess { .. } => None, + GuardianApprovalRequest::Shell { id, .. } + | GuardianApprovalRequest::ExecCommand { id, .. } + | GuardianApprovalRequest::ApplyPatch { id, .. } + | GuardianApprovalRequest::McpToolCall { id, .. } + | GuardianApprovalRequest::RequestPermissions { id, .. } => Some(id), + GuardianApprovalRequest::NetworkAccess { .. } => None, #[cfg(unix)] - ApprovalRequest::Execve { id, .. } => Some(id), + GuardianApprovalRequest::Execve { id, .. } => Some(id), } } pub(crate) fn guardian_request_turn_id<'a>( - request: &'a ApprovalRequest, + request: &'a GuardianApprovalRequest, default_turn_id: &'a str, ) -> &'a str { match request { - ApprovalRequest::NetworkAccess { turn_id, .. } - | ApprovalRequest::RequestPermissions { turn_id, .. } => turn_id, - ApprovalRequest::Shell { .. } - | ApprovalRequest::ExecCommand { .. } - | ApprovalRequest::ApplyPatch { .. } - | ApprovalRequest::McpToolCall { .. } => default_turn_id, + GuardianApprovalRequest::NetworkAccess { turn_id, .. } + | GuardianApprovalRequest::RequestPermissions { turn_id, .. } => turn_id, + GuardianApprovalRequest::Shell { .. } + | GuardianApprovalRequest::ExecCommand { .. } + | GuardianApprovalRequest::ApplyPatch { .. } + | GuardianApprovalRequest::McpToolCall { .. } => default_turn_id, #[cfg(unix)] - ApprovalRequest::Execve { .. } => default_turn_id, + GuardianApprovalRequest::Execve { .. } => default_turn_id, } } pub(crate) fn format_guardian_action_pretty( - action: &ApprovalRequest, + action: &GuardianApprovalRequest, ) -> serde_json::Result { let value = guardian_approval_request_to_json(action)?; let (value, truncated) = truncate_guardian_action_value(value); @@ -1131,7 +1131,7 @@ mod tests { #[test] fn exec_approval_event_is_projected_from_shell_request() { - let request = ApprovalRequest::Shell { + let request = GuardianApprovalRequest::Shell { id: "call-1".to_string(), command: vec!["echo".to_string(), "hi".to_string()], hook_command: "echo hi".to_string(), @@ -1169,7 +1169,7 @@ mod tests { fn apply_patch_approval_event_is_projected_from_request() { let path = test_path_buf("/tmp/file.txt"); let abs_path = path.abs(); - let request = ApprovalRequest::ApplyPatch { + let request = GuardianApprovalRequest::ApplyPatch { id: "call-1".to_string(), cwd: test_path_buf("/tmp").abs(), files: vec![abs_path], @@ -1206,7 +1206,7 @@ mod tests { #[test] fn request_permissions_event_is_projected_from_request() { - let request = ApprovalRequest::RequestPermissions { + let request = GuardianApprovalRequest::RequestPermissions { id: "call-1".to_string(), turn_id: "turn-1".to_string(), reason: Some("need outbound network".to_string()), @@ -1240,7 +1240,7 @@ mod tests { #[test] fn network_exec_approval_event_is_projected_from_request() { - let request = ApprovalRequest::NetworkAccess { + let request = GuardianApprovalRequest::NetworkAccess { id: "network-1".to_string(), turn_id: "turn-1".to_string(), target: "https://example.com:443".to_string(), @@ -1299,7 +1299,7 @@ mod tests { #[test] fn mcp_tool_approval_compat_response_uses_session_label_when_present() { - let request = ApprovalRequest::McpToolCall { + let request = GuardianApprovalRequest::McpToolCall { id: "call-1".to_string(), server: "custom_server".to_string(), tool_name: "dangerous_tool".to_string(), @@ -1338,7 +1338,7 @@ mod tests { #[test] fn mcp_tool_approval_compat_response_uses_synthetic_decline_for_abort() { - let request = ApprovalRequest::McpToolCall { + let request = GuardianApprovalRequest::McpToolCall { id: "call-1".to_string(), server: "custom_server".to_string(), tool_name: "dangerous_tool".to_string(), diff --git a/codex-rs/core/src/guardian/mod.rs b/codex-rs/core/src/guardian/mod.rs index 0eb3a91b40..8bd2621546 100644 --- a/codex-rs/core/src/guardian/mod.rs +++ b/codex-rs/core/src/guardian/mod.rs @@ -23,7 +23,7 @@ use codex_protocol::protocol::GuardianAssessmentOutcome; use serde::Deserialize; use serde::Serialize; -pub(crate) use approval_request::ApprovalRequest; +pub(crate) use approval_request::GuardianApprovalRequest; pub(crate) use approval_request::GuardianMcpAnnotations; pub(crate) use approval_request::GuardianNetworkAccessTrigger; #[allow(unused_imports)] diff --git a/codex-rs/core/src/guardian/prompt.rs b/codex-rs/core/src/guardian/prompt.rs index 290cf04b9c..b1b132a984 100644 --- a/codex-rs/core/src/guardian/prompt.rs +++ b/codex-rs/core/src/guardian/prompt.rs @@ -15,12 +15,12 @@ use codex_utils_output_truncation::approx_token_count; use codex_utils_output_truncation::approx_tokens_from_byte_count; use super::AUTO_REVIEW_DENIED_ACTION_APPROVAL_DEVELOPER_PREFIX; -use super::ApprovalRequest; use super::GUARDIAN_MAX_MESSAGE_ENTRY_TOKENS; use super::GUARDIAN_MAX_MESSAGE_TRANSCRIPT_TOKENS; use super::GUARDIAN_MAX_TOOL_ENTRY_TOKENS; use super::GUARDIAN_MAX_TOOL_TRANSCRIPT_TOKENS; use super::GUARDIAN_RECENT_ENTRY_LIMIT; +use super::GuardianApprovalRequest; use super::GuardianAssessment; use super::TRUNCATION_TAG; use super::approval_request::format_guardian_action_pretty; @@ -89,7 +89,7 @@ pub(crate) enum GuardianPromptMode { pub(crate) async fn build_guardian_prompt_items( session: &Session, retry_reason: Option, - request: ApprovalRequest, + request: GuardianApprovalRequest, mode: GuardianPromptMode, ) -> serde_json::Result { let history = session.clone_history().await; @@ -173,7 +173,7 @@ pub(crate) async fn build_guardian_prompt_items( push_text(format!("\n{note}\n")); } match &request { - ApprovalRequest::NetworkAccess { trigger, .. } => { + GuardianApprovalRequest::NetworkAccess { trigger, .. } => { push_text(">>> APPROVAL REQUEST START\n".to_string()); push_text("Below is a proposed network access request under review.\n".to_string()); if trigger.is_some() { diff --git a/codex-rs/core/src/guardian/review.rs b/codex-rs/core/src/guardian/review.rs index 9528cafe14..850d84dd2a 100644 --- a/codex-rs/core/src/guardian/review.rs +++ b/codex-rs/core/src/guardian/review.rs @@ -24,9 +24,9 @@ use tokio_util::sync::CancellationToken; use crate::session::session::Session; use crate::session::turn_context::TurnContext; -use super::ApprovalRequest; use super::GUARDIAN_REVIEW_TIMEOUT; use super::GUARDIAN_REVIEWER_NAME; +use super::GuardianApprovalRequest; use super::GuardianAssessment; use super::GuardianAssessmentOutcome; use super::GuardianRejection; @@ -234,7 +234,7 @@ async fn run_guardian_review( session: Arc, turn: Arc, review_id: String, - request: ApprovalRequest, + request: GuardianApprovalRequest, retry_reason: Option, approval_request_source: GuardianApprovalRequestSource, external_cancel: Option, @@ -523,7 +523,7 @@ pub(crate) async fn review_approval_request( session: &Arc, turn: &Arc, review_id: String, - request: ApprovalRequest, + request: GuardianApprovalRequest, retry_reason: Option, ) -> ReviewDecision { // Box the delegated review future so callers do not inline the entire @@ -544,7 +544,7 @@ pub(crate) async fn review_approval_request_with_cancel( session: &Arc, turn: &Arc, review_id: String, - request: ApprovalRequest, + request: GuardianApprovalRequest, retry_reason: Option, approval_request_source: GuardianApprovalRequestSource, cancel_token: CancellationToken, @@ -565,7 +565,7 @@ pub(crate) fn spawn_approval_request_review( session: Arc, turn: Arc, review_id: String, - request: ApprovalRequest, + request: GuardianApprovalRequest, retry_reason: Option, approval_request_source: GuardianApprovalRequestSource, cancel_token: CancellationToken, @@ -610,7 +610,7 @@ pub(crate) fn spawn_approval_request_review( pub(super) async fn run_guardian_review_session( session: Arc, turn: Arc, - request: ApprovalRequest, + request: GuardianApprovalRequest, retry_reason: Option, schema: serde_json::Value, external_cancel: Option, diff --git a/codex-rs/core/src/guardian/review_session.rs b/codex-rs/core/src/guardian/review_session.rs index f5626d4f4f..a9d3aea48a 100644 --- a/codex-rs/core/src/guardian/review_session.rs +++ b/codex-rs/core/src/guardian/review_session.rs @@ -44,9 +44,9 @@ use codex_features::Feature; use codex_model_provider_info::ModelProviderInfo; use codex_utils_absolute_path::AbsolutePathBuf; -use super::ApprovalRequest; use super::GUARDIAN_REVIEW_TIMEOUT; use super::GUARDIAN_REVIEWER_NAME; +use super::GuardianApprovalRequest; use super::prompt::GuardianPromptMode; use super::prompt::GuardianTranscriptCursor; use super::prompt::build_guardian_prompt_items; @@ -67,7 +67,7 @@ pub(crate) struct GuardianReviewSessionParams { pub(crate) parent_session: Arc, pub(crate) parent_turn: Arc, pub(crate) spawn_config: Config, - pub(crate) request: ApprovalRequest, + pub(crate) request: GuardianApprovalRequest, pub(crate) retry_reason: Option, pub(crate) schema: Value, pub(crate) model: String, @@ -1101,7 +1101,7 @@ mod tests { parent_session: Arc::new(session), parent_turn: Arc::new(turn), spawn_config, - request: ApprovalRequest::Shell { + request: GuardianApprovalRequest::Shell { id: "shell-1".to_string(), command: vec!["git".to_string(), "status".to_string()], hook_command: "git status".to_string(), diff --git a/codex-rs/core/src/guardian/tests.rs b/codex-rs/core/src/guardian/tests.rs index 2b0d4e0de5..14e5a0ddf5 100644 --- a/codex-rs/core/src/guardian/tests.rs +++ b/codex-rs/core/src/guardian/tests.rs @@ -313,7 +313,7 @@ async fn build_guardian_prompt_full_mode_preserves_initial_review_format() -> an let prompt = build_guardian_prompt_items( session.as_ref(), Some("Sandbox denied outbound git push to github.com.".to_string()), - ApprovalRequest::Shell { + GuardianApprovalRequest::Shell { id: "shell-1".to_string(), command: vec!["git".to_string(), "push".to_string()], hook_command: "git push".to_string(), @@ -368,7 +368,7 @@ async fn build_guardian_prompt_delta_mode_preserves_original_numbering() -> anyh let prompt = build_guardian_prompt_items( session.as_ref(), /*retry_reason*/ None, - ApprovalRequest::Shell { + GuardianApprovalRequest::Shell { id: "shell-2".to_string(), command: vec!["git".to_string(), "push".to_string()], hook_command: "git push".to_string(), @@ -407,7 +407,7 @@ async fn build_guardian_prompt_delta_mode_handles_empty_delta() -> anyhow::Resul let prompt = build_guardian_prompt_items( session.as_ref(), /*retry_reason*/ None, - ApprovalRequest::Shell { + GuardianApprovalRequest::Shell { id: "shell-2".to_string(), command: vec!["git".to_string(), "push".to_string()], hook_command: "git push".to_string(), @@ -443,7 +443,7 @@ async fn build_guardian_prompt_stale_delta_cursor_falls_back_to_full_prompt() -> let prompt = build_guardian_prompt_items( session.as_ref(), /*retry_reason*/ None, - ApprovalRequest::Shell { + GuardianApprovalRequest::Shell { id: "shell-3".to_string(), command: vec!["git".to_string(), "push".to_string()], hook_command: "git push".to_string(), @@ -525,7 +525,7 @@ async fn build_guardian_prompt_stale_delta_version_falls_back_to_full_prompt() - let prompt = build_guardian_prompt_items( session.as_ref(), /*retry_reason*/ None, - ApprovalRequest::Shell { + GuardianApprovalRequest::Shell { id: "shell-4".to_string(), command: vec!["git".to_string(), "push".to_string()], hook_command: "git push".to_string(), @@ -690,7 +690,7 @@ fn guardian_truncate_text_keeps_prefix_suffix_and_xml_marker() { #[test] fn format_guardian_action_pretty_truncates_large_string_fields() -> serde_json::Result<()> { let patch = "line\n".repeat(100_000); - let action = ApprovalRequest::ApplyPatch { + let action = GuardianApprovalRequest::ApplyPatch { id: "patch-1".to_string(), cwd: test_path_buf("/tmp").abs(), files: Vec::new(), @@ -710,7 +710,7 @@ fn format_guardian_action_pretty_truncates_large_string_fields() -> serde_json:: #[test] fn format_guardian_action_pretty_reports_no_truncation_for_small_payload() -> serde_json::Result<()> { - let action = ApprovalRequest::ApplyPatch { + let action = GuardianApprovalRequest::ApplyPatch { id: "patch-1".to_string(), cwd: test_path_buf("/tmp").abs(), files: Vec::new(), @@ -727,7 +727,7 @@ fn format_guardian_action_pretty_reports_no_truncation_for_small_payload() -> se #[test] fn guardian_approval_request_to_json_renders_mcp_tool_call_shape() -> serde_json::Result<()> { - let action = ApprovalRequest::McpToolCall { + let action = GuardianApprovalRequest::McpToolCall { id: "call-1".to_string(), server: "mcp_server".to_string(), tool_name: "browser_navigate".to_string(), @@ -770,7 +770,7 @@ fn guardian_approval_request_to_json_renders_mcp_tool_call_shape() -> serde_json #[test] fn guardian_approval_request_to_json_renders_network_access_trigger() -> serde_json::Result<()> { let cwd = test_path_buf("/repo").abs(); - let action = ApprovalRequest::NetworkAccess { + let action = GuardianApprovalRequest::NetworkAccess { id: "network-1".to_string(), turn_id: "turn-1".to_string(), target: "https://example.com:443".to_string(), @@ -821,7 +821,7 @@ async fn build_guardian_prompt_items_explains_network_access_review_scope() -> a let prompt = build_guardian_prompt_items( session.as_ref(), Some("Network access to \"example.com\" is blocked by policy.".to_string()), - ApprovalRequest::NetworkAccess { + GuardianApprovalRequest::NetworkAccess { id: "network-1".to_string(), turn_id: "turn-1".to_string(), target: "https://example.com:443".to_string(), @@ -886,7 +886,7 @@ async fn build_guardian_prompt_items_explains_network_access_review_scope() -> a fn guardian_assessment_action_redacts_apply_patch_patch_text() { let cwd = test_path_buf("/tmp").abs(); let file = test_path_buf("/tmp/guardian.txt").abs(); - let action = ApprovalRequest::ApplyPatch { + let action = GuardianApprovalRequest::ApplyPatch { id: "patch-1".to_string(), cwd: cwd.clone(), files: vec![file.clone()], @@ -907,7 +907,7 @@ fn guardian_assessment_action_redacts_apply_patch_patch_text() { #[test] fn guardian_request_turn_id_prefers_network_access_owner_turn() { - let network_access = ApprovalRequest::NetworkAccess { + let network_access = GuardianApprovalRequest::NetworkAccess { id: "network-1".to_string(), turn_id: "owner-turn".to_string(), target: "https://example.com:443".to_string(), @@ -917,7 +917,7 @@ fn guardian_request_turn_id_prefers_network_access_owner_turn() { port: 443, trigger: None, }; - let apply_patch = ApprovalRequest::ApplyPatch { + let apply_patch = GuardianApprovalRequest::ApplyPatch { id: "patch-1".to_string(), cwd: test_path_buf("/tmp").abs(), files: vec![test_path_buf("/tmp/guardian.txt").abs()], @@ -938,7 +938,7 @@ fn guardian_request_turn_id_prefers_network_access_owner_turn() { #[test] fn guardian_request_target_item_id_omits_network_access_trigger_call_id() { - let network_access = ApprovalRequest::NetworkAccess { + let network_access = GuardianApprovalRequest::NetworkAccess { id: "network-1".to_string(), turn_id: "owner-turn".to_string(), target: "https://example.com:443".to_string(), @@ -971,7 +971,7 @@ async fn cancelled_guardian_review_emits_terminal_abort_without_warning() { &session, &turn, "review-cancelled-guardian".to_string(), - ApprovalRequest::ApplyPatch { + GuardianApprovalRequest::ApplyPatch { id: "patch-1".to_string(), cwd: test_path_buf("/tmp").abs(), files: vec![test_path_buf("/tmp/guardian.txt").abs()], @@ -1261,7 +1261,7 @@ async fn guardian_review_request_layout_matches_model_visible_request_snapshot() let turn = Arc::new(turn); seed_guardian_parent_history(&session, &turn).await; - let request = ApprovalRequest::Shell { + let request = GuardianApprovalRequest::Shell { id: "shell-1".to_string(), command: vec![ "git".to_string(), @@ -1372,7 +1372,7 @@ async fn build_guardian_prompt_items_includes_parent_session_id() -> anyhow::Res let prompt = build_guardian_prompt_items( &session, /*retry_reason*/ None, - ApprovalRequest::Shell { + GuardianApprovalRequest::Shell { id: "shell-1".to_string(), command: vec!["git".to_string(), "status".to_string()], hook_command: "git status".to_string(), @@ -1447,7 +1447,7 @@ async fn guardian_reuses_prompt_cache_key_and_appends_prior_reviews() -> anyhow: let (session, turn) = guardian_test_session_and_turn(&server).await; seed_guardian_parent_history(&session, &turn).await; - let first_request = ApprovalRequest::Shell { + let first_request = GuardianApprovalRequest::Shell { id: "shell-1".to_string(), command: vec!["git".to_string(), "push".to_string()], hook_command: "git push".to_string(), @@ -1488,7 +1488,7 @@ async fn guardian_reuses_prompt_cache_key_and_appends_prior_reviews() -> anyhow: turn.as_ref(), ) .await; - let second_request = ApprovalRequest::Shell { + let second_request = GuardianApprovalRequest::Shell { id: "shell-2".to_string(), command: vec![ "git".to_string(), @@ -1533,7 +1533,7 @@ async fn guardian_reuses_prompt_cache_key_and_appends_prior_reviews() -> anyhow: turn.as_ref(), ) .await; - let third_request = ApprovalRequest::Shell { + let third_request = GuardianApprovalRequest::Shell { id: "shell-3".to_string(), command: vec!["git".to_string(), "push".to_string()], hook_command: "git push".to_string(), @@ -1729,7 +1729,7 @@ async fn guardian_reused_trunk_ignores_stale_prior_turn_completion() -> anyhow:: let first_outcome = run_guardian_review_session_for_test( Arc::clone(&session), Arc::clone(&turn), - ApprovalRequest::Shell { + GuardianApprovalRequest::Shell { id: "shell-1".to_string(), command: vec!["git".to_string(), "push".to_string()], hook_command: "git push".to_string(), @@ -1772,7 +1772,7 @@ async fn guardian_reused_trunk_ignores_stale_prior_turn_completion() -> anyhow:: let second_outcome = run_guardian_review_session_for_test( Arc::clone(&session), Arc::clone(&turn), - ApprovalRequest::Shell { + GuardianApprovalRequest::Shell { id: "shell-2".to_string(), command: vec!["git".to_string(), "push".to_string()], hook_command: "git push".to_string(), @@ -1852,7 +1852,7 @@ async fn guardian_review_surfaces_responses_api_errors_in_rejection_reason() -> &session, &turn, "review-shell-guardian-error".to_string(), - ApprovalRequest::Shell { + GuardianApprovalRequest::Shell { id: "shell-guardian-error".to_string(), command: vec!["git".to_string(), "push".to_string()], hook_command: "git push".to_string(), @@ -1987,7 +1987,7 @@ async fn guardian_parallel_reviews_fork_from_last_committed_trunk_history() -> a let (session, turn) = guardian_test_session_and_turn_with_base_url(server.uri()).await; seed_guardian_parent_history(&session, &turn).await; - let initial_request = ApprovalRequest::Shell { + let initial_request = GuardianApprovalRequest::Shell { id: "shell-guardian-1".to_string(), command: vec!["git".to_string(), "status".to_string()], hook_command: "git status".to_string(), @@ -2031,7 +2031,7 @@ async fn guardian_parallel_reviews_fork_from_last_committed_trunk_history() -> a ) .await; - let second_request = ApprovalRequest::Shell { + let second_request = GuardianApprovalRequest::Shell { id: "shell-guardian-2".to_string(), command: vec!["git".to_string(), "diff".to_string()], hook_command: "git diff".to_string(), @@ -2040,7 +2040,7 @@ async fn guardian_parallel_reviews_fork_from_last_committed_trunk_history() -> a additional_permissions: None, justification: Some("Inspect pending changes before proceeding.".to_string()), }; - let third_request = ApprovalRequest::Shell { + let third_request = GuardianApprovalRequest::Shell { id: "shell-guardian-3".to_string(), command: vec!["git".to_string(), "push".to_string()], hook_command: "git push".to_string(), diff --git a/codex-rs/core/src/mcp_tool_call.rs b/codex-rs/core/src/mcp_tool_call.rs index ee14978676..a63051186c 100644 --- a/codex-rs/core/src/mcp_tool_call.rs +++ b/codex-rs/core/src/mcp_tool_call.rs @@ -17,7 +17,7 @@ use crate::config::edit::ConfigEdit; use crate::config::edit::ConfigEditsBuilder; use crate::config::load_global_mcp_servers; use crate::connectors; -use crate::guardian::ApprovalRequest; +use crate::guardian::GuardianApprovalRequest; use crate::guardian::GuardianMcpAnnotations; use crate::guardian::MCP_TOOL_APPROVAL_ACCEPT; use crate::guardian::MCP_TOOL_APPROVAL_ACCEPT_AND_REMEMBER; @@ -884,7 +884,7 @@ fn with_mcp_tool_call_thread_id_meta( struct McpToolApprovalElicitationRequest<'a> { server: &'a str, - approval_request: &'a ApprovalRequest, + approval_request: &'a GuardianApprovalRequest, tool_params: Option<&'a serde_json::Value>, tool_params_display: Option<&'a [RenderedMcpToolApprovalParam]>, question: RequestUserInputQuestion, @@ -1155,8 +1155,8 @@ pub(crate) fn build_mcp_tool_approval_request( hook_tool_name: &str, invocation: &McpInvocation, metadata: Option<&McpToolApprovalMetadata>, -) -> ApprovalRequest { - ApprovalRequest::McpToolCall { +) -> GuardianApprovalRequest { + GuardianApprovalRequest::McpToolCall { id: call_id.to_string(), server: invocation.server.clone(), tool_name: invocation.tool.clone(), diff --git a/codex-rs/core/src/mcp_tool_call_tests.rs b/codex-rs/core/src/mcp_tool_call_tests.rs index eb1457b6ea..a48be0d030 100644 --- a/codex-rs/core/src/mcp_tool_call_tests.rs +++ b/codex-rs/core/src/mcp_tool_call_tests.rs @@ -1,6 +1,6 @@ use super::*; use crate::config::ConfigBuilder; -use crate::guardian::ApprovalRequest; +use crate::guardian::GuardianApprovalRequest; use crate::guardian::GuardianMcpAnnotations; use crate::guardian::MCP_TOOL_APPROVAL_CANCEL; use crate::guardian::MCP_TOOL_APPROVAL_CONNECTOR_DESCRIPTION_KEY; @@ -123,7 +123,7 @@ fn approval_prompt_request( tool_name: &str, arguments: Option, metadata: Option<&McpToolApprovalMetadata>, -) -> ApprovalRequest { +) -> GuardianApprovalRequest { build_mcp_tool_approval_request( "call-1", tool_name, @@ -1257,7 +1257,7 @@ fn guardian_mcp_review_request_includes_invocation_metadata() { assert_eq!( request, - ApprovalRequest::McpToolCall { + GuardianApprovalRequest::McpToolCall { id: "call-1".to_string(), server: CODEX_APPS_MCP_SERVER_NAME.to_string(), tool_name: "browser_navigate".to_string(), @@ -1299,7 +1299,7 @@ fn guardian_mcp_review_request_includes_annotations_when_present() { assert_eq!( request, - ApprovalRequest::McpToolCall { + GuardianApprovalRequest::McpToolCall { id: "call-1".to_string(), server: "custom_server".to_string(), tool_name: "dangerous_tool".to_string(), diff --git a/codex-rs/core/src/session/mod.rs b/codex-rs/core/src/session/mod.rs index 9acad52989..57f5dab799 100644 --- a/codex-rs/core/src/session/mod.rs +++ b/codex-rs/core/src/session/mod.rs @@ -32,7 +32,7 @@ use crate::context::PersonalitySpecInstructions; use crate::default_skill_metadata_budget; use crate::environment_selection::ResolvedTurnEnvironments; use crate::exec_policy::ExecPolicyManager; -use crate::guardian::ApprovalRequest; +use crate::guardian::GuardianApprovalRequest; use crate::installation_id::resolve_installation_id; use crate::parse_turn_item; use crate::path_utils::normalize_for_native_workdir; @@ -1845,7 +1845,7 @@ impl Session { pub async fn request_command_approval_for_request( &self, turn_context: &TurnContext, - approval_request: ApprovalRequest, + approval_request: GuardianApprovalRequest, approval_id: Option, reason: Option, network_approval_context: Option, @@ -1930,7 +1930,7 @@ impl Session { pub async fn request_patch_approval_for_request( &self, turn_context: &TurnContext, - approval_request: ApprovalRequest, + approval_request: GuardianApprovalRequest, reason: Option, grant_root: Option, ) -> oneshot::Receiver { @@ -2029,7 +2029,7 @@ impl Session { } let requested_permissions = args.permissions; - let approval_request = ApprovalRequest::RequestPermissions { + let approval_request = GuardianApprovalRequest::RequestPermissions { id: call_id.clone(), turn_id: turn_context.sub_id.clone(), reason: args.reason.clone(), diff --git a/codex-rs/core/src/tools/network_approval.rs b/codex-rs/core/src/tools/network_approval.rs index f1ff599c6a..31c6ecdb95 100644 --- a/codex-rs/core/src/tools/network_approval.rs +++ b/codex-rs/core/src/tools/network_approval.rs @@ -1,4 +1,4 @@ -use crate::guardian::ApprovalRequest; +use crate::guardian::GuardianApprovalRequest; use crate::guardian::GuardianNetworkAccessTrigger; use crate::guardian::guardian_rejection_message; use crate::guardian::guardian_timeout_message; @@ -463,7 +463,7 @@ impl NetworkApprovalService { || format!("network-access {target}"), |call| call.command.clone(), ); - let approval_request = ApprovalRequest::NetworkAccess { + let approval_request = GuardianApprovalRequest::NetworkAccess { id: guardian_approval_id.clone(), turn_id: owner_call .as_ref() diff --git a/codex-rs/core/src/tools/orchestrator.rs b/codex-rs/core/src/tools/orchestrator.rs index f04b5dedf8..54227006dc 100644 --- a/codex-rs/core/src/tools/orchestrator.rs +++ b/codex-rs/core/src/tools/orchestrator.rs @@ -398,7 +398,7 @@ impl ToolOrchestrator { if evaluate_permission_request_hooks && let Some(permission_request) = approval_request .as_ref() - .and_then(crate::guardian::ApprovalRequest::permission_request_payload) + .and_then(crate::guardian::GuardianApprovalRequest::permission_request_payload) { match run_permission_request_hooks( approval_ctx.session, diff --git a/codex-rs/core/src/tools/runtimes/apply_patch.rs b/codex-rs/core/src/tools/runtimes/apply_patch.rs index 165789db8e..35b5cfde45 100644 --- a/codex-rs/core/src/tools/runtimes/apply_patch.rs +++ b/codex-rs/core/src/tools/runtimes/apply_patch.rs @@ -4,7 +4,7 @@ //! selected turn environment filesystem for both local and remote turns, with //! sandboxing enforced by the explicit filesystem sandbox context. use crate::exec::is_likely_sandbox_denied; -use crate::guardian::ApprovalRequest; +use crate::guardian::GuardianApprovalRequest; use crate::guardian::review_approval_request; use crate::tools::sandboxing::Approvable; use crate::tools::sandboxing::ApprovalCtx; @@ -51,8 +51,8 @@ impl ApplyPatchRuntime { Self } - fn build_approval_request(req: &ApplyPatchRequest, call_id: &str) -> ApprovalRequest { - ApprovalRequest::ApplyPatch { + fn build_approval_request(req: &ApplyPatchRequest, call_id: &str) -> GuardianApprovalRequest { + GuardianApprovalRequest::ApplyPatch { id: call_id.to_string(), cwd: req.action.cwd.clone(), files: req.file_paths.clone(), @@ -179,7 +179,7 @@ impl Approvable for ApplyPatchRuntime { &self, req: &ApplyPatchRequest, ctx: &ApprovalCtx<'_>, - ) -> Option { + ) -> Option { Some(Self::build_approval_request(req, ctx.call_id)) } } diff --git a/codex-rs/core/src/tools/runtimes/apply_patch_tests.rs b/codex-rs/core/src/tools/runtimes/apply_patch_tests.rs index 38ba6d39d1..fa908c7176 100644 --- a/codex-rs/core/src/tools/runtimes/apply_patch_tests.rs +++ b/codex-rs/core/src/tools/runtimes/apply_patch_tests.rs @@ -1,5 +1,5 @@ use super::*; -use crate::guardian::ApprovalRequest; +use crate::guardian::GuardianApprovalRequest; use crate::tools::sandboxing::SandboxAttempt; use codex_protocol::config_types::WindowsSandboxLevel; use codex_protocol::models::AdditionalPermissionProfile; @@ -70,7 +70,7 @@ fn guardian_review_request_includes_patch_context() { assert_eq!( guardian_request, - ApprovalRequest::ApplyPatch { + GuardianApprovalRequest::ApplyPatch { id: "call-1".to_string(), cwd: expected_cwd, files: request.file_paths, diff --git a/codex-rs/core/src/tools/runtimes/shell.rs b/codex-rs/core/src/tools/runtimes/shell.rs index 4195383522..5d77c64d1f 100644 --- a/codex-rs/core/src/tools/runtimes/shell.rs +++ b/codex-rs/core/src/tools/runtimes/shell.rs @@ -10,7 +10,7 @@ pub(crate) mod zsh_fork_backend; use crate::command_canonicalization::canonicalize_command_for_approval; use crate::exec::ExecCapturePolicy; -use crate::guardian::ApprovalRequest; +use crate::guardian::GuardianApprovalRequest; use crate::guardian::GuardianNetworkAccessTrigger; use crate::guardian::review_approval_request; use crate::sandboxing::ExecOptions; @@ -120,8 +120,8 @@ impl ShellRuntime { }) } - fn build_approval_request(req: &ShellRequest, call_id: String) -> ApprovalRequest { - ApprovalRequest::Shell { + fn build_approval_request(req: &ShellRequest, call_id: String) -> GuardianApprovalRequest { + GuardianApprovalRequest::Shell { id: call_id, command: req.command.clone(), hook_command: req.hook_command.clone(), @@ -206,7 +206,7 @@ impl Approvable for ShellRuntime { &self, req: &ShellRequest, ctx: &ApprovalCtx<'_>, - ) -> Option { + ) -> Option { Some(Self::build_approval_request(req, ctx.call_id.to_string())) } diff --git a/codex-rs/core/src/tools/runtimes/shell/unix_escalation.rs b/codex-rs/core/src/tools/runtimes/shell/unix_escalation.rs index 5ce7c16257..f1ae85bec5 100644 --- a/codex-rs/core/src/tools/runtimes/shell/unix_escalation.rs +++ b/codex-rs/core/src/tools/runtimes/shell/unix_escalation.rs @@ -3,7 +3,7 @@ use crate::exec::ExecCapturePolicy; use crate::exec::ExecExpiration; use crate::exec::cancel_when_either; use crate::exec::is_likely_sandbox_denied; -use crate::guardian::ApprovalRequest; +use crate::guardian::GuardianApprovalRequest; use crate::guardian::guardian_rejection_message; use crate::guardian::guardian_timeout_message; use crate::guardian::new_guardian_review_id; @@ -406,7 +406,7 @@ impl CoreShellActionProvider { .pause_for(async move { // 1) Run PermissionRequest hooks let effective_approval_id = approval_id.clone().unwrap_or_else(|| call_id.clone()); - let approval_request = ApprovalRequest::Execve { + let approval_request = GuardianApprovalRequest::Execve { id: call_id.clone(), source, program: program.to_string_lossy().into_owned(), diff --git a/codex-rs/core/src/tools/runtimes/unified_exec.rs b/codex-rs/core/src/tools/runtimes/unified_exec.rs index 1263b13986..55c64fd6d0 100644 --- a/codex-rs/core/src/tools/runtimes/unified_exec.rs +++ b/codex-rs/core/src/tools/runtimes/unified_exec.rs @@ -7,7 +7,7 @@ the process manager to spawn PTYs once an ExecRequest is prepared. use crate::command_canonicalization::canonicalize_command_for_approval; use crate::exec::ExecCapturePolicy; use crate::exec::ExecExpiration; -use crate::guardian::ApprovalRequest; +use crate::guardian::GuardianApprovalRequest; use crate::guardian::GuardianNetworkAccessTrigger; use crate::guardian::review_approval_request; use crate::sandboxing::ExecOptions; @@ -110,8 +110,11 @@ impl<'a> UnifiedExecRuntime<'a> { } } - fn build_approval_request(req: &UnifiedExecRequest, call_id: String) -> ApprovalRequest { - ApprovalRequest::ExecCommand { + fn build_approval_request( + req: &UnifiedExecRequest, + call_id: String, + ) -> GuardianApprovalRequest { + GuardianApprovalRequest::ExecCommand { id: call_id, command: req.command.clone(), hook_command: req.hook_command.clone(), @@ -202,7 +205,7 @@ impl Approvable for UnifiedExecRuntime<'_> { &self, req: &UnifiedExecRequest, ctx: &ApprovalCtx<'_>, - ) -> Option { + ) -> Option { Some(Self::build_approval_request(req, ctx.call_id.to_string())) } diff --git a/codex-rs/core/src/tools/sandboxing.rs b/codex-rs/core/src/tools/sandboxing.rs index a30198cdf9..2ef5c8f2b7 100644 --- a/codex-rs/core/src/tools/sandboxing.rs +++ b/codex-rs/core/src/tools/sandboxing.rs @@ -4,7 +4,7 @@ //! `ApprovalCtx`, `Approvable`) together with the sandbox orchestration traits //! and helpers (`Sandboxable`, `ToolRuntime`, `SandboxAttempt`, etc.). -use crate::guardian::ApprovalRequest; +use crate::guardian::GuardianApprovalRequest; use crate::sandboxing::ExecOptions; use crate::sandboxing::SandboxPermissions; use crate::session::session::Session; @@ -312,7 +312,11 @@ pub(crate) trait Approvable { /// Return the canonical approval action for this request when the runtime /// participates in approval hooks and/or guardian review. - fn approval_request(&self, _req: &Req, _ctx: &ApprovalCtx<'_>) -> Option { + fn approval_request( + &self, + _req: &Req, + _ctx: &ApprovalCtx<'_>, + ) -> Option { None } From f06870f376d803c7f6d6526e2b83c2fe9d11ee91 Mon Sep 17 00:00:00 2001 From: Abhinav Vedmala Date: Sat, 2 May 2026 00:31:09 -0700 Subject: [PATCH 05/12] move MCP approval prompts back to MCP --- codex-rs/core/src/codex_delegate.rs | 5 +- codex-rs/core/src/codex_delegate_tests.rs | 4 +- .../core/src/guardian/approval_request.rs | 453 +----------------- codex-rs/core/src/guardian/mod.rs | 43 -- codex-rs/core/src/mcp_tool_call.rs | 359 +++++++++++++- codex-rs/core/src/mcp_tool_call_tests.rs | 205 +++++--- 6 files changed, 500 insertions(+), 569 deletions(-) diff --git a/codex-rs/core/src/codex_delegate.rs b/codex-rs/core/src/codex_delegate.rs index e3c23ab859..1dd8cf7180 100644 --- a/codex-rs/core/src/codex_delegate.rs +++ b/codex-rs/core/src/codex_delegate.rs @@ -32,12 +32,13 @@ use tokio_util::sync::CancellationToken; use crate::config::Config; use crate::environment_selection::ResolvedTurnEnvironments; use crate::guardian::GuardianApprovalRequest; -use crate::guardian::is_mcp_tool_approval_question_id; use crate::guardian::new_guardian_review_id; use crate::guardian::routes_approval_to_guardian; use crate::guardian::spawn_approval_request_review; use crate::mcp_tool_call::build_mcp_tool_approval_request; +use crate::mcp_tool_call::is_mcp_tool_approval_question_id; use crate::mcp_tool_call::lookup_mcp_tool_metadata; +use crate::mcp_tool_call::mcp_tool_approval_compat_response; use crate::session::Codex; use crate::session::CodexSpawnArgs; use crate::session::CodexSpawnOk; @@ -707,7 +708,7 @@ async fn maybe_auto_review_mcp_request_user_input( Some(&review_cancel), ) .await; - approval_request.mcp_tool_approval_compat_response(question, decision) + mcp_tool_approval_compat_response(&approval_request, question, decision) } async fn handle_request_permissions( diff --git a/codex-rs/core/src/codex_delegate_tests.rs b/codex-rs/core/src/codex_delegate_tests.rs index 9260acaeca..454e4aa660 100644 --- a/codex-rs/core/src/codex_delegate_tests.rs +++ b/codex-rs/core/src/codex_delegate_tests.rs @@ -1,6 +1,6 @@ use super::*; -use crate::guardian::MCP_TOOL_APPROVAL_DECLINE_SYNTHETIC; -use crate::guardian::MCP_TOOL_APPROVAL_QUESTION_ID_PREFIX; +use crate::mcp_tool_call::MCP_TOOL_APPROVAL_DECLINE_SYNTHETIC; +use crate::mcp_tool_call::MCP_TOOL_APPROVAL_QUESTION_ID_PREFIX; use async_channel::bounded; use codex_protocol::config_types::ApprovalsReviewer; use codex_protocol::models::NetworkPermissions; diff --git a/codex-rs/core/src/guardian/approval_request.rs b/codex-rs/core/src/guardian/approval_request.rs index 4002dc91ea..8deb4720c0 100644 --- a/codex-rs/core/src/guardian/approval_request.rs +++ b/codex-rs/core/src/guardian/approval_request.rs @@ -16,18 +16,12 @@ use codex_protocol::protocol::FileChange; use codex_protocol::protocol::ReviewDecision; use codex_protocol::request_permissions::RequestPermissionProfile; use codex_protocol::request_permissions::RequestPermissionsEvent; -use codex_protocol::request_user_input::RequestUserInputAnswer; -use codex_protocol::request_user_input::RequestUserInputQuestion; -use codex_protocol::request_user_input::RequestUserInputQuestionOption; -use codex_protocol::request_user_input::RequestUserInputResponse; use codex_utils_absolute_path::AbsolutePathBuf; use serde::Serialize; use serde_json::Value; use super::GUARDIAN_MAX_ACTION_STRING_TOKENS; use super::prompt::guardian_truncate_text; -use crate::mcp_tool_approval_templates::RenderedMcpToolApprovalParam; -use crate::mcp_tool_approval_templates::render_mcp_tool_approval_template; use crate::tools::hook_names::HookToolName; use crate::tools::sandboxing::PermissionRequestPayload; @@ -105,41 +99,6 @@ pub(crate) enum GuardianApprovalRequest { }, } -#[derive(Clone, Copy, Debug, Eq, PartialEq)] -pub(crate) struct McpToolApprovalPromptOptions { - pub(crate) allow_session_remember: bool, - pub(crate) allow_persistent_approval: bool, -} - -#[derive(Clone, Debug, PartialEq)] -pub(crate) struct McpToolApprovalPrompt { - pub(crate) question: RequestUserInputQuestion, - pub(crate) message_override: Option, - pub(crate) tool_params: Option, - pub(crate) tool_params_display: Option>, -} - -pub(crate) const MCP_TOOL_APPROVAL_ACCEPT: &str = "Allow"; -pub(crate) const MCP_TOOL_APPROVAL_ACCEPT_FOR_SESSION: &str = "Allow for this session"; -pub(crate) const MCP_TOOL_APPROVAL_ACCEPT_AND_REMEMBER: &str = "Allow and don't ask me again"; -pub(crate) const MCP_TOOL_APPROVAL_CANCEL: &str = "Cancel"; -pub(crate) const MCP_TOOL_APPROVAL_DECLINE_SYNTHETIC: &str = "__codex_mcp_decline__"; -pub(crate) const MCP_TOOL_APPROVAL_QUESTION_ID_PREFIX: &str = "mcp_tool_call_approval"; -pub(crate) const MCP_TOOL_APPROVAL_KIND_KEY: &str = "codex_approval_kind"; -pub(crate) const MCP_TOOL_APPROVAL_KIND_MCP_TOOL_CALL: &str = "mcp_tool_call"; -pub(crate) const MCP_TOOL_APPROVAL_PERSIST_KEY: &str = "persist"; -pub(crate) const MCP_TOOL_APPROVAL_PERSIST_SESSION: &str = "session"; -pub(crate) const MCP_TOOL_APPROVAL_PERSIST_ALWAYS: &str = "always"; -pub(crate) const MCP_TOOL_APPROVAL_SOURCE_KEY: &str = "source"; -pub(crate) const MCP_TOOL_APPROVAL_SOURCE_CONNECTOR: &str = "connector"; -pub(crate) const MCP_TOOL_APPROVAL_CONNECTOR_ID_KEY: &str = "connector_id"; -pub(crate) const MCP_TOOL_APPROVAL_CONNECTOR_NAME_KEY: &str = "connector_name"; -pub(crate) const MCP_TOOL_APPROVAL_CONNECTOR_DESCRIPTION_KEY: &str = "connector_description"; -pub(crate) const MCP_TOOL_APPROVAL_TOOL_TITLE_KEY: &str = "tool_title"; -pub(crate) const MCP_TOOL_APPROVAL_TOOL_DESCRIPTION_KEY: &str = "tool_description"; -pub(crate) const MCP_TOOL_APPROVAL_TOOL_PARAMS_KEY: &str = "tool_params"; -pub(crate) const MCP_TOOL_APPROVAL_TOOL_PARAMS_DISPLAY_KEY: &str = "tool_params_display"; - impl GuardianApprovalRequest { pub(crate) fn permission_request_payload(&self) -> Option { match self { @@ -350,311 +309,6 @@ impl GuardianApprovalRequest { Self::Execve { .. } => None, } } - - pub(crate) fn mcp_tool_approval_prompt( - &self, - question_id: String, - prompt_options: McpToolApprovalPromptOptions, - monitor_reason: Option<&str>, - ) -> Option { - let Self::McpToolCall { - server, - tool_name, - arguments, - connector_id, - connector_name, - tool_title, - .. - } = self - else { - return None; - }; - - let rendered_template = render_mcp_tool_approval_template( - server, - connector_id.as_deref(), - connector_name.as_deref(), - tool_title.as_deref(), - arguments.as_ref(), - ); - let tool_params_display = rendered_template - .as_ref() - .map(|rendered_template| rendered_template.tool_params_display.clone()) - .or_else(|| build_mcp_tool_approval_display_params(arguments.as_ref())); - let question_override = rendered_template - .as_ref() - .map(|rendered_template| rendered_template.question.as_str()); - let mut question = build_mcp_tool_approval_question( - question_id, - server, - tool_name, - connector_name.as_deref(), - prompt_options, - question_override, - ); - question.question = mcp_tool_approval_question_text(question.question, monitor_reason); - - Some(McpToolApprovalPrompt { - question, - message_override: rendered_template.as_ref().and_then(|rendered_template| { - monitor_reason - .is_none() - .then_some(rendered_template.elicitation_message.clone()) - }), - tool_params: rendered_template - .as_ref() - .and_then(|rendered_template| rendered_template.tool_params.clone()) - .or_else(|| arguments.clone()), - tool_params_display, - }) - } - - pub(crate) fn mcp_tool_approval_elicitation_meta( - &self, - tool_params: Option<&Value>, - tool_params_display: Option<&[RenderedMcpToolApprovalParam]>, - prompt_options: McpToolApprovalPromptOptions, - ) -> Option { - let Self::McpToolCall { - server, - connector_id, - connector_name, - connector_description, - tool_title, - tool_description, - .. - } = self - else { - return None; - }; - - let mut meta = serde_json::Map::new(); - meta.insert( - MCP_TOOL_APPROVAL_KIND_KEY.to_string(), - serde_json::Value::String(MCP_TOOL_APPROVAL_KIND_MCP_TOOL_CALL.to_string()), - ); - match ( - prompt_options.allow_session_remember, - prompt_options.allow_persistent_approval, - ) { - (true, true) => { - meta.insert( - MCP_TOOL_APPROVAL_PERSIST_KEY.to_string(), - serde_json::json!([ - MCP_TOOL_APPROVAL_PERSIST_SESSION, - MCP_TOOL_APPROVAL_PERSIST_ALWAYS, - ]), - ); - } - (true, false) => { - meta.insert( - MCP_TOOL_APPROVAL_PERSIST_KEY.to_string(), - serde_json::Value::String(MCP_TOOL_APPROVAL_PERSIST_SESSION.to_string()), - ); - } - (false, true) => { - meta.insert( - MCP_TOOL_APPROVAL_PERSIST_KEY.to_string(), - serde_json::Value::String(MCP_TOOL_APPROVAL_PERSIST_ALWAYS.to_string()), - ); - } - (false, false) => {} - } - if let Some(tool_title) = tool_title.as_ref() { - meta.insert( - MCP_TOOL_APPROVAL_TOOL_TITLE_KEY.to_string(), - serde_json::Value::String(tool_title.clone()), - ); - } - if let Some(tool_description) = tool_description.as_ref() { - meta.insert( - MCP_TOOL_APPROVAL_TOOL_DESCRIPTION_KEY.to_string(), - serde_json::Value::String(tool_description.clone()), - ); - } - if server == "codex_apps" - && (connector_id.is_some() - || connector_name.is_some() - || connector_description.is_some()) - { - meta.insert( - MCP_TOOL_APPROVAL_SOURCE_KEY.to_string(), - serde_json::Value::String(MCP_TOOL_APPROVAL_SOURCE_CONNECTOR.to_string()), - ); - if let Some(connector_id) = connector_id.as_deref() { - meta.insert( - MCP_TOOL_APPROVAL_CONNECTOR_ID_KEY.to_string(), - serde_json::Value::String(connector_id.to_string()), - ); - } - if let Some(connector_name) = connector_name.as_ref() { - meta.insert( - MCP_TOOL_APPROVAL_CONNECTOR_NAME_KEY.to_string(), - serde_json::Value::String(connector_name.clone()), - ); - } - if let Some(connector_description) = connector_description.as_ref() { - meta.insert( - MCP_TOOL_APPROVAL_CONNECTOR_DESCRIPTION_KEY.to_string(), - serde_json::Value::String(connector_description.clone()), - ); - } - } - if let Some(tool_params) = tool_params { - meta.insert( - MCP_TOOL_APPROVAL_TOOL_PARAMS_KEY.to_string(), - tool_params.clone(), - ); - } - if let Some(tool_params_display) = tool_params_display - && let Ok(tool_params_display) = serde_json::to_value(tool_params_display) - { - meta.insert( - MCP_TOOL_APPROVAL_TOOL_PARAMS_DISPLAY_KEY.to_string(), - tool_params_display, - ); - } - - (!meta.is_empty()).then_some(serde_json::Value::Object(meta)) - } - - pub(crate) fn mcp_tool_approval_compat_response( - &self, - question: &RequestUserInputQuestion, - decision: ReviewDecision, - ) -> Option { - let Self::McpToolCall { .. } = self else { - return None; - }; - - let selected_label = match decision { - ReviewDecision::ApprovedForSession => question - .options - .as_ref() - .and_then(|options| { - options - .iter() - .find(|option| option.label == MCP_TOOL_APPROVAL_ACCEPT_FOR_SESSION) - }) - .map(|option| option.label.clone()) - .unwrap_or_else(|| MCP_TOOL_APPROVAL_ACCEPT.to_string()), - ReviewDecision::Approved - | ReviewDecision::ApprovedExecpolicyAmendment { .. } - | ReviewDecision::NetworkPolicyAmendment { .. } => MCP_TOOL_APPROVAL_ACCEPT.to_string(), - ReviewDecision::Denied | ReviewDecision::TimedOut | ReviewDecision::Abort => { - MCP_TOOL_APPROVAL_DECLINE_SYNTHETIC.to_string() - } - }; - - Some(RequestUserInputResponse { - answers: HashMap::from([( - question.id.clone(), - RequestUserInputAnswer { - answers: vec![selected_label], - }, - )]), - }) - } -} - -pub(crate) fn mcp_tool_approval_question_id(call_id: &str) -> String { - format!("{MCP_TOOL_APPROVAL_QUESTION_ID_PREFIX}_{call_id}") -} - -pub(crate) fn is_mcp_tool_approval_question_id(question_id: &str) -> bool { - question_id - .strip_prefix(MCP_TOOL_APPROVAL_QUESTION_ID_PREFIX) - .is_some_and(|suffix| suffix.starts_with('_')) -} - -fn build_mcp_tool_approval_question( - question_id: String, - server: &str, - tool_name: &str, - connector_name: Option<&str>, - prompt_options: McpToolApprovalPromptOptions, - question_override: Option<&str>, -) -> RequestUserInputQuestion { - let question = question_override - .map(ToString::to_string) - .unwrap_or_else(|| { - build_mcp_tool_approval_fallback_message(server, tool_name, connector_name) - }); - let question = format!("{}?", question.trim_end_matches('?')); - - let mut options = vec![RequestUserInputQuestionOption { - label: MCP_TOOL_APPROVAL_ACCEPT.to_string(), - description: "Run the tool and continue.".to_string(), - }]; - if prompt_options.allow_session_remember { - options.push(RequestUserInputQuestionOption { - label: MCP_TOOL_APPROVAL_ACCEPT_FOR_SESSION.to_string(), - description: "Run the tool and remember this choice for this session.".to_string(), - }); - } - if prompt_options.allow_persistent_approval { - options.push(RequestUserInputQuestionOption { - label: MCP_TOOL_APPROVAL_ACCEPT_AND_REMEMBER.to_string(), - description: "Run the tool and remember this choice for future tool calls.".to_string(), - }); - } - options.push(RequestUserInputQuestionOption { - label: MCP_TOOL_APPROVAL_CANCEL.to_string(), - description: "Cancel this tool call.".to_string(), - }); - - RequestUserInputQuestion { - id: question_id, - header: "Approve app tool call?".to_string(), - question, - is_other: false, - is_secret: false, - options: Some(options), - } -} - -fn build_mcp_tool_approval_fallback_message( - server: &str, - tool_name: &str, - connector_name: Option<&str>, -) -> String { - let actor = connector_name - .map(str::trim) - .filter(|name| !name.is_empty()) - .map(ToString::to_string) - .unwrap_or_else(|| { - if server == "codex_apps" { - "this app".to_string() - } else { - format!("the {server} MCP server") - } - }); - format!("Allow {actor} to run tool \"{tool_name}\"?") -} - -fn mcp_tool_approval_question_text(question: String, monitor_reason: Option<&str>) -> String { - match monitor_reason.map(str::trim) { - Some(reason) if !reason.is_empty() => { - format!("Tool call needs your approval. Reason: {reason}") - } - _ => question, - } -} - -fn build_mcp_tool_approval_display_params( - tool_params: Option<&Value>, -) -> Option> { - let tool_params = tool_params?.as_object()?; - let mut display_params = tool_params - .iter() - .map(|(name, value)| RenderedMcpToolApprovalParam { - name: name.clone(), - value: value.clone(), - display_name: name.clone(), - }) - .collect::>(); - display_params.sort_by(|left, right| left.name.cmp(&right.name)); - Some(display_params) } #[derive(Debug, Clone, PartialEq, Serialize)] @@ -959,7 +613,9 @@ pub(crate) fn guardian_approval_request_to_json( } } -pub(crate) fn guardian_assessment_action(action: &GuardianApprovalRequest) -> GuardianAssessmentAction { +pub(crate) fn guardian_assessment_action( + action: &GuardianApprovalRequest, +) -> GuardianAssessmentAction { match action { GuardianApprovalRequest::Shell { command, cwd, .. } => { command_assessment_action(GuardianCommandSource::Shell, command, cwd) @@ -980,10 +636,12 @@ pub(crate) fn guardian_assessment_action(action: &GuardianApprovalRequest) -> Gu argv: argv.clone(), cwd: cwd.clone(), }, - GuardianApprovalRequest::ApplyPatch { cwd, files, .. } => GuardianAssessmentAction::ApplyPatch { - cwd: cwd.clone(), - files: files.clone(), - }, + GuardianApprovalRequest::ApplyPatch { cwd, files, .. } => { + GuardianAssessmentAction::ApplyPatch { + cwd: cwd.clone(), + files: files.clone(), + } + } GuardianApprovalRequest::NetworkAccess { id: _id, turn_id: _turn_id, @@ -1024,7 +682,9 @@ pub(crate) fn guardian_assessment_action(action: &GuardianApprovalRequest) -> Gu } } -pub(crate) fn guardian_reviewed_action(request: &GuardianApprovalRequest) -> GuardianReviewedAction { +pub(crate) fn guardian_reviewed_action( + request: &GuardianApprovalRequest, +) -> GuardianReviewedAction { match request { GuardianApprovalRequest::Shell { sandbox_permissions, @@ -1076,7 +736,9 @@ pub(crate) fn guardian_reviewed_action(request: &GuardianApprovalRequest) -> Gua connector_name: connector_name.clone(), tool_title: tool_title.clone(), }, - GuardianApprovalRequest::RequestPermissions { .. } => GuardianReviewedAction::RequestPermissions {}, + GuardianApprovalRequest::RequestPermissions { .. } => { + GuardianReviewedAction::RequestPermissions {} + } } } @@ -1124,7 +786,6 @@ pub(crate) fn format_guardian_action_pretty( mod tests { use super::*; use codex_protocol::protocol::FileChange; - use codex_protocol::protocol::ReviewDecision; use codex_utils_absolute_path::test_support::PathBufExt; use codex_utils_absolute_path::test_support::test_path_buf; use pretty_assertions::assert_eq; @@ -1296,88 +957,4 @@ mod tests { ]) ); } - - #[test] - fn mcp_tool_approval_compat_response_uses_session_label_when_present() { - let request = GuardianApprovalRequest::McpToolCall { - id: "call-1".to_string(), - server: "custom_server".to_string(), - tool_name: "dangerous_tool".to_string(), - hook_tool_name: "custom_server__dangerous_tool".to_string(), - arguments: None, - connector_id: None, - connector_name: None, - connector_description: None, - tool_title: None, - tool_description: None, - annotations: None, - }; - let question = RequestUserInputQuestion { - id: "q-1".to_string(), - header: "Approve app tool call?".to_string(), - question: "Allow this app tool?".to_string(), - is_other: false, - is_secret: false, - options: Some(vec![RequestUserInputQuestionOption { - label: MCP_TOOL_APPROVAL_ACCEPT_FOR_SESSION.to_string(), - description: "Remember until session ends".to_string(), - }]), - }; - - let response = request - .mcp_tool_approval_compat_response(&question, ReviewDecision::ApprovedForSession) - .expect("compat response"); - - assert_eq!( - response.answers.get("q-1"), - Some(&RequestUserInputAnswer { - answers: vec![MCP_TOOL_APPROVAL_ACCEPT_FOR_SESSION.to_string()], - }) - ); - } - - #[test] - fn mcp_tool_approval_compat_response_uses_synthetic_decline_for_abort() { - let request = GuardianApprovalRequest::McpToolCall { - id: "call-1".to_string(), - server: "custom_server".to_string(), - tool_name: "dangerous_tool".to_string(), - hook_tool_name: "custom_server__dangerous_tool".to_string(), - arguments: None, - connector_id: None, - connector_name: None, - connector_description: None, - tool_title: None, - tool_description: None, - annotations: None, - }; - let question = RequestUserInputQuestion { - id: "q-1".to_string(), - header: "Approve app tool call?".to_string(), - question: "Allow this app tool?".to_string(), - is_other: false, - is_secret: false, - options: None, - }; - - let response = request - .mcp_tool_approval_compat_response(&question, ReviewDecision::Abort) - .expect("compat response"); - - assert_eq!( - response.answers.get("q-1"), - Some(&RequestUserInputAnswer { - answers: vec![MCP_TOOL_APPROVAL_DECLINE_SYNTHETIC.to_string()], - }) - ); - } - - #[test] - fn mcp_tool_approval_question_id_helpers_round_trip() { - let question_id = mcp_tool_approval_question_id("call-1"); - - assert_eq!(question_id, "mcp_tool_call_approval_call-1"); - assert!(is_mcp_tool_approval_question_id(&question_id)); - assert!(!is_mcp_tool_approval_question_id("other_question")); - } } diff --git a/codex-rs/core/src/guardian/mod.rs b/codex-rs/core/src/guardian/mod.rs index 8bd2621546..256a616b97 100644 --- a/codex-rs/core/src/guardian/mod.rs +++ b/codex-rs/core/src/guardian/mod.rs @@ -26,50 +26,7 @@ use serde::Serialize; pub(crate) use approval_request::GuardianApprovalRequest; pub(crate) use approval_request::GuardianMcpAnnotations; pub(crate) use approval_request::GuardianNetworkAccessTrigger; -#[allow(unused_imports)] -pub(crate) use approval_request::MCP_TOOL_APPROVAL_ACCEPT; -#[allow(unused_imports)] -pub(crate) use approval_request::MCP_TOOL_APPROVAL_ACCEPT_AND_REMEMBER; -#[allow(unused_imports)] -pub(crate) use approval_request::MCP_TOOL_APPROVAL_ACCEPT_FOR_SESSION; -#[allow(unused_imports)] -pub(crate) use approval_request::MCP_TOOL_APPROVAL_CANCEL; -#[allow(unused_imports)] -pub(crate) use approval_request::MCP_TOOL_APPROVAL_CONNECTOR_DESCRIPTION_KEY; -#[allow(unused_imports)] -pub(crate) use approval_request::MCP_TOOL_APPROVAL_CONNECTOR_ID_KEY; -#[allow(unused_imports)] -pub(crate) use approval_request::MCP_TOOL_APPROVAL_CONNECTOR_NAME_KEY; -#[allow(unused_imports)] -pub(crate) use approval_request::MCP_TOOL_APPROVAL_DECLINE_SYNTHETIC; -#[allow(unused_imports)] -pub(crate) use approval_request::MCP_TOOL_APPROVAL_KIND_KEY; -#[allow(unused_imports)] -pub(crate) use approval_request::MCP_TOOL_APPROVAL_KIND_MCP_TOOL_CALL; -#[allow(unused_imports)] -pub(crate) use approval_request::MCP_TOOL_APPROVAL_PERSIST_ALWAYS; -#[allow(unused_imports)] -pub(crate) use approval_request::MCP_TOOL_APPROVAL_PERSIST_KEY; -#[allow(unused_imports)] -pub(crate) use approval_request::MCP_TOOL_APPROVAL_PERSIST_SESSION; -#[allow(unused_imports)] -pub(crate) use approval_request::MCP_TOOL_APPROVAL_QUESTION_ID_PREFIX; -#[allow(unused_imports)] -pub(crate) use approval_request::MCP_TOOL_APPROVAL_SOURCE_CONNECTOR; -#[allow(unused_imports)] -pub(crate) use approval_request::MCP_TOOL_APPROVAL_SOURCE_KEY; -#[allow(unused_imports)] -pub(crate) use approval_request::MCP_TOOL_APPROVAL_TOOL_DESCRIPTION_KEY; -#[allow(unused_imports)] -pub(crate) use approval_request::MCP_TOOL_APPROVAL_TOOL_PARAMS_DISPLAY_KEY; -#[allow(unused_imports)] -pub(crate) use approval_request::MCP_TOOL_APPROVAL_TOOL_PARAMS_KEY; -#[allow(unused_imports)] -pub(crate) use approval_request::MCP_TOOL_APPROVAL_TOOL_TITLE_KEY; -pub(crate) use approval_request::McpToolApprovalPromptOptions; pub(crate) use approval_request::guardian_approval_request_to_json; -pub(crate) use approval_request::is_mcp_tool_approval_question_id; -pub(crate) use approval_request::mcp_tool_approval_question_id; pub(crate) use review::guardian_rejection_message; pub(crate) use review::guardian_timeout_message; pub(crate) use review::is_guardian_reviewer_source; diff --git a/codex-rs/core/src/mcp_tool_call.rs b/codex-rs/core/src/mcp_tool_call.rs index a63051186c..60cfc03c9f 100644 --- a/codex-rs/core/src/mcp_tool_call.rs +++ b/codex-rs/core/src/mcp_tool_call.rs @@ -19,24 +19,16 @@ use crate::config::load_global_mcp_servers; use crate::connectors; use crate::guardian::GuardianApprovalRequest; use crate::guardian::GuardianMcpAnnotations; -use crate::guardian::MCP_TOOL_APPROVAL_ACCEPT; -use crate::guardian::MCP_TOOL_APPROVAL_ACCEPT_AND_REMEMBER; -use crate::guardian::MCP_TOOL_APPROVAL_ACCEPT_FOR_SESSION; -use crate::guardian::MCP_TOOL_APPROVAL_DECLINE_SYNTHETIC; -use crate::guardian::MCP_TOOL_APPROVAL_PERSIST_ALWAYS; -use crate::guardian::MCP_TOOL_APPROVAL_PERSIST_KEY; -use crate::guardian::MCP_TOOL_APPROVAL_PERSIST_SESSION; -use crate::guardian::McpToolApprovalPromptOptions; use crate::guardian::guardian_approval_request_to_json; use crate::guardian::guardian_rejection_message; use crate::guardian::guardian_timeout_message; -use crate::guardian::mcp_tool_approval_question_id; use crate::guardian::new_guardian_review_id; use crate::guardian::review_approval_request; use crate::guardian::routes_approval_to_guardian; use crate::hook_runtime::run_permission_request_hooks; use crate::mcp_openai_file::rewrite_mcp_tool_arguments_for_openai_files; use crate::mcp_tool_approval_templates::RenderedMcpToolApprovalParam; +use crate::mcp_tool_approval_templates::render_mcp_tool_approval_template; use crate::session::session::Session; use crate::session::turn_context::TurnContext; use codex_analytics::AppInvocation; @@ -61,6 +53,7 @@ use codex_protocol::protocol::ReviewDecision; use codex_protocol::request_user_input::RequestUserInputAnswer; use codex_protocol::request_user_input::RequestUserInputArgs; use codex_protocol::request_user_input::RequestUserInputQuestion; +use codex_protocol::request_user_input::RequestUserInputQuestionOption; use codex_protocol::request_user_input::RequestUserInputResponse; use codex_rmcp_client::ElicitationAction; use codex_rmcp_client::ElicitationResponse; @@ -882,6 +875,45 @@ fn with_mcp_tool_call_thread_id_meta( } } +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +struct McpToolApprovalPromptOptions { + allow_session_remember: bool, + allow_persistent_approval: bool, +} + +#[derive(Clone, Debug, PartialEq)] +struct McpToolApprovalPrompt { + question: RequestUserInputQuestion, + message_override: Option, + tool_params: Option, + tool_params_display: Option>, +} + +pub(crate) const MCP_TOOL_APPROVAL_ACCEPT: &str = "Allow"; +pub(crate) const MCP_TOOL_APPROVAL_ACCEPT_FOR_SESSION: &str = "Allow for this session"; +const MCP_TOOL_APPROVAL_ACCEPT_AND_REMEMBER: &str = "Allow and don't ask me again"; +const MCP_TOOL_APPROVAL_CANCEL: &str = "Cancel"; +// Internal-only token used when guardian auto-reviews delegated MCP approvals on the +// RequestUserInput compatibility path. That legacy MCP prompt has allow/cancel labels but no +// real "Decline" answer, so this lets guardian denials round-trip distinctly from user cancel. +// This is not a user-facing option. +pub(crate) const MCP_TOOL_APPROVAL_DECLINE_SYNTHETIC: &str = "__codex_mcp_decline__"; +pub(crate) const MCP_TOOL_APPROVAL_QUESTION_ID_PREFIX: &str = "mcp_tool_call_approval"; +const MCP_TOOL_APPROVAL_KIND_KEY: &str = "codex_approval_kind"; +const MCP_TOOL_APPROVAL_KIND_MCP_TOOL_CALL: &str = "mcp_tool_call"; +pub(crate) const MCP_TOOL_APPROVAL_PERSIST_KEY: &str = "persist"; +pub(crate) const MCP_TOOL_APPROVAL_PERSIST_SESSION: &str = "session"; +pub(crate) const MCP_TOOL_APPROVAL_PERSIST_ALWAYS: &str = "always"; +const MCP_TOOL_APPROVAL_SOURCE_KEY: &str = "source"; +const MCP_TOOL_APPROVAL_SOURCE_CONNECTOR: &str = "connector"; +const MCP_TOOL_APPROVAL_CONNECTOR_ID_KEY: &str = "connector_id"; +const MCP_TOOL_APPROVAL_CONNECTOR_NAME_KEY: &str = "connector_name"; +const MCP_TOOL_APPROVAL_CONNECTOR_DESCRIPTION_KEY: &str = "connector_description"; +const MCP_TOOL_APPROVAL_TOOL_TITLE_KEY: &str = "tool_title"; +const MCP_TOOL_APPROVAL_TOOL_DESCRIPTION_KEY: &str = "tool_description"; +const MCP_TOOL_APPROVAL_TOOL_PARAMS_KEY: &str = "tool_params"; +const MCP_TOOL_APPROVAL_TOOL_PARAMS_DISPLAY_KEY: &str = "tool_params_display"; + struct McpToolApprovalElicitationRequest<'a> { server: &'a str, approval_request: &'a GuardianApprovalRequest, @@ -902,6 +934,309 @@ struct McpToolApprovalKey { tool_name: String, } +pub(crate) fn mcp_tool_approval_question_id(call_id: &str) -> String { + format!("{MCP_TOOL_APPROVAL_QUESTION_ID_PREFIX}_{call_id}") +} + +pub(crate) fn is_mcp_tool_approval_question_id(question_id: &str) -> bool { + question_id + .strip_prefix(MCP_TOOL_APPROVAL_QUESTION_ID_PREFIX) + .is_some_and(|suffix| suffix.starts_with('_')) +} + +fn mcp_tool_approval_prompt( + approval_request: &GuardianApprovalRequest, + question_id: String, + prompt_options: McpToolApprovalPromptOptions, + monitor_reason: Option<&str>, +) -> Option { + let GuardianApprovalRequest::McpToolCall { + server, + tool_name, + arguments, + connector_id, + connector_name, + tool_title, + .. + } = approval_request + else { + return None; + }; + + let rendered_template = render_mcp_tool_approval_template( + server, + connector_id.as_deref(), + connector_name.as_deref(), + tool_title.as_deref(), + arguments.as_ref(), + ); + let tool_params_display = rendered_template + .as_ref() + .map(|rendered_template| rendered_template.tool_params_display.clone()) + .or_else(|| build_mcp_tool_approval_display_params(arguments.as_ref())); + let question_override = rendered_template + .as_ref() + .map(|rendered_template| rendered_template.question.as_str()); + let mut question = build_mcp_tool_approval_question( + question_id, + server, + tool_name, + connector_name.as_deref(), + prompt_options, + question_override, + ); + question.question = mcp_tool_approval_question_text(question.question, monitor_reason); + + Some(McpToolApprovalPrompt { + question, + message_override: rendered_template.as_ref().and_then(|rendered_template| { + monitor_reason + .is_none() + .then_some(rendered_template.elicitation_message.clone()) + }), + tool_params: rendered_template + .as_ref() + .and_then(|rendered_template| rendered_template.tool_params.clone()) + .or_else(|| arguments.clone()), + tool_params_display, + }) +} + +fn mcp_tool_approval_elicitation_meta( + approval_request: &GuardianApprovalRequest, + tool_params: Option<&JsonValue>, + tool_params_display: Option<&[RenderedMcpToolApprovalParam]>, + prompt_options: McpToolApprovalPromptOptions, +) -> Option { + let GuardianApprovalRequest::McpToolCall { + server, + connector_id, + connector_name, + connector_description, + tool_title, + tool_description, + .. + } = approval_request + else { + return None; + }; + + let mut meta = serde_json::Map::new(); + meta.insert( + MCP_TOOL_APPROVAL_KIND_KEY.to_string(), + JsonValue::String(MCP_TOOL_APPROVAL_KIND_MCP_TOOL_CALL.to_string()), + ); + match ( + prompt_options.allow_session_remember, + prompt_options.allow_persistent_approval, + ) { + (true, true) => { + meta.insert( + MCP_TOOL_APPROVAL_PERSIST_KEY.to_string(), + serde_json::json!([ + MCP_TOOL_APPROVAL_PERSIST_SESSION, + MCP_TOOL_APPROVAL_PERSIST_ALWAYS, + ]), + ); + } + (true, false) => { + meta.insert( + MCP_TOOL_APPROVAL_PERSIST_KEY.to_string(), + JsonValue::String(MCP_TOOL_APPROVAL_PERSIST_SESSION.to_string()), + ); + } + (false, true) => { + meta.insert( + MCP_TOOL_APPROVAL_PERSIST_KEY.to_string(), + JsonValue::String(MCP_TOOL_APPROVAL_PERSIST_ALWAYS.to_string()), + ); + } + (false, false) => {} + } + if let Some(tool_title) = tool_title.as_ref() { + meta.insert( + MCP_TOOL_APPROVAL_TOOL_TITLE_KEY.to_string(), + JsonValue::String(tool_title.clone()), + ); + } + if let Some(tool_description) = tool_description.as_ref() { + meta.insert( + MCP_TOOL_APPROVAL_TOOL_DESCRIPTION_KEY.to_string(), + JsonValue::String(tool_description.clone()), + ); + } + if server == "codex_apps" + && (connector_id.is_some() || connector_name.is_some() || connector_description.is_some()) + { + meta.insert( + MCP_TOOL_APPROVAL_SOURCE_KEY.to_string(), + JsonValue::String(MCP_TOOL_APPROVAL_SOURCE_CONNECTOR.to_string()), + ); + if let Some(connector_id) = connector_id.as_deref() { + meta.insert( + MCP_TOOL_APPROVAL_CONNECTOR_ID_KEY.to_string(), + JsonValue::String(connector_id.to_string()), + ); + } + if let Some(connector_name) = connector_name.as_ref() { + meta.insert( + MCP_TOOL_APPROVAL_CONNECTOR_NAME_KEY.to_string(), + JsonValue::String(connector_name.clone()), + ); + } + if let Some(connector_description) = connector_description.as_ref() { + meta.insert( + MCP_TOOL_APPROVAL_CONNECTOR_DESCRIPTION_KEY.to_string(), + JsonValue::String(connector_description.clone()), + ); + } + } + if let Some(tool_params) = tool_params { + meta.insert( + MCP_TOOL_APPROVAL_TOOL_PARAMS_KEY.to_string(), + tool_params.clone(), + ); + } + if let Some(tool_params_display) = tool_params_display + && let Ok(tool_params_display) = serde_json::to_value(tool_params_display) + { + meta.insert( + MCP_TOOL_APPROVAL_TOOL_PARAMS_DISPLAY_KEY.to_string(), + tool_params_display, + ); + } + + (!meta.is_empty()).then_some(JsonValue::Object(meta)) +} + +pub(crate) fn mcp_tool_approval_compat_response( + approval_request: &GuardianApprovalRequest, + question: &RequestUserInputQuestion, + decision: ReviewDecision, +) -> Option { + let GuardianApprovalRequest::McpToolCall { .. } = approval_request else { + return None; + }; + + let selected_label = match decision { + ReviewDecision::ApprovedForSession => question + .options + .as_ref() + .and_then(|options| { + options + .iter() + .find(|option| option.label == MCP_TOOL_APPROVAL_ACCEPT_FOR_SESSION) + }) + .map(|option| option.label.clone()) + .unwrap_or_else(|| MCP_TOOL_APPROVAL_ACCEPT.to_string()), + ReviewDecision::Approved + | ReviewDecision::ApprovedExecpolicyAmendment { .. } + | ReviewDecision::NetworkPolicyAmendment { .. } => MCP_TOOL_APPROVAL_ACCEPT.to_string(), + ReviewDecision::Denied | ReviewDecision::TimedOut | ReviewDecision::Abort => { + MCP_TOOL_APPROVAL_DECLINE_SYNTHETIC.to_string() + } + }; + + Some(RequestUserInputResponse { + answers: HashMap::from([( + question.id.clone(), + RequestUserInputAnswer { + answers: vec![selected_label], + }, + )]), + }) +} + +fn build_mcp_tool_approval_question( + question_id: String, + server: &str, + tool_name: &str, + connector_name: Option<&str>, + prompt_options: McpToolApprovalPromptOptions, + question_override: Option<&str>, +) -> RequestUserInputQuestion { + let question = question_override + .map(ToString::to_string) + .unwrap_or_else(|| { + build_mcp_tool_approval_fallback_message(server, tool_name, connector_name) + }); + let question = format!("{}?", question.trim_end_matches('?')); + + let mut options = vec![RequestUserInputQuestionOption { + label: MCP_TOOL_APPROVAL_ACCEPT.to_string(), + description: "Run the tool and continue.".to_string(), + }]; + if prompt_options.allow_session_remember { + options.push(RequestUserInputQuestionOption { + label: MCP_TOOL_APPROVAL_ACCEPT_FOR_SESSION.to_string(), + description: "Run the tool and remember this choice for this session.".to_string(), + }); + } + if prompt_options.allow_persistent_approval { + options.push(RequestUserInputQuestionOption { + label: MCP_TOOL_APPROVAL_ACCEPT_AND_REMEMBER.to_string(), + description: "Run the tool and remember this choice for future tool calls.".to_string(), + }); + } + options.push(RequestUserInputQuestionOption { + label: MCP_TOOL_APPROVAL_CANCEL.to_string(), + description: "Cancel this tool call.".to_string(), + }); + + RequestUserInputQuestion { + id: question_id, + header: "Approve app tool call?".to_string(), + question, + is_other: false, + is_secret: false, + options: Some(options), + } +} + +fn build_mcp_tool_approval_fallback_message( + server: &str, + tool_name: &str, + connector_name: Option<&str>, +) -> String { + let actor = connector_name + .map(str::trim) + .filter(|name| !name.is_empty()) + .map(ToString::to_string) + .unwrap_or_else(|| { + if server == "codex_apps" { + "this app".to_string() + } else { + format!("the {server} MCP server") + } + }); + format!("Allow {actor} to run tool \\\"{tool_name}\\\"?") +} + +fn mcp_tool_approval_question_text(question: String, monitor_reason: Option<&str>) -> String { + match monitor_reason.map(str::trim) { + Some(reason) if !reason.is_empty() => { + format!("Tool call needs your approval. Reason: {reason}") + } + _ => question, + } +} + +fn build_mcp_tool_approval_display_params( + tool_params: Option<&JsonValue>, +) -> Option> { + let tool_params = tool_params?.as_object()?; + let mut display_params = tool_params + .iter() + .map(|(name, value)| RenderedMcpToolApprovalParam { + name: name.clone(), + value: value.clone(), + display_name: name.clone(), + }) + .collect::>(); + display_params.sort_by(|left, right| left.name.cmp(&right.name)); + Some(display_params) +} + fn mcp_tool_approval_prompt_options( session_approval_key: Option<&McpToolApprovalKey>, persistent_approval_key: Option<&McpToolApprovalKey>, @@ -1029,7 +1364,8 @@ async fn maybe_request_mcp_tool_approval( tool_call_mcp_elicitation_enabled, ); let question_id = mcp_tool_approval_question_id(call_id); - let Some(prompt) = approval_request.mcp_tool_approval_prompt( + let Some(prompt) = mcp_tool_approval_prompt( + &approval_request, question_id.clone(), prompt_options, monitor_reason.as_deref(), @@ -1358,7 +1694,8 @@ fn build_mcp_tool_approval_elicitation_request( turn_id: Some(turn_context.sub_id.clone()), server_name: request.server.to_string(), request: McpServerElicitationRequest::Form { - meta: request.approval_request.mcp_tool_approval_elicitation_meta( + meta: mcp_tool_approval_elicitation_meta( + request.approval_request, request.tool_params, request.tool_params_display, request.prompt_options, diff --git a/codex-rs/core/src/mcp_tool_call_tests.rs b/codex-rs/core/src/mcp_tool_call_tests.rs index a48be0d030..bbfe891127 100644 --- a/codex-rs/core/src/mcp_tool_call_tests.rs +++ b/codex-rs/core/src/mcp_tool_call_tests.rs @@ -2,19 +2,6 @@ use super::*; use crate::config::ConfigBuilder; use crate::guardian::GuardianApprovalRequest; use crate::guardian::GuardianMcpAnnotations; -use crate::guardian::MCP_TOOL_APPROVAL_CANCEL; -use crate::guardian::MCP_TOOL_APPROVAL_CONNECTOR_DESCRIPTION_KEY; -use crate::guardian::MCP_TOOL_APPROVAL_CONNECTOR_ID_KEY; -use crate::guardian::MCP_TOOL_APPROVAL_CONNECTOR_NAME_KEY; -use crate::guardian::MCP_TOOL_APPROVAL_DECLINE_SYNTHETIC; -use crate::guardian::MCP_TOOL_APPROVAL_KIND_KEY; -use crate::guardian::MCP_TOOL_APPROVAL_KIND_MCP_TOOL_CALL; -use crate::guardian::MCP_TOOL_APPROVAL_SOURCE_CONNECTOR; -use crate::guardian::MCP_TOOL_APPROVAL_SOURCE_KEY; -use crate::guardian::MCP_TOOL_APPROVAL_TOOL_DESCRIPTION_KEY; -use crate::guardian::MCP_TOOL_APPROVAL_TOOL_PARAMS_DISPLAY_KEY; -use crate::guardian::MCP_TOOL_APPROVAL_TOOL_PARAMS_KEY; -use crate::guardian::MCP_TOOL_APPROVAL_TOOL_TITLE_KEY; use crate::session::tests::make_session_and_context; use crate::session::tests::make_session_and_context_with_rx; use crate::state::ActiveTurn; @@ -320,22 +307,90 @@ fn approval_question_text_prepends_safety_reason() { /*metadata*/ None, ); assert_eq!( - request - .mcp_tool_approval_prompt( - "q".to_string(), - prompt_options( - /*allow_session_remember*/ false, - /*allow_persistent_approval*/ false, - ), - Some("This tool may contact an external system."), - ) - .expect("mcp approval prompt") - .question - .question, + mcp_tool_approval_prompt( + &request, + "q".to_string(), + prompt_options( + /*allow_session_remember*/ false, /*allow_persistent_approval*/ false, + ), + Some("This tool may contact an external system."), + ) + .expect("mcp approval prompt") + .question + .question, "Tool call needs your approval. Reason: This tool may contact an external system." ); } +#[test] +fn mcp_tool_approval_compat_response_uses_session_label_when_present() { + let request = approval_prompt_request( + "custom_server", + "dangerous_tool", + /*arguments*/ None, + /*metadata*/ None, + ); + let question = RequestUserInputQuestion { + id: "q-1".to_string(), + header: "Approve app tool call?".to_string(), + question: "Allow this app tool?".to_string(), + is_other: false, + is_secret: false, + options: Some(vec![RequestUserInputQuestionOption { + label: MCP_TOOL_APPROVAL_ACCEPT_FOR_SESSION.to_string(), + description: "Remember until session ends".to_string(), + }]), + }; + + let response = + mcp_tool_approval_compat_response(&request, &question, ReviewDecision::ApprovedForSession) + .expect("compat response"); + + assert_eq!( + response.answers.get("q-1"), + Some(&RequestUserInputAnswer { + answers: vec![MCP_TOOL_APPROVAL_ACCEPT_FOR_SESSION.to_string()], + }) + ); +} + +#[test] +fn mcp_tool_approval_compat_response_uses_synthetic_decline_for_abort() { + let request = approval_prompt_request( + "custom_server", + "dangerous_tool", + /*arguments*/ None, + /*metadata*/ None, + ); + let question = RequestUserInputQuestion { + id: "q-1".to_string(), + header: "Approve app tool call?".to_string(), + question: "Allow this app tool?".to_string(), + is_other: false, + is_secret: false, + options: None, + }; + + let response = mcp_tool_approval_compat_response(&request, &question, ReviewDecision::Abort) + .expect("compat response"); + + assert_eq!( + response.answers.get("q-1"), + Some(&RequestUserInputAnswer { + answers: vec![MCP_TOOL_APPROVAL_DECLINE_SYNTHETIC.to_string()], + }) + ); +} + +#[test] +fn mcp_tool_approval_question_id_helpers_round_trip() { + let question_id = mcp_tool_approval_question_id("call-1"); + + assert_eq!(question_id, "mcp_tool_call_approval_call-1"); + assert!(is_mcp_tool_approval_question_id(&question_id)); + assert!(!is_mcp_tool_approval_question_id("other_question")); +} + #[tokio::test] async fn mcp_tool_call_span_records_expected_fields() { let buffer: &'static std::sync::Mutex> = @@ -543,15 +598,15 @@ async fn approval_elicitation_request_uses_message_override_and_preserves_tool_p })), Some(&metadata), ); - let prompt = approval_request - .mcp_tool_approval_prompt( - "q".to_string(), - prompt_options( - /*allow_session_remember*/ true, /*allow_persistent_approval*/ true, - ), - /*monitor_reason*/ None, - ) - .expect("mcp approval prompt"); + let prompt = mcp_tool_approval_prompt( + &approval_request, + "q".to_string(), + prompt_options( + /*allow_session_remember*/ true, /*allow_persistent_approval*/ true, + ), + /*monitor_reason*/ None, + ) + .expect("mcp approval prompt"); let request = build_mcp_tool_approval_elicitation_request( &session, @@ -625,13 +680,13 @@ async fn approval_elicitation_request_uses_message_override_and_preserves_tool_p #[test] fn custom_mcp_tool_question_mentions_server_name() { - let question = approval_prompt_request( - "custom_server", - "run_action", - /*arguments*/ None, - /*metadata*/ None, - ) - .mcp_tool_approval_prompt( + let question = mcp_tool_approval_prompt( + &approval_prompt_request( + "custom_server", + "run_action", + /*arguments*/ None, + /*metadata*/ None, + ), "q".to_string(), prompt_options( /*allow_session_remember*/ false, /*allow_persistent_approval*/ false, @@ -658,13 +713,13 @@ fn custom_mcp_tool_question_mentions_server_name() { #[test] fn codex_apps_tool_question_uses_fallback_app_label() { - let question = approval_prompt_request( - CODEX_APPS_MCP_SERVER_NAME, - "run_action", - /*arguments*/ None, - /*metadata*/ None, - ) - .mcp_tool_approval_prompt( + let question = mcp_tool_approval_prompt( + &approval_prompt_request( + CODEX_APPS_MCP_SERVER_NAME, + "run_action", + /*arguments*/ None, + /*metadata*/ None, + ), "q".to_string(), prompt_options( /*allow_session_remember*/ true, /*allow_persistent_approval*/ true, @@ -689,13 +744,13 @@ fn trusted_codex_apps_tool_question_offers_always_allow() { /*tool_title*/ None, /*tool_description*/ None, ); - let question = approval_prompt_request( - CODEX_APPS_MCP_SERVER_NAME, - "run_action", - /*arguments*/ None, - Some(&metadata), - ) - .mcp_tool_approval_prompt( + let question = mcp_tool_approval_prompt( + &approval_prompt_request( + CODEX_APPS_MCP_SERVER_NAME, + "run_action", + /*arguments*/ None, + Some(&metadata), + ), "q".to_string(), prompt_options( /*allow_session_remember*/ true, /*allow_persistent_approval*/ true, @@ -743,13 +798,13 @@ fn codex_apps_tool_question_without_elicitation_omits_always_allow() { /*tool_title*/ None, /*tool_description*/ None, ); - let question = approval_prompt_request( - CODEX_APPS_MCP_SERVER_NAME, - "run_action", - /*arguments*/ None, - Some(&metadata), - ) - .mcp_tool_approval_prompt( + let question = mcp_tool_approval_prompt( + &approval_prompt_request( + CODEX_APPS_MCP_SERVER_NAME, + "run_action", + /*arguments*/ None, + Some(&metadata), + ), "q".to_string(), mcp_tool_approval_prompt_options( Some(&session_key), @@ -778,13 +833,13 @@ fn codex_apps_tool_question_without_elicitation_omits_always_allow() { #[test] fn custom_mcp_tool_question_offers_session_remember_and_always_allow() { - let question = approval_prompt_request( - "custom_server", - "run_action", - /*arguments*/ None, - /*metadata*/ None, - ) - .mcp_tool_approval_prompt( + let question = mcp_tool_approval_prompt( + &approval_prompt_request( + "custom_server", + "run_action", + /*arguments*/ None, + /*metadata*/ None, + ), "q".to_string(), prompt_options( /*allow_session_remember*/ true, /*allow_persistent_approval*/ true, @@ -1181,7 +1236,8 @@ fn approval_elicitation_meta_marks_tool_approvals() { /*metadata*/ None, ); assert_eq!( - request.mcp_tool_approval_elicitation_meta( + mcp_tool_approval_elicitation_meta( + &request, /*tool_params*/ None, /*tool_params_display*/ None, prompt_options( @@ -1210,7 +1266,8 @@ fn approval_elicitation_meta_merges_session_and_always_persist_for_custom_server Some(&metadata), ); assert_eq!( - request.mcp_tool_approval_elicitation_meta( + mcp_tool_approval_elicitation_meta( + &request, Some(&serde_json::json!({"id": 1})), /*tool_params_display*/ None, prompt_options( @@ -1433,7 +1490,8 @@ fn approval_elicitation_meta_includes_connector_source_for_codex_apps() { Some(&metadata), ); assert_eq!( - request.mcp_tool_approval_elicitation_meta( + mcp_tool_approval_elicitation_meta( + &request, Some(&serde_json::json!({ "calendar_id": "primary", })), @@ -1475,7 +1533,8 @@ fn approval_elicitation_meta_merges_session_and_always_persist_with_connector_so Some(&metadata), ); assert_eq!( - request.mcp_tool_approval_elicitation_meta( + mcp_tool_approval_elicitation_meta( + &request, Some(&serde_json::json!({ "calendar_id": "primary", })), From a1c0d3e5b34bbb25482e7504d76c3604c87a1237 Mon Sep 17 00:00:00 2001 From: Abhinav Vedmala Date: Sat, 2 May 2026 00:43:12 -0700 Subject: [PATCH 06/12] trim MCP approval prompt helpers --- codex-rs/core/src/codex_delegate_tests.rs | 5 ++--- codex-rs/core/src/mcp_tool_call.rs | 20 ++++++++------------ codex-rs/core/src/mcp_tool_call_tests.rs | 4 ++-- 3 files changed, 12 insertions(+), 17 deletions(-) diff --git a/codex-rs/core/src/codex_delegate_tests.rs b/codex-rs/core/src/codex_delegate_tests.rs index 454e4aa660..fa86d97d2e 100644 --- a/codex-rs/core/src/codex_delegate_tests.rs +++ b/codex-rs/core/src/codex_delegate_tests.rs @@ -1,6 +1,5 @@ use super::*; use crate::mcp_tool_call::MCP_TOOL_APPROVAL_DECLINE_SYNTHETIC; -use crate::mcp_tool_call::MCP_TOOL_APPROVAL_QUESTION_ID_PREFIX; use async_channel::bounded; use codex_protocol::config_types::ApprovalsReviewer; use codex_protocol::models::NetworkPermissions; @@ -504,7 +503,7 @@ async fn delegated_mcp_guardian_abort_returns_synthetic_decline_answer() { call_id: "call-1".to_string(), turn_id: "child-turn-1".to_string(), questions: vec![RequestUserInputQuestion { - id: format!("{MCP_TOOL_APPROVAL_QUESTION_ID_PREFIX}_call-1"), + id: "mcp_tool_call_approval_call-1".to_string(), header: "Approve app tool call?".to_string(), question: "Allow this app tool?".to_string(), is_other: false, @@ -520,7 +519,7 @@ async fn delegated_mcp_guardian_abort_returns_synthetic_decline_answer() { response, Some(RequestUserInputResponse { answers: HashMap::from([( - format!("{MCP_TOOL_APPROVAL_QUESTION_ID_PREFIX}_call-1"), + "mcp_tool_call_approval_call-1".to_string(), RequestUserInputAnswer { answers: vec![MCP_TOOL_APPROVAL_DECLINE_SYNTHETIC.to_string()], }, diff --git a/codex-rs/core/src/mcp_tool_call.rs b/codex-rs/core/src/mcp_tool_call.rs index 60cfc03c9f..b813d9ea2a 100644 --- a/codex-rs/core/src/mcp_tool_call.rs +++ b/codex-rs/core/src/mcp_tool_call.rs @@ -875,7 +875,7 @@ fn with_mcp_tool_call_thread_id_meta( } } -#[derive(Clone, Copy, Debug, Eq, PartialEq)] +#[derive(Clone, Copy)] struct McpToolApprovalPromptOptions { allow_session_remember: bool, allow_persistent_approval: bool, @@ -889,8 +889,8 @@ struct McpToolApprovalPrompt { tool_params_display: Option>, } -pub(crate) const MCP_TOOL_APPROVAL_ACCEPT: &str = "Allow"; -pub(crate) const MCP_TOOL_APPROVAL_ACCEPT_FOR_SESSION: &str = "Allow for this session"; +const MCP_TOOL_APPROVAL_ACCEPT: &str = "Allow"; +const MCP_TOOL_APPROVAL_ACCEPT_FOR_SESSION: &str = "Allow for this session"; const MCP_TOOL_APPROVAL_ACCEPT_AND_REMEMBER: &str = "Allow and don't ask me again"; const MCP_TOOL_APPROVAL_CANCEL: &str = "Cancel"; // Internal-only token used when guardian auto-reviews delegated MCP approvals on the @@ -898,12 +898,12 @@ const MCP_TOOL_APPROVAL_CANCEL: &str = "Cancel"; // real "Decline" answer, so this lets guardian denials round-trip distinctly from user cancel. // This is not a user-facing option. pub(crate) const MCP_TOOL_APPROVAL_DECLINE_SYNTHETIC: &str = "__codex_mcp_decline__"; -pub(crate) const MCP_TOOL_APPROVAL_QUESTION_ID_PREFIX: &str = "mcp_tool_call_approval"; +const MCP_TOOL_APPROVAL_QUESTION_ID_PREFIX: &str = "mcp_tool_call_approval"; const MCP_TOOL_APPROVAL_KIND_KEY: &str = "codex_approval_kind"; const MCP_TOOL_APPROVAL_KIND_MCP_TOOL_CALL: &str = "mcp_tool_call"; -pub(crate) const MCP_TOOL_APPROVAL_PERSIST_KEY: &str = "persist"; -pub(crate) const MCP_TOOL_APPROVAL_PERSIST_SESSION: &str = "session"; -pub(crate) const MCP_TOOL_APPROVAL_PERSIST_ALWAYS: &str = "always"; +const MCP_TOOL_APPROVAL_PERSIST_KEY: &str = "persist"; +const MCP_TOOL_APPROVAL_PERSIST_SESSION: &str = "session"; +const MCP_TOOL_APPROVAL_PERSIST_ALWAYS: &str = "always"; const MCP_TOOL_APPROVAL_SOURCE_KEY: &str = "source"; const MCP_TOOL_APPROVAL_SOURCE_CONNECTOR: &str = "connector"; const MCP_TOOL_APPROVAL_CONNECTOR_ID_KEY: &str = "connector_id"; @@ -934,10 +934,6 @@ struct McpToolApprovalKey { tool_name: String, } -pub(crate) fn mcp_tool_approval_question_id(call_id: &str) -> String { - format!("{MCP_TOOL_APPROVAL_QUESTION_ID_PREFIX}_{call_id}") -} - pub(crate) fn is_mcp_tool_approval_question_id(question_id: &str) -> bool { question_id .strip_prefix(MCP_TOOL_APPROVAL_QUESTION_ID_PREFIX) @@ -1363,7 +1359,7 @@ async fn maybe_request_mcp_tool_approval( persistent_approval_key.as_ref(), tool_call_mcp_elicitation_enabled, ); - let question_id = mcp_tool_approval_question_id(call_id); + let question_id = format!("{MCP_TOOL_APPROVAL_QUESTION_ID_PREFIX}_{call_id}"); let Some(prompt) = mcp_tool_approval_prompt( &approval_request, question_id.clone(), diff --git a/codex-rs/core/src/mcp_tool_call_tests.rs b/codex-rs/core/src/mcp_tool_call_tests.rs index bbfe891127..446edb4a5a 100644 --- a/codex-rs/core/src/mcp_tool_call_tests.rs +++ b/codex-rs/core/src/mcp_tool_call_tests.rs @@ -383,8 +383,8 @@ fn mcp_tool_approval_compat_response_uses_synthetic_decline_for_abort() { } #[test] -fn mcp_tool_approval_question_id_helpers_round_trip() { - let question_id = mcp_tool_approval_question_id("call-1"); +fn mcp_tool_approval_question_id_detection_round_trips() { + let question_id = format!("{MCP_TOOL_APPROVAL_QUESTION_ID_PREFIX}_call-1"); assert_eq!(question_id, "mcp_tool_call_approval_call-1"); assert!(is_mcp_tool_approval_question_id(&question_id)); From 280698fcf6448f31079f6f1c624c0e82e23fc841 Mon Sep 17 00:00:00 2001 From: Abhinav Vedmala Date: Sat, 2 May 2026 10:21:50 -0700 Subject: [PATCH 07/12] fix MCP fallback prompt quotes --- codex-rs/core/src/mcp_tool_call.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/codex-rs/core/src/mcp_tool_call.rs b/codex-rs/core/src/mcp_tool_call.rs index b813d9ea2a..9a653301b3 100644 --- a/codex-rs/core/src/mcp_tool_call.rs +++ b/codex-rs/core/src/mcp_tool_call.rs @@ -1205,7 +1205,7 @@ fn build_mcp_tool_approval_fallback_message( format!("the {server} MCP server") } }); - format!("Allow {actor} to run tool \\\"{tool_name}\\\"?") + format!("Allow {actor} to run tool \"{tool_name}\"?") } fn mcp_tool_approval_question_text(question: String, monitor_reason: Option<&str>) -> String { From 7113173442d0435343d297ff46c18d2a2f2f19ee Mon Sep 17 00:00:00 2001 From: Abhinav Vedmala Date: Sat, 2 May 2026 11:03:35 -0700 Subject: [PATCH 08/12] reduce mcp approval prompt diff churn --- codex-rs/core/src/mcp_tool_call.rs | 426 ++++++++++++++--------------- 1 file changed, 213 insertions(+), 213 deletions(-) diff --git a/codex-rs/core/src/mcp_tool_call.rs b/codex-rs/core/src/mcp_tool_call.rs index 9a653301b3..a49297e0cc 100644 --- a/codex-rs/core/src/mcp_tool_call.rs +++ b/codex-rs/core/src/mcp_tool_call.rs @@ -881,6 +881,16 @@ struct McpToolApprovalPromptOptions { allow_persistent_approval: bool, } +struct McpToolApprovalElicitationRequest<'a> { + server: &'a str, + approval_request: &'a GuardianApprovalRequest, + tool_params: Option<&'a serde_json::Value>, + tool_params_display: Option<&'a [RenderedMcpToolApprovalParam]>, + question: RequestUserInputQuestion, + message_override: Option<&'a str>, + prompt_options: McpToolApprovalPromptOptions, +} + #[derive(Clone, Debug, PartialEq)] struct McpToolApprovalPrompt { question: RequestUserInputQuestion, @@ -914,19 +924,15 @@ const MCP_TOOL_APPROVAL_TOOL_DESCRIPTION_KEY: &str = "tool_description"; const MCP_TOOL_APPROVAL_TOOL_PARAMS_KEY: &str = "tool_params"; const MCP_TOOL_APPROVAL_TOOL_PARAMS_DISPLAY_KEY: &str = "tool_params_display"; -struct McpToolApprovalElicitationRequest<'a> { - server: &'a str, - approval_request: &'a GuardianApprovalRequest, - tool_params: Option<&'a serde_json::Value>, - tool_params_display: Option<&'a [RenderedMcpToolApprovalParam]>, - question: RequestUserInputQuestion, - message_override: Option<&'a str>, - prompt_options: McpToolApprovalPromptOptions, -} - const MCP_TOOL_CALL_ARC_MONITOR_CALLSITE_DEFAULT: &str = "mcp_tool_call__default"; const MCP_TOOL_CALL_ARC_MONITOR_CALLSITE_ALWAYS_ALLOW: &str = "mcp_tool_call__always_allow"; +pub(crate) fn is_mcp_tool_approval_question_id(question_id: &str) -> bool { + question_id + .strip_prefix(MCP_TOOL_APPROVAL_QUESTION_ID_PREFIX) + .is_some_and(|suffix| suffix.starts_with('_')) +} + #[derive(Clone, Debug, PartialEq, Eq, Serialize)] struct McpToolApprovalKey { server: String, @@ -934,12 +940,6 @@ struct McpToolApprovalKey { tool_name: String, } -pub(crate) fn is_mcp_tool_approval_question_id(question_id: &str) -> bool { - question_id - .strip_prefix(MCP_TOOL_APPROVAL_QUESTION_ID_PREFIX) - .is_some_and(|suffix| suffix.starts_with('_')) -} - fn mcp_tool_approval_prompt( approval_request: &GuardianApprovalRequest, question_id: String, @@ -998,113 +998,6 @@ fn mcp_tool_approval_prompt( }) } -fn mcp_tool_approval_elicitation_meta( - approval_request: &GuardianApprovalRequest, - tool_params: Option<&JsonValue>, - tool_params_display: Option<&[RenderedMcpToolApprovalParam]>, - prompt_options: McpToolApprovalPromptOptions, -) -> Option { - let GuardianApprovalRequest::McpToolCall { - server, - connector_id, - connector_name, - connector_description, - tool_title, - tool_description, - .. - } = approval_request - else { - return None; - }; - - let mut meta = serde_json::Map::new(); - meta.insert( - MCP_TOOL_APPROVAL_KIND_KEY.to_string(), - JsonValue::String(MCP_TOOL_APPROVAL_KIND_MCP_TOOL_CALL.to_string()), - ); - match ( - prompt_options.allow_session_remember, - prompt_options.allow_persistent_approval, - ) { - (true, true) => { - meta.insert( - MCP_TOOL_APPROVAL_PERSIST_KEY.to_string(), - serde_json::json!([ - MCP_TOOL_APPROVAL_PERSIST_SESSION, - MCP_TOOL_APPROVAL_PERSIST_ALWAYS, - ]), - ); - } - (true, false) => { - meta.insert( - MCP_TOOL_APPROVAL_PERSIST_KEY.to_string(), - JsonValue::String(MCP_TOOL_APPROVAL_PERSIST_SESSION.to_string()), - ); - } - (false, true) => { - meta.insert( - MCP_TOOL_APPROVAL_PERSIST_KEY.to_string(), - JsonValue::String(MCP_TOOL_APPROVAL_PERSIST_ALWAYS.to_string()), - ); - } - (false, false) => {} - } - if let Some(tool_title) = tool_title.as_ref() { - meta.insert( - MCP_TOOL_APPROVAL_TOOL_TITLE_KEY.to_string(), - JsonValue::String(tool_title.clone()), - ); - } - if let Some(tool_description) = tool_description.as_ref() { - meta.insert( - MCP_TOOL_APPROVAL_TOOL_DESCRIPTION_KEY.to_string(), - JsonValue::String(tool_description.clone()), - ); - } - if server == "codex_apps" - && (connector_id.is_some() || connector_name.is_some() || connector_description.is_some()) - { - meta.insert( - MCP_TOOL_APPROVAL_SOURCE_KEY.to_string(), - JsonValue::String(MCP_TOOL_APPROVAL_SOURCE_CONNECTOR.to_string()), - ); - if let Some(connector_id) = connector_id.as_deref() { - meta.insert( - MCP_TOOL_APPROVAL_CONNECTOR_ID_KEY.to_string(), - JsonValue::String(connector_id.to_string()), - ); - } - if let Some(connector_name) = connector_name.as_ref() { - meta.insert( - MCP_TOOL_APPROVAL_CONNECTOR_NAME_KEY.to_string(), - JsonValue::String(connector_name.clone()), - ); - } - if let Some(connector_description) = connector_description.as_ref() { - meta.insert( - MCP_TOOL_APPROVAL_CONNECTOR_DESCRIPTION_KEY.to_string(), - JsonValue::String(connector_description.clone()), - ); - } - } - if let Some(tool_params) = tool_params { - meta.insert( - MCP_TOOL_APPROVAL_TOOL_PARAMS_KEY.to_string(), - tool_params.clone(), - ); - } - if let Some(tool_params_display) = tool_params_display - && let Ok(tool_params_display) = serde_json::to_value(tool_params_display) - { - meta.insert( - MCP_TOOL_APPROVAL_TOOL_PARAMS_DISPLAY_KEY.to_string(), - tool_params_display, - ); - } - - (!meta.is_empty()).then_some(JsonValue::Object(meta)) -} - pub(crate) fn mcp_tool_approval_compat_response( approval_request: &GuardianApprovalRequest, question: &RequestUserInputQuestion, @@ -1143,96 +1036,6 @@ pub(crate) fn mcp_tool_approval_compat_response( }) } -fn build_mcp_tool_approval_question( - question_id: String, - server: &str, - tool_name: &str, - connector_name: Option<&str>, - prompt_options: McpToolApprovalPromptOptions, - question_override: Option<&str>, -) -> RequestUserInputQuestion { - let question = question_override - .map(ToString::to_string) - .unwrap_or_else(|| { - build_mcp_tool_approval_fallback_message(server, tool_name, connector_name) - }); - let question = format!("{}?", question.trim_end_matches('?')); - - let mut options = vec![RequestUserInputQuestionOption { - label: MCP_TOOL_APPROVAL_ACCEPT.to_string(), - description: "Run the tool and continue.".to_string(), - }]; - if prompt_options.allow_session_remember { - options.push(RequestUserInputQuestionOption { - label: MCP_TOOL_APPROVAL_ACCEPT_FOR_SESSION.to_string(), - description: "Run the tool and remember this choice for this session.".to_string(), - }); - } - if prompt_options.allow_persistent_approval { - options.push(RequestUserInputQuestionOption { - label: MCP_TOOL_APPROVAL_ACCEPT_AND_REMEMBER.to_string(), - description: "Run the tool and remember this choice for future tool calls.".to_string(), - }); - } - options.push(RequestUserInputQuestionOption { - label: MCP_TOOL_APPROVAL_CANCEL.to_string(), - description: "Cancel this tool call.".to_string(), - }); - - RequestUserInputQuestion { - id: question_id, - header: "Approve app tool call?".to_string(), - question, - is_other: false, - is_secret: false, - options: Some(options), - } -} - -fn build_mcp_tool_approval_fallback_message( - server: &str, - tool_name: &str, - connector_name: Option<&str>, -) -> String { - let actor = connector_name - .map(str::trim) - .filter(|name| !name.is_empty()) - .map(ToString::to_string) - .unwrap_or_else(|| { - if server == "codex_apps" { - "this app".to_string() - } else { - format!("the {server} MCP server") - } - }); - format!("Allow {actor} to run tool \"{tool_name}\"?") -} - -fn mcp_tool_approval_question_text(question: String, monitor_reason: Option<&str>) -> String { - match monitor_reason.map(str::trim) { - Some(reason) if !reason.is_empty() => { - format!("Tool call needs your approval. Reason: {reason}") - } - _ => question, - } -} - -fn build_mcp_tool_approval_display_params( - tool_params: Option<&JsonValue>, -) -> Option> { - let tool_params = tool_params?.as_object()?; - let mut display_params = tool_params - .iter() - .map(|(name, value)| RenderedMcpToolApprovalParam { - name: name.clone(), - value: value.clone(), - display_name: name.clone(), - }) - .collect::>(); - display_params.sort_by(|left, right| left.name.cmp(&right.name)); - Some(display_params) -} - fn mcp_tool_approval_prompt_options( session_approval_key: Option<&McpToolApprovalKey>, persistent_approval_key: Option<&McpToolApprovalKey>, @@ -1707,6 +1510,203 @@ fn build_mcp_tool_approval_elicitation_request( } } +fn mcp_tool_approval_elicitation_meta( + approval_request: &GuardianApprovalRequest, + tool_params: Option<&JsonValue>, + tool_params_display: Option<&[RenderedMcpToolApprovalParam]>, + prompt_options: McpToolApprovalPromptOptions, +) -> Option { + let GuardianApprovalRequest::McpToolCall { + server, + connector_id, + connector_name, + connector_description, + tool_title, + tool_description, + .. + } = approval_request + else { + return None; + }; + + let mut meta = serde_json::Map::new(); + meta.insert( + MCP_TOOL_APPROVAL_KIND_KEY.to_string(), + JsonValue::String(MCP_TOOL_APPROVAL_KIND_MCP_TOOL_CALL.to_string()), + ); + match ( + prompt_options.allow_session_remember, + prompt_options.allow_persistent_approval, + ) { + (true, true) => { + meta.insert( + MCP_TOOL_APPROVAL_PERSIST_KEY.to_string(), + serde_json::json!([ + MCP_TOOL_APPROVAL_PERSIST_SESSION, + MCP_TOOL_APPROVAL_PERSIST_ALWAYS, + ]), + ); + } + (true, false) => { + meta.insert( + MCP_TOOL_APPROVAL_PERSIST_KEY.to_string(), + JsonValue::String(MCP_TOOL_APPROVAL_PERSIST_SESSION.to_string()), + ); + } + (false, true) => { + meta.insert( + MCP_TOOL_APPROVAL_PERSIST_KEY.to_string(), + JsonValue::String(MCP_TOOL_APPROVAL_PERSIST_ALWAYS.to_string()), + ); + } + (false, false) => {} + } + if let Some(tool_title) = tool_title.as_ref() { + meta.insert( + MCP_TOOL_APPROVAL_TOOL_TITLE_KEY.to_string(), + JsonValue::String(tool_title.clone()), + ); + } + if let Some(tool_description) = tool_description.as_ref() { + meta.insert( + MCP_TOOL_APPROVAL_TOOL_DESCRIPTION_KEY.to_string(), + JsonValue::String(tool_description.clone()), + ); + } + if server == CODEX_APPS_MCP_SERVER_NAME + && (connector_id.is_some() || connector_name.is_some() || connector_description.is_some()) + { + meta.insert( + MCP_TOOL_APPROVAL_SOURCE_KEY.to_string(), + JsonValue::String(MCP_TOOL_APPROVAL_SOURCE_CONNECTOR.to_string()), + ); + if let Some(connector_id) = connector_id.as_deref() { + meta.insert( + MCP_TOOL_APPROVAL_CONNECTOR_ID_KEY.to_string(), + JsonValue::String(connector_id.to_string()), + ); + } + if let Some(connector_name) = connector_name.as_ref() { + meta.insert( + MCP_TOOL_APPROVAL_CONNECTOR_NAME_KEY.to_string(), + JsonValue::String(connector_name.clone()), + ); + } + if let Some(connector_description) = connector_description.as_ref() { + meta.insert( + MCP_TOOL_APPROVAL_CONNECTOR_DESCRIPTION_KEY.to_string(), + JsonValue::String(connector_description.clone()), + ); + } + } + if let Some(tool_params) = tool_params { + meta.insert( + MCP_TOOL_APPROVAL_TOOL_PARAMS_KEY.to_string(), + tool_params.clone(), + ); + } + if let Some(tool_params_display) = tool_params_display + && let Ok(tool_params_display) = serde_json::to_value(tool_params_display) + { + meta.insert( + MCP_TOOL_APPROVAL_TOOL_PARAMS_DISPLAY_KEY.to_string(), + tool_params_display, + ); + } + + (!meta.is_empty()).then_some(JsonValue::Object(meta)) +} + +fn build_mcp_tool_approval_question( + question_id: String, + server: &str, + tool_name: &str, + connector_name: Option<&str>, + prompt_options: McpToolApprovalPromptOptions, + question_override: Option<&str>, +) -> RequestUserInputQuestion { + let question = question_override + .map(ToString::to_string) + .unwrap_or_else(|| { + build_mcp_tool_approval_fallback_message(server, tool_name, connector_name) + }); + let question = format!("{}?", question.trim_end_matches('?')); + + let mut options = vec![RequestUserInputQuestionOption { + label: MCP_TOOL_APPROVAL_ACCEPT.to_string(), + description: "Run the tool and continue.".to_string(), + }]; + if prompt_options.allow_session_remember { + options.push(RequestUserInputQuestionOption { + label: MCP_TOOL_APPROVAL_ACCEPT_FOR_SESSION.to_string(), + description: "Run the tool and remember this choice for this session.".to_string(), + }); + } + if prompt_options.allow_persistent_approval { + options.push(RequestUserInputQuestionOption { + label: MCP_TOOL_APPROVAL_ACCEPT_AND_REMEMBER.to_string(), + description: "Run the tool and remember this choice for future tool calls.".to_string(), + }); + } + options.push(RequestUserInputQuestionOption { + label: MCP_TOOL_APPROVAL_CANCEL.to_string(), + description: "Cancel this tool call.".to_string(), + }); + + RequestUserInputQuestion { + id: question_id, + header: "Approve app tool call?".to_string(), + question, + is_other: false, + is_secret: false, + options: Some(options), + } +} + +fn build_mcp_tool_approval_fallback_message( + server: &str, + tool_name: &str, + connector_name: Option<&str>, +) -> String { + let actor = connector_name + .map(str::trim) + .filter(|name| !name.is_empty()) + .map(ToString::to_string) + .unwrap_or_else(|| { + if server == CODEX_APPS_MCP_SERVER_NAME { + "this app".to_string() + } else { + format!("the {server} MCP server") + } + }); + format!("Allow {actor} to run tool \"{tool_name}\"?") +} + +fn mcp_tool_approval_question_text(question: String, monitor_reason: Option<&str>) -> String { + match monitor_reason.map(str::trim) { + Some(reason) if !reason.is_empty() => { + format!("Tool call needs your approval. Reason: {reason}") + } + _ => question, + } +} + +fn build_mcp_tool_approval_display_params( + tool_params: Option<&JsonValue>, +) -> Option> { + let tool_params = tool_params?.as_object()?; + let mut display_params = tool_params + .iter() + .map(|(name, value)| RenderedMcpToolApprovalParam { + name: name.clone(), + value: value.clone(), + display_name: name.clone(), + }) + .collect::>(); + display_params.sort_by(|left, right| left.name.cmp(&right.name)); + Some(display_params) +} + fn parse_mcp_tool_approval_elicitation_response( response: Option, question_id: &str, From 27c2bdc3e703baa46a8c87f4caeeb1855c4a3c95 Mon Sep 17 00:00:00 2001 From: Abhinav Vedmala Date: Sat, 2 May 2026 11:08:34 -0700 Subject: [PATCH 09/12] restore mcp approval helper ordering --- codex-rs/core/src/mcp_tool_call.rs | 148 ++++++++++++++--------------- 1 file changed, 74 insertions(+), 74 deletions(-) diff --git a/codex-rs/core/src/mcp_tool_call.rs b/codex-rs/core/src/mcp_tool_call.rs index a49297e0cc..9f1421627b 100644 --- a/codex-rs/core/src/mcp_tool_call.rs +++ b/codex-rs/core/src/mcp_tool_call.rs @@ -1469,6 +1469,80 @@ async fn lookup_mcp_app_usage_metadata( }) } +fn build_mcp_tool_approval_question( + question_id: String, + server: &str, + tool_name: &str, + connector_name: Option<&str>, + prompt_options: McpToolApprovalPromptOptions, + question_override: Option<&str>, +) -> RequestUserInputQuestion { + let question = question_override + .map(ToString::to_string) + .unwrap_or_else(|| { + build_mcp_tool_approval_fallback_message(server, tool_name, connector_name) + }); + let question = format!("{}?", question.trim_end_matches('?')); + + let mut options = vec![RequestUserInputQuestionOption { + label: MCP_TOOL_APPROVAL_ACCEPT.to_string(), + description: "Run the tool and continue.".to_string(), + }]; + if prompt_options.allow_session_remember { + options.push(RequestUserInputQuestionOption { + label: MCP_TOOL_APPROVAL_ACCEPT_FOR_SESSION.to_string(), + description: "Run the tool and remember this choice for this session.".to_string(), + }); + } + if prompt_options.allow_persistent_approval { + options.push(RequestUserInputQuestionOption { + label: MCP_TOOL_APPROVAL_ACCEPT_AND_REMEMBER.to_string(), + description: "Run the tool and remember this choice for future tool calls.".to_string(), + }); + } + options.push(RequestUserInputQuestionOption { + label: MCP_TOOL_APPROVAL_CANCEL.to_string(), + description: "Cancel this tool call.".to_string(), + }); + + RequestUserInputQuestion { + id: question_id, + header: "Approve app tool call?".to_string(), + question, + is_other: false, + is_secret: false, + options: Some(options), + } +} + +fn build_mcp_tool_approval_fallback_message( + server: &str, + tool_name: &str, + connector_name: Option<&str>, +) -> String { + let actor = connector_name + .map(str::trim) + .filter(|name| !name.is_empty()) + .map(ToString::to_string) + .unwrap_or_else(|| { + if server == CODEX_APPS_MCP_SERVER_NAME { + "this app".to_string() + } else { + format!("the {server} MCP server") + } + }); + format!("Allow {actor} to run tool \"{tool_name}\"?") +} + +fn mcp_tool_approval_question_text(question: String, monitor_reason: Option<&str>) -> String { + match monitor_reason.map(str::trim) { + Some(reason) if !reason.is_empty() => { + format!("Tool call needs your approval. Reason: {reason}") + } + _ => question, + } +} + fn arc_monitor_interrupt_message(reason: &str) -> String { let reason = reason.trim(); if reason.is_empty() { @@ -1617,80 +1691,6 @@ fn mcp_tool_approval_elicitation_meta( (!meta.is_empty()).then_some(JsonValue::Object(meta)) } -fn build_mcp_tool_approval_question( - question_id: String, - server: &str, - tool_name: &str, - connector_name: Option<&str>, - prompt_options: McpToolApprovalPromptOptions, - question_override: Option<&str>, -) -> RequestUserInputQuestion { - let question = question_override - .map(ToString::to_string) - .unwrap_or_else(|| { - build_mcp_tool_approval_fallback_message(server, tool_name, connector_name) - }); - let question = format!("{}?", question.trim_end_matches('?')); - - let mut options = vec![RequestUserInputQuestionOption { - label: MCP_TOOL_APPROVAL_ACCEPT.to_string(), - description: "Run the tool and continue.".to_string(), - }]; - if prompt_options.allow_session_remember { - options.push(RequestUserInputQuestionOption { - label: MCP_TOOL_APPROVAL_ACCEPT_FOR_SESSION.to_string(), - description: "Run the tool and remember this choice for this session.".to_string(), - }); - } - if prompt_options.allow_persistent_approval { - options.push(RequestUserInputQuestionOption { - label: MCP_TOOL_APPROVAL_ACCEPT_AND_REMEMBER.to_string(), - description: "Run the tool and remember this choice for future tool calls.".to_string(), - }); - } - options.push(RequestUserInputQuestionOption { - label: MCP_TOOL_APPROVAL_CANCEL.to_string(), - description: "Cancel this tool call.".to_string(), - }); - - RequestUserInputQuestion { - id: question_id, - header: "Approve app tool call?".to_string(), - question, - is_other: false, - is_secret: false, - options: Some(options), - } -} - -fn build_mcp_tool_approval_fallback_message( - server: &str, - tool_name: &str, - connector_name: Option<&str>, -) -> String { - let actor = connector_name - .map(str::trim) - .filter(|name| !name.is_empty()) - .map(ToString::to_string) - .unwrap_or_else(|| { - if server == CODEX_APPS_MCP_SERVER_NAME { - "this app".to_string() - } else { - format!("the {server} MCP server") - } - }); - format!("Allow {actor} to run tool \"{tool_name}\"?") -} - -fn mcp_tool_approval_question_text(question: String, monitor_reason: Option<&str>) -> String { - match monitor_reason.map(str::trim) { - Some(reason) if !reason.is_empty() => { - format!("Tool call needs your approval. Reason: {reason}") - } - _ => question, - } -} - fn build_mcp_tool_approval_display_params( tool_params: Option<&JsonValue>, ) -> Option> { From 11655ee6b32aed224343795b8f5756e497edbde7 Mon Sep 17 00:00:00 2001 From: Abhinav Vedmala Date: Sat, 2 May 2026 11:18:55 -0700 Subject: [PATCH 10/12] restore mcp approval constant ordering --- codex-rs/core/src/mcp_tool_call.rs | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/codex-rs/core/src/mcp_tool_call.rs b/codex-rs/core/src/mcp_tool_call.rs index 9f1421627b..d1afef307f 100644 --- a/codex-rs/core/src/mcp_tool_call.rs +++ b/codex-rs/core/src/mcp_tool_call.rs @@ -899,16 +899,16 @@ struct McpToolApprovalPrompt { tool_params_display: Option>, } -const MCP_TOOL_APPROVAL_ACCEPT: &str = "Allow"; -const MCP_TOOL_APPROVAL_ACCEPT_FOR_SESSION: &str = "Allow for this session"; -const MCP_TOOL_APPROVAL_ACCEPT_AND_REMEMBER: &str = "Allow and don't ask me again"; -const MCP_TOOL_APPROVAL_CANCEL: &str = "Cancel"; +pub(crate) const MCP_TOOL_APPROVAL_QUESTION_ID_PREFIX: &str = "mcp_tool_call_approval"; +pub(crate) const MCP_TOOL_APPROVAL_ACCEPT: &str = "Allow"; +pub(crate) const MCP_TOOL_APPROVAL_ACCEPT_FOR_SESSION: &str = "Allow for this session"; // Internal-only token used when guardian auto-reviews delegated MCP approvals on the // RequestUserInput compatibility path. That legacy MCP prompt has allow/cancel labels but no // real "Decline" answer, so this lets guardian denials round-trip distinctly from user cancel. // This is not a user-facing option. pub(crate) const MCP_TOOL_APPROVAL_DECLINE_SYNTHETIC: &str = "__codex_mcp_decline__"; -const MCP_TOOL_APPROVAL_QUESTION_ID_PREFIX: &str = "mcp_tool_call_approval"; +const MCP_TOOL_APPROVAL_ACCEPT_AND_REMEMBER: &str = "Allow and don't ask me again"; +const MCP_TOOL_APPROVAL_CANCEL: &str = "Cancel"; const MCP_TOOL_APPROVAL_KIND_KEY: &str = "codex_approval_kind"; const MCP_TOOL_APPROVAL_KIND_MCP_TOOL_CALL: &str = "mcp_tool_call"; const MCP_TOOL_APPROVAL_PERSIST_KEY: &str = "persist"; From c30a4d2756c3370d7822f6d4dbd757e0042c3966 Mon Sep 17 00:00:00 2001 From: Abhinav Vedmala Date: Sat, 2 May 2026 11:21:15 -0700 Subject: [PATCH 11/12] restore elicitation meta helper name --- codex-rs/core/src/mcp_tool_call.rs | 4 ++-- codex-rs/core/src/mcp_tool_call_tests.rs | 8 ++++---- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/codex-rs/core/src/mcp_tool_call.rs b/codex-rs/core/src/mcp_tool_call.rs index d1afef307f..fd9ad4f7dd 100644 --- a/codex-rs/core/src/mcp_tool_call.rs +++ b/codex-rs/core/src/mcp_tool_call.rs @@ -1567,7 +1567,7 @@ fn build_mcp_tool_approval_elicitation_request( turn_id: Some(turn_context.sub_id.clone()), server_name: request.server.to_string(), request: McpServerElicitationRequest::Form { - meta: mcp_tool_approval_elicitation_meta( + meta: build_mcp_tool_approval_elicitation_meta( request.approval_request, request.tool_params, request.tool_params_display, @@ -1584,7 +1584,7 @@ fn build_mcp_tool_approval_elicitation_request( } } -fn mcp_tool_approval_elicitation_meta( +fn build_mcp_tool_approval_elicitation_meta( approval_request: &GuardianApprovalRequest, tool_params: Option<&JsonValue>, tool_params_display: Option<&[RenderedMcpToolApprovalParam]>, diff --git a/codex-rs/core/src/mcp_tool_call_tests.rs b/codex-rs/core/src/mcp_tool_call_tests.rs index 446edb4a5a..f45ea6c38c 100644 --- a/codex-rs/core/src/mcp_tool_call_tests.rs +++ b/codex-rs/core/src/mcp_tool_call_tests.rs @@ -1236,7 +1236,7 @@ fn approval_elicitation_meta_marks_tool_approvals() { /*metadata*/ None, ); assert_eq!( - mcp_tool_approval_elicitation_meta( + build_mcp_tool_approval_elicitation_meta( &request, /*tool_params*/ None, /*tool_params_display*/ None, @@ -1266,7 +1266,7 @@ fn approval_elicitation_meta_merges_session_and_always_persist_for_custom_server Some(&metadata), ); assert_eq!( - mcp_tool_approval_elicitation_meta( + build_mcp_tool_approval_elicitation_meta( &request, Some(&serde_json::json!({"id": 1})), /*tool_params_display*/ None, @@ -1490,7 +1490,7 @@ fn approval_elicitation_meta_includes_connector_source_for_codex_apps() { Some(&metadata), ); assert_eq!( - mcp_tool_approval_elicitation_meta( + build_mcp_tool_approval_elicitation_meta( &request, Some(&serde_json::json!({ "calendar_id": "primary", @@ -1533,7 +1533,7 @@ fn approval_elicitation_meta_merges_session_and_always_persist_with_connector_so Some(&metadata), ); assert_eq!( - mcp_tool_approval_elicitation_meta( + build_mcp_tool_approval_elicitation_meta( &request, Some(&serde_json::json!({ "calendar_id": "primary", From dbff525377e7e41f092493604e537cf3550fe0fc Mon Sep 17 00:00:00 2001 From: Abhinav Vedmala Date: Sat, 2 May 2026 11:22:28 -0700 Subject: [PATCH 12/12] document mcp approval prompt helpers --- codex-rs/core/src/mcp_tool_call.rs | 3 +++ 1 file changed, 3 insertions(+) diff --git a/codex-rs/core/src/mcp_tool_call.rs b/codex-rs/core/src/mcp_tool_call.rs index fd9ad4f7dd..1b1ddbf1ea 100644 --- a/codex-rs/core/src/mcp_tool_call.rs +++ b/codex-rs/core/src/mcp_tool_call.rs @@ -940,6 +940,7 @@ struct McpToolApprovalKey { tool_name: String, } +/// Builds the user-facing MCP approval prompt from the canonical approval request. fn mcp_tool_approval_prompt( approval_request: &GuardianApprovalRequest, question_id: String, @@ -998,6 +999,8 @@ fn mcp_tool_approval_prompt( }) } +/// Converts a guardian MCP approval decision into the legacy RequestUserInput +/// response shape used by delegated compatibility flows. pub(crate) fn mcp_tool_approval_compat_response( approval_request: &GuardianApprovalRequest, question: &RequestUserInputQuestion,