mirror of
https://github.com/openai/codex.git
synced 2026-11-24 23:20:47 +00:00
Report per-server MCP startup durations (#63613)
## Why Required MCP servers can finish at different times even when their startup notifications arrive together. Notification arrival times cannot show how long each server took to start. ## What changed Measure each startup attempt and expose its elapsed milliseconds as `durationMs` on `ready` and `failed` updates from `mcpServer/startupStatus/updated`. Successful Codex Apps reconnects report their own duration. Reused connections, `starting`, and `cancelled` updates carry `null`. The protocol accepts notifications from older servers that omit the field. ## Testing Cover distinct durations for fast and slow required servers, timing through lease registration for newly opened shared connections, and a fresh duration after Codex Apps recovery. GitOrigin-RevId: 39c0c418149dd2b220828be04d998085f57acf2d
This commit is contained in:
committed by
copyberry
parent
32119bac26
commit
abc92e6bd4
@@ -3139,6 +3139,15 @@
|
||||
},
|
||||
"McpServerStatusUpdatedNotification": {
|
||||
"properties": {
|
||||
"durationMs": {
|
||||
"description": "Elapsed startup time for a measured attempt. Older servers omit this field.",
|
||||
"format": "uint64",
|
||||
"minimum": 0.0,
|
||||
"type": [
|
||||
"integer",
|
||||
"null"
|
||||
]
|
||||
},
|
||||
"environmentId": {
|
||||
"description": "Registration scope, not necessarily the server's execution environment.",
|
||||
"type": [
|
||||
|
||||
+9
@@ -16327,6 +16327,15 @@
|
||||
"McpServerStatusUpdatedNotification": {
|
||||
"$schema": "http://json-schema.org/draft-07/schema#",
|
||||
"properties": {
|
||||
"durationMs": {
|
||||
"description": "Elapsed startup time for a measured attempt. Older servers omit this field.",
|
||||
"format": "uint64",
|
||||
"minimum": 0.0,
|
||||
"type": [
|
||||
"integer",
|
||||
"null"
|
||||
]
|
||||
},
|
||||
"environmentId": {
|
||||
"description": "Registration scope, not necessarily the server's execution environment.",
|
||||
"type": [
|
||||
|
||||
+9
@@ -12261,6 +12261,15 @@
|
||||
"McpServerStatusUpdatedNotification": {
|
||||
"$schema": "http://json-schema.org/draft-07/schema#",
|
||||
"properties": {
|
||||
"durationMs": {
|
||||
"description": "Elapsed startup time for a measured attempt. Older servers omit this field.",
|
||||
"format": "uint64",
|
||||
"minimum": 0.0,
|
||||
"type": [
|
||||
"integer",
|
||||
"null"
|
||||
]
|
||||
},
|
||||
"environmentId": {
|
||||
"description": "Registration scope, not necessarily the server's execution environment.",
|
||||
"type": [
|
||||
|
||||
+9
@@ -18,6 +18,15 @@
|
||||
}
|
||||
},
|
||||
"properties": {
|
||||
"durationMs": {
|
||||
"description": "Elapsed startup time for a measured attempt. Older servers omit this field.",
|
||||
"format": "uint64",
|
||||
"minimum": 0.0,
|
||||
"type": [
|
||||
"integer",
|
||||
"null"
|
||||
]
|
||||
},
|
||||
"environmentId": {
|
||||
"description": "Registration scope, not necessarily the server's execution environment.",
|
||||
"type": [
|
||||
|
||||
BIN
Binary file not shown.
BIN
Binary file not shown.
+5
-1
@@ -8,4 +8,8 @@ export type McpServerStatusUpdatedNotification = { threadId: string | null, name
|
||||
/**
|
||||
* Registration scope, not necessarily the server's execution environment.
|
||||
*/
|
||||
environmentId: string | null, status: McpServerStartupState, error: string | null, failureReason: McpServerStartupFailureReason | null, };
|
||||
environmentId: string | null, status: McpServerStartupState,
|
||||
/**
|
||||
* Elapsed startup time for a measured attempt. Older servers omit this field.
|
||||
*/
|
||||
durationMs?: number | null, error: string | null, failureReason: McpServerStartupFailureReason | null, };
|
||||
|
||||
@@ -2233,6 +2233,12 @@ mod tests {
|
||||
.ok_or_else(|| anyhow::anyhow!("missing MCP login completion fixture"))?,
|
||||
)?;
|
||||
assert!(mcp_login_completion_ts.contains("loginId?: string | null"));
|
||||
let mcp_status_update_ts = std::str::from_utf8(
|
||||
fixture_tree
|
||||
.get(Path::new("v2/McpServerStatusUpdatedNotification.ts"))
|
||||
.ok_or_else(|| anyhow::anyhow!("missing MCP status update fixture"))?,
|
||||
)?;
|
||||
assert!(mcp_status_update_ts.contains("durationMs?: number | null"));
|
||||
let typescript_index = std::str::from_utf8(
|
||||
fixture_tree
|
||||
.get(Path::new("index.ts"))
|
||||
@@ -2428,6 +2434,8 @@ mod tests {
|
||||
&& matches!(field_prefix.trim(), "startedAtMs?" | "completedAtMs?"))
|
||||
|| (path == Path::new("v2/McpServerOauthLoginCompletedNotification.ts")
|
||||
&& field_prefix.trim() == "loginId?")
|
||||
|| (path == Path::new("v2/McpServerStatusUpdatedNotification.ts")
|
||||
&& field_prefix.trim() == "durationMs?")
|
||||
|| (path == Path::new("v2/McpServerStatus.ts")
|
||||
&& field_prefix.trim() == "environmentId?")
|
||||
|| (path == Path::new("v2/ProcessExitedNotification.ts")
|
||||
|
||||
@@ -394,6 +394,9 @@ pub struct McpServerStatusUpdatedNotification {
|
||||
/// Registration scope, not necessarily the server's execution environment.
|
||||
pub environment_id: Option<String>,
|
||||
pub status: McpServerStartupState,
|
||||
/// Elapsed startup time for a measured attempt. Older servers omit this field.
|
||||
#[ts(type = "number | null", optional)]
|
||||
pub duration_ms: Option<u64>,
|
||||
pub error: Option<String>,
|
||||
pub failure_reason: Option<McpServerStartupFailureReason>,
|
||||
}
|
||||
|
||||
@@ -2783,7 +2783,7 @@ fn mcp_server_status_accepts_older_inventory_without_runtime_status() {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mcp_server_status_updated_accepts_missing_thread_id() {
|
||||
fn mcp_server_status_updated_accepts_missing_thread_id_and_duration() {
|
||||
let notification: McpServerStatusUpdatedNotification = serde_json::from_value(json!({
|
||||
"name": "optional_broken",
|
||||
"status": "failed",
|
||||
@@ -2796,6 +2796,7 @@ fn mcp_server_status_updated_accepts_missing_thread_id() {
|
||||
name: "optional_broken".to_string(),
|
||||
environment_id: None,
|
||||
status: McpServerStartupState::Failed,
|
||||
duration_ms: None,
|
||||
error: Some("handshake failed".to_string()),
|
||||
failure_reason: None,
|
||||
};
|
||||
@@ -2807,6 +2808,7 @@ fn mcp_server_status_updated_accepts_missing_thread_id() {
|
||||
"name": "optional_broken",
|
||||
"environmentId": null,
|
||||
"status": "failed",
|
||||
"durationMs": null,
|
||||
"error": "handshake failed",
|
||||
"failureReason": null,
|
||||
})
|
||||
@@ -2814,13 +2816,14 @@ fn mcp_server_status_updated_accepts_missing_thread_id() {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mcp_server_status_updated_serializes_failure_reason() {
|
||||
fn mcp_server_status_updated_serializes_failure_reason_and_duration() {
|
||||
let notification =
|
||||
ServerNotification::McpServerStatusUpdated(McpServerStatusUpdatedNotification {
|
||||
thread_id: Some("thread-1".to_string()),
|
||||
name: "expired-oauth".to_string(),
|
||||
environment_id: Some("remote".to_string()),
|
||||
status: McpServerStartupState::Failed,
|
||||
duration_ms: Some(482),
|
||||
error: Some("OAuth credentials expired".to_string()),
|
||||
failure_reason: Some(McpServerStartupFailureReason::ReauthenticationRequired),
|
||||
});
|
||||
@@ -2834,6 +2837,7 @@ fn mcp_server_status_updated_serializes_failure_reason() {
|
||||
"name": "expired-oauth",
|
||||
"environmentId": "remote",
|
||||
"status": "failed",
|
||||
"durationMs": 482,
|
||||
"error": "OAuth credentials expired",
|
||||
"failureReason": "reauthenticationRequired",
|
||||
},
|
||||
|
||||
@@ -588,6 +588,14 @@ switching models. Setting `friendly` or `pragmatic` can replace a previous
|
||||
thread's existing instructions or change explicitly supplied base instructions.
|
||||
The old `features.personality` flag is ignored.
|
||||
|
||||
# MCP server startup
|
||||
|
||||
`mcpServer/startupStatus/updated` reports each server's startup state. On
|
||||
`ready` or `failed`, `durationMs` gives the elapsed milliseconds for that
|
||||
server's startup attempt, even when notifications arrive together. It is null
|
||||
when there is no new measurement, including for reused connections, `starting`
|
||||
and `cancelled`. Older servers omit the field.
|
||||
|
||||
# MCP server capabilities
|
||||
|
||||
`mcpServerStatus/list` returns `serverCapabilities` for each initialized MCP server
|
||||
|
||||
@@ -243,6 +243,7 @@ pub(crate) async fn apply_bespoke_event_handling(
|
||||
name: update.server,
|
||||
environment_id: update.environment_id,
|
||||
status,
|
||||
duration_ms: update.duration_ms,
|
||||
error,
|
||||
failure_reason,
|
||||
};
|
||||
|
||||
@@ -150,7 +150,7 @@ async fn desktop_socket_mcp_startup(
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn recording_widget_server() -> (MockServer, serde_json::Value) {
|
||||
async fn recording_widget_server(initialize_delay: Duration) -> (MockServer, serde_json::Value) {
|
||||
let server = MockServer::start().await;
|
||||
let tool = json!({
|
||||
"name": "open_widget",
|
||||
@@ -179,15 +179,71 @@ async fn recording_widget_server() -> (MockServer, serde_json::Value) {
|
||||
}),
|
||||
_ => return ResponseTemplate::new(202),
|
||||
};
|
||||
ResponseTemplate::new(200).set_body_json(json!({
|
||||
let response = ResponseTemplate::new(200).set_body_json(json!({
|
||||
"jsonrpc": "2.0", "id": request["id"], "result": result
|
||||
}))
|
||||
}));
|
||||
if request["method"] == "initialize" {
|
||||
response.set_delay(initialize_delay)
|
||||
} else {
|
||||
response
|
||||
}
|
||||
})
|
||||
.mount(&server)
|
||||
.await;
|
||||
(server, tool)
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn required_mcp_servers_report_independent_startup_durations() -> Result<()> {
|
||||
const DELAY_MS: u64 = 500;
|
||||
let (fast, _) = recording_widget_server(Duration::ZERO).await;
|
||||
let (slow, _) = recording_widget_server(Duration::from_millis(DELAY_MS)).await;
|
||||
let codex_home = TempDir::new()?;
|
||||
mock_responses_config(&fast.uri())
|
||||
.with_root_config("mcp_oauth_credentials_store = \"file\"")
|
||||
.with_extra_config(&format!(
|
||||
r#"[mcp_servers.fast]
|
||||
url = "{}/mcp"
|
||||
required = true
|
||||
|
||||
[mcp_servers.slow]
|
||||
url = "{}/mcp"
|
||||
required = true"#,
|
||||
fast.uri(),
|
||||
slow.uri()
|
||||
))
|
||||
.write(codex_home.path())?;
|
||||
let mut app = TestAppServer::builder()
|
||||
.with_codex_home(codex_home.path())
|
||||
.build_initialized()
|
||||
.await?;
|
||||
|
||||
// Required servers finish before thread/start returns and the client sees their updates.
|
||||
let thread = app.start_thread(ThreadStartParams::default()).await?.thread;
|
||||
let mut durations = BTreeMap::new();
|
||||
for name in ["fast", "slow"] {
|
||||
let ready = timeout(
|
||||
DEFAULT_READ_TIMEOUT,
|
||||
app.read_stream_until_matching_notification("required MCP ready", |notification| {
|
||||
notification.method == "mcpServer/startupStatus/updated"
|
||||
&& notification.params.as_ref().is_some_and(|params| {
|
||||
params["threadId"] == thread.id
|
||||
&& params["name"] == name
|
||||
&& params["status"] == "ready"
|
||||
})
|
||||
}),
|
||||
)
|
||||
.await??;
|
||||
let duration_ms = ready.params.expect("ready params")["durationMs"]
|
||||
.as_u64()
|
||||
.expect("measured duration");
|
||||
durations.insert(name, duration_ms);
|
||||
}
|
||||
assert!(durations["slow"] >= DELAY_MS, "{durations:?}");
|
||||
assert!(durations["fast"] < durations["slow"], "{durations:?}");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test_case("http_headers = { Authorization = \"Bearer fixed-test-token\" }", 1; "fixed authorization")]
|
||||
#[test_case("", 2; "stored OAuth authority")]
|
||||
#[tokio::test]
|
||||
@@ -195,7 +251,7 @@ async fn mcp_server_status_discovers_thread_inventory(
|
||||
headers: &str,
|
||||
expected_lightweight_initializations: usize,
|
||||
) -> Result<()> {
|
||||
let (server, tool) = recording_widget_server().await;
|
||||
let (server, tool) = recording_widget_server(Duration::ZERO).await;
|
||||
let codex_home = TempDir::new()?;
|
||||
mock_responses_config(&server.uri())
|
||||
.with_root_config("mcp_oauth_credentials_store = \"file\"")
|
||||
@@ -298,7 +354,7 @@ async fn mcp_server_status_discovers_thread_inventory(
|
||||
|
||||
#[tokio::test]
|
||||
async fn mcp_server_status_list_discovers_only_the_requested_page() -> Result<()> {
|
||||
let (server, _) = recording_widget_server().await;
|
||||
let (server, _) = recording_widget_server(Duration::ZERO).await;
|
||||
let codex_home = TempDir::new()?;
|
||||
mock_responses_config(&server.uri())
|
||||
.with_extra_config(&format!(
|
||||
@@ -1866,16 +1922,19 @@ async fn mcp_server_status_keeps_same_named_environment_inventory_separate() ->
|
||||
})
|
||||
})
|
||||
.await?;
|
||||
let params = notification.params.expect("notes ready params");
|
||||
let duration_ms = params["durationMs"].as_u64().expect("measured duration");
|
||||
assert_eq!(
|
||||
notification.params,
|
||||
Some(serde_json::json!({
|
||||
params,
|
||||
json!({
|
||||
"threadId": thread.id,
|
||||
"name": "notes",
|
||||
"environmentId": "env-a",
|
||||
"status": "ready",
|
||||
"durationMs": duration_ms,
|
||||
"error": null,
|
||||
"failureReason": null,
|
||||
}))
|
||||
})
|
||||
);
|
||||
let response: ListMcpServerStatusResponse = app
|
||||
.request(|request_id| ClientRequest::McpServerStatusList {
|
||||
|
||||
@@ -1522,6 +1522,7 @@ async fn thread_start_emits_mcp_server_status_updated_notifications() -> Result<
|
||||
name: "optional_broken".to_string(),
|
||||
environment_id: None,
|
||||
status: McpServerStartupState::Starting,
|
||||
duration_ms: None,
|
||||
error: None,
|
||||
failure_reason: None,
|
||||
}
|
||||
@@ -1556,6 +1557,7 @@ async fn thread_start_emits_mcp_server_status_updated_notifications() -> Result<
|
||||
assert_eq!(failed.thread_id, Some(start_response.thread.id));
|
||||
assert_eq!(failed.name, "optional_broken");
|
||||
assert_eq!(failed.status, McpServerStartupState::Failed);
|
||||
assert!(failed.duration_ms.is_some());
|
||||
assert_eq!(failed.failure_reason, None);
|
||||
assert!(
|
||||
failed
|
||||
|
||||
@@ -948,6 +948,7 @@ impl McpConnectionSet {
|
||||
.scoped_environment_id()
|
||||
.map(str::to_owned),
|
||||
status,
|
||||
duration_ms: None,
|
||||
},
|
||||
)
|
||||
.await;
|
||||
@@ -1005,10 +1006,12 @@ impl McpConnectionSet {
|
||||
} else {
|
||||
(None, None)
|
||||
};
|
||||
let initial_measurement = Arc::new(OnceLock::new());
|
||||
let mut async_managed_client = AsyncManagedClient::new(
|
||||
ema_auth.clone(),
|
||||
server_key.clone(),
|
||||
startup_submit_id.clone(),
|
||||
Arc::clone(&initial_measurement),
|
||||
server,
|
||||
store_mode,
|
||||
keyring_backend_kind,
|
||||
@@ -1095,6 +1098,7 @@ impl McpConnectionSet {
|
||||
server: server_name.clone(),
|
||||
environment_id: server_key.scoped_environment_id().map(str::to_owned),
|
||||
status: McpStartupStatus::Starting,
|
||||
duration_ms: None,
|
||||
},
|
||||
)
|
||||
.await;
|
||||
@@ -1164,6 +1168,9 @@ impl McpConnectionSet {
|
||||
}
|
||||
};
|
||||
|
||||
let duration_ms = initial_measurement
|
||||
.get()
|
||||
.and_then(|measurement| measurement.duration_ms_for(&status));
|
||||
let _ = emit_update(
|
||||
submit_id.as_str(),
|
||||
tx_event,
|
||||
@@ -1171,6 +1178,7 @@ impl McpConnectionSet {
|
||||
server: server_name.clone(),
|
||||
environment_id: server_key.scoped_environment_id().map(str::to_owned),
|
||||
status,
|
||||
duration_ms,
|
||||
},
|
||||
)
|
||||
.await;
|
||||
@@ -1224,6 +1232,7 @@ impl McpConnectionSet {
|
||||
server: server.name().to_owned(),
|
||||
environment_id: server.scoped_environment_id().map(str::to_owned),
|
||||
status: McpStartupStatus::Starting,
|
||||
duration_ms: None,
|
||||
},
|
||||
)
|
||||
.await;
|
||||
@@ -1253,6 +1262,7 @@ impl McpConnectionSet {
|
||||
server: key.name().to_owned(),
|
||||
environment_id: key.scoped_environment_id().map(str::to_owned),
|
||||
status: McpStartupStatus::Ready,
|
||||
duration_ms: None,
|
||||
},
|
||||
)
|
||||
.await;
|
||||
|
||||
@@ -9,6 +9,7 @@ use std::sync::Mutex;
|
||||
use std::sync::OnceLock;
|
||||
use std::sync::Weak;
|
||||
use std::time::Duration;
|
||||
use std::time::Instant;
|
||||
|
||||
use codex_async_utils::OrCancelExt;
|
||||
use codex_connectors::ConnectorRuntimeContextKey;
|
||||
@@ -203,6 +204,8 @@ pub(crate) struct ConnectionLease {
|
||||
pub(crate) struct ConnectionSlot {
|
||||
state: Mutex<SlotState>,
|
||||
shutdown_tasks: OnceLock<TaskTracker>,
|
||||
/// Set only if this acquisition started the selected connection.
|
||||
pub(crate) started_at: OnceLock<Instant>,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
@@ -325,6 +328,7 @@ impl McpConnectionPool {
|
||||
// Older or failed servers leave other chats to initialize privately
|
||||
// with their own elicitation authority.
|
||||
drop(lease);
|
||||
let _ = slot.started_at.set(Instant::now());
|
||||
start(cancellation, /*sharing_declined*/ None).await
|
||||
}
|
||||
}
|
||||
@@ -339,6 +343,7 @@ impl McpConnectionPool {
|
||||
start: impl Fn(CancellationToken, Option<CancellationToken>) -> ManagedClientFuture,
|
||||
) -> Result<(Arc<ConnectionLease>, AcquisitionRole), StartupOutcomeError> {
|
||||
loop {
|
||||
let mut started_at = None;
|
||||
let (lease, role) = {
|
||||
let mut state = slot
|
||||
.state
|
||||
@@ -374,6 +379,7 @@ impl McpConnectionPool {
|
||||
} else {
|
||||
let startup_cancellation = CancellationToken::new();
|
||||
let sharing_declined = CancellationToken::new();
|
||||
started_at = Some(Instant::now());
|
||||
let client =
|
||||
start(startup_cancellation.clone(), Some(sharing_declined.clone()));
|
||||
// Startup belongs to the connection, including if its first chat is cancelled.
|
||||
@@ -410,6 +416,9 @@ impl McpConnectionPool {
|
||||
lease.release();
|
||||
continue;
|
||||
}
|
||||
if let Some(started_at) = started_at {
|
||||
let _ = slot.started_at.set(started_at);
|
||||
}
|
||||
return Ok((lease, role));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -30,6 +30,7 @@ use std::env;
|
||||
use std::ffi::OsString;
|
||||
use std::sync::Arc;
|
||||
use std::sync::Mutex as StdMutex;
|
||||
use std::sync::OnceLock;
|
||||
use std::sync::atomic::AtomicBool;
|
||||
use std::sync::atomic::Ordering;
|
||||
use std::time::Duration;
|
||||
@@ -210,7 +211,9 @@ impl CodexAppsStartupReconnect {
|
||||
|
||||
let reconnect = Arc::clone(self);
|
||||
let attempt = async move {
|
||||
let started_at = Instant::now();
|
||||
let result = (reconnect.factory)().await;
|
||||
let duration_ms = elapsed_ms(started_at);
|
||||
let startup_status_context = reconnect.startup_status_context.clone();
|
||||
let recovered = {
|
||||
let mut state = reconnect
|
||||
@@ -253,6 +256,7 @@ impl CodexAppsStartupReconnect {
|
||||
.scoped_environment_id()
|
||||
.map(str::to_owned),
|
||||
status: McpStartupStatus::Ready,
|
||||
duration_ms: Some(duration_ms),
|
||||
}),
|
||||
})
|
||||
.await;
|
||||
@@ -269,6 +273,34 @@ impl CodexAppsStartupReconnect {
|
||||
}
|
||||
}
|
||||
|
||||
fn elapsed_ms(started_at: Instant) -> u64 {
|
||||
u64::try_from(started_at.elapsed().as_millis()).unwrap_or(u64::MAX)
|
||||
}
|
||||
|
||||
pub(crate) struct StartupMeasurement {
|
||||
duration_ms: u64,
|
||||
succeeded: bool,
|
||||
}
|
||||
|
||||
impl StartupMeasurement {
|
||||
fn new(started_at: Instant, outcome: &Result<ManagedClient, StartupOutcomeError>) -> Self {
|
||||
Self {
|
||||
duration_ms: elapsed_ms(started_at),
|
||||
succeeded: outcome.is_ok(),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn duration_ms_for(&self, status: &McpStartupStatus) -> Option<u64> {
|
||||
// Apps recovery or a legacy fallback may have supplied a working client
|
||||
// after the attempt we timed failed.
|
||||
match status {
|
||||
McpStartupStatus::Ready => self.succeeded.then_some(self.duration_ms),
|
||||
McpStartupStatus::Failed { .. } => (!self.succeeded).then_some(self.duration_ms),
|
||||
McpStartupStatus::Starting | McpStartupStatus::Cancelled => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn codex_apps_reconnect_backoff(consecutive_failures: u32) -> Duration {
|
||||
let exponent = consecutive_failures.saturating_sub(1).min(5);
|
||||
CODEX_APPS_RECONNECT_INITIAL_BACKOFF
|
||||
@@ -308,7 +340,7 @@ impl ManagedClientStartup {
|
||||
&self,
|
||||
sharing_declined: Option<CancellationToken>,
|
||||
publish_apps: Option<watch::Sender<Option<std::sync::Weak<RmcpClient>>>>,
|
||||
) -> ManagedClientFuture {
|
||||
) -> impl Future<Output = Result<ManagedClient, StartupOutcomeError>> + Send + use<> {
|
||||
// A new attempt must not expose capabilities from an earlier connection.
|
||||
*self
|
||||
.server_capabilities
|
||||
@@ -493,10 +525,7 @@ impl ManagedClientStartup {
|
||||
startup_complete.store(true, Ordering::Release);
|
||||
outcome
|
||||
};
|
||||
originator
|
||||
.scope(codex_rmcp_client::McpRequestTrace::current().scope(Box::pin(startup)))
|
||||
.boxed()
|
||||
.shared()
|
||||
originator.scope(codex_rmcp_client::McpRequestTrace::current().scope(Box::pin(startup)))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -526,6 +555,7 @@ impl AsyncManagedClient {
|
||||
ema_auth: Option<crate::ema_auth::EmaAuthContext>,
|
||||
server_key: McpServerKey,
|
||||
startup_submit_id: String,
|
||||
initial_measurement: Arc<OnceLock<StartupMeasurement>>,
|
||||
server: EffectiveMcpServer,
|
||||
store_mode: OAuthCredentialsStoreMode,
|
||||
keyring_backend_kind: AuthKeyringBackendKind,
|
||||
@@ -623,7 +653,7 @@ impl AsyncManagedClient {
|
||||
let client = async move {
|
||||
let outcome = pool
|
||||
.connect(
|
||||
slot,
|
||||
Arc::clone(&slot),
|
||||
key,
|
||||
server_capabilities,
|
||||
pool_catalog,
|
||||
@@ -631,7 +661,10 @@ impl AsyncManagedClient {
|
||||
|cancellation, sharing_declined| {
|
||||
let mut shared_startup = (*startup).clone();
|
||||
shared_startup.cancel_token = cancellation;
|
||||
shared_startup.start(sharing_declined, /*publish_apps*/ None)
|
||||
shared_startup
|
||||
.start(sharing_declined, /*publish_apps*/ None)
|
||||
.boxed()
|
||||
.shared()
|
||||
},
|
||||
)
|
||||
.await
|
||||
@@ -647,6 +680,10 @@ impl AsyncManagedClient {
|
||||
}
|
||||
client
|
||||
});
|
||||
// Include lease registration, but don't count joining an existing connection.
|
||||
if let Some(&started_at) = slot.started_at.get() {
|
||||
let _ = initial_measurement.set(StartupMeasurement::new(started_at, &outcome));
|
||||
}
|
||||
startup_complete.store(true, Ordering::Release);
|
||||
outcome
|
||||
}
|
||||
@@ -654,13 +691,26 @@ impl AsyncManagedClient {
|
||||
.shared();
|
||||
(client, Some(connection_slot))
|
||||
} else {
|
||||
(startup.start(/*sharing_declined*/ None, publish_apps), None)
|
||||
let startup = startup.start(/*sharing_declined*/ None, publish_apps);
|
||||
let client = async move {
|
||||
// Deferred connections can remain dormant until the first poll.
|
||||
let started_at = Instant::now();
|
||||
let outcome = startup.await;
|
||||
let _ = initial_measurement.set(StartupMeasurement::new(started_at, &outcome));
|
||||
outcome
|
||||
}
|
||||
.boxed()
|
||||
.shared();
|
||||
(client, None)
|
||||
};
|
||||
let startup_reconnect = is_codex_apps_mcp_server.then(|| {
|
||||
let startup = Arc::clone(&startup);
|
||||
Arc::new(
|
||||
CodexAppsStartupReconnect::new(Arc::new(move || {
|
||||
startup.start(/*sharing_declined*/ None, /*publish_apps*/ None)
|
||||
startup
|
||||
.start(/*sharing_declined*/ None, /*publish_apps*/ None)
|
||||
.boxed()
|
||||
.shared()
|
||||
}))
|
||||
.with_startup_status_context(
|
||||
startup_submit_id,
|
||||
@@ -1750,6 +1800,15 @@ mod tests {
|
||||
use rmcp::model::MetaObject;
|
||||
use rmcp::transport::auth::AuthError;
|
||||
|
||||
#[test]
|
||||
fn failed_startup_timing_does_not_describe_a_recovered_connection() {
|
||||
let failed = Err(StartupOutcomeError::from(anyhow!(
|
||||
"initial connection failed"
|
||||
)));
|
||||
let measurement = StartupMeasurement::new(Instant::now(), &failed);
|
||||
assert_eq!(measurement.duration_ms_for(&McpStartupStatus::Ready), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn startup_outcome_error_identifies_authentication_required() {
|
||||
let error = anyhow::Error::new(AuthError::AuthorizationRequired)
|
||||
|
||||
@@ -78,6 +78,7 @@ async fn forward_events_filters_private_events_before_blocked_send_is_cancelled(
|
||||
server: "pending".to_string(),
|
||||
environment_id: None,
|
||||
status: McpStartupStatus::Starting,
|
||||
duration_ms: None,
|
||||
}),
|
||||
EventMsg::McpStartupComplete(McpStartupCompleteEvent::default()),
|
||||
] {
|
||||
|
||||
@@ -46,6 +46,7 @@ use core_test_support::skip_if_wine_exec;
|
||||
use core_test_support::test_codex::test_codex;
|
||||
use core_test_support::test_codex::test_env;
|
||||
use core_test_support::wait_for_event;
|
||||
use core_test_support::wait_for_event_match;
|
||||
use core_test_support::wait_for_mcp_server;
|
||||
use pretty_assertions::assert_eq;
|
||||
use serde_json::Value;
|
||||
@@ -1124,6 +1125,7 @@ pub(super) async fn cached_stdio_first_use_scenario() -> anyhow::Result<Vec<Valu
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn cached_stdio_negotiates_sharing_on_first_use() -> anyhow::Result<()> {
|
||||
const LEASE_OPEN_DELAY_MS: u64 = 100;
|
||||
skip_if_no_network!(Ok(()));
|
||||
core_test_support::skip_if_remote!(Ok(()), "the shared stdio fixture runs on the host");
|
||||
skip_if_wine_exec!(Ok(()), "requires the native stdio server");
|
||||
@@ -1153,7 +1155,11 @@ async fn cached_stdio_negotiates_sharing_on_first_use() -> anyhow::Result<()> {
|
||||
"cached_rmcp": {
|
||||
"command": command,
|
||||
"cwd": config.cwd,
|
||||
"env": { "MCP_TEST_DYNAMIC_SERVER_METADATA": "1" },
|
||||
"env": {
|
||||
"MCP_TEST_DYNAMIC_SERVER_METADATA": "1",
|
||||
"MCP_TEST_LEASE_EVENTS_FILE": config.codex_home.join("mcp-leases"),
|
||||
"MCP_TEST_LEASE_OPEN_DELAY_MS": LEASE_OPEN_DELAY_MS.to_string(),
|
||||
},
|
||||
"enabled_tools": ["echo"]
|
||||
}
|
||||
}))
|
||||
@@ -1205,6 +1211,24 @@ async fn cached_stdio_negotiates_sharing_on_first_use() -> anyhow::Result<()> {
|
||||
assert_ne!(processes[0], processes[1]);
|
||||
assert_eq!(processes[1], processes[2]);
|
||||
|
||||
for (thread, started_process) in [(&first, true), (&second, false)] {
|
||||
let duration_ms = wait_for_event_match(thread, |event| match event {
|
||||
EventMsg::McpStartupUpdate(update)
|
||||
if update.server == SERVER_NAME
|
||||
&& matches!(update.status, McpStartupStatus::Ready) =>
|
||||
{
|
||||
Some(update.duration_ms)
|
||||
}
|
||||
_ => None,
|
||||
})
|
||||
.await;
|
||||
if started_process {
|
||||
assert!(duration_ms.is_some_and(|ms| ms >= LEASE_OPEN_DELAY_MS));
|
||||
} else {
|
||||
assert_eq!(duration_ms, None);
|
||||
}
|
||||
}
|
||||
|
||||
let response =
|
||||
responses::mount_sse_once(&responses_server, responses::sse_completed("unrelated")).await;
|
||||
legacy_sibling
|
||||
|
||||
@@ -2059,15 +2059,23 @@ async fn apps_guidance_and_deferred_namespace_appear_after_recovery_within_a_tur
|
||||
release_apps_recovery
|
||||
.send(())
|
||||
.expect("background Apps recovery should still be waiting");
|
||||
wait_for_event(&test.codex, |event| {
|
||||
matches!(
|
||||
event,
|
||||
EventMsg::McpStartupUpdate(update)
|
||||
if update.server == CODEX_APPS_MCP_SERVER_NAME
|
||||
&& matches!(update.status, codex_protocol::protocol::McpStartupStatus::Ready)
|
||||
)
|
||||
let duration_ms = core_test_support::wait_for_event_match(&test.codex, |event| match event {
|
||||
EventMsg::McpStartupUpdate(update)
|
||||
if update.server == CODEX_APPS_MCP_SERVER_NAME
|
||||
&& matches!(
|
||||
update.status,
|
||||
codex_protocol::protocol::McpStartupStatus::Ready
|
||||
) =>
|
||||
{
|
||||
Some(update.duration_ms)
|
||||
}
|
||||
_ => None,
|
||||
})
|
||||
.await;
|
||||
assert!(
|
||||
duration_ms.is_some(),
|
||||
"Apps recovery should report its own startup duration"
|
||||
);
|
||||
|
||||
test.codex
|
||||
.submit(Op::UserInputAnswer {
|
||||
|
||||
@@ -4277,6 +4277,10 @@ pub struct McpStartupUpdateEvent {
|
||||
pub environment_id: Option<String>,
|
||||
/// Current startup status.
|
||||
pub status: McpStartupStatus,
|
||||
/// Time spent initializing this server, when reporting a measured startup outcome.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[ts(type = "number | null", optional)]
|
||||
pub duration_ms: Option<u64>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Deserialize, Serialize, JsonSchema, TS)]
|
||||
@@ -6937,12 +6941,14 @@ mod tests {
|
||||
error: "boom".to_string(),
|
||||
reason: Some(McpStartupFailureReason::ReauthenticationRequired),
|
||||
},
|
||||
duration_ms: Some(1_250),
|
||||
}),
|
||||
};
|
||||
|
||||
let value = serde_json::to_value(&event)?;
|
||||
assert_eq!(value["msg"]["type"], "mcp_startup_update");
|
||||
assert_eq!(value["msg"]["server"], "srv");
|
||||
assert_eq!(value["msg"]["duration_ms"], 1_250);
|
||||
assert_eq!(value["msg"]["status"]["state"], "failed");
|
||||
assert_eq!(value["msg"]["status"]["error"], "boom");
|
||||
assert_eq!(
|
||||
|
||||
@@ -766,6 +766,14 @@ impl ServerHandler for TestToolServer {
|
||||
.and_then(|params| params.get("leaseId"))
|
||||
.ok_or_else(|| McpError::invalid_params("missing lease ID", None))?;
|
||||
record_lease_event(&request.method, id)?;
|
||||
if request.method == "codex/connection/open"
|
||||
&& let Ok(delay) = std::env::var("MCP_TEST_LEASE_OPEN_DELAY_MS")
|
||||
{
|
||||
let delay = delay
|
||||
.parse()
|
||||
.map_err(|_| McpError::invalid_params("invalid lease delay", None))?;
|
||||
sleep(Duration::from_millis(delay)).await;
|
||||
}
|
||||
Ok(rmcp::model::CustomResult(serde_json::json!({})))
|
||||
}
|
||||
|
||||
|
||||
@@ -333,6 +333,7 @@ mod tests {
|
||||
thread_id: Some(thread_id.to_string()),
|
||||
name: "sentry".to_string(),
|
||||
status: McpServerStartupState::Failed,
|
||||
duration_ms: None,
|
||||
error: Some("sentry is not logged in".to_string()),
|
||||
failure_reason: None,
|
||||
});
|
||||
@@ -350,6 +351,7 @@ mod tests {
|
||||
thread_id: None,
|
||||
name: "sentry".to_string(),
|
||||
status: McpServerStartupState::Failed,
|
||||
duration_ms: None,
|
||||
error: Some("sentry is not logged in".to_string()),
|
||||
failure_reason: None,
|
||||
});
|
||||
|
||||
@@ -8408,6 +8408,7 @@ async fn primary_thread_ignores_child_mcp_startup_notifications() {
|
||||
thread_id: Some(child_thread_id.to_string()),
|
||||
name: "sentry".to_string(),
|
||||
status: McpServerStartupState::Failed,
|
||||
duration_ms: None,
|
||||
error: Some("sentry is not logged in".to_string()),
|
||||
failure_reason: None,
|
||||
}),
|
||||
@@ -8468,39 +8469,6 @@ async fn primary_thread_ignores_child_mcp_startup_notifications() {
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn app_scoped_mcp_startup_notifications_do_not_render_in_active_thread() {
|
||||
let (mut app, mut app_event_rx, _op_rx) = make_test_app_with_channels().await;
|
||||
while app_event_rx.try_recv().is_ok() {}
|
||||
let app_server = crate::start_embedded_app_server_for_picker(app.chat_widget.config_ref())
|
||||
.await
|
||||
.expect("embedded app server");
|
||||
let thread_id = ThreadId::new();
|
||||
app.primary_thread_id = Some(thread_id);
|
||||
app.active_thread_id = Some(thread_id);
|
||||
|
||||
app.handle_app_server_event(
|
||||
&app_server,
|
||||
codex_app_server_client::AppServerEvent::ServerNotification(Box::new(
|
||||
ServerNotification::McpServerStatusUpdated(McpServerStatusUpdatedNotification {
|
||||
environment_id: None,
|
||||
thread_id: None,
|
||||
name: "sentry".to_string(),
|
||||
status: McpServerStartupState::Failed,
|
||||
error: Some("sentry is not logged in".to_string()),
|
||||
failure_reason: None,
|
||||
}),
|
||||
)),
|
||||
)
|
||||
.await;
|
||||
|
||||
assert!(app_event_rx.try_recv().is_err());
|
||||
assert_eq!(
|
||||
app.chat_widget.active_cell_transcript_lines(/*width*/ 120),
|
||||
None
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn active_side_thread_renders_live_mcp_startup_notifications() {
|
||||
let (mut app, mut app_event_rx, _op_rx) = make_test_app_with_channels().await;
|
||||
@@ -8568,6 +8536,7 @@ async fn active_side_thread_renders_live_mcp_startup_notifications() {
|
||||
thread_id: Some(side_thread_id.to_string()),
|
||||
name: name.to_string(),
|
||||
status,
|
||||
duration_ms: None,
|
||||
error: matches!(status, McpServerStartupState::Failed)
|
||||
.then(|| "sentry is not logged in".to_string()),
|
||||
failure_reason: None,
|
||||
|
||||
@@ -67,6 +67,7 @@ async fn backend_sessions_parked_request_does_not_hide_disconnect() -> Result<()
|
||||
thread_id: Some(thread_id.to_string()),
|
||||
name: "tools".into(),
|
||||
status: McpServerStartupState::Failed,
|
||||
duration_ms: None,
|
||||
error: Some("startup failed".into()),
|
||||
failure_reason: None,
|
||||
},
|
||||
|
||||
@@ -756,6 +756,7 @@ async fn daemon_ctrl_c_during_mcp_startup_does_not_show_background_exit_menu() -
|
||||
thread_id: Some(thread_id.to_string()),
|
||||
name: "slow".to_string(),
|
||||
status: McpServerStartupState::Starting,
|
||||
duration_ms: None,
|
||||
error: None,
|
||||
failure_reason: None,
|
||||
}),
|
||||
|
||||
@@ -45,6 +45,7 @@ async fn remote_mcp_startup_settles_when_attaching_mid_round() -> Result<()> {
|
||||
thread_id: Some(id.to_string()),
|
||||
name: name.to_string(),
|
||||
status,
|
||||
duration_ms: None,
|
||||
error: None,
|
||||
failure_reason: None,
|
||||
})
|
||||
@@ -162,6 +163,7 @@ async fn remote_mcp_startup_reports_terminal_only_failures_and_cancellations() -
|
||||
environment_id: None,
|
||||
thread_id: Some(id.to_string()),
|
||||
name: name.to_string(),
|
||||
duration_ms: None,
|
||||
error: (status == Failed).then(|| error.to_string()),
|
||||
failure_reason: (status == Failed).then_some(ReauthenticationRequired),
|
||||
status,
|
||||
@@ -267,6 +269,7 @@ async fn subagent_mcp_startup_settles_while_cached_servers_remain_deferred() {
|
||||
thread_id: Some(subagent_thread_id.to_string()),
|
||||
name: name.to_string(),
|
||||
status,
|
||||
duration_ms: None,
|
||||
error: None,
|
||||
failure_reason: None,
|
||||
}),
|
||||
@@ -317,6 +320,7 @@ async fn resumed_subagent_mcp_startup_settles_while_cached_servers_remain_deferr
|
||||
thread_id: Some(subagent_thread_id.to_string()),
|
||||
name: "eager".to_string(),
|
||||
status,
|
||||
duration_ms: None,
|
||||
error: None,
|
||||
failure_reason: None,
|
||||
}),
|
||||
@@ -348,6 +352,7 @@ async fn side_conversations_settle_despite_unreported_locally_configured_servers
|
||||
thread_id: Some(side_thread_id.to_string()),
|
||||
name: "eager".to_string(),
|
||||
status,
|
||||
duration_ms: None,
|
||||
error: None,
|
||||
failure_reason: None,
|
||||
}),
|
||||
@@ -357,3 +362,37 @@ async fn side_conversations_settle_despite_unreported_locally_configured_servers
|
||||
|
||||
assert!(!app.chat_widget.is_task_running_for_test());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn app_scoped_mcp_startup_notifications_do_not_render_in_active_thread() {
|
||||
let (mut app, mut app_event_rx, _op_rx) = make_test_app_with_channels().await;
|
||||
while app_event_rx.try_recv().is_ok() {}
|
||||
let app_server = crate::start_embedded_app_server_for_picker(app.chat_widget.config_ref())
|
||||
.await
|
||||
.expect("embedded app server");
|
||||
let thread_id = ThreadId::new();
|
||||
app.primary_thread_id = Some(thread_id);
|
||||
app.active_thread_id = Some(thread_id);
|
||||
|
||||
app.handle_app_server_event(
|
||||
&app_server,
|
||||
codex_app_server_client::AppServerEvent::ServerNotification(Box::new(
|
||||
ServerNotification::McpServerStatusUpdated(McpServerStatusUpdatedNotification {
|
||||
environment_id: None,
|
||||
thread_id: None,
|
||||
name: "sentry".to_string(),
|
||||
status: McpServerStartupState::Failed,
|
||||
duration_ms: None,
|
||||
error: Some("sentry is not logged in".to_string()),
|
||||
failure_reason: None,
|
||||
}),
|
||||
)),
|
||||
)
|
||||
.await;
|
||||
|
||||
assert!(app_event_rx.try_recv().is_err());
|
||||
assert_eq!(
|
||||
app.chat_widget.active_cell_transcript_lines(/*width*/ 120),
|
||||
None
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1576,6 +1576,7 @@ async fn startup_thread_started_discards_another_threads_buffered_events() {
|
||||
thread_id: Some(other_thread_id.to_string()),
|
||||
name: "other".to_string(),
|
||||
status: McpServerStartupState::Starting,
|
||||
duration_ms: None,
|
||||
error: None,
|
||||
failure_reason: None,
|
||||
},
|
||||
@@ -1790,6 +1791,7 @@ async fn send_failed_mcp_startup(
|
||||
thread_id: Some(thread_id.to_string()),
|
||||
name: "fixture".to_string(),
|
||||
status: McpServerStartupState::Failed,
|
||||
duration_ms: None,
|
||||
error: Some("fixture failed".to_string()),
|
||||
failure_reason: None,
|
||||
}),
|
||||
|
||||
@@ -205,6 +205,7 @@ async fn mcp_startup_summary_counts_servers_and_sign_in_subset() -> Result<()> {
|
||||
thread_id: None,
|
||||
name: name.into(),
|
||||
status,
|
||||
duration_ms: None,
|
||||
error: (status == Failed).then(|| format!("MCP {name}: connection unavailable")),
|
||||
failure_reason,
|
||||
}),
|
||||
|
||||
@@ -220,6 +220,7 @@ async fn unavailable_thread_new_and_clear_start_a_writable_session() -> Result<(
|
||||
thread_id: Some(id.to_string()),
|
||||
name: "slow".into(),
|
||||
status: McpServerStartupState::Starting,
|
||||
duration_ms: None,
|
||||
error: None,
|
||||
failure_reason: None,
|
||||
}),
|
||||
|
||||
@@ -1135,6 +1135,7 @@ mod tests {
|
||||
thread_id: Some(thread_id.to_string()),
|
||||
name: "sentry".to_string(),
|
||||
status: codex_app_server_protocol::McpServerStartupState::Failed,
|
||||
duration_ms: None,
|
||||
error: Some("sentry is not logged in".to_string()),
|
||||
failure_reason: None,
|
||||
},
|
||||
|
||||
@@ -808,6 +808,7 @@ async fn guardian_cleanup_drops_stale_reviews_and_restores_mcp_status() {
|
||||
thread_id: None,
|
||||
name: "alpha".to_string(),
|
||||
status: McpServerStartupState::Starting,
|
||||
duration_ms: None,
|
||||
error: None,
|
||||
failure_reason: None,
|
||||
});
|
||||
|
||||
@@ -9,6 +9,7 @@ fn notify_mcp_status(chat: &mut ChatWidget, name: &str, status: McpServerStartup
|
||||
thread_id: Some("thread-1".to_string()),
|
||||
name: name.to_string(),
|
||||
status,
|
||||
duration_ms: None,
|
||||
error: None,
|
||||
failure_reason: None,
|
||||
}),
|
||||
@@ -23,6 +24,7 @@ fn notify_mcp_status_error(chat: &mut ChatWidget, name: &str, error: &str) {
|
||||
thread_id: Some("thread-1".to_string()),
|
||||
name: name.to_string(),
|
||||
status: McpServerStartupState::Failed,
|
||||
duration_ms: None,
|
||||
error: Some(error.to_string()),
|
||||
failure_reason: None,
|
||||
}),
|
||||
@@ -54,6 +56,7 @@ async fn mcp_startup_ignores_status_for_other_thread() {
|
||||
thread_id: Some(child_thread_id.to_string()),
|
||||
name: "sentry".to_string(),
|
||||
status,
|
||||
duration_ms: None,
|
||||
error: matches!(status, McpServerStartupState::Failed)
|
||||
.then(|| "sentry is not logged in".to_string()),
|
||||
failure_reason: None,
|
||||
@@ -85,6 +88,7 @@ async fn mcp_apps_readiness_retries_an_in_flight_installed_mention_lookup() {
|
||||
thread_id: None,
|
||||
name: "codex_apps".to_string(),
|
||||
status: McpServerStartupState::Ready,
|
||||
duration_ms: None,
|
||||
error: None,
|
||||
failure_reason: None,
|
||||
});
|
||||
@@ -552,6 +556,7 @@ async fn app_server_mcp_startup_failure_renders_warning_history() {
|
||||
name: "notes".to_string(),
|
||||
environment_id: Some(environment_id.to_string()),
|
||||
status: McpServerStartupState::Starting,
|
||||
duration_ms: None,
|
||||
error: None,
|
||||
failure_reason: None,
|
||||
});
|
||||
@@ -570,6 +575,7 @@ async fn app_server_mcp_startup_failure_renders_warning_history() {
|
||||
name: "notes".to_string(),
|
||||
environment_id: Some("env-a".to_string()),
|
||||
status: McpServerStartupState::Failed,
|
||||
duration_ms: None,
|
||||
error: Some("MCP client for `notes` failed to start: handshake failed".to_string()),
|
||||
failure_reason: None,
|
||||
});
|
||||
@@ -595,6 +601,7 @@ async fn app_server_mcp_startup_failure_renders_warning_history() {
|
||||
name: "notes".to_string(),
|
||||
environment_id: Some("env-b".to_string()),
|
||||
status: McpServerStartupState::Ready,
|
||||
duration_ms: None,
|
||||
error: None,
|
||||
failure_reason: None,
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user