From 4b0e2a0bffcc9ca4781dd38e27032591d25e8996 Mon Sep 17 00:00:00 2001 From: mchen-oai Date: Mon, 10 Aug 2026 18:01:20 +0000 Subject: [PATCH] Support MCP form input in full-access user threads (#37864) ## Why Standard MCP forms can require user-entered values even when tool permissions are otherwise auto-approved in full-access sessions. ## What changed - Recognize the `openai/standard-form-input` client extension and surface non-approval forms in full-access, user-initiated root threads. - Keep approval forms, automation and subagent threads, headless sessions, and clients without the capability on their existing decline or review paths. - Treat the capability as client-only so it is not advertised to MCP servers, and enable it after session startup so required servers cannot block startup waiting for form input. ## Testing Add unit and app-server coverage for accepted form round trips, declined cases, approval metadata safeguards, resumed threads, and extension filtering. GitOrigin-RevId: 053bfe397a5c79eceef90a81d13e2aca6353af43 --- codex-rs/app-server/README.md | 4 + codex-rs/app-server/tests/common/lib.rs | 1 + codex-rs/app-server/tests/common/rollout.rs | 30 +- .../tests/suite/v2/mcp_server_elicitation.rs | 119 ++++-- .../app-server/tests/suite/v2/mcp_tool.rs | 286 +++++++++++++- codex-rs/codex-mcp/src/client_capabilities.rs | 5 +- .../src/client_capabilities_tests.rs | 8 + .../codex-mcp/src/connection_manager_tests.rs | 362 ++++++++++++++++++ codex-rs/codex-mcp/src/elicitation.rs | 79 +++- codex-rs/codex-mcp/src/runtime.rs | 4 + codex-rs/core/src/session/mcp_runtime.rs | 2 +- codex-rs/core/src/thread_manager.rs | 14 +- codex-rs/protocol/src/mcp.rs | 49 +++ codex-rs/protocol/src/mcp_approval_meta.rs | 3 + 14 files changed, 895 insertions(+), 71 deletions(-) diff --git a/codex-rs/app-server/README.md b/codex-rs/app-server/README.md index 1e06484675..8025227c08 100644 --- a/codex-rs/app-server/README.md +++ b/codex-rs/app-server/README.md @@ -93,11 +93,15 @@ extended forms, clients must handle the request envelope, including a fallback for unsupported field types. `mcpServerOpenaiFormElicitation: true` remains a legacy alias for declaring the `openai/form` extension. +`openai/standard-form-input` indicates support for collecting and returning +input from standard MCP forms. + ```json { "capabilities": { "extensions": { "openai/form": {}, + "openai/standard-form-input": {}, "io.modelcontextprotocol/ui": { "mimeTypes": ["text/html;profile=mcp-app"] } diff --git a/codex-rs/app-server/tests/common/lib.rs b/codex-rs/app-server/tests/common/lib.rs index 1cb946128c..ad6d99ae5c 100644 --- a/codex-rs/app-server/tests/common/lib.rs +++ b/codex-rs/app-server/tests/common/lib.rs @@ -45,6 +45,7 @@ pub use responses::create_shell_command_sse_response; pub use rollout::create_fake_paginated_rollout; pub use rollout::create_fake_parented_rollout_with_source; pub use rollout::create_fake_rollout; +pub use rollout::create_fake_rollout_with_session_and_thread_source; pub use rollout::create_fake_rollout_with_source; pub use rollout::create_fake_rollout_with_text_elements; pub use rollout::create_fake_rollout_with_token_usage; diff --git a/codex-rs/app-server/tests/common/rollout.rs b/codex-rs/app-server/tests/common/rollout.rs index d254d6ac84..9aebb3f870 100644 --- a/codex-rs/app-server/tests/common/rollout.rs +++ b/codex-rs/app-server/tests/common/rollout.rs @@ -7,6 +7,7 @@ use codex_protocol::protocol::SessionMeta; use codex_protocol::protocol::SessionMetaLine; use codex_protocol::protocol::SessionSource; use codex_protocol::protocol::ThreadHistoryMode; +use codex_protocol::protocol::ThreadSource; use codex_protocol::protocol::TokenCountEvent; use codex_protocol::protocol::TokenUsage; use codex_protocol::protocol::TokenUsageInfo; @@ -160,6 +161,30 @@ pub fn create_fake_rollout_with_source( model_provider: Option<&str>, git_info: Option, source: SessionSource, +) -> Result { + create_fake_rollout_with_session_and_thread_source( + codex_home, + filename_ts, + meta_rfc3339, + preview, + model_provider, + git_info, + source, + /*thread_source*/ None, + ) +} + +/// Create a minimal rollout file with explicit session and thread sources. +#[allow(clippy::too_many_arguments)] +pub fn create_fake_rollout_with_session_and_thread_source( + codex_home: &Path, + filename_ts: &str, + meta_rfc3339: &str, + preview: &str, + model_provider: Option<&str>, + git_info: Option, + source: SessionSource, + thread_source: Option, ) -> Result { create_fake_rollout_with_source_and_parent_thread_id( codex_home, @@ -169,6 +194,7 @@ pub fn create_fake_rollout_with_source( model_provider, git_info, source, + thread_source, /*session_id*/ None, /*parent_thread_id*/ None, ) @@ -195,6 +221,7 @@ pub fn create_fake_parented_rollout_with_source( model_provider, git_info, source, + /*thread_source*/ None, Some(session_id), Some(parent_thread_id), ) @@ -209,6 +236,7 @@ fn create_fake_rollout_with_source_and_parent_thread_id( model_provider: Option<&str>, git_info: Option, source: SessionSource, + thread_source: Option, session_id: Option, parent_thread_id: Option, ) -> Result { @@ -234,7 +262,7 @@ fn create_fake_rollout_with_source_and_parent_thread_id( originator: "codex".to_string(), cli_version: "0.0.0".to_string(), source, - thread_source: None, + thread_source, agent_path: None, agent_nickname: None, agent_role: None, diff --git a/codex-rs/app-server/tests/suite/v2/mcp_server_elicitation.rs b/codex-rs/app-server/tests/suite/v2/mcp_server_elicitation.rs index e14fd225c2..8dfefccc11 100644 --- a/codex-rs/app-server/tests/suite/v2/mcp_server_elicitation.rs +++ b/codex-rs/app-server/tests/suite/v2/mcp_server_elicitation.rs @@ -41,6 +41,7 @@ use codex_app_server_protocol::TurnStatus; use codex_app_server_protocol::UserInput as V2UserInput; use codex_config::types::AuthCredentialsStoreMode; use codex_mcp::MCP_TOOL_CODEX_APPS_META_KEY; +use codex_protocol::mcp::OPENAI_STANDARD_FORM_INPUT_EXTENSION_ID; use codex_protocol::mcp_approval_meta as approval_meta; use core_test_support::assert_regex_match; use core_test_support::responses; @@ -158,7 +159,29 @@ impl StrictReviewScenario { #[tokio::test(flavor = "multi_thread", worker_threads = 4)] async fn mcp_server_form_elicitation_round_trip() -> Result<()> { - let mut fixture = ElicitationRoundTripFixture::start(ElicitationScenario::StandardForm).await?; + let fixture = ElicitationRoundTripFixture::start(ElicitationScenario::StandardForm).await?; + assert_standard_form_elicitation_round_trip(fixture).await +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn mcp_server_form_elicitation_round_trip_in_full_access() -> Result<()> { + let fixture = ElicitationRoundTripFixture::start_with_thread_params( + ElicitationScenario::StandardForm, + ThreadStartParams { + model: Some("mock-model".to_string()), + approval_policy: Some(AskForApproval::Never), + sandbox: Some(SandboxMode::DangerFullAccess), + thread_source: Some(codex_app_server_protocol::ThreadSource::User), + ..Default::default() + }, + ) + .await?; + assert_standard_form_elicitation_round_trip(fixture).await +} + +async fn assert_standard_form_elicitation_round_trip( + mut fixture: ElicitationRoundTripFixture, +) -> Result<()> { let (request_id, params) = fixture.read_elicitation().await?; let requested_schema: McpElicitationSchema = serde_json::from_value(serde_json::to_value( ElicitationSchema::builder() @@ -559,6 +582,58 @@ struct ElicitationRoundTripFixture { impl ElicitationRoundTripFixture { async fn start(scenario: ElicitationScenario) -> Result { + let strict = if let ElicitationScenario::Strict(strict) = scenario { + Some(strict) + } else { + None + }; + Self::start_with_thread_params( + scenario, + ThreadStartParams { + model: Some("mock-model".to_string()), + approval_policy: strict.map(|strict| match strict { + Review::Never | Review::FullAccess => AskForApproval::Never, + _ => AskForApproval::OnRequest, + }), + approvals_reviewer: strict + .filter(|strict| *strict == Review::ApproveForMe) + .map(|_| ApprovalsReviewer::AutoReview), + sandbox: strict + .filter(|strict| *strict == Review::FullAccess) + .map(|_| SandboxMode::DangerFullAccess), + config: strict.map(|strict| { + let mut config = HashMap::from([( + "features.guardian_approval".to_string(), + json!(strict != Review::GuardianDisabled), + )]); + if matches!( + strict, + Review::AppReviewerUser + | Review::AppReviewerNoncanonicalId + | Review::AppReviewerSpoofedId + ) { + config.insert( + format!("apps.{CONNECTOR_ID}.approvals_reviewer"), + json!("user"), + ); + } else if strict == Review::AppDefaultReviewerUser { + config.insert( + "apps._default.approvals_reviewer".to_string(), + json!("user"), + ); + } + config + }), + ..Default::default() + }, + ) + .await + } + + async fn start_with_thread_params( + scenario: ElicitationScenario, + thread_params: ThreadStartParams, + ) -> Result { let (responses_server, response_mock, apps_server_url, apps_server_handle) = start_elicitation_services(scenario).await?; let codex_home = TempDir::new()?; @@ -600,6 +675,10 @@ impl ElicitationRoundTripFixture { Some(InitializeCapabilities { experimental_api: true, mcp_server_openai_form_elicitation: true, + extensions: Some(HashMap::from([( + OPENAI_STANDARD_FORM_INPUT_EXTENSION_ID.to_string(), + json!({}), + )])), ..Default::default() }), ), @@ -607,43 +686,7 @@ impl ElicitationRoundTripFixture { .await??; let thread_start_id = mcp - .send_thread_start_request_with_auto_env(ThreadStartParams { - model: Some("mock-model".to_string()), - approval_policy: strict.map(|strict| match strict { - Review::Never | Review::FullAccess => AskForApproval::Never, - _ => AskForApproval::OnRequest, - }), - approvals_reviewer: strict - .filter(|strict| *strict == Review::ApproveForMe) - .map(|_| ApprovalsReviewer::AutoReview), - sandbox: strict - .filter(|strict| *strict == Review::FullAccess) - .map(|_| SandboxMode::DangerFullAccess), - config: strict.map(|strict| { - let mut config = HashMap::from([( - "features.guardian_approval".to_string(), - json!(strict != Review::GuardianDisabled), - )]); - if matches!( - strict, - Review::AppReviewerUser - | Review::AppReviewerNoncanonicalId - | Review::AppReviewerSpoofedId - ) { - config.insert( - format!("apps.{CONNECTOR_ID}.approvals_reviewer"), - json!("user"), - ); - } else if strict == Review::AppDefaultReviewerUser { - config.insert( - "apps._default.approvals_reviewer".to_string(), - json!("user"), - ); - } - config - }), - ..Default::default() - }) + .send_thread_start_request_with_auto_env(thread_params) .await?; let thread_start_resp: JSONRPCResponse = timeout( DEFAULT_READ_TIMEOUT, diff --git a/codex-rs/app-server/tests/suite/v2/mcp_tool.rs b/codex-rs/app-server/tests/suite/v2/mcp_tool.rs index 6ac1272697..2e40008067 100644 --- a/codex-rs/app-server/tests/suite/v2/mcp_tool.rs +++ b/codex-rs/app-server/tests/suite/v2/mcp_tool.rs @@ -1,10 +1,13 @@ use std::borrow::Cow; +use std::collections::HashMap; +use std::path::Path; use std::sync::Arc; use std::time::Duration; use anyhow::Result; use app_test_support::MockResponsesConfig; use app_test_support::TestAppServer; +use app_test_support::create_fake_rollout_with_session_and_thread_source; use app_test_support::create_final_assistant_message_sse_response; use app_test_support::create_mock_responses_server_sequence; use axum::Router; @@ -38,6 +41,9 @@ use codex_app_server_protocol::TurnStartParams; use codex_app_server_protocol::TurnStartResponse; use codex_app_server_protocol::UserInput as V2UserInput; use codex_features::Feature; +use codex_protocol::mcp::OPENAI_STANDARD_FORM_INPUT_EXTENSION_ID; +use codex_protocol::protocol::SessionSource as CoreSessionSource; +use codex_protocol::protocol::ThreadSource as CoreThreadSource; use codex_utils_path_uri::PathUri; use codex_utils_pty::DEFAULT_OUTPUT_BYTES_CAP; use core_test_support::responses; @@ -157,7 +163,7 @@ async fn mcp_server_tool_call_returns_tool_result() -> Result<()> { } #[tokio::test(flavor = "multi_thread", worker_threads = 2)] -async fn mcp_server_tool_call_uses_session_client_extensions() -> Result<()> { +async fn mcp_server_tool_call_forwards_only_server_extensions() -> Result<()> { let responses_server = responses::start_mock_server().await; let (mcp_server_url, mcp_server_handle) = start_mcp_server().await?; let codex_home = TempDir::new()?; @@ -186,10 +192,13 @@ async fn mcp_server_tool_call_uses_session_client_extensions() -> Result<()> { request_attestation: false, mcp_server_openai_form_elicitation: true, opt_out_notification_methods: None, - extensions: Some(std::collections::HashMap::from([( - "io.modelcontextprotocol/ui".to_string(), - app_ui.clone(), - )])), + extensions: Some(HashMap::from([ + ("io.modelcontextprotocol/ui".to_string(), app_ui.clone()), + ( + OPENAI_STANDARD_FORM_INPUT_EXTENSION_ID.to_string(), + json!({}), + ), + ])), }), ) .await?; @@ -371,23 +380,247 @@ async fn mcp_server_tool_call_returns_error_for_unknown_thread() -> Result<()> { #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn mcp_server_tool_call_round_trips_elicitation() -> Result<()> { + mcp_server_tool_call_round_trips_elicitation_for_thread(ElicitationThread::Start { + params: ThreadStartParams { + model: Some("mock-model".to_string()), + approval_policy: Some(codex_app_server_protocol::AskForApproval::UnlessTrusted), + ..Default::default() + }, + session_source: "vscode", + client_advertises_standard_form_input: false, + }) + .await +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn mcp_server_tool_call_round_trips_user_input_in_full_access_for_user_thread_with_form_input_capability() +-> Result<()> { + mcp_server_tool_call_round_trips_elicitation_for_thread(ElicitationThread::Start { + params: ThreadStartParams { + model: Some("mock-model".to_string()), + approval_policy: Some(codex_app_server_protocol::AskForApproval::Never), + sandbox: Some(codex_app_server_protocol::SandboxMode::DangerFullAccess), + thread_source: Some(codex_app_server_protocol::ThreadSource::User), + ..Default::default() + }, + session_source: "vscode", + client_advertises_standard_form_input: true, + }) + .await +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn mcp_server_tool_call_round_trips_user_input_for_custom_frontend_user_thread_with_form_input_capability() +-> Result<()> { + mcp_server_tool_call_round_trips_elicitation_for_thread(ElicitationThread::Start { + params: ThreadStartParams { + model: Some("mock-model".to_string()), + approval_policy: Some(codex_app_server_protocol::AskForApproval::Never), + sandbox: Some(codex_app_server_protocol::SandboxMode::DangerFullAccess), + thread_source: Some(codex_app_server_protocol::ThreadSource::User), + ..Default::default() + }, + session_source: "chatgpt", + client_advertises_standard_form_input: true, + }) + .await +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn mcp_server_tool_call_uses_current_frontend_for_full_access_elicitation() -> Result<()> { + mcp_server_tool_call_round_trips_elicitation_for_thread(ElicitationThread::Resume { + source: CoreSessionSource::Exec, + params: ThreadResumeParams { + model: Some("mock-model".to_string()), + approval_policy: Some(codex_app_server_protocol::AskForApproval::Never), + sandbox: Some(codex_app_server_protocol::SandboxMode::DangerFullAccess), + ..Default::default() + }, + }) + .await +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn mcp_server_tool_call_declines_full_access_elicitation_without_form_input_capability() +-> Result<()> { + assert_full_access_form_elicitation_is_declined(FullAccessElicitationCase { + thread_source: Some(codex_app_server_protocol::ThreadSource::User), + client_advertises_standard_form_input: false, + }) + .await +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn mcp_server_tool_call_declines_full_access_elicitation_with_unspecified_thread_source() +-> Result<()> { + assert_full_access_form_elicitation_is_declined(FullAccessElicitationCase { + thread_source: None, + client_advertises_standard_form_input: true, + }) + .await +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn mcp_server_tool_call_declines_full_access_elicitation_for_automation_thread() -> Result<()> +{ + assert_full_access_form_elicitation_is_declined(FullAccessElicitationCase { + thread_source: Some(codex_app_server_protocol::ThreadSource::Feature( + "automation".to_string(), + )), + client_advertises_standard_form_input: true, + }) + .await +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn mcp_server_tool_call_declines_full_access_elicitation_for_subagent_thread() -> Result<()> { + assert_full_access_form_elicitation_is_declined(FullAccessElicitationCase { + thread_source: Some(codex_app_server_protocol::ThreadSource::Subagent), + client_advertises_standard_form_input: true, + }) + .await +} + +struct FullAccessElicitationCase { + thread_source: Option, + client_advertises_standard_form_input: bool, +} + +async fn assert_full_access_form_elicitation_is_declined( + case: FullAccessElicitationCase, +) -> Result<()> { let responses_server = responses::start_mock_server().await; let (mcp_server_url, mcp_server_handle) = start_mcp_server().await?; let codex_home = TempDir::new()?; mcp_tool_config(&responses_server.uri(), &mcp_server_url, AUTO_COMPACT_LIMIT) .write(codex_home.path())?; - let mut mcp = TestAppServer::builder() - .with_codex_home(codex_home.path()) - .build_initialized() - .await?; - let ThreadStartResponse { thread, .. } = mcp + let mut mcp = initialize_elicitation_app_server( + codex_home.path(), + "vscode", + case.client_advertises_standard_form_input, + ) + .await?; + let ThreadStartResponse { + thread, + approval_policy, + sandbox, + .. + } = mcp .start_thread(ThreadStartParams { model: Some("mock-model".to_string()), - approval_policy: Some(codex_app_server_protocol::AskForApproval::UnlessTrusted), + approval_policy: Some(codex_app_server_protocol::AskForApproval::Never), + sandbox: Some(codex_app_server_protocol::SandboxMode::DangerFullAccess), + thread_source: case.thread_source, ..Default::default() }) .await?; + assert_eq!( + approval_policy, + codex_app_server_protocol::AskForApproval::Never + ); + assert_eq!( + sandbox, + codex_app_server_protocol::SandboxPolicy::DangerFullAccess + ); + + let request_id = mcp + .send_mcp_server_tool_call_request(McpServerToolCallParams { + thread_id: thread.id, + server: TEST_SERVER_NAME.to_string(), + tool: TEST_TOOL_NAME.to_string(), + arguments: Some(json!({ + "message": ELICITATION_TRIGGER_MESSAGE, + })), + meta: None, + }) + .await?; + let response: McpServerToolCallResponse = + timeout(DEFAULT_READ_TIMEOUT, mcp.read_response(request_id)).await??; + assert_eq!( + response.content, + vec![json!({"type": "text", "text": "declined"})] + ); + + mcp_server_handle.abort(); + let _ = mcp_server_handle.await; + + Ok(()) +} + +enum ElicitationThread { + Start { + params: ThreadStartParams, + session_source: &'static str, + client_advertises_standard_form_input: bool, + }, + Resume { + source: CoreSessionSource, + params: ThreadResumeParams, + }, +} + +async fn mcp_server_tool_call_round_trips_elicitation_for_thread( + mut elicitation_thread: ElicitationThread, +) -> Result<()> { + let responses_server = responses::start_mock_server().await; + let (mcp_server_url, mcp_server_handle) = start_mcp_server().await?; + let codex_home = TempDir::new()?; + mcp_tool_config(&responses_server.uri(), &mcp_server_url, AUTO_COMPACT_LIMIT) + .write(codex_home.path())?; + + if let ElicitationThread::Resume { source, params } = &mut elicitation_thread { + params.thread_id = create_fake_rollout_with_session_and_thread_source( + codex_home.path(), + "2025-02-01T10-00-00", + "2025-02-01T10:00:00Z", + "Saved user message", + Some("mock_provider"), + /*git_info*/ None, + source.clone(), + Some(CoreThreadSource::User), + )?; + } + + let (session_source, client_advertises_standard_form_input) = match &elicitation_thread { + ElicitationThread::Start { + session_source, + client_advertises_standard_form_input, + .. + } => (*session_source, *client_advertises_standard_form_input), + ElicitationThread::Resume { .. } => ("vscode", true), + }; + let mut mcp = initialize_elicitation_app_server( + codex_home.path(), + session_source, + client_advertises_standard_form_input, + ) + .await?; + let thread = match elicitation_thread { + ElicitationThread::Start { params, .. } => mcp.start_thread(params).await?.thread, + ElicitationThread::Resume { source, params } => { + let resume_id = mcp.send_thread_resume_request(params).await?; + let ThreadResumeResponse { + thread, + approval_policy, + sandbox, + .. + } = timeout(DEFAULT_READ_TIMEOUT, mcp.read_response(resume_id)).await??; + assert_eq!( + thread.source, + codex_app_server_protocol::SessionSource::from(source) + ); + assert_eq!( + approval_policy, + codex_app_server_protocol::AskForApproval::Never + ); + assert_eq!( + sandbox, + codex_app_server_protocol::SandboxPolicy::DangerFullAccess + ); + thread + } + }; let tool_call_request_id = mcp .send_mcp_server_tool_call_request(McpServerToolCallParams { @@ -459,6 +692,37 @@ async fn mcp_server_tool_call_round_trips_elicitation() -> Result<()> { Ok(()) } +async fn initialize_elicitation_app_server( + codex_home: &Path, + session_source: &str, + client_advertises_standard_form_input: bool, +) -> Result { + let mut mcp = TestAppServer::builder() + .with_codex_home(codex_home) + .with_args(&["--session-source", session_source]) + .build() + .await?; + mcp.initialize_with_capabilities( + ClientInfo { + name: "codex_test".to_string(), + title: None, + version: "0.1.0".to_string(), + }, + Some(InitializeCapabilities { + experimental_api: true, + extensions: client_advertises_standard_form_input.then(|| { + HashMap::from([( + OPENAI_STANDARD_FORM_INPUT_EXTENSION_ID.to_string(), + json!({}), + )]) + }), + ..Default::default() + }), + ) + .await?; + Ok(mcp) +} + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn mcp_server_elicitation_survives_environment_runtime_refresh() -> Result<()> { let responses_server = responses::start_mock_server().await; diff --git a/codex-rs/codex-mcp/src/client_capabilities.rs b/codex-rs/codex-mcp/src/client_capabilities.rs index 0be38c3799..c4b36abf52 100644 --- a/codex-rs/codex-mcp/src/client_capabilities.rs +++ b/codex-rs/codex-mcp/src/client_capabilities.rs @@ -3,6 +3,7 @@ use std::collections::HashMap; use codex_protocol::mcp::ClientMcpExtensions; use codex_protocol::mcp::MCP_APP_UI_EXTENSION_ID; use codex_protocol::mcp::OPENAI_FORM_EXTENSION_ID; +use codex_protocol::mcp::OPENAI_STANDARD_FORM_INPUT_EXTENSION_ID; use serde_json::Map; use serde_json::Value; @@ -21,7 +22,9 @@ pub fn client_mcp_extensions( .filter(|(id, _)| { matches!( id.as_str(), - OPENAI_FORM_EXTENSION_ID | MCP_APP_UI_EXTENSION_ID + OPENAI_FORM_EXTENSION_ID + | OPENAI_STANDARD_FORM_INPUT_EXTENSION_ID + | MCP_APP_UI_EXTENSION_ID ) }) .map(|(id, value)| (id.clone(), value.clone())) diff --git a/codex-rs/codex-mcp/src/client_capabilities_tests.rs b/codex-rs/codex-mcp/src/client_capabilities_tests.rs index 88e76cc522..35d2ec3b46 100644 --- a/codex-rs/codex-mcp/src/client_capabilities_tests.rs +++ b/codex-rs/codex-mcp/src/client_capabilities_tests.rs @@ -17,6 +17,10 @@ fn selects_only_supported_mcp_extensions() { let extensions = HashMap::from([ (MCP_APP_UI_EXTENSION_ID.to_string(), app_ui.clone()), (OPENAI_FORM_EXTENSION_ID.to_string(), json!({})), + ( + OPENAI_STANDARD_FORM_INPUT_EXTENSION_ID.to_string(), + json!({}), + ), ("example/other".to_string(), json!({"enabled": true})), ]); @@ -28,6 +32,10 @@ fn selects_only_supported_mcp_extensions() { ClientMcpExtensions::new(HashMap::from([ (MCP_APP_UI_EXTENSION_ID.to_string(), app_ui), (OPENAI_FORM_EXTENSION_ID.to_string(), json!({})), + ( + OPENAI_STANDARD_FORM_INPUT_EXTENSION_ID.to_string(), + json!({}), + ), ])) ); } diff --git a/codex-rs/codex-mcp/src/connection_manager_tests.rs b/codex-rs/codex-mcp/src/connection_manager_tests.rs index c4add7f930..94565ace66 100644 --- a/codex-rs/codex-mcp/src/connection_manager_tests.rs +++ b/codex-rs/codex-mcp/src/connection_manager_tests.rs @@ -3,6 +3,8 @@ use crate::McpBinding; use crate::elicitation::ElicitationLifecycle; use crate::elicitation::ElicitationRequestManager; use crate::elicitation::ElicitationRequestRouter; +use crate::elicitation::ElicitationReviewRequest; +use crate::elicitation::ElicitationReviewer; use crate::elicitation::elicitation_is_rejected_by_policy; use crate::rmcp_client::AsyncManagedClient; use crate::rmcp_client::CODEX_APPS_RECONNECT_INITIAL_BACKOFF; @@ -36,6 +38,7 @@ use codex_exec_server_test_support::environment_manager_without_environments; use codex_login::AuthHeaders; use codex_login::CodexAuth; use codex_protocol::ToolName; +use codex_protocol::approvals::ElicitationRequest; use codex_protocol::mcp::ClientMcpExtensions; use codex_protocol::mcp::McpServerInfo; use codex_protocol::models::PermissionProfile; @@ -75,6 +78,7 @@ use std::path::PathBuf; use std::sync::Arc; use std::sync::atomic::AtomicBool; use std::sync::atomic::AtomicUsize; +use std::sync::atomic::Ordering; use tempfile::tempdir; use tokio::io::DuplexStream; use tokio::sync::Notify; @@ -722,6 +726,364 @@ async fn disabled_permissions_do_not_auto_accept_elicitation_with_requested_fiel ); } +fn full_access_form_input_enabled_router() -> ElicitationRequestRouter { + let router = ElicitationRequestRouter::default(); + router.enable_full_access_form_input(); + router +} + +fn elicitation_meta(value: serde_json::Value) -> Option { + let serde_json::Value::Object(map) = value else { + panic!("elicitation metadata must be an object"); + }; + Some(rmcp::model::RequestMetaObject::from(map)) +} + +fn requested_user_input_schema() -> rmcp::model::ElicitationSchema { + rmcp::model::ElicitationSchema::builder() + .required_property( + "message", + rmcp::model::PrimitiveSchemaDefinition::String(rmcp::model::StringSchema::new()), + ) + .build() + .expect("schema should build") +} + +#[derive(Default)] +struct DecliningElicitationReviewer { + review_count: AtomicUsize, +} + +impl ElicitationReviewer for DecliningElicitationReviewer { + fn review( + &self, + _request: ElicitationReviewRequest, + ) -> BoxFuture<'static, anyhow::Result>> { + self.review_count.fetch_add(1, Ordering::SeqCst); + async { + Ok(Some(ElicitationResponse { + action: ElicitationAction::Decline, + content: None, + meta: None, + })) + } + .boxed() + } +} + +async fn assert_elicitation_declined_with_reviewer_calls( + approval_policy: AskForApproval, + server_name: &str, + elicitation: ElicitRequestParams, + expected_reviewer_calls: usize, +) { + let reviewer = Arc::new(DecliningElicitationReviewer::default()); + let manager = ElicitationRequestManager::new( + approval_policy, + PermissionProfile::Disabled, + Some(reviewer.clone()), + /*lifecycle*/ None, + full_access_form_input_enabled_router(), + ); + let (tx_event, rx_event) = async_channel::bounded(1); + let sender = manager.make_sender(server_name.to_string(), Some(tx_event)); + + let response = tokio::select! { + biased; + event = rx_event.recv() => { + panic!("elicitation unexpectedly reached the user: {event:?}"); + } + response = sender( + NumberOrString::Number(1), + codex_rmcp_client::Elicitation::Mcp(elicitation), + ) => response.expect("elicitation should be declined"), + }; + + assert_eq!( + response, + ElicitationResponse { + action: ElicitationAction::Decline, + content: None, + meta: None, + }, + ); + assert_eq!( + reviewer.review_count.load(Ordering::SeqCst), + expected_reviewer_calls + ); + assert!(rx_event.try_recv().is_err()); +} + +async fn assert_requested_user_input_is_declined( + approval_policy: AskForApproval, + permission_profile: PermissionProfile, + router: ElicitationRequestRouter, +) { + let manager = ElicitationRequestManager::new( + approval_policy, + permission_profile, + /*reviewer*/ None, + /*lifecycle*/ None, + router, + ); + let (tx_event, rx_event) = async_channel::bounded(1); + let sender = manager.make_sender("server".to_string(), Some(tx_event)); + + let response = tokio::select! { + biased; + event = rx_event.recv() => { + panic!("user-input form unexpectedly reached the user: {event:?}"); + } + response = sender( + NumberOrString::Number(1), + codex_rmcp_client::Elicitation::Mcp( + ElicitRequestParams::FormElicitationParams { + meta: None, + message: "What should I say?".to_string(), + requested_schema: requested_user_input_schema(), + }, + ), + ) => response.expect("restricted user-input request should decline"), + }; + + assert_eq!( + response, + ElicitationResponse { + action: ElicitationAction::Decline, + content: None, + meta: None, + }, + ); + assert!(rx_event.try_recv().is_err()); +} + +#[tokio::test] +async fn disabled_permissions_do_not_surface_user_input_when_auto_denied() { + let router = full_access_form_input_enabled_router(); + router.set_auto_deny(/*auto_deny*/ true); + assert_requested_user_input_is_declined( + AskForApproval::Never, + PermissionProfile::Disabled, + router, + ) + .await; +} + +#[tokio::test] +async fn plugin_tool_suggestion_elicitations_are_declined_before_review() { + assert_elicitation_declined_with_reviewer_calls( + AskForApproval::OnRequest, + "server", + ElicitRequestParams::FormElicitationParams { + meta: elicitation_meta(serde_json::json!({ + "codex_approval_kind": "tool_suggestion", + })), + message: "Install this app?".to_string(), + requested_schema: rmcp::model::ElicitationSchema::builder() + .build() + .expect("schema should build"), + }, + /*expected_reviewer_calls*/ 0, + ) + .await; +} + +#[tokio::test] +async fn disabled_permissions_surface_requested_user_input_without_metadata() { + assert_disabled_permissions_surface_requested_user_input(/*meta*/ None).await; +} + +#[tokio::test] +async fn disabled_permissions_surface_requested_user_input_with_non_codex_approval_metadata() { + assert_disabled_permissions_surface_requested_user_input(elicitation_meta(serde_json::json!({ + "origin": "https://example.com", + "persist": "always", + }))) + .await; +} + +async fn assert_disabled_permissions_surface_requested_user_input( + meta: Option, +) { + let router = full_access_form_input_enabled_router(); + let reviewer = Arc::new(DecliningElicitationReviewer::default()); + let manager = ElicitationRequestManager::new( + AskForApproval::Never, + PermissionProfile::Disabled, + Some(reviewer.clone()), + /*lifecycle*/ None, + router.clone(), + ); + let (tx_event, rx_event) = async_channel::bounded(1); + let sender = manager.make_sender("server".to_string(), Some(tx_event)); + let requested_schema = requested_user_input_schema(); + let mut pending = tokio::spawn(sender( + NumberOrString::Number(1), + codex_rmcp_client::Elicitation::Mcp(ElicitRequestParams::FormElicitationParams { + meta: meta.clone(), + message: "What should I say?".to_string(), + requested_schema: requested_schema.clone(), + }), + )); + let request = tokio::select! { + event = rx_event.recv() => { + let EventMsg::ElicitationRequest(request) = event.expect("user-input event").msg else { + panic!("expected MCP user-input elicitation"); + }; + request + } + response = &mut pending => { + panic!("user input resolved without reaching the user: {response:?}"); + } + }; + + assert_eq!( + request.request, + ElicitationRequest::Form { + meta: meta + .map(serde_json::to_value) + .transpose() + .expect("user-input metadata should serialize"), + message: "What should I say?".to_string(), + requested_schema: serde_json::to_value(requested_schema) + .expect("schema should serialize"), + }, + ); + assert_eq!(request.server_name, "server"); + assert_eq!(reviewer.review_count.load(Ordering::SeqCst), 0); + + let codex_protocol::mcp::RequestId::String(request_id) = request.id else { + panic!("expected Codex-owned string request ID"); + }; + let user_response = ElicitationResponse { + action: ElicitationAction::Accept, + content: Some(serde_json::json!({ "message": "The actual user response." })), + meta: None, + }; + router + .resolve( + "server".to_string(), + NumberOrString::String(request_id.into()), + user_response.clone(), + ) + .await + .expect("actual user response should resolve the elicitation"); + assert_eq!( + pending + .await + .expect("user-input task should complete") + .expect("user input should resolve"), + user_response, + ); +} + +#[tokio::test] +async fn disabled_permissions_decline_requested_user_input_with_approval_metadata() { + assert_elicitation_declined_with_reviewer_calls( + AskForApproval::Never, + "node_repl", + ElicitRequestParams::FormElicitationParams { + meta: elicitation_meta(serde_json::json!({ + "codex_approval_kind": "mcp_tool_call", + "connector_id": "browser-use", + "tool_name": "access_browser_origin", + })), + message: "Allow Browser Use to access this website?".to_string(), + requested_schema: + rmcp::model::ElicitationSchema::builder() + .required_property( + "confirmation", + rmcp::model::PrimitiveSchemaDefinition::String( + rmcp::model::StringSchema::new(), + ), + ) + .build() + .expect("schema should build"), + }, + /*expected_reviewer_calls*/ 0, + ) + .await; +} + +#[tokio::test] +async fn restricted_never_policy_does_not_surface_requested_user_input() { + assert_requested_user_input_is_declined( + AskForApproval::Never, + PermissionProfile::default(), + full_access_form_input_enabled_router(), + ) + .await; +} + +#[tokio::test] +async fn granular_policy_does_not_surface_requested_user_input() { + assert_requested_user_input_is_declined( + AskForApproval::Granular(GranularApprovalConfig { + sandbox_approval: true, + rules: true, + skill_approval: true, + request_permissions: true, + mcp_elicitations: false, + }), + PermissionProfile::Disabled, + full_access_form_input_enabled_router(), + ) + .await; +} + +#[tokio::test] +async fn on_request_approval_forms_remain_with_the_reviewer() { + assert_elicitation_declined_with_reviewer_calls( + AskForApproval::OnRequest, + "server", + ElicitRequestParams::FormElicitationParams { + meta: elicitation_meta(serde_json::json!({ + "codex_request_type": "approval_request", + "codex_approval_kind": "mcp_tool_call", + "tool_name": "test_tool", + })), + message: "Approve this action?".to_string(), + requested_schema: rmcp::model::ElicitationSchema::builder() + .build() + .expect("schema should build"), + }, + /*expected_reviewer_calls*/ 1, + ) + .await; +} + +#[tokio::test] +async fn disabled_permissions_decline_user_input_without_an_event_channel() { + let manager = ElicitationRequestManager::new( + AskForApproval::Never, + PermissionProfile::Disabled, + /*reviewer*/ None, + /*lifecycle*/ None, + full_access_form_input_enabled_router(), + ); + let sender = manager.make_sender("server".to_string(), /*tx_event*/ None); + + let response = sender( + NumberOrString::Number(1), + codex_rmcp_client::Elicitation::Mcp(ElicitRequestParams::FormElicitationParams { + meta: None, + message: "What should I say?".to_string(), + requested_schema: requested_user_input_schema(), + }), + ) + .await + .expect("headless user-input request should decline"); + + assert_eq!( + response, + ElicitationResponse { + action: ElicitationAction::Decline, + content: None, + meta: None, + }, + ); +} + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn concurrent_authority_updates_never_auto_approve_mixed_policy() { let manager = ElicitationRequestManager::new( diff --git a/codex-rs/codex-mcp/src/elicitation.rs b/codex-rs/codex-mcp/src/elicitation.rs index 1bb6ffc05f..4a9064da0d 100644 --- a/codex-rs/codex-mcp/src/elicitation.rs +++ b/codex-rs/codex-mcp/src/elicitation.rs @@ -21,6 +21,8 @@ use async_channel::Sender; use codex_protocol::approvals::ElicitationRequest; use codex_protocol::approvals::ElicitationRequestEvent; use codex_protocol::mcp::RequestId as ProtocolRequestId; +use codex_protocol::mcp_approval_meta::APPROVAL_KIND_KEY; +use codex_protocol::mcp_approval_meta::APPROVAL_KIND_TOOL_SUGGESTION; use codex_protocol::mcp_approval_meta::APPROVALS_REVIEWER_KEY; use codex_protocol::mcp_approval_meta::STRICT_AUTO_REVIEW_KEY; use codex_protocol::models::PermissionProfile; @@ -94,6 +96,7 @@ struct ActiveElicitation { pub(crate) struct ElicitationRequestRouter { requests: Arc>, auto_deny: Arc, + full_access_form_input_enabled: Arc, } struct PendingElicitationRequest { @@ -122,6 +125,15 @@ impl ElicitationRequestRouter { self.auto_deny.store(auto_deny, Ordering::Relaxed); } + pub(crate) fn full_access_form_input_enabled(&self) -> bool { + self.full_access_form_input_enabled.load(Ordering::Acquire) + } + + pub(crate) fn enable_full_access_form_input(&self) { + self.full_access_form_input_enabled + .store(true, Ordering::Release); + } + pub(crate) async fn resolve( &self, server_name: String, @@ -213,6 +225,19 @@ impl ElicitationRequestManager { }); } + if elicitation + .meta() + .and_then(|meta| meta.get(APPROVAL_KIND_KEY)) + .and_then(serde_json::Value::as_str) + == Some(APPROVAL_KIND_TOOL_SUGGESTION) + { + return Ok(ElicitationResponse { + action: ElicitationAction::Decline, + content: None, + meta: None, + }); + } + let Ok(authority) = authority.lock().map(|authority| authority.clone()) else { return Ok(ElicitationResponse { action: ElicitationAction::Decline, @@ -273,12 +298,12 @@ impl ElicitationRequestManager { Some(_) => return Ok(strict_auto_review_decline()), } - if mcp_permission_prompt_is_auto_approved( + let permission_prompt_is_auto_approved = mcp_permission_prompt_is_auto_approved( approval_policy, &permission_profile, McpPermissionPromptAutoApproveContext::default(), - ) && can_auto_accept_elicitation(&elicitation) - { + ); + if permission_prompt_is_auto_approved && can_auto_accept_elicitation(&elicitation) { return Ok(ElicitationResponse { action: ElicitationAction::Accept, content: Some(serde_json::json!({})), @@ -286,22 +311,40 @@ impl ElicitationRequestManager { }); } - if elicitation_is_rejected_by_policy(approval_policy) { - return Ok(ElicitationResponse { - action: ElicitationAction::Decline, - content: None, - meta: None, - }); - } + let should_surface_form_in_full_access = router.full_access_form_input_enabled() + && permission_prompt_is_auto_approved + && matches!( + &elicitation, + Elicitation::Mcp( + rmcp::model::ElicitRequestParams::FormElicitationParams { + meta, + requested_schema, + .. + } + ) if !requested_schema.properties.is_empty() + && !meta + .as_ref() + .is_some_and(|meta| meta.contains_key(APPROVAL_KIND_KEY)) + ); - if let Some(reviewer) = reviewer { - let request = ElicitationReviewRequest { - server_name: server_name.clone(), - request_id: id.clone(), - elicitation: elicitation.clone(), - }; - if let Some(response) = reviewer.review(request).await? { - return Ok(response); + if !should_surface_form_in_full_access { + if elicitation_is_rejected_by_policy(approval_policy) { + return Ok(ElicitationResponse { + action: ElicitationAction::Decline, + content: None, + meta: None, + }); + } + + if let Some(reviewer) = reviewer { + let request = ElicitationReviewRequest { + server_name: server_name.clone(), + request_id: id.clone(), + elicitation: elicitation.clone(), + }; + if let Some(response) = reviewer.review(request).await? { + return Ok(response); + } } } diff --git a/codex-rs/codex-mcp/src/runtime.rs b/codex-rs/codex-mcp/src/runtime.rs index c7c1a44bdd..dec1858b8a 100644 --- a/codex-rs/codex-mcp/src/runtime.rs +++ b/codex-rs/codex-mcp/src/runtime.rs @@ -364,6 +364,10 @@ impl McpRuntime { self.elicitation_router.set_auto_deny(auto_deny); } + pub fn enable_full_access_form_input(&self) { + self.elicitation_router.enable_full_access_form_input(); + } + pub async fn resolve_elicitation( &self, server_name: String, diff --git a/codex-rs/core/src/session/mcp_runtime.rs b/codex-rs/core/src/session/mcp_runtime.rs index 62d5d4638a..5f868a4fb5 100644 --- a/codex-rs/core/src/session/mcp_runtime.rs +++ b/codex-rs/core/src/session/mcp_runtime.rs @@ -191,7 +191,7 @@ impl Session { codex_apps_tools_cache: self.services.mcp_manager.codex_apps_tools_cache(), tool_catalog_cache: self.services.mcp_manager.tool_catalog_cache(), codex_apps_tools_cache_key: connector_runtime_context_key(auth.as_ref()), - client_mcp_extensions: self.services.client_mcp_extensions.clone(), + client_mcp_extensions: self.services.client_mcp_extensions.for_mcp_servers(), auth, codex_apps_auth_manager, elicitation_reviewer, diff --git a/codex-rs/core/src/thread_manager.rs b/codex-rs/core/src/thread_manager.rs index a6f27ee312..f35d293ecc 100644 --- a/codex-rs/core/src/thread_manager.rs +++ b/codex-rs/core/src/thread_manager.rs @@ -49,6 +49,7 @@ use codex_protocol::config_types::CollaborationModeMask; use codex_protocol::error::CodexErr; use codex_protocol::error::Result as CodexResult; use codex_protocol::mcp::ClientMcpExtensions; +use codex_protocol::mcp::OPENAI_STANDARD_FORM_INPUT_EXTENSION_ID; use codex_protocol::openai_models::ModelPreset; use codex_protocol::protocol::Event; use codex_protocol::protocol::EventMsg; @@ -1763,7 +1764,7 @@ impl ThreadManagerState { session_source, forked_from_thread_id, parent_thread_id, - thread_source, + thread_source: thread_source.clone(), originator, agent_control, dynamic_tools, @@ -1786,6 +1787,17 @@ impl ThreadManagerState { codex_sandboxing::WindowsSandboxProxySettingsMode::Reconcile, })) .await?; + // Enable Full Access form input only after session startup so a required MCP server cannot + // block startup while waiting for form input. + if session + .services + .client_mcp_extensions + .contains(OPENAI_STANDARD_FORM_INPUT_EXTENSION_ID) + && matches!(thread_source.as_ref(), Some(ThreadSource::User)) + && !tracked_session_source.is_non_root_agent() + { + session.services.mcp_runtime.enable_full_access_form_input(); + } let new_thread = self .finalize_thread_spawn(session, io, tracked_session_source) .await?; diff --git a/codex-rs/protocol/src/mcp.rs b/codex-rs/protocol/src/mcp.rs index f6aea6fea8..7012d2b9f1 100644 --- a/codex-rs/protocol/src/mcp.rs +++ b/codex-rs/protocol/src/mcp.rs @@ -11,9 +11,14 @@ use ts_rs::TS; /// Extension ID for OpenAI form elicitation. pub const OPENAI_FORM_EXTENSION_ID: &str = "openai/form"; +/// Extension ID for standard MCP form elicitations that require user-entered input. +pub const OPENAI_STANDARD_FORM_INPUT_EXTENSION_ID: &str = "openai/standard-form-input"; /// Extension ID for MCP App UI rendering. pub const MCP_APP_UI_EXTENSION_ID: &str = "io.modelcontextprotocol/ui"; +/// Client extensions that must not be advertised to MCP servers. +const MCP_CLIENT_ONLY_EXTENSION_IDS: [&str; 1] = [OPENAI_STANDARD_FORM_INPUT_EXTENSION_ID]; + /// MCP extensions supplied by the client that created a Codex session. #[derive(Clone, Debug, Default, Eq, PartialEq)] pub struct ClientMcpExtensions { @@ -38,6 +43,16 @@ impl ClientMcpExtensions { self.extensions.get(extension_id) } + /// Returns only client extensions that should be advertised to MCP servers. + pub fn for_mcp_servers(&self) -> Self { + Self::new( + self.extensions + .iter() + .filter(|(id, _)| !MCP_CLIENT_ONLY_EXTENSION_IDS.contains(&id.as_str())) + .map(|(id, settings)| (id.clone(), settings.clone())), + ) + } + /// Iterates over the extensions and their settings. pub fn iter(&self) -> impl Iterator { self.extensions @@ -378,6 +393,40 @@ mod tests { use super::*; + #[test] + fn client_mcp_extensions_for_mcp_servers_excludes_client_only_extensions() { + let openai_form_settings = serde_json::json!({ "version": 1 }); + let app_ui_settings = serde_json::json!({ "mimeTypes": ["text/html"] }); + let future_server_extension_settings = serde_json::json!({ "version": 2 }); + let extensions = ClientMcpExtensions::new([ + ( + OPENAI_FORM_EXTENSION_ID.to_string(), + openai_form_settings.clone(), + ), + (MCP_APP_UI_EXTENSION_ID.to_string(), app_ui_settings.clone()), + ( + OPENAI_STANDARD_FORM_INPUT_EXTENSION_ID.to_string(), + serde_json::json!({}), + ), + ( + "example/future-server-extension".to_string(), + future_server_extension_settings.clone(), + ), + ]); + + assert_eq!( + extensions.for_mcp_servers(), + ClientMcpExtensions::new([ + (OPENAI_FORM_EXTENSION_ID.to_string(), openai_form_settings), + (MCP_APP_UI_EXTENSION_ID.to_string(), app_ui_settings), + ( + "example/future-server-extension".to_string(), + future_server_extension_settings, + ), + ]) + ); + } + #[test] fn resource_size_deserializes_without_narrowing() { let resource = serde_json::json!({ diff --git a/codex-rs/protocol/src/mcp_approval_meta.rs b/codex-rs/protocol/src/mcp_approval_meta.rs index 8b221ae741..4aebdd9e67 100644 --- a/codex-rs/protocol/src/mcp_approval_meta.rs +++ b/codex-rs/protocol/src/mcp_approval_meta.rs @@ -1,3 +1,6 @@ +/// Identifies privileged Codex approvals. Changing this key or adding another +/// privileged discriminator requires updating the MCP elicitation router's +/// form-forwarding safeguards. pub const APPROVAL_KIND_KEY: &str = "codex_approval_kind"; pub const APPROVAL_KIND_MCP_TOOL_CALL: &str = "mcp_tool_call"; pub const APPROVAL_KIND_TOOL_SUGGESTION: &str = "tool_suggestion";