Files
codex/codex-rs/tui/src/chatwidget/mcp_startup.rs
T
Felipe Coury 5a440c03f2 fix(tui): scope MCP startup status by thread (#26639)
## Why

MCP startup failures from spawned subagents were rendered as global
notifications, so a child thread's failure could pollute the visible
parent transcript. Routing the notification to the child exposed two
related replay problems: session refresh could discard the buffered
event, and a newly created child `ChatWidget` did not know the expected
MCP server set, which could leave its startup spinner running after
every server had settled.

MCP startup diagnostics should remain visible in the thread that owns
the startup without affecting other transcripts. The protocol also needs
to support a future app-scoped MCP lifecycle where startup is not owned
by any thread.

## Reported Behavior

The [originating Slack
report](https://openai.slack.com/archives/C08JZTV654K/p1780604538859939)
called out that using subagents could turn MCP startup failures into a
wall of yellow CLI warnings because repeated failures were not
deduplicated. The intended behavior is for those diagnostics to remain
visible once in the thread that owns the startup, without polluting the
parent transcript.

## What Changed

- add nullable `threadId` ownership to `mcpServer/startupStatus/updated`
- populate it from the app-server conversation ID for the current
thread-scoped lifecycle and regenerate the protocol schema and
TypeScript artifacts
- treat a missing or null `threadId` as app-scoped without injecting it
into the active chat transcript
- route and buffer thread-owned MCP startup notifications by thread in
the TUI
- preserve buffered MCP startup events across child session refresh
- seed expected MCP servers before replaying a thread snapshot so
startup reaches its terminal state
- suppress an identical repeated failure warning for the same server
within one startup round

The owning thread still renders the detailed failure and final `MCP
startup incomplete (...)` summary.

## How to Test

1. Configure an optional MCP server named `smoke` that exits during
initialization.
2. Launch the TUI with multi-agent support enabled.
3. Confirm the main thread's own startup failure renders one detailed
`smoke` warning and one incomplete-startup summary.
4. Spawn exactly one subagent.
5. Confirm the parent transcript does not receive the subagent's MCP
startup failure.
6. Switch to the subagent thread and confirm it contains exactly one
detailed `smoke` failure and one incomplete-startup summary.
7. Confirm the subagent's MCP startup spinner disappears and the thread
remains usable.
8. Switch between the parent and subagent and confirm the warnings
neither move nor duplicate.

Targeted tests:

- `just test -p codex-app-server-protocol`
- `just test -p codex-app-server
thread_start_emits_mcp_server_status_updated_notifications`
- `just test -p codex-tui mcp_startup`

The parent/child behavior and spinner completion were also exercised
manually in tmux. `just argument-comment-lint` was attempted but blocked
by an unrelated local Bazel LLVM empty-glob failure; touched Rust
callsites were inspected manually.
2026-06-07 20:12:05 -07:00

283 lines
11 KiB
Rust

//! MCP startup state and status handling for the chat widget.
//!
//! The app server reports MCP server startup as per-server status updates. This
//! module keeps the TUI's buffered startup round state coherent and translates
//! those updates into status headers, warnings, and queued-input release points.
use std::collections::BTreeSet;
use codex_app_server_protocol::McpServerStartupState;
use codex_app_server_protocol::McpServerStatusUpdatedNotification;
use super::ChatWidget;
const MCP_STARTUP_SINGLE_HEADER_PREFIX: &str = "Booting MCP server:";
const MCP_STARTUP_MULTI_HEADER_PREFIX: &str = "Starting MCP servers";
#[derive(Debug, Clone)]
pub(crate) enum McpStartupStatus {
Starting,
Ready,
Failed { error: String },
Cancelled,
}
impl ChatWidget {
/// Record one MCP startup update, promoting it into either the active startup
/// round or a buffered "next" round.
///
/// This path has to deal with lossy app-server delivery. After
/// `finish_mcp_startup()` or `finish_mcp_startup_after_lag()`, we briefly
/// ignore incoming updates so stale events from the just-finished round do not
/// reopen startup. While that guard is active we buffer updates for a possible
/// next round, and only reactivate once the buffered set is coherent enough to
/// treat as a fresh startup round.
fn update_mcp_startup_status(
&mut self,
server: String,
status: McpStartupStatus,
complete_when_settled: bool,
) {
let mut activated_pending_round = false;
let startup_status = if self.mcp_startup_ignore_updates_until_next_start {
// Ignore-mode buffers the next plausible round so stale post-finish
// updates cannot immediately reopen startup. A fresh `Starting`
// update resets the buffer only if we have not already seen a
// pending-round `Starting`; this preserves valid interleavings like
// `alpha: Starting -> alpha: Ready -> beta: Starting`.
if matches!(status, McpStartupStatus::Starting)
&& !self.mcp_startup_pending_next_round_saw_starting
{
self.mcp_startup_pending_next_round.clear();
self.mcp_startup_allow_terminal_only_next_round = false;
}
self.mcp_startup_pending_next_round_saw_starting |=
matches!(status, McpStartupStatus::Starting);
self.mcp_startup_pending_next_round.insert(server, status);
let Some(expected_servers) = &self.mcp_startup_expected_servers else {
return;
};
let saw_full_round = expected_servers.is_empty()
|| expected_servers
.iter()
.all(|name| self.mcp_startup_pending_next_round.contains_key(name));
let saw_starting = self
.mcp_startup_pending_next_round
.values()
.any(|state| matches!(state, McpStartupStatus::Starting));
if !(saw_full_round
&& (saw_starting || self.mcp_startup_allow_terminal_only_next_round))
{
return;
}
// The buffered map now looks like a complete next round, so promote it
// to the active round and resume normal completion tracking.
self.mcp_startup_ignore_updates_until_next_start = false;
self.mcp_startup_allow_terminal_only_next_round = false;
self.mcp_startup_pending_next_round_saw_starting = false;
activated_pending_round = true;
std::mem::take(&mut self.mcp_startup_pending_next_round)
} else {
// Normal path: fold the update into the active round and surface
// per-server failures immediately.
let mut startup_status = self.mcp_startup_status.take().unwrap_or_default();
if let McpStartupStatus::Failed { error } = &status {
let already_reported = matches!(
startup_status.get(&server),
Some(McpStartupStatus::Failed { error: previous }) if previous == error
);
if !already_reported {
self.on_warning(error);
}
}
startup_status.insert(server, status);
startup_status
};
if activated_pending_round {
// A promoted buffered round may already contain terminal failures.
for state in startup_status.values() {
if let McpStartupStatus::Failed { error } = state {
self.on_warning(error);
}
}
}
self.mcp_startup_status = Some(startup_status);
self.update_task_running_state();
// App-server-backed startup completes when every expected server has
// reported a non-Starting status. Lag handling can force an earlier
// settle via `finish_mcp_startup_after_lag()`.
if complete_when_settled
&& let Some(current) = &self.mcp_startup_status
&& let Some(expected_servers) = &self.mcp_startup_expected_servers
&& !current.is_empty()
&& expected_servers
.iter()
.all(|name| current.contains_key(name))
&& current
.values()
.all(|state| !matches!(state, McpStartupStatus::Starting))
{
let mut failed = Vec::new();
let mut cancelled = Vec::new();
for (name, state) in current {
match state {
McpStartupStatus::Ready => {}
McpStartupStatus::Failed { .. } => failed.push(name.clone()),
McpStartupStatus::Cancelled => cancelled.push(name.clone()),
McpStartupStatus::Starting => {}
}
}
failed.sort();
cancelled.sort();
self.finish_mcp_startup(failed, cancelled);
return;
}
if let Some(current) = &self.mcp_startup_status {
// Otherwise keep the status header focused on the remaining
// in-progress servers for the active round.
let total = current.len();
let mut starting: Vec<_> = current
.iter()
.filter_map(|(name, state)| {
if matches!(state, McpStartupStatus::Starting) {
Some(name)
} else {
None
}
})
.collect();
starting.sort();
if let Some(first) = starting.first() {
let completed = total.saturating_sub(starting.len());
let max_to_show = 3;
let mut to_show: Vec<String> = starting
.iter()
.take(max_to_show)
.map(ToString::to_string)
.collect();
if starting.len() > max_to_show {
to_show.push("…".to_string());
}
let header = if total > 1 {
format!(
"{MCP_STARTUP_MULTI_HEADER_PREFIX} ({completed}/{total}): {}",
to_show.join(", ")
)
} else {
format!("{MCP_STARTUP_SINGLE_HEADER_PREFIX} {first}")
};
self.set_status_header(header);
}
}
self.request_redraw();
}
pub(crate) fn set_mcp_startup_expected_servers<I>(&mut self, server_names: I)
where
I: IntoIterator<Item = String>,
{
self.mcp_startup_expected_servers = Some(server_names.into_iter().collect());
}
pub(super) fn finish_mcp_startup(&mut self, failed: Vec<String>, cancelled: Vec<String>) {
if !cancelled.is_empty() {
self.on_warning(format!(
"MCP startup interrupted. The following servers were not initialized: {}",
cancelled.join(", ")
));
}
let mut parts = Vec::new();
if !failed.is_empty() {
parts.push(format!("failed: {}", failed.join(", ")));
}
if !parts.is_empty() {
self.on_warning(format!("MCP startup incomplete ({})", parts.join("; ")));
}
let mcp_startup_owned_status = self.status_header_is_mcp_startup_owned();
self.mcp_startup_status = None;
self.mcp_startup_ignore_updates_until_next_start = true;
self.mcp_startup_allow_terminal_only_next_round = false;
self.mcp_startup_pending_next_round.clear();
self.mcp_startup_pending_next_round_saw_starting = false;
self.update_task_running_state();
if self.bottom_pane.is_task_running() && mcp_startup_owned_status {
self.restore_reasoning_status_header();
}
self.maybe_send_next_queued_input();
self.request_redraw();
}
pub(crate) fn finish_mcp_startup_after_lag(&mut self) {
if self.mcp_startup_ignore_updates_until_next_start {
if self.mcp_startup_pending_next_round.is_empty() {
self.mcp_startup_pending_next_round_saw_starting = false;
}
self.mcp_startup_allow_terminal_only_next_round = true;
}
let Some(current) = &self.mcp_startup_status else {
return;
};
let mut failed = Vec::new();
let mut cancelled = Vec::new();
let mut server_names: BTreeSet<String> = current.keys().cloned().collect();
if let Some(expected_servers) = &self.mcp_startup_expected_servers {
server_names.extend(expected_servers.iter().cloned());
}
for name in server_names {
match current.get(&name) {
Some(McpStartupStatus::Ready) => {}
Some(McpStartupStatus::Failed { .. }) => failed.push(name),
Some(McpStartupStatus::Cancelled | McpStartupStatus::Starting) | None => {
cancelled.push(name);
}
}
}
failed.sort();
failed.dedup();
cancelled.sort();
cancelled.dedup();
self.finish_mcp_startup(failed, cancelled);
}
pub(super) fn status_header_is_mcp_startup_owned(&self) -> bool {
self.status_state
.current_status
.header
.starts_with(MCP_STARTUP_SINGLE_HEADER_PREFIX)
|| self
.status_state
.current_status
.header
.starts_with(MCP_STARTUP_MULTI_HEADER_PREFIX)
}
pub(super) fn on_mcp_server_status_updated(
&mut self,
notification: McpServerStatusUpdatedNotification,
) {
let status = match notification.status {
McpServerStartupState::Starting => McpStartupStatus::Starting,
McpServerStartupState::Ready => McpStartupStatus::Ready,
McpServerStartupState::Failed => McpStartupStatus::Failed {
error: notification.error.unwrap_or_else(|| {
format!("MCP client for `{}` failed to start", notification.name)
}),
},
McpServerStartupState::Cancelled => McpStartupStatus::Cancelled,
};
self.update_mcp_startup_status(
notification.name,
status,
/*complete_when_settled*/ true,
);
}
}