pub(crate) mod recorded; use std::collections::HashMap; use std::time::Duration; use std::time::Instant; use crate::config::Config; use crate::config::edit::ConfigEdit; use crate::config::edit::ConfigEditsBuilder; use crate::guardian::GuardianMcpAnnotations; use crate::guardian::GuardianReviewContext; 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::step_context::StepContext; use crate::session::turn_context::TurnContext; use crate::tools::ApprovalContext; use crate::tools::ApprovalResolution; use crate::tools::ApprovalResolutionSource; use crate::tools::context::ToolCallOrigin; use crate::tools::hook_names::HookToolName; use crate::tools::lifecycle::process_mcp_tool_result; use crate::tools::sandboxing::ApprovalAction; use crate::tools::sandboxing::ToolError; use crate::turn_metadata::ExecutionMetadata; use akode_config::ConfigLayerSource; use akode_config::types::AppToolApproval; use akode_extension_api::McpToolContext; use akode_features::Feature; use akode_file_system::FileSystemSandboxContext; use akode_mcp::McpPermissionPromptAutoApproveContext; use akode_mcp::McpPermissionSource; use akode_mcp::McpToolRequestMetaHook; use akode_mcp::PreparedMcpCall; use akode_mcp::SandboxState; use akode_mcp::ToolInfo; use akode_mcp::mcp_permission_prompt_is_auto_approved; use akode_prompts::ResolvedModelMessages; use akode_protocol::approvals::ElicitationRequest; use akode_protocol::items::McpAppDisplayMode; use akode_protocol::items::McpAppUi; use akode_protocol::items::McpToolCallError; use akode_protocol::items::McpToolCallItem; use akode_protocol::items::McpToolCallStatus; use akode_protocol::items::TurnItem; use akode_protocol::mcp::CONFIRMATION_POLICIES_META_KEY; use akode_protocol::mcp::CallToolResult; use akode_protocol::mcp::is_node_repl_backed_server; use akode_protocol::mcp_approval_meta::APPROVAL_KIND_KEY as MCP_TOOL_APPROVAL_KIND_KEY; use akode_protocol::mcp_approval_meta::APPROVAL_KIND_MCP_TOOL_CALL as MCP_TOOL_APPROVAL_KIND_MCP_TOOL_CALL; use akode_protocol::mcp_approval_meta::CANCELLATION_REASON_KEY; use akode_protocol::mcp_approval_meta::McpApprovalCancellationReason; use akode_protocol::mcp_approval_meta::PERSIST_ALWAYS as MCP_TOOL_APPROVAL_PERSIST_ALWAYS; use akode_protocol::mcp_approval_meta::PERSIST_KEY as MCP_TOOL_APPROVAL_PERSIST_KEY; use akode_protocol::mcp_approval_meta::PERSIST_SESSION as MCP_TOOL_APPROVAL_PERSIST_SESSION; use akode_protocol::mcp_approval_meta::TOOL_ANNOTATIONS_KEY as MCP_TOOL_APPROVAL_TOOL_ANNOTATIONS_KEY; use akode_protocol::mcp_approval_meta::TOOL_DESCRIPTION_KEY as MCP_TOOL_APPROVAL_TOOL_DESCRIPTION_KEY; use akode_protocol::mcp_approval_meta::TOOL_NAME_KEY as MCP_TOOL_APPROVAL_TOOL_NAME_KEY; use akode_protocol::mcp_approval_meta::TOOL_PARAMS_DISPLAY_KEY as MCP_TOOL_APPROVAL_TOOL_PARAMS_DISPLAY_KEY; use akode_protocol::mcp_approval_meta::TOOL_PARAMS_KEY as MCP_TOOL_APPROVAL_TOOL_PARAMS_KEY; use akode_protocol::mcp_approval_meta::TOOL_TITLE_KEY as MCP_TOOL_APPROVAL_TOOL_TITLE_KEY; use akode_protocol::openai_models::InputModality; use akode_protocol::protocol::AskForApproval; use akode_protocol::protocol::McpInvocation; use akode_protocol::protocol::ReviewDecision; use akode_protocol::request_user_input::RequestUserInputAnswer; use akode_protocol::request_user_input::RequestUserInputArgs; use akode_protocol::request_user_input::RequestUserInputQuestion; use akode_protocol::request_user_input::RequestUserInputQuestionOption; use akode_protocol::request_user_input::RequestUserInputResponse; use akode_rmcp_client::ElicitationAction; use akode_rmcp_client::ElicitationResponse; use akode_tools::ToolName; use akode_utils_absolute_path::AbsolutePathBuf; use akode_utils_output_truncation::TruncationPolicy; use akode_utils_output_truncation::truncate_mcp_tool_result; use akode_utils_output_truncation::truncate_text; use akode_utils_path_uri::PathUri; use akode_utils_pty::DEFAULT_OUTPUT_BYTES_CAP; use rmcp::model::ToolAnnotations; use serde::Deserialize; use serde::Serialize; use serde_json::Value as JsonValue; use std::sync::Arc; use tokio_util::sync::CancellationToken; use toml_edit::value; use tracing::Instrument; use tracing::Span; use tracing::error; use tracing::field::Empty; use url::Url; mod telemetry; use telemetry::McpCallMetricOutcome; use telemetry::emit_mcp_call_metrics; use telemetry::mcp_call_metric_outcome; use telemetry::record_mcp_call_outcome_span_telemetry; const MCP_RESULT_TELEMETRY_META_KEY: &str = "codex/telemetry"; const MCP_RESULT_TELEMETRY_SPAN_KEY: &str = "span"; const MCP_RESULT_TELEMETRY_TARGET_ID_KEY: &str = "target_id"; const MCP_RESULT_TELEMETRY_DID_TRIGGER_SERVER_USER_FLOW_KEY: &str = "did_trigger_server_user_flow"; const MCP_RESULT_TELEMETRY_TARGET_ID_SPAN_ATTR: &str = "codex.mcp.target.id"; const MCP_RESULT_TELEMETRY_SERVER_USER_FLOW_SPAN_ATTR: &str = "codex.mcp.server_user_flow.triggered"; const MCP_RESULT_TELEMETRY_TARGET_ID_MAX_CHARS: usize = 256; const MCP_TOOL_CALL_EVENT_RESULT_MAX_BYTES: usize = DEFAULT_OUTPUT_BYTES_CAP; fn parse_mcp_tool_arguments(arguments: &str) -> serde_json::Result> { if arguments.trim().is_empty() { Ok(None) } else { serde_json::from_str(arguments).map(Some) } } /// Handles the specified tool call and dispatches the appropriate MCP tool-call /// item lifecycle events to the `Session`. #[expect(clippy::too_many_arguments)] pub(crate) async fn handle_mcp_tool_call( sess: Arc, step_context: &Arc, cancellation_token: &CancellationToken, call_id: String, originating_call: Option, advertised_tool: &ToolInfo, prepared_call: anyhow::Result, hook_tool_name: HookToolName, invocation_tool_name: ToolName, arguments: String, ) -> HandledMcpToolCall { let turn_context = &step_context.turn; let server = advertised_tool.server_name.clone(); let tool_name = advertised_tool.tool.name.to_string(); let arguments_value = match parse_mcp_tool_arguments(&arguments) { Ok(value) => value, Err(e) => { error!("failed to parse tool call arguments: {e}"); return HandledMcpToolCall { result: CallToolResult::from_error_text(format!("err: {e}")), tool_input: JsonValue::Object(serde_json::Map::new()), }; } }; let invocation = McpInvocation { server: server.clone(), tool: tool_name.clone(), arguments: arguments_value.clone(), }; let prepared = prepared_call.map(|call| { let metadata = mcp_tool_metadata(call.tool_info(), call.plugin_id()); (call, metadata) }); let (prepared_call, metadata) = match prepared { Ok(prepared) => prepared, Err(error) => { let item_metadata = McpToolCallItemMetadata::from_tool_metadata(&server, /*metadata*/ None); let result = notify_mcp_tool_call_skip( sess.as_ref(), turn_context.as_ref(), &call_id, invocation, item_metadata, format!("{error:#}"), /*already_started*/ false, ) .await; return HandledMcpToolCall { result: CallToolResult::from_result(result), tool_input: arguments_value .unwrap_or_else(|| JsonValue::Object(serde_json::Map::new())), }; } }; let item_metadata = McpToolCallItemMetadata::from_tool_metadata(&server, Some(&metadata)); let approval_policy = mcp_tool_approval_policy(&prepared_call); let _approval_metadata = sess.register_mcp_tool_approval_metadata( &call_id, &invocation, metadata.clone(), GuardianReviewContext::from(step_context), capture_environment_permissions(prepared_call.permission_source()), ); notify_mcp_tool_call_started( sess.as_ref(), turn_context.as_ref(), &call_id, invocation.clone(), item_metadata.clone(), ) .await; if let Some(approval) = maybe_request_mcp_tool_approval( &sess, step_context, cancellation_token, &call_id, &invocation, &invocation_tool_name, &hook_tool_name, &metadata, prepared_call.config(), prepared_call.permission_source(), prepared_call.server_environment_id(), approval_policy, ) .await { let cancellation_outcome = matches!(approval.decision, ReviewDecision::Abort) .then(|| McpCallMetricOutcome::approval_cancelled(approval.source)); let result = match approval.decision { decision @ (ReviewDecision::Approved | ReviewDecision::ApprovedForSession | ReviewDecision::ApprovedMcpPolicyAmendment | ReviewDecision::ApprovedExecpolicyAmendment { .. } | ReviewDecision::NetworkPolicyAmendment { .. }) => { return handle_approved_mcp_tool_call( &sess, step_context.as_ref(), &call_id, originating_call.as_ref(), invocation, prepared_call, metadata, item_metadata, McpToolApprovalApplication::Apply { decision, policy: approval_policy, }, ) .await; } ReviewDecision::Denied { rejection } => { notify_mcp_tool_call_skip( sess.as_ref(), turn_context.as_ref(), &call_id, invocation, item_metadata.clone(), rejection, /*already_started*/ true, ) .await } ReviewDecision::TimedOut => { notify_mcp_tool_call_skip( sess.as_ref(), turn_context.as_ref(), &call_id, invocation, item_metadata.clone(), ResolvedModelMessages::from_model(turn_context.model_info()) .auto_review() .timeout_instructions .to_string(), /*already_started*/ true, ) .await } ReviewDecision::Abort => { let message = match approval.cancellation_reason { // Older clients do not send provenance. Preserve their // cancellation behavior without assigning them a user reason. Some(McpApprovalCancellationReason::User) | None => { "user cancelled MCP tool call" } Some(McpApprovalCancellationReason::Interrupted) => { "MCP tool call cancelled before approval" } Some(McpApprovalCancellationReason::NonInteractive) => { "MCP tool call cancelled: interactive approval is unavailable in exec mode" } } .to_string(); notify_mcp_tool_call_skip( sess.as_ref(), turn_context.as_ref(), &call_id, invocation, item_metadata.clone(), message, /*already_started*/ true, ) .await } }; let status = if result.is_ok() { "ok" } else { "error" }; let outcome = cancellation_outcome.unwrap_or_else(|| McpCallMetricOutcome::from_status(status)); emit_mcp_call_metrics( &step_context.session_telemetry, &outcome, &server, &tool_name, /*duration*/ None, ); return HandledMcpToolCall { result: CallToolResult::from_result(result), tool_input: arguments_value .unwrap_or_else(|| JsonValue::Object(serde_json::Map::new())), }; } handle_approved_mcp_tool_call( &sess, step_context.as_ref(), &call_id, originating_call.as_ref(), invocation, prepared_call, metadata, item_metadata, McpToolApprovalApplication::NotRequired, ) .await } pub(crate) struct HandledMcpToolCall { pub(crate) result: CallToolResult, pub(crate) tool_input: JsonValue, } #[derive(Clone, Debug, PartialEq, Eq)] struct McpToolCallItemMetadata { mcp_app_resource_uri: Option, mcp_app_ui: Option, plugin_id: Option, read_only_hint: Option, } impl McpToolCallItemMetadata { fn from_tool_metadata(_server: &str, metadata: Option<&McpToolApprovalMetadata>) -> Self { Self { mcp_app_resource_uri: metadata .and_then(|metadata| metadata.mcp_app_resource_uri.clone()), mcp_app_ui: metadata.and_then(|metadata| metadata.mcp_app_ui.clone()), plugin_id: metadata.and_then(|metadata| metadata.plugin_id.clone()), read_only_hint: metadata .and_then(|metadata| metadata.annotations.as_ref()) .and_then(|annotations| annotations.read_only_hint), } } } #[expect( clippy::too_many_arguments, reason = "MCP approval must be applied inside the prepared call's catalog lease" )] async fn handle_approved_mcp_tool_call( sess: &Arc, step_context: &StepContext, call_id: &str, originating_call: Option<&ToolCallOrigin>, invocation: McpInvocation, prepared_call: PreparedMcpCall, metadata: McpToolApprovalMetadata, item_metadata: McpToolCallItemMetadata, approval_application: McpToolApprovalApplication, ) -> HandledMcpToolCall { let turn_context = step_context.turn.as_ref(); let server = invocation.server.clone(); let tool_name = invocation.tool.clone(); let arguments_value = invocation.arguments.clone(); let server_origin = prepared_call.server_origin().map(str::to_string); let start = Instant::now(); let tool_input = arguments_value .clone() .unwrap_or_else(|| JsonValue::Object(serde_json::Map::new())); let mut request_error_code = None; let result = async { let result = async { let result = prepared_call .call_with_preparation(/*requested_timeout*/ None, || async { if let McpToolApprovalApplication::Apply { decision, policy } = &approval_application { let session_approval_key = session_mcp_tool_approval_key( &invocation, Some(&metadata), policy.mode, ); let persistent_approval_key = if policy.allow_persistent { persistent_mcp_tool_approval_key( &invocation, Some(&metadata), policy.mode, ) } else { None }; apply_mcp_tool_approval_decision( sess, turn_context, decision, session_approval_key, persistent_approval_key, ) .await; } let mut request_meta = build_mcp_tool_call_request_meta( step_context, &server, call_id, Some(&metadata), ); if let Some(recipient) = sess .services .thread_extension_data .get::() && recipient.matches( prepared_call.server_name(), &prepared_call.config().mcp_server_catalog, ) && let Some(JsonValue::Object(meta)) = &mut request_meta { meta.insert( "x-codex-root-turn-id".into(), serde_json::json!(turn_context.turn_metadata_state.root_turn_id()), ); } let request_meta = with_mcp_tool_call_ids_meta( request_meta, &sess.thread_id.to_string(), &sess.session_id().to_string(), originating_call, ); let request_meta = augment_mcp_tool_request_meta_with_sandbox_state( step_context, &prepared_call, request_meta, ) .await?; let mcp_call_trace = sess .services .rollout_thread_trace .start_mcp_call_trace(call_id); let mut request_meta = mcp_call_trace.add_request_meta(request_meta); if let Some(hook) = sess .services .thread_extension_data .get::() { hook.apply( &prepared_call, sess.thread_id, &turn_context.sub_id, call_id, &mut request_meta, ) .await?; } // The model-supplied arguments are what the MCP server receives. Ok((arguments_value, request_meta)) }) .await .map_err(|error| { request_error_code = akode_rmcp_client::request_error_code(&error); format!("tool call error: {error:?}") }); // Keep the backend response intact, before callbacks or model/UI limits can change it. sess.services.rollout_thread_trace.record_mcp_tool_result( &turn_context.sub_id, call_id, &result, ); let mut result = result?; let mcp_tool = McpToolContext::from_prepared_call( &prepared_call, turn_context.config.mcp_servers.get().get(&server), ); process_mcp_tool_result( sess, turn_context, call_id, &mcp_tool, &tool_input, &mut result, ) .await; sanitize_mcp_tool_result_for_model( &step_context.settings.model_info.input_modalities, Ok(result), ) } .await; record_mcp_result_span_telemetry(&Span::current(), &result, request_error_code); result } .instrument(mcp_tool_call_span( sess, turn_context, McpToolCallSpanFields { server_name: &server, tool_name: &tool_name, call_id, server_origin: server_origin.as_deref(), }, )) .await; if let Err(error) = &result { tracing::warn!("MCP tool call error: {error:?}"); } let duration = start.elapsed(); // Direct and Code Mode calls share this boundary. Once an approved call enters // it, conservatively attribute returned errors too: they may contain peer data. sess.services.executed_tool_calls.record_mcp_source( akode_protocol::mcp::McpAttributionSource { connector_id: None, plugin_id: prepared_call.plugin_id().map(str::to_string), server_name: prepared_call.server_name().to_string(), tool_name: prepared_call.tool_info().tool.name.to_string(), first_turn_id: turn_context.sub_id.clone(), }, ); notify_mcp_tool_call_completed( sess, turn_context, call_id, invocation, item_metadata, duration, truncate_mcp_tool_result_for_event(&result), ) .await; let outcome = mcp_call_metric_outcome(&result).with_request_error_code(request_error_code); emit_mcp_call_metrics( &step_context.session_telemetry, &outcome, &server, &tool_name, Some(duration), ); HandledMcpToolCall { result: CallToolResult::from_result(result), tool_input, } } fn mcp_tool_call_span( session: &Session, turn_context: &TurnContext, fields: McpToolCallSpanFields<'_>, ) -> Span { let transport = match fields.server_origin { Some("stdio") => "stdio", Some("in_process") => "in_process", Some(_) => "streamable_http", None => "", }; let span = tracing::info_span!( "mcp.tools.call", otel.kind = "client", rpc.system = "jsonrpc", rpc.method = "tools/call", mcp.server.name = fields.server_name, mcp.server.origin = fields.server_origin.unwrap_or(""), mcp.transport = transport, tool.name = fields.tool_name, tool.call_id = fields.call_id, conversation.id = %session.thread_id, session.id = %session.thread_id, turn.id = turn_context.sub_id.as_str(), server.address = Empty, server.port = Empty, codex.mcp.target.id = Empty, codex.mcp.server_user_flow.triggered = Empty, error.type = Empty, codex.mcp.error.code = Empty, ); record_server_fields(&span, fields.server_origin); span } struct McpToolCallSpanFields<'a> { server_name: &'a str, tool_name: &'a str, call_id: &'a str, server_origin: Option<&'a str>, } fn record_server_fields(span: &Span, url: Option<&str>) { let Some(url) = url else { return; }; let Ok(parsed) = Url::parse(url) else { return; }; if let Some(host) = parsed.host_str() { span.record("server.address", host); } if let Some(port) = parsed.port_or_known_default() { span.record("server.port", port as i64); } } fn record_mcp_result_span_telemetry( span: &Span, result: &Result, request_error_code: Option<&str>, ) { let outcome = mcp_call_metric_outcome(result).with_request_error_code(request_error_code); record_mcp_call_outcome_span_telemetry(span, &outcome); let Some(span_telemetry) = result .as_ref() .ok() .and_then(|result| result.meta.as_ref()) .and_then(JsonValue::as_object) .and_then(|meta| meta.get(MCP_RESULT_TELEMETRY_META_KEY)) .and_then(JsonValue::as_object) .and_then(|telemetry| telemetry.get(MCP_RESULT_TELEMETRY_SPAN_KEY)) .and_then(JsonValue::as_object) else { return; }; if let Some(target_id) = span_telemetry .get(MCP_RESULT_TELEMETRY_TARGET_ID_KEY) .and_then(JsonValue::as_str) .filter(|target_id| !target_id.is_empty()) { span.record( MCP_RESULT_TELEMETRY_TARGET_ID_SPAN_ATTR, truncate_str_to_char_boundary(target_id, MCP_RESULT_TELEMETRY_TARGET_ID_MAX_CHARS), ); } if let Some(did_trigger_server_user_flow) = span_telemetry .get(MCP_RESULT_TELEMETRY_DID_TRIGGER_SERVER_USER_FLOW_KEY) .and_then(JsonValue::as_bool) { span.record( MCP_RESULT_TELEMETRY_SERVER_USER_FLOW_SPAN_ATTR, did_trigger_server_user_flow, ); } } fn truncate_str_to_char_boundary(value: &str, max_chars: usize) -> &str { match value.char_indices().nth(max_chars) { Some((index, _)) => &value[..index], None => value, } } async fn augment_mcp_tool_request_meta_with_sandbox_state( step_context: &StepContext, prepared_call: &PreparedMcpCall, mut meta: Option, ) -> anyhow::Result> { let supports_sandbox_state_meta = prepared_call .server_supports_sandbox_state_meta_capability() .await .unwrap_or(false); if !supports_sandbox_state_meta { return Ok(meta); } let server_environment_id = prepared_call.server_environment_id(); let Some(sandbox_cwd) = prepared_call .config() .environment_cwds .get(server_environment_id) .cloned() .or_else(|| sandbox_cwd_for_mcp_server(step_context, server_environment_id)) else { return Ok(meta); }; // TODO(anp): Build this metadata from the server's captured // TurnEnvironment::sandbox_context instead of the runtime-wide Landlock value. prepared_call .augment_sandbox_metadata( &mut meta, SandboxState { permission_profile: prepared_call.permission_profile().clone(), codex_linux_sandbox_exe: prepared_call.config().codex_linux_sandbox_exe.clone(), sandbox_cwd, use_legacy_landlock: prepared_call.config().use_legacy_landlock, use_mxc: prepared_call .config() .environment_use_mxc .get(server_environment_id) .copied() .unwrap_or(false), }, ) .await?; Ok(meta) } fn sandbox_cwd_for_mcp_server(step_context: &StepContext, environment_id: &str) -> Option { if let Some(environment) = step_context .environments .turn_environments() .find(|environment| environment.selection.environment_id == environment_id) { return Some(environment.cwd().clone()); } if environment_id == akode_config::DEFAULT_MCP_SERVER_ENVIRONMENT_ID { #[allow(deprecated)] return Some(PathUri::from_abs_path(&step_context.turn.cwd)); } None } fn sanitize_mcp_tool_result_for_model( input_modalities: &[InputModality], result: Result, ) -> Result { let supports_image_input = input_modalities.contains(&InputModality::Image); let supports_audio_input = input_modalities.contains(&InputModality::Audio); if supports_image_input && supports_audio_input { return result; } result.map(|call_tool_result| CallToolResult { content: call_tool_result .content .iter() .map(|block| { if let Some(content_type) = block.get("type").and_then(serde_json::Value::as_str) { if content_type == "image" && !supports_image_input { return serde_json::json!({ "type": "text", "text": "", }); } if content_type == "audio" && !supports_audio_input { return serde_json::json!({ "type": "text", "text": "