mirror of
https://github.com/openai/codex.git
synced 2026-11-27 23:31:09 +00:00
Keep MCP user interaction on the root thread (#46066)
## Why MCP requests that need human input, including browser sign-in, must be handled by the root thread. Subagents need guidance to hand these blockers to their parent without prompting the user or automatically accepting requests that require input. ## What changed - Reject interactive MCP elicitations and tool approval prompts in subagents with guidance to ask the parent and wait before retrying. - Recognize browser authentication and `codex_requires_user_input` metadata even when the form schema is empty, while preserving automatic permission approvals and review decisions. - Carry user-interaction eligibility through MCP runtime creation and connection reuse, and guard prompt registration. - Preserve connector authentication diagnostics alongside handoff guidance, subject to normal tool-output limits. ## Testing Add unit and integration coverage for blocked subagent prompts, root browser authentication, automatic approval and review, connection reuse, and authentication diagnostic preservation and truncation. Add a request-history snapshot for browser-auth handoff guidance. GitOrigin-RevId: 83e146b6e5c1a2a22a34681ad45615f504b3c96c
This commit is contained in:
1 parent
5e636ea760
commit
40584fad87
24 files changed
+1330
-153
No files matched your search
@@ -269,6 +269,7 @@ pub async fn list_accessible_connectors_from_mcp_tools_with_mcp_manager(
|
||||
client_mcp_extensions: ClientMcpExtensions::default(),
|
||||
auth: auth.clone(),
|
||||
auth_manager: codex_apps_auth_manager,
|
||||
allow_user_interaction: true,
|
||||
elicitation_reviewer: None,
|
||||
elicitation_lifecycle: None,
|
||||
})
|
||||
|
||||
@@ -781,7 +781,7 @@ async fn maybe_request_codex_apps_auth_elicitation(
|
||||
url: plan.elicitation.url,
|
||||
elicitation_id: plan.elicitation.elicitation_id,
|
||||
};
|
||||
let response = sess
|
||||
let outcome = match sess
|
||||
.request_mcp_server_elicitation(
|
||||
turn_context,
|
||||
CODEX_APPS_MCP_SERVER_NAME.to_string(),
|
||||
@@ -789,8 +789,33 @@ async fn maybe_request_codex_apps_auth_elicitation(
|
||||
request,
|
||||
)
|
||||
.await
|
||||
.response;
|
||||
if !response
|
||||
{
|
||||
Ok(outcome) => outcome,
|
||||
Err(error) => {
|
||||
let mut result = result;
|
||||
// Direct output prefers structured content. Preserve its diagnostic as
|
||||
// text so both output paths show it alongside the recovery guidance.
|
||||
if let Some(structured_content) = result.structured_content.take() {
|
||||
result.content.push(serde_json::json!({
|
||||
"type": "text",
|
||||
"text": structured_content.to_string(),
|
||||
}));
|
||||
}
|
||||
result.content.insert(
|
||||
/*index*/ 0,
|
||||
serde_json::json!({
|
||||
"type": "text",
|
||||
"text": format!(
|
||||
"Authentication for {} could not be completed. {error}",
|
||||
plan.auth_failure.connector_name
|
||||
),
|
||||
}),
|
||||
);
|
||||
return result;
|
||||
}
|
||||
};
|
||||
if !outcome
|
||||
.response
|
||||
.as_ref()
|
||||
.is_some_and(|response| response.action == ElicitationAction::Accept)
|
||||
{
|
||||
@@ -1597,6 +1622,10 @@ pub(crate) async fn request_mcp_tool_user_approval(
|
||||
);
|
||||
}
|
||||
|
||||
if turn_context.session_source.is_non_root_agent() {
|
||||
return ReviewDecision::denied(codex_mcp::MCP_ELICITATION_HANDOFF_MESSAGE);
|
||||
}
|
||||
|
||||
let tool_call_mcp_elicitation_enabled = turn_context
|
||||
.config
|
||||
.features
|
||||
@@ -1662,9 +1691,13 @@ pub(crate) async fn request_mcp_tool_user_approval(
|
||||
.map(|rendered_template| rendered_template.elicitation_message.as_str()),
|
||||
prompt_options,
|
||||
});
|
||||
let outcome = sess
|
||||
let outcome = match sess
|
||||
.request_mcp_server_elicitation(turn_context, server.clone(), request_id, request)
|
||||
.await;
|
||||
.await
|
||||
{
|
||||
Ok(outcome) => outcome,
|
||||
Err(error) => return ReviewDecision::denied(error.to_string()),
|
||||
};
|
||||
(
|
||||
outcome.sent,
|
||||
parse_mcp_tool_approval_elicitation_response(outcome.response, &question_id),
|
||||
|
||||
@@ -13,6 +13,9 @@ use crate::session::tests::update_turn_settings_for_test;
|
||||
use crate::session::turn_context::TurnEnvironment;
|
||||
use crate::state::ActiveTurn;
|
||||
use crate::test_support::models_manager_with_provider;
|
||||
use crate::tools::context::McpToolOutput;
|
||||
use crate::tools::context::ToolOutput;
|
||||
use crate::tools::context::ToolPayload;
|
||||
use crate::tools::hook_names::HookToolName;
|
||||
use crate::turn_metadata::ExecutionMetadata;
|
||||
use codex_app_server_protocol as app_server_protocol;
|
||||
@@ -30,6 +33,7 @@ use codex_hooks::HooksConfig;
|
||||
use codex_model_provider::create_model_provider;
|
||||
use codex_protocol::ResponseItemId;
|
||||
use codex_protocol::models::PermissionProfile;
|
||||
use codex_protocol::models::ResponseInputItem;
|
||||
use codex_protocol::openai_models::ReasoningEffort as ReasoningEffortConfig;
|
||||
use codex_protocol::protocol::AskForApproval;
|
||||
use codex_protocol::protocol::EnvironmentConfig;
|
||||
@@ -1724,6 +1728,88 @@ async fn codex_apps_auth_elicitation_granular_mcp_disabled_returns_original_resu
|
||||
assert!(rx_event.try_recv().is_err());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn codex_apps_auth_elicitation_returns_subagent_handoff_and_diagnostics() {
|
||||
let (session, mut turn_context, rx_event) = make_session_and_context_with_rx().await;
|
||||
Arc::get_mut(&mut turn_context)
|
||||
.expect("single turn context ref")
|
||||
.session_source = SessionSource::SubAgent(SubAgentSource::Review);
|
||||
let structured_content = serde_json::json!({
|
||||
"error": "reauthentication_required", "status": 401
|
||||
});
|
||||
let mut result = codex_apps_auth_failure_result();
|
||||
result.structured_content = Some(structured_content.clone());
|
||||
let diagnostic = format!(
|
||||
"Connector reauthentication required: {}",
|
||||
"diagnostic detail ".repeat(/*n*/ 500)
|
||||
);
|
||||
result.content[0]["text"] = serde_json::json!(diagnostic);
|
||||
let metadata = codex_apps_auth_failure_metadata();
|
||||
let returned = tokio::time::timeout(
|
||||
std::time::Duration::from_secs(1),
|
||||
maybe_request_codex_apps_auth_elicitation(
|
||||
&session,
|
||||
&turn_context,
|
||||
turn_context.approval_policy(),
|
||||
"call_123",
|
||||
CODEX_APPS_MCP_SERVER_NAME,
|
||||
Some(&metadata),
|
||||
result.clone(),
|
||||
),
|
||||
)
|
||||
.await
|
||||
.expect("subagent auth must not wait for user input");
|
||||
|
||||
assert_eq!(returned.meta, result.meta);
|
||||
assert_eq!(returned.is_error, Some(true));
|
||||
assert!(rx_event.try_recv().is_err());
|
||||
|
||||
let output = McpToolOutput {
|
||||
result: returned,
|
||||
tool_input: serde_json::json!({}),
|
||||
result_metadata_capture_allowed: true,
|
||||
wall_time: std::time::Duration::ZERO,
|
||||
original_image_detail_supported: false,
|
||||
truncation_policy: TruncationPolicy::Tokens(256),
|
||||
};
|
||||
let payload = ToolPayload::Function {
|
||||
arguments: "{}".to_string(),
|
||||
};
|
||||
let code_mode = output.code_mode_result(&payload);
|
||||
assert_eq!(code_mode["isError"], serde_json::json!(true));
|
||||
assert!(code_mode.get("_meta").is_none());
|
||||
let code_text = code_mode["content"]
|
||||
.as_array()
|
||||
.expect("MCP content")
|
||||
.iter()
|
||||
.map(|item| item["text"].as_str().expect("auth diagnostic text"))
|
||||
.collect::<Vec<_>>()
|
||||
.join("\n");
|
||||
assert!(code_text.contains("Authentication for Google Calendar could not be completed."));
|
||||
assert!(code_text.contains(codex_mcp::MCP_ELICITATION_HANDOFF_MESSAGE));
|
||||
assert!(code_text.contains(&diagnostic));
|
||||
assert!(code_text.contains(&structured_content.to_string()));
|
||||
assert_eq!(output.tool_result_metadata(), result.meta.as_ref());
|
||||
let mut expected_hook = code_mode;
|
||||
expected_hook["_meta"] = result.meta.expect("original auth metadata");
|
||||
assert_eq!(
|
||||
output.post_tool_use_response("call_123", &payload),
|
||||
Some(expected_hook)
|
||||
);
|
||||
|
||||
let ResponseInputItem::FunctionCallOutput {
|
||||
output: truncated, ..
|
||||
} = output.to_response_item("call_123", &payload)
|
||||
else {
|
||||
panic!("expected FunctionCallOutput");
|
||||
};
|
||||
let truncated_text = truncated.body.to_text().expect("truncated auth diagnostic");
|
||||
assert!(truncated_text.contains(codex_mcp::MCP_ELICITATION_HANDOFF_MESSAGE));
|
||||
assert!(truncated_text.contains("truncated"));
|
||||
assert!(!truncated_text.contains(&diagnostic));
|
||||
assert_eq!(truncated.success, Some(false));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn codex_apps_auth_elicitation_enabled_by_default_requests_elicitation() {
|
||||
let (session, turn_context, rx_event) = make_session_and_context_with_rx().await;
|
||||
|
||||
@@ -556,16 +556,20 @@ impl Session {
|
||||
server_name: String,
|
||||
request_id: RequestId,
|
||||
request: ElicitationRequest,
|
||||
) -> McpServerElicitationOutcome {
|
||||
) -> anyhow::Result<McpServerElicitationOutcome> {
|
||||
anyhow::ensure!(
|
||||
!turn_context.session_source.is_non_root_agent(),
|
||||
codex_mcp::MCP_ELICITATION_HANDOFF_MESSAGE
|
||||
);
|
||||
if self.services.mcp_runtime.elicitations_auto_deny() {
|
||||
return McpServerElicitationOutcome {
|
||||
return Ok(McpServerElicitationOutcome {
|
||||
response: Some(ElicitationResponse {
|
||||
action: codex_rmcp_client::ElicitationAction::Accept,
|
||||
content: Some(serde_json::json!({})),
|
||||
meta: None,
|
||||
}),
|
||||
sent: false,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
let _elicitation = self.services.elicitations.register();
|
||||
@@ -617,10 +621,10 @@ impl Session {
|
||||
plugin_install_telemetry.tool_name.as_str(),
|
||||
);
|
||||
}
|
||||
McpServerElicitationOutcome {
|
||||
Ok(McpServerElicitationOutcome {
|
||||
response: rx_response.await.ok(),
|
||||
sent: true,
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
#[expect(
|
||||
|
||||
@@ -404,6 +404,7 @@ impl Session {
|
||||
client_mcp_extensions: self.services.client_mcp_extensions.for_mcp_servers(),
|
||||
auth,
|
||||
auth_manager: Some(Arc::clone(&self.services.auth_manager)),
|
||||
allow_user_interaction: !desired.session_source.is_non_root_agent(),
|
||||
elicitation_reviewer,
|
||||
elicitation_lifecycle: Some(self.mcp_elicitation_lifecycle()),
|
||||
}
|
||||
|
||||
@@ -87,6 +87,7 @@ use codex_protocol::permissions::FileSystemSandboxPolicy;
|
||||
use codex_protocol::permissions::FileSystemSandboxPolicyContext;
|
||||
use codex_protocol::permissions::FileSystemSpecialPath;
|
||||
use codex_protocol::protocol::EnvironmentConfigState;
|
||||
use codex_protocol::protocol::InternalSessionSource;
|
||||
use codex_protocol::protocol::SandboxPolicy;
|
||||
use codex_protocol::protocol::TurnEnvironmentSelections;
|
||||
use codex_protocol::request_permissions::PermissionGrantScope;
|
||||
@@ -652,7 +653,8 @@ async fn request_mcp_server_elicitation_auto_accepts_when_auto_deny_is_enabled()
|
||||
}),
|
||||
},
|
||||
)
|
||||
.await;
|
||||
.await
|
||||
.expect("root thread elicitation should be accepted");
|
||||
|
||||
assert_eq!(
|
||||
response.response,
|
||||
@@ -666,6 +668,58 @@ async fn request_mcp_server_elicitation_auto_accepts_when_auto_deny_is_enabled()
|
||||
assert!(rx.try_recv().is_err());
|
||||
}
|
||||
|
||||
#[test_case(false; "interactive")]
|
||||
#[test_case(true; "auto_accept")]
|
||||
#[tokio::test]
|
||||
async fn request_mcp_server_elicitation_rejects_non_root_threads(auto_deny: bool) {
|
||||
for source in [
|
||||
SessionSource::SubAgent(SubAgentSource::Review),
|
||||
SessionSource::Internal(InternalSessionSource::Guardian),
|
||||
] {
|
||||
let (session, mut turn_context, rx) = make_session_and_context_with_rx().await;
|
||||
Arc::get_mut(&mut turn_context)
|
||||
.expect("turn context should not be shared")
|
||||
.session_source = source;
|
||||
*session.active_turn.lock().await = Some(ActiveTurn::default());
|
||||
session
|
||||
.services
|
||||
.mcp_runtime
|
||||
.set_elicitations_auto_deny(auto_deny);
|
||||
let paused = session.subscribe_elicitation_pause_state();
|
||||
|
||||
let Err(error) = tokio::time::timeout(
|
||||
Duration::from_secs(1),
|
||||
session.request_mcp_server_elicitation(
|
||||
turn_context.as_ref(),
|
||||
"codex_apps".to_string(),
|
||||
RequestId::String("request-1".into()),
|
||||
ElicitationRequest::Url {
|
||||
meta: None,
|
||||
message: "Connect this app to continue.".to_string(),
|
||||
url: "https://example.com/connect".to_string(),
|
||||
elicitation_id: "connect-1".to_string(),
|
||||
},
|
||||
),
|
||||
)
|
||||
.await
|
||||
.expect("non-root elicitation must not wait for user input") else {
|
||||
panic!("non-root elicitation must be rejected");
|
||||
};
|
||||
|
||||
assert_eq!(
|
||||
error.to_string(),
|
||||
codex_mcp::MCP_ELICITATION_HANDOFF_MESSAGE
|
||||
);
|
||||
assert!(rx.try_recv().is_err());
|
||||
assert!(!*paused.borrow());
|
||||
assert!(
|
||||
!paused
|
||||
.has_changed()
|
||||
.expect("elicitation service should remain available")
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn interrupting_regular_turn_waiting_on_startup_prewarm_emits_turn_aborted() {
|
||||
let (sess, tc, rx) = make_session_and_context_with_rx().await;
|
||||
|
||||
@@ -254,7 +254,8 @@ impl RequestPluginInstallHandler {
|
||||
request_id,
|
||||
request,
|
||||
)
|
||||
.await;
|
||||
.await
|
||||
.map_err(|error| FunctionCallError::RespondToModel(error.to_string()))?;
|
||||
let response = elicitation.response;
|
||||
if let Some(response) = response.as_ref() {
|
||||
maybe_persist_disabled_install_request(&session, &turn, &tool, response).await;
|
||||
|
||||
Reference in new issue
Block a user