diff --git a/codex-rs/analytics/src/client.rs b/codex-rs/analytics/src/client.rs index 32d66da972..7174197dd9 100644 --- a/codex-rs/analytics/src/client.rs +++ b/codex-rs/analytics/src/client.rs @@ -751,6 +751,15 @@ impl AnalyticsEventsClient { )); } + pub fn track_mcp_runtime_refresh( + &self, + event: crate::mcp_runtime_refresh::McpRuntimeRefreshEvent, + ) { + self.record_fact(AnalyticsFact::Custom( + CustomAnalyticsFact::McpRuntimeRefresh(Box::new(event)), + )); + } + pub fn track_image_preparation(&self, fact: ImagePreparationFact) { self.record_fact(AnalyticsFact::Custom( CustomAnalyticsFact::ImagePreparation(Box::new(fact)), diff --git a/codex-rs/analytics/src/events.rs b/codex-rs/analytics/src/events.rs index b2453caafc..ee8166dd29 100644 --- a/codex-rs/analytics/src/events.rs +++ b/codex-rs/analytics/src/events.rs @@ -80,6 +80,7 @@ pub(crate) enum TrackEventRequest { Compaction(Box), Goal(Box), ThreadHintStatus(Box), + McpRuntimeRefresh(Box), TurnEvent(Box), TurnSteer(CodexTurnSteerEventRequest), ArtifactOperation(CodexArtifactOperationEventRequest), @@ -178,6 +179,7 @@ impl TrackEventRequest { Self::Compaction(event) => event.event_type, Self::Goal(event) => event.event_type, Self::ThreadHintStatus(event) => event.event_type, + Self::McpRuntimeRefresh(event) => event.event_type, Self::TurnEvent(event) => event.event_type, Self::TurnSteer(event) => event.event_type, Self::ArtifactOperation(event) => event.event_type, diff --git a/codex-rs/analytics/src/facts.rs b/codex-rs/analytics/src/facts.rs index dcebb56141..7e4e1970df 100644 --- a/codex-rs/analytics/src/facts.rs +++ b/codex-rs/analytics/src/facts.rs @@ -621,6 +621,7 @@ pub(crate) enum CustomAnalyticsFact { Compaction(Box), Goal(Box), ThreadHintStatus(Box), + McpRuntimeRefresh(Box), GuardianReview(Box), GuardianV2(Box), TurnResolvedConfig(Box), diff --git a/codex-rs/analytics/src/lib.rs b/codex-rs/analytics/src/lib.rs index 768903d898..7666dad3b5 100644 --- a/codex-rs/analytics/src/lib.rs +++ b/codex-rs/analytics/src/lib.rs @@ -6,6 +6,7 @@ mod event_transport; mod events; mod facts; mod guardian_v2; +mod mcp_runtime_refresh; mod product_attribution; mod reducer; mod thread_hint; @@ -84,6 +85,7 @@ pub use facts::TurnTokenUsageFact; pub use facts::build_track_events_context; pub use guardian_v2::GuardianV2Event; pub use guardian_v2::GuardianV2EventKind; +pub use mcp_runtime_refresh::McpRuntimeRefreshEvent; pub use product_attribution::ThreadProductUpdate; pub use thread_hint::ThreadHintStatus; pub use thread_hint::ThreadHintStatusEvent; diff --git a/codex-rs/analytics/src/mcp_runtime_refresh.rs b/codex-rs/analytics/src/mcp_runtime_refresh.rs new file mode 100644 index 0000000000..726ab0af32 --- /dev/null +++ b/codex-rs/analytics/src/mcp_runtime_refresh.rs @@ -0,0 +1,32 @@ +//! MCP runtime publication analytics without configuration contents. + +use crate::events::CodexAppServerClientMetadata; +use crate::events::CodexRuntimeMetadata; +use codex_protocol::protocol::ThreadSource; +use serde::Serialize; + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct McpRuntimeRefreshEvent { + pub thread_id: String, + pub reasons: Vec, + pub occurred_at_ms: u64, +} + +#[derive(Serialize)] +pub(crate) struct McpRuntimeRefreshEventRequest { + pub(crate) event_type: &'static str, + pub(crate) event_params: McpRuntimeRefreshEventParams, +} + +#[derive(Serialize)] +pub(crate) struct McpRuntimeRefreshEventParams { + pub(crate) thread_id: String, + pub(crate) session_id: String, + pub(crate) app_server_client: CodexAppServerClientMetadata, + pub(crate) runtime: CodexRuntimeMetadata, + pub(crate) reasons: Vec, + pub(crate) occurred_at_ms: u64, + pub(crate) thread_source: Option, + pub(crate) subagent_source: Option, + pub(crate) parent_thread_id: Option, +} diff --git a/codex-rs/analytics/src/product_attribution.rs b/codex-rs/analytics/src/product_attribution.rs index da5958f35d..f5a848fcf7 100644 --- a/codex-rs/analytics/src/product_attribution.rs +++ b/codex-rs/analytics/src/product_attribution.rs @@ -82,6 +82,7 @@ fn event_thread_id(event: &TrackEventRequest) -> Option<&str> { TrackEventRequest::Compaction(event) => Some(&event.event_params.thread_id), TrackEventRequest::Goal(event) => Some(&event.event_params.thread_id), TrackEventRequest::ThreadHintStatus(event) => Some(&event.event_params.thread_id), + TrackEventRequest::McpRuntimeRefresh(event) => Some(&event.event_params.thread_id), TrackEventRequest::TurnEvent(event) => Some(&event.event_params.thread_id), TrackEventRequest::TurnSteer(event) => Some(&event.event_params.thread_id), TrackEventRequest::ArtifactOperation(event) => Some(&event.event_params.thread_id), diff --git a/codex-rs/analytics/src/reducer.rs b/codex-rs/analytics/src/reducer.rs index d4d5bc90b3..b9c2ad774f 100644 --- a/codex-rs/analytics/src/reducer.rs +++ b/codex-rs/analytics/src/reducer.rs @@ -123,6 +123,9 @@ use crate::facts::TurnTokenUsageFact; use crate::guardian_v2::GuardianV2EventKind; use crate::guardian_v2::GuardianV2EventParams; use crate::guardian_v2::GuardianV2EventRequest; +use crate::mcp_runtime_refresh::McpRuntimeRefreshEvent; +use crate::mcp_runtime_refresh::McpRuntimeRefreshEventParams; +use crate::mcp_runtime_refresh::McpRuntimeRefreshEventRequest; use crate::now_unix_millis; use crate::now_unix_seconds; use crate::option_i64_to_u64; @@ -212,6 +215,7 @@ pub(crate) fn valid_plugin_measurement_row(row: &PluginMeasurementRow) -> bool { // Match the fact queue capacity: analytics must not retain an unlimited number // of incomplete turns when lifecycle facts are dropped. const MAX_PENDING_TURNS: usize = 256; +const MAX_PENDING_MCP_RUNTIME_REFRESHES: usize = 256; #[derive(Default)] pub(crate) struct AnalyticsReducer { @@ -227,6 +231,7 @@ pub(crate) struct AnalyticsReducer { item_review_summaries: HashMap, // Bounded to 256 entries, keeping linear lookups small; evict the oldest entry when full. pending_mcp_tool_elicitations: VecDeque<(ToolItemKey, ElicitationType)>, + pending_mcp_runtime_refreshes: VecDeque, } struct ConnectionState { @@ -378,6 +383,12 @@ impl<'a> AnalyticsDropSite<'a> { } } +type ThreadContext<'a> = ( + &'a ConnectionState, + &'a ThreadAnalyticsState, + &'a ThreadMetadataState, +); + enum MissingAnalyticsContext { ThreadConnection, Connection { connection_id: u64 }, @@ -777,6 +788,9 @@ impl AnalyticsReducer { ))); } } + CustomAnalyticsFact::McpRuntimeRefresh(input) => { + self.ingest_mcp_runtime_refresh(*input, out); + } CustomAnalyticsFact::GuardianV2(input) => { let event_type = match &input.kind { GuardianV2EventKind::Classification { .. } => { @@ -1339,6 +1353,56 @@ impl AnalyticsReducer { subagent_thread_started_event_request(input), )); } + self.flush_pending_mcp_runtime_refreshes(out); + } + + fn ingest_mcp_runtime_refresh( + &mut self, + input: McpRuntimeRefreshEvent, + out: &mut Vec, + ) { + if let Some(event) = self.mcp_runtime_refresh_request(&input) { + out.push(event); + return; + } + if self.pending_mcp_runtime_refreshes.len() >= MAX_PENDING_MCP_RUNTIME_REFRESHES { + self.pending_mcp_runtime_refreshes.pop_front(); + } + self.pending_mcp_runtime_refreshes.push_back(input); + } + + fn flush_pending_mcp_runtime_refreshes(&mut self, out: &mut Vec) { + let pending = std::mem::take(&mut self.pending_mcp_runtime_refreshes); + for input in pending { + if let Some(event) = self.mcp_runtime_refresh_request(&input) { + out.push(event); + } else { + self.pending_mcp_runtime_refreshes.push_back(input); + } + } + } + + fn mcp_runtime_refresh_request( + &self, + input: &McpRuntimeRefreshEvent, + ) -> Option { + let (connection, thread, metadata) = self.thread_context(&input.thread_id).ok()?; + Some(TrackEventRequest::McpRuntimeRefresh(Box::new( + McpRuntimeRefreshEventRequest { + event_type: "codex_mcp_runtime_refresh_event", + event_params: McpRuntimeRefreshEventParams { + thread_id: input.thread_id.clone(), + session_id: metadata.session_id.clone(), + app_server_client: thread.app_server_client(connection), + runtime: connection.runtime.clone(), + reasons: input.reasons.clone(), + occurred_at_ms: input.occurred_at_ms, + thread_source: metadata.thread_source.clone(), + subagent_source: metadata.subagent_source.clone(), + parent_thread_id: metadata.parent_thread_id.clone(), + }, + }, + ))) } fn ingest_guardian_review( @@ -2523,6 +2587,7 @@ impl AnalyticsReducer { }, }, )); + self.flush_pending_mcp_runtime_refreshes(out); } fn ingest_compaction(&mut self, input: CodexCompactionEvent, out: &mut Vec) { @@ -2887,39 +2952,39 @@ impl AnalyticsReducer { thread.connection_id } - fn thread_connection_or_warn( - &self, - drop_site: AnalyticsDropSite<'_>, - ) -> Option<&ConnectionState> { - let Some(connection_id) = self.thread_connection_id(drop_site.thread_id) else { - warn_missing_analytics_context(&drop_site, MissingAnalyticsContext::ThreadConnection); - return None; - }; - let Some(connection_state) = self.connections.get(&connection_id) else { - warn_missing_analytics_context( - &drop_site, - MissingAnalyticsContext::Connection { connection_id }, - ); - return None; - }; - Some(connection_state) - } - fn thread_context_or_warn( &self, drop_site: AnalyticsDropSite<'_>, - ) -> Option<( - &ConnectionState, - &ThreadAnalyticsState, - &ThreadMetadataState, - )> { - let connection_state = self.thread_connection_or_warn(drop_site)?; - let thread_state = self.threads.get(drop_site.thread_id)?; - let Some(thread_metadata) = thread_state.metadata.as_ref() else { - warn_missing_analytics_context(&drop_site, MissingAnalyticsContext::ThreadMetadata); - return None; - }; - Some((connection_state, thread_state, thread_metadata)) + ) -> Option> { + match self.thread_context(drop_site.thread_id) { + Ok(context) => Some(context), + Err(missing) => { + warn_missing_analytics_context(&drop_site, missing); + None + } + } + } + + fn thread_context( + &self, + thread_id: &str, + ) -> Result, MissingAnalyticsContext> { + let connection_id = self + .thread_connection_id(thread_id) + .ok_or(MissingAnalyticsContext::ThreadConnection)?; + let connection = self + .connections + .get(&connection_id) + .ok_or(MissingAnalyticsContext::Connection { connection_id })?; + let thread = self + .threads + .get(thread_id) + .ok_or(MissingAnalyticsContext::ThreadConnection)?; + let metadata = thread + .metadata + .as_ref() + .ok_or(MissingAnalyticsContext::ThreadMetadata)?; + Ok((connection, thread, metadata)) } } diff --git a/codex-rs/core/config.schema.json b/codex-rs/core/config.schema.json index 55826ef220..69fabdec66 100644 --- a/codex-rs/core/config.schema.json +++ b/codex-rs/core/config.schema.json @@ -1222,6 +1222,9 @@ "mcp_oauth_refresh_coordination": { "type": "boolean" }, + "mcp_refresh_reason_telemetry": { + "type": "boolean" + }, "mcp_shared_repl_cwd": { "type": "boolean" }, @@ -8700,6 +8703,9 @@ "mcp_oauth_refresh_coordination": { "type": "boolean" }, + "mcp_refresh_reason_telemetry": { + "type": "boolean" + }, "mcp_shared_repl_cwd": { "type": "boolean" }, diff --git a/codex-rs/core/src/session/mcp.rs b/codex-rs/core/src/session/mcp.rs index 54f5716a47..811fd6b6ba 100644 --- a/codex-rs/core/src/session/mcp.rs +++ b/codex-rs/core/src/session/mcp.rs @@ -1,3 +1,4 @@ +use super::mcp_refresh::McpRefreshInvalidationGuard; use super::mcp_refresh::McpRefreshPermit; use super::mcp_runtime::McpDesiredState; use super::*; @@ -284,7 +285,7 @@ impl Session { ); } } - let Some(mut refresh_invalidation) = self.mcp_refresh.claim(self.thread_id) else { + let Some(refresh_invalidation) = self.mcp_refresh.claim(self.thread_id) else { return; }; let auth = self.services.auth_manager.auth().await; @@ -311,7 +312,7 @@ impl Session { Some(self.mcp_elicitation_reviewer()), ) .await; - refresh_invalidation.published = true; + self.finish_mcp_refresh(refresh_invalidation); } } @@ -428,7 +429,7 @@ impl Session { .await .map_err(|_| anyhow::anyhow!("MCP runtime refresh semaphore closed"))?; // This is forced work even when there was no pending invalidation. - let mut refresh_invalidation = self + let refresh_invalidation = self .mcp_refresh .claim_forced(self.thread_id, McpRefreshReason::HardRefreshCodexAppsTools); let auth = self.services.auth_manager.auth().await; @@ -473,7 +474,9 @@ impl Session { .scope(self.services.mcp_runtime.replace_fresh(input)) .await; self.services.thread_extension_data.insert(selected_plugins); - refresh_invalidation.published = refreshed.is_ok(); + if refreshed.is_ok() { + self.finish_mcp_refresh(refresh_invalidation); + } refreshed } @@ -482,6 +485,15 @@ impl Session { self.services.mcp_runtime.invalidate_apps_tool_refresh(); } + fn finish_mcp_refresh(&self, mut refresh: McpRefreshInvalidationGuard<'_>) { + refresh.mark_published(); + if self.enabled(Feature::McpRefreshReasonTelemetry) { + self.services + .analytics_events_client + .track_mcp_runtime_refresh(refresh.analytics_event(self.thread_id)); + } + } + #[tracing::instrument( name = "mcp.runtime.resolve_for_step", skip_all, @@ -908,7 +920,7 @@ impl Session { state.session_configuration.original_config_do_not_use = Arc::new(config); } // Claim after config mutation, before capturing the state this forced refresh handles. - let mut refresh_invalidation = self + let refresh_invalidation = self .mcp_refresh .claim_forced(self.thread_id, McpRefreshReason::SkillMcpDependenciesAdded); let auth = self.services.auth_manager.auth().await; @@ -951,7 +963,7 @@ impl Session { elicitation_reviewer, ) .await; - refresh_invalidation.published = true; + self.finish_mcp_refresh(refresh_invalidation); } pub(crate) fn ready_selected_capability_roots( diff --git a/codex-rs/core/src/session/mcp_refresh.rs b/codex-rs/core/src/session/mcp_refresh.rs index e2a6714515..cf248c0c24 100644 --- a/codex-rs/core/src/session/mcp_refresh.rs +++ b/codex-rs/core/src/session/mcp_refresh.rs @@ -1,5 +1,7 @@ use crate::McpRefreshReason; +use codex_analytics::McpRuntimeRefreshEvent; use codex_protocol::ThreadId; +use indexmap::IndexSet; use std::collections::BTreeSet; use std::sync::Mutex; use std::sync::atomic::AtomicBool; @@ -126,7 +128,27 @@ pub(super) struct McpRefreshPermit<'a> { pub(super) struct McpRefreshInvalidationGuard<'a> { refresh: &'a McpRefresh, reasons: BTreeSet, - pub(super) published: bool, + published: bool, +} + +impl McpRefreshInvalidationGuard<'_> { + pub(super) fn mark_published(&mut self) { + self.published = true; + } + + pub(super) fn analytics_event(&self, thread_id: ThreadId) -> McpRuntimeRefreshEvent { + // Multiple plugin change IDs can map to the same exported reason. + let labels: IndexSet<_> = self + .reasons + .iter() + .map(McpRefreshReason::telemetry_label) + .collect(); + McpRuntimeRefreshEvent { + thread_id: thread_id.to_string(), + reasons: labels.into_iter().map(str::to_owned).collect(), + occurred_at_ms: codex_analytics::now_unix_millis(), + } + } } impl Drop for McpRefreshInvalidationGuard<'_> { diff --git a/codex-rs/core/src/thread_manager.rs b/codex-rs/core/src/thread_manager.rs index 216f911c92..5715aa063b 100644 --- a/codex-rs/core/src/thread_manager.rs +++ b/codex-rs/core/src/thread_manager.rs @@ -280,7 +280,7 @@ enum ShutdownOutcome { type StartupMcpInvalidations = std::sync::Mutex>; -/// Identifies the cause of an MCP runtime publication in CLI diagnostics. +/// Identifies the cause of an MCP runtime publication in diagnostics and telemetry. #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] pub enum McpRefreshReason { AccountAuthReloaded, @@ -325,6 +325,52 @@ pub enum McpRefreshReason { InstalledPluginMetadata(uuid::Uuid), } +impl McpRefreshReason { + pub(crate) fn telemetry_label(&self) -> &'static str { + match self { + Self::AccountAuthReloaded => "account_auth_reloaded", + Self::AccountLoggedOut => "account_logged_out", + Self::AccountLoginCompleted => "account_login_completed", + Self::AccountPluginCacheChanged => "account_plugin_cache_changed", + Self::AccountWorkspaceSwitched => "account_workspace_switched", + Self::AuthChangeNotification => "auth_change_notification", + Self::CodexAppsToolRefresh => "codex_apps_tool_refresh", + Self::CurrentEnvironmentsChanged => "current_environments_changed", + Self::DisabledPluginSelectionChanged => "disabled_plugin_selection_changed", + Self::EffectivePluginsChanged => "effective_plugins_changed", + Self::EnterpriseAuthDisabled => "enterprise_auth_disabled", + Self::EnvironmentBindingsChanged => "environment_bindings_changed", + Self::ExecutorCapabilityDiscoveryRecovered => "executor_capability_discovery_recovered", + Self::ExecutorCapabilityInventoryChanged => "executor_capability_inventory_changed", + Self::ExplicitInvalidation => "explicit_invalidation", + Self::ExplicitServerReconnect => "explicit_server_reconnect", + Self::ExtensionCatalogChanged => "extension_catalog_changed", + Self::HardRefreshCodexAppsTools => "hard_refresh_codex_apps_tools", + Self::MarketplaceUpgraded => "marketplace_upgraded", + Self::McpConfigReloaded => "mcp_config_reloaded", + Self::McpOAuthLoginCompleted => "mcp_oauth_login_completed", + Self::NonCuratedPluginCacheRefreshed => "non_curated_plugin_cache_refreshed", + Self::OAuthCredentialsRecovered => "oauth_credentials_recovered", + Self::PluginInstalled => "plugin_installed", + Self::PluginOAuthLoginCompleted => "plugin_oauth_login_completed", + Self::PluginUninstalled => "plugin_uninstalled", + Self::PreviousRefreshUnpublished => "previous_refresh_unpublished", + Self::RemotePluginUninstalled => "remote_plugin_uninstalled", + Self::RuntimeAuthChanged => "runtime_auth_changed", + Self::SelectedCapabilityRootsChanged => "selected_capability_roots_changed", + Self::ServerStartupFailed => "server_startup_failed", + Self::SessionMcpInputsChanged => "session_mcp_inputs_changed", + Self::SessionPermissionsGranted => "session_permissions_granted", + Self::SkillMcpDependenciesAdded => "skill_mcp_dependencies_added", + Self::TaskStartedExecutorDiscovery => "task_started_executor_discovery", + Self::TurnStartContributorPreparedMcp => "turn_start_contributor_prepared_mcp", + Self::UserConfigFilesReloaded => "user_config_files_reloaded", + Self::UserConfigReloaded => "user_config_reloaded", + Self::InstalledPluginMetadata(_) => "installed_plugin_metadata", + } + } +} + /// [`ThreadManager`] is responsible for creating threads and maintaining /// them in memory. pub struct ThreadManager { diff --git a/codex-rs/core/tests/suite/mcp_auth_elicitation.rs b/codex-rs/core/tests/suite/mcp_auth_elicitation.rs index e096d544c6..52afc71448 100644 --- a/codex-rs/core/tests/suite/mcp_auth_elicitation.rs +++ b/codex-rs/core/tests/suite/mcp_auth_elicitation.rs @@ -1,9 +1,10 @@ -//! Verify MCP prompts and elicitation analytics through actual turns. +//! Exercise MCP analytics with real Core sessions and a mock analytics backend. use anyhow::Result; use codex_analytics::AnalyticsEventsClient; use codex_analytics::AppServerRpcTransport; use codex_app_server_protocol as app; +use codex_core::McpRefreshReason; use codex_core::RestrictRootCapabilities; use codex_core::StartThreadOptions; use codex_core::TurnInputRequest; @@ -16,6 +17,7 @@ use codex_extension_api::ToolLifecycleFuture; use codex_features::Feature; use codex_login::CodexAuth; use codex_mcp::CODEX_APPS_MCP_SERVER_NAME; +use codex_mcp::McpSnapshotDetail; use codex_protocol::SessionId; use codex_protocol::approvals::ElicitationRequest; use codex_protocol::config_types::ApprovalsReviewer; @@ -40,15 +42,20 @@ use core_test_support::apps_test_server::recorded_apps_tool_calls; use core_test_support::apps_test_server::search_capable_apps_builder; use core_test_support::responses; use core_test_support::skip_if_no_network; +use core_test_support::test_codex::TestCodex; +use core_test_support::test_codex::test_codex; use core_test_support::wait_for_event; use core_test_support::wait_for_mcp_server; +use futures::FutureExt; use pretty_assertions::assert_eq; use serde_json::Value; use serde_json::json; use std::sync::Arc; use std::time::Duration; use test_case::test_case; +use uuid::Uuid; use wiremock::Mock; +use wiremock::MockServer; use wiremock::Request; use wiremock::Respond; use wiremock::ResponseTemplate; @@ -139,6 +146,114 @@ impl ToolLifecycleContributor for RemoveAuthMetadata { } } +async fn analytics_client(server: &MockServer) -> AnalyticsEventsClient { + Mock::given(method("POST")) + .and(path("/codex/analytics-events/events")) + .respond_with(ResponseTemplate::new(/*status*/ 200)) + .mount(server) + .await; + + AnalyticsEventsClient::new( + codex_core::test_support::auth_manager_from_auth( + CodexAuth::create_dummy_chatgpt_auth_for_testing(), + ), + server.uri(), + /*analytics_enabled*/ Some(true), + ) +} + +fn track_thread_start(client: &AnalyticsEventsClient, test: &TestCodex) -> Result<()> { + let session = &test.session_configured; + client.track_initialize( + /*connection_id*/ 1, + app::InitializeParams::default(), + "test-client".to_string(), + AppServerRpcTransport::Stdio, + ); + let thread_response = serde_json::from_value(json!({ + "thread": { + "id": session.thread_id, "sessionId": session.session_id.to_string(), "preview": "", + "ephemeral": false, "modelProvider": session.model_provider_id, + "createdAt": 1, "updatedAt": 1, "status": {"type": "idle"}, + "cwd": session.cwd, "cliVersion": "0.0.0", "source": "exec", "turns": [], + }, + "model": session.model, "modelProvider": session.model_provider_id, "cwd": session.cwd, + "approvalPolicy": app::AskForApproval::from(session.approval_policy), + "approvalsReviewer": app::ApprovalsReviewer::from(session.approvals_reviewer), + "sandbox": app::SandboxPolicy::from(test.config.permissions.effective_permission_profile().to_legacy_sandbox_policy(test.config.cwd.as_path())?), + }))?; + client.track_response( + /*connection_id*/ 1, + app::RequestId::Integer(1), + &app::ClientResponsePayload::ThreadStart(thread_response), + ); + Ok(()) +} + +#[tokio::test] +async fn mcp_refresh_reports_distinct_reasons_after_thread_start() -> Result<()> { + skip_if_no_network!(Ok(())); + const EVENT: &str = "codex_mcp_runtime_refresh_event"; + let server = responses::start_mock_server().await; + let client = analytics_client(&server).await; + let test = test_codex() + .with_analytics_events_client(client.clone()) + .with_config(|config| { + config + .features + .set_enabled(Feature::McpRefreshReasonTelemetry, /*enabled*/ true) + .expect("refresh telemetry should be configurable"); + }) + .build_with_auto_env(&server) + .await?; + + // On this single-thread runtime, queue every reason before prewarm can run. + for reason in [ + McpRefreshReason::InstalledPluginMetadata(Uuid::from_u128(1)), + McpRefreshReason::InstalledPluginMetadata(Uuid::from_u128(2)), + McpRefreshReason::PluginInstalled, + ] { + test.thread_manager + .invalidate_mcp_runtimes_for(reason) + .now_or_never() + .expect("uncontended invalidation should finish in one poll"); + } + // A status read waits for pending refreshes without starting a model turn. + test.codex + .mcp_server_status_snapshot( + "unused", + /*environment_id*/ None, + McpSnapshotDetail::ToolsAndAuthOnly, + /*expected_registration*/ None, + ) + .await?; + + client.flush().await; + assert!( + responses::received_analytics_events(&server, EVENT) + .await + .is_empty() + ); + track_thread_start(&client, &test)?; + client.flush().await; + + let events = responses::received_analytics_events(&server, EVENT).await; + let [event] = events.as_slice() else { + anyhow::bail!("expected one refresh event, received {events:?}"); + }; + let params = &event["event_params"]; + let session = &test.session_configured; + assert_eq!( + json!([params["thread_id"], params["session_id"], params["reasons"]]), + json!([ + session.thread_id, + session.session_id, + ["plugin_installed", "installed_plugin_metadata"] + ]) + ); + Ok(()) +} + #[test_case(Scenario::DefaultAuth; "auth requests elicitation by default")] #[test_case(Scenario::ModernAuth; "modern accepted auth")] #[test_case(Scenario::AuthMetadataRemoved; "auth metadata removed by callback")] @@ -158,11 +273,7 @@ async fn actual_turn_elicitation_analytics(scenario: Scenario) -> Result<()> { ); let server = responses::start_mock_server().await; AppsTestServer::mount_searchable(&server).await?; - Mock::given(method("POST")) - .and(path("/codex/analytics-events/events")) - .respond_with(ResponseTemplate::new(/*status*/ 200)) - .mount(&server) - .await; + let client = analytics_client(&server).await; if auth_failure { Mock::given(method("POST")) @@ -200,13 +311,6 @@ async fn actual_turn_elicitation_analytics(scenario: Scenario) -> Result<()> { ) .await; - let client = AnalyticsEventsClient::new( - codex_core::test_support::auth_manager_from_auth( - CodexAuth::create_dummy_chatgpt_auth_for_testing(), - ), - server.uri(), - /*analytics_enabled*/ Some(true), - ); let mut builder = search_capable_apps_builder(server.uri()) .with_analytics_events_client(client.clone()) .with_config(move |config| { @@ -244,29 +348,7 @@ approvals_reviewer = "user" let test = builder.build_with_auto_env(&server).await?; let session = &test.session_configured; let thread_id = session.thread_id.to_string(); - client.track_initialize( - /*connection_id*/ 1, - app::InitializeParams::default(), - "test-client".to_string(), - AppServerRpcTransport::Stdio, - ); - let thread_response = serde_json::from_value(json!({ - "thread": { - "id": thread_id, "sessionId": session.session_id.to_string(), "preview": "", - "ephemeral": false, "modelProvider": session.model_provider_id, - "createdAt": 1, "updatedAt": 1, "status": {"type": "idle"}, - "cwd": session.cwd, "cliVersion": "0.0.0", "source": "exec", "turns": [], - }, - "model": session.model, "modelProvider": session.model_provider_id, "cwd": session.cwd, - "approvalPolicy": app::AskForApproval::from(session.approval_policy), - "approvalsReviewer": app::ApprovalsReviewer::from(session.approvals_reviewer), - "sandbox": app::SandboxPolicy::from(test.config.permissions.effective_permission_profile().to_legacy_sandbox_policy(test.config.cwd.as_path())?), - }))?; - client.track_response( - /*connection_id*/ 1, - app::RequestId::Integer(1), - &app::ClientResponsePayload::ThreadStart(thread_response), - ); + track_thread_start(&client, &test)?; let request = TurnInputRequest::user_input(vec![UserInput::Text { text: "Use [$calendar](app://calendar) to create a calendar event.".to_string(), diff --git a/codex-rs/features/src/lib.rs b/codex-rs/features/src/lib.rs index 69554bf7c6..cf02753ecb 100644 --- a/codex-rs/features/src/lib.rs +++ b/codex-rs/features/src/lib.rs @@ -235,6 +235,8 @@ pub enum Feature { CwdRelativeTurnDiffs, /// Enable runtime metrics snapshots via a manual reader. RuntimeMetrics, + /// Record the causes consumed by successful MCP runtime refreshes. + McpRefreshReasonTelemetry, /// Capture internal direct-tool dependency paths for turn attribution. CriticalPathTiming, /// Enable startup memory extraction and file-backed memory consolidation. @@ -1572,6 +1574,12 @@ pub const FEATURES: &[FeatureSpec] = &[ stage: Stage::UnderDevelopment, default_enabled: false, }, + FeatureSpec { + id: Feature::McpRefreshReasonTelemetry, + key: "mcp_refresh_reason_telemetry", + stage: Stage::UnderDevelopment, + default_enabled: false, + }, FeatureSpec { id: Feature::CriticalPathTiming, key: "critical_path_timing",