Add elicitation classification support to app and MCP analytics (#45649)

## What changed

Add an optional `elicitation_type` to app-used and MCP tool-call events, with `auth_or_link` and `approval` classifications and `null` for unclassified calls. Existing core app-use tracking passes `None`.

Expose an API to queue MCP classifications by thread, turn, and item before completion. Preserve them across turn completion, consume them on item completion, and clear them on thread closure. Bound pending classifications to 256 entries, evicting the oldest when full.

## Testing

Add coverage for serialization, first-classification retention during app-use deduplication, per-call classification across turn completion, pending-state eviction and cleanup, and exclusion of tool arguments from emitted events.

GitOrigin-RevId: 185a2ccb38153e123fc731231edff0259a26bce3
This commit is contained in:
priyanshusingh-de authored and copyberry committed 2026-09-15 08:28:03 +00:00
1 parent a8964cb1ba
commit b0af519c39
9 files changed
+421 -42

No files matched your search

+144 -31
View File
@@ -6,6 +6,7 @@ use crate::events::CodexAcceptedLineFingerprintsEventRequest;
use crate::events::CodexAppMentionedEventRequest;
use crate::events::CodexAppServerClientMetadata;
use crate::events::CodexAppUsedEventRequest;
use crate::events::CodexAppUsedMetadata;
use crate::events::CodexCommandExecutionEventParams;
use crate::events::CodexCommandExecutionEventRequest;
use crate::events::CodexCompactionEventRequest;
@@ -66,6 +67,7 @@ use crate::facts::CompactionTrigger;
use crate::facts::ControlToolCallFact;
use crate::facts::ControlToolCallStatus;
use crate::facts::CustomAnalyticsFact;
use crate::facts::ElicitationType;
use crate::facts::ExternalAgentConfigImportCompletedInput;
use crate::facts::ExternalAgentConfigImportFailureInput;
use crate::facts::HookRunFact;
@@ -75,6 +77,7 @@ use crate::facts::ImagePreparationFact;
use crate::facts::ImagePreparationMetadata;
use crate::facts::InputError;
use crate::facts::InvocationType;
use crate::facts::McpToolCallElicitation;
use crate::facts::PluginInstallFailedInput;
use crate::facts::PluginInstallRequestSource;
use crate::facts::PluginInstallRequested;
@@ -1185,14 +1188,17 @@ fn app_used_event_serializes_expected_shape() {
let tracking = test_tracking_context("thread-2", "turn-2");
let event = TrackEventRequest::AppUsed(CodexAppUsedEventRequest {
event_type: "codex_app_used",
event_params: codex_app_metadata(
&tracking,
AppInvocation {
connector_id: Some("drive".to_string()),
app_name: Some("Google Drive".to_string()),
invocation_type: Some(InvocationType::Implicit),
},
),
event_params: CodexAppUsedMetadata {
app: codex_app_metadata(
&tracking,
AppInvocation {
connector_id: Some("drive".to_string()),
app_name: Some("Google Drive".to_string()),
invocation_type: Some(InvocationType::Implicit),
},
),
elicitation_type: None,
},
});
let payload = serde_json::to_value(&event).expect("serialize app used event");
@@ -1208,7 +1214,8 @@ fn app_used_event_serializes_expected_shape() {
"app_name": "Google Drive",
"product_client_id": TEST_PRODUCT_CLIENT_ID,
"invoke_type": "implicit",
"model_slug": "gpt-5"
"model_slug": "gpt-5",
"elicitation_type": null
}
})
);
@@ -1641,28 +1648,6 @@ fn compaction_implementation_serializes_remote_v2() {
assert_eq!(payload, json!("responses_compaction_v2"));
}
#[test]
fn app_used_dedupe_is_keyed_by_turn_and_connector() {
let (sender, _receiver) = mpsc::channel(1);
let queue = AnalyticsEventsQueue {
sender,
app_used_emitted_keys: Arc::new(Mutex::new(HashSet::new())),
plugin_used_emitted_keys: Arc::new(Mutex::new(HashSet::new())),
};
let app = AppInvocation {
connector_id: Some("calendar".to_string()),
app_name: Some("Calendar".to_string()),
invocation_type: Some(InvocationType::Implicit),
};
let turn_1 = test_tracking_context("thread-1", "turn-1");
let turn_2 = test_tracking_context("thread-1", "turn-2");
assert_eq!(queue.should_enqueue_app_used(&turn_1, &app), true);
assert_eq!(queue.should_enqueue_app_used(&turn_1, &app), false);
assert_eq!(queue.should_enqueue_app_used(&turn_2, &app), true);
}
#[test]
fn thread_initialized_event_serializes_expected_shape() {
let event = TrackEventRequest::ThreadInitialized(ThreadInitializedEvent {
@@ -4715,6 +4700,7 @@ async fn reducer_ingests_app_and_plugin_facts() {
app_name: Some("Drive".to_string()),
invocation_type: Some(InvocationType::Implicit),
},
elicitation_type: Some(ElicitationType::AuthOrLink),
})),
&mut events,
)
@@ -4733,6 +4719,10 @@ async fn reducer_ingests_app_and_plugin_facts() {
assert_eq!(payload.as_array().expect("events array").len(), 3);
assert_eq!(payload[0]["event_type"], "codex_app_mentioned");
assert_eq!(payload[1]["event_type"], "codex_app_used");
assert_eq!(
payload[1]["event_params"]["elicitation_type"],
"auth_or_link"
);
assert_eq!(payload[2]["event_type"], "codex_plugin_used");
assert_eq!(
payload[0]["event_params"]["product_client_id"],
@@ -5885,6 +5875,129 @@ async fn turn_event_counts_completed_tool_items() {
assert_eq!(payload["event_params"]["image_generation_count"], json!(1));
}
#[tokio::test]
async fn mcp_elicitation_classification_survives_turn_completion_and_preserves_call_grain() {
let mut reducer = AnalyticsReducer::default();
let mut events = Vec::new();
ingest_turn_prerequisites(
&mut reducer,
&mut events,
/*include_initialize*/ true,
/*include_resolved_config*/ true,
/*include_started*/ true,
/*include_token_usage*/ false,
)
.await;
let mut items = Vec::new();
for (item_id, connector_id, elicitation_type) in [
("auth", "calendar", Some(ElicitationType::AuthOrLink)),
("retry", "calendar", None),
("denied", "drive", Some(ElicitationType::Approval)),
] {
let item = ThreadItem::McpToolCall {
id: item_id.to_string(),
server: "server".to_string(),
tool: "search".to_string(),
status: McpToolCallStatus::Completed,
arguments: json!({ "token": "synthetic-private-input" }),
app_context: Some(McpToolCallAppContext {
connector_id: connector_id.to_string(),
link_id: None,
resource_uri: None,
app_name: None,
action_name: None,
}),
mcp_app_resource_uri: None,
plugin_id: None,
read_only_hint: None,
result: None,
error: None,
duration_ms: Some(2),
};
reducer
.ingest(
AnalyticsFact::Notification(Box::new(ServerNotification::ItemStarted(
ItemStartedNotification {
thread_id: "thread-2".to_string(),
turn_id: "turn-2".to_string(),
started_at_ms: 998,
item: item.clone(),
},
))),
&mut events,
)
.await;
if let Some(elicitation_type) = elicitation_type {
reducer
.ingest(
AnalyticsFact::Custom(CustomAnalyticsFact::McpToolCallElicitation(
McpToolCallElicitation {
thread_id: "thread-2".to_string(),
turn_id: "turn-2".to_string(),
item_id: item_id.to_string(),
elicitation_type,
},
)),
&mut events,
)
.await;
}
items.push(item);
}
reducer
.ingest(
AnalyticsFact::Notification(Box::new(sample_turn_completed_notification(
"thread-2",
"turn-2",
AppServerTurnStatus::Completed,
/*codex_error_info*/ None,
))),
&mut events,
)
.await;
for item in items {
reducer
.ingest(
AnalyticsFact::Notification(Box::new(ServerNotification::ItemCompleted(
ItemCompletedNotification {
thread_id: "thread-2".to_string(),
turn_id: "turn-2".to_string(),
completed_at_ms: 1_000,
item,
},
))),
&mut events,
)
.await;
}
let payload = serde_json::to_value(&events).expect("serialize analytics events");
let classifications = payload
.as_array()
.expect("analytics events array")
.iter()
.filter(|event| event["event_type"] == "codex_mcp_tool_call_event")
.map(|event| {
json!({
"item_id": event["event_params"]["item_id"],
"connector_id": event["event_params"]["connector_id"],
"elicitation_type": event["event_params"].get("elicitation_type")
.expect("elicitation_type must be present"),
})
})
.collect::<Vec<_>>();
assert_eq!(
classifications,
vec![
json!({"item_id": "auth", "connector_id": "calendar", "elicitation_type": "auth_or_link"}),
json!({"item_id": "retry", "connector_id": "calendar", "elicitation_type": null}),
json!({"item_id": "denied", "connector_id": "drive", "elicitation_type": "approval"}),
]
);
assert!(!payload.to_string().contains("synthetic-private-input"));
}
#[tokio::test]
async fn turn_and_tool_events_read_current_trusted_root() {
let mut reducer = AnalyticsReducer::default();