Skip to content

Commit 0a8fb85

Browse files
committed
Wait for MCP cleanup before session shutdown
Why: Retired connections and duplicate shutdown callers could report completion before owned stdio cleanup was confirmed, especially after caller cancellation or a failed termination attempt. What changed: Replace Arc-count polling with explicit connection leases, retain failed retired generations for retry, propagate cleanup failures through runtime and session shutdown, and publish shutdown completion only after the shared MCP cleanup barrier resolves. Validation: Pass codex-mcp 188/188, core shutdown 5/5, refresh cleanup, pending reuse, cancellation and retry regressions, app-server MCP status 10/10, focused MCP hook/proxy reruns, fmt, scoped fix, and diff checks.
1 parent 20e4d94 commit 0a8fb85

13 files changed

Lines changed: 403 additions & 102 deletions

File tree

‎codex-rs/app-server/src/request_processors/apps_processor/installed.rs‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -127,7 +127,7 @@ impl AppsRequestProcessor {
127127
))
128128
};
129129
cancellation_token.cancel();
130-
runtime.shutdown().await;
130+
runtime.shutdown().await?;
131131
result
132132
}
133133
.await;

‎codex-rs/codex-mcp/src/binding.rs‎

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@ use tokio::sync::RwLock;
2222

2323
use crate::McpConfig;
2424
use crate::binding_clients::McpBindingClients;
25+
use crate::connection_manager::McpConnectionLease;
2526
use crate::connection_manager::McpConnectionSet;
2627
use crate::rmcp_client::ManagedClient;
2728
use crate::server::McpServerMetadata;
@@ -30,6 +31,7 @@ use crate::tools::ToolInfo;
3031
/// The exact tool catalog and execution handles shared by compatible sampling steps.
3132
pub struct McpBinding {
3233
connections: Arc<McpConnectionSet>,
34+
_lease: McpConnectionLease,
3335
clients: Arc<McpBindingClients>,
3436
config: Arc<McpConfig>,
3537
plugins_available: bool,
@@ -58,8 +60,10 @@ impl McpBinding {
5860
tools: Vec<ToolInfo>,
5961
calls: HashMap<(String, String), PreparedMcpCall>,
6062
) -> Self {
63+
let lease = connections.acquire_lease();
6164
Self {
6265
connections,
66+
_lease: lease,
6367
clients,
6468
config,
6569
plugins_available,
@@ -169,7 +173,7 @@ impl fmt::Debug for McpBinding {
169173
/// one [`McpBinding`].
170174
#[derive(Clone)]
171175
pub struct PreparedMcpCall {
172-
_connections: Arc<McpConnectionSet>,
176+
_lease: McpConnectionLease,
173177
client: Arc<ManagedClient>,
174178
config: Arc<McpConfig>,
175179
catalog_revision: u64,
@@ -198,8 +202,9 @@ impl PreparedMcpCall {
198202
selected_plugin_server: bool,
199203
) -> Self {
200204
let server_name = tool_info.server_name.clone();
205+
let lease = connections.acquire_lease();
201206
Self {
202-
_connections: connections,
207+
_lease: lease,
203208
client,
204209
config,
205210
catalog_revision,

‎codex-rs/codex-mcp/src/binding_tests.rs‎

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -231,14 +231,14 @@ async fn prepared_call_keeps_captured_connection_and_authority_after_refresh() -
231231
);
232232

233233
drop(old.step);
234-
assert!(
235-
old_connections.upgrade().is_some(),
236-
"the prepared call should keep its captured connection set alive"
237-
);
238-
drop(old_call);
239234
assert!(
240235
old_connections.upgrade().is_none(),
241-
"the captured connection set should be released with the prepared call"
236+
"explicit leases should not retain the whole captured connection set"
237+
);
238+
assert_eq!(
239+
old_call._lease.active_count(),
240+
1,
241+
"the prepared call should keep one explicit connection lease"
242242
);
243243
Ok(())
244244
}

‎codex-rs/codex-mcp/src/connection_manager.rs‎

Lines changed: 149 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@ pub use tool_catalog::tool_is_model_visible;
2424
use std::collections::HashMap;
2525
use std::sync::Arc;
2626
use std::sync::OnceLock;
27+
use std::sync::atomic::AtomicUsize;
2728
use std::sync::atomic::Ordering;
2829
use std::time::Duration;
2930

@@ -69,13 +70,30 @@ use codex_protocol::protocol::McpStartupStatus;
6970
use codex_protocol::protocol::McpStartupUpdateEvent;
7071
use codex_rmcp_client::determine_streamable_http_auth_status_from_credentials;
7172
use tokio::sync::Mutex;
73+
use tokio::sync::Notify;
7274
use tokio::sync::RwLock;
7375
use tokio::sync::watch;
7476
use tokio::task::JoinSet;
7577
use tracing::warn;
7678

7779
static LIVE_CONNECTIONS: Gauge = Gauge::new("mcp.connections.live");
7880

81+
fn collect_shutdown_failures(outcomes: Vec<Result<()>>) -> Result<()> {
82+
let failures = outcomes
83+
.into_iter()
84+
.filter_map(Result::err)
85+
.map(|error| format!("{error:#}"))
86+
.collect::<Vec<_>>();
87+
if failures.is_empty() {
88+
Ok(())
89+
} else {
90+
Err(anyhow!(
91+
"one or more MCP servers failed to shut down: {}",
92+
failures.join("; ")
93+
))
94+
}
95+
}
96+
7997
pub(crate) struct McpServerConnection {
8098
identity: Option<McpServerConnectionIdentity>,
8199
client: AsyncManagedClient,
@@ -128,12 +146,12 @@ impl McpServerConnection {
128146
self.client.client().await
129147
}
130148

131-
pub(crate) async fn shutdown(&self) {
149+
pub(crate) async fn shutdown(&self) -> Result<()> {
132150
if self.startup_is_dormant() {
133151
self.client.cancel_token.cancel();
134-
return;
152+
return Ok(());
135153
}
136-
self.client.shutdown().await;
154+
self.client.shutdown().await
137155
}
138156

139157
fn cancel_startup(&self) {
@@ -192,6 +210,69 @@ pub(crate) struct McpConnectionSet {
192210
prefix_mcp_tool_names: bool,
193211
non_prefixed_mcp_tool_servers: Vec<String>,
194212
elicitation_requests: ElicitationRequestManager,
213+
lease_tracker: Arc<McpConnectionLeaseTracker>,
214+
}
215+
216+
struct McpConnectionLeaseTracker {
217+
active: AtomicUsize,
218+
released: Notify,
219+
}
220+
221+
pub(crate) struct McpConnectionLease {
222+
tracker: Arc<McpConnectionLeaseTracker>,
223+
}
224+
225+
impl Clone for McpConnectionLease {
226+
fn clone(&self) -> Self {
227+
self.tracker.active.fetch_add(1, Ordering::Relaxed);
228+
Self {
229+
tracker: Arc::clone(&self.tracker),
230+
}
231+
}
232+
}
233+
234+
impl Drop for McpConnectionLease {
235+
fn drop(&mut self) {
236+
if self.tracker.active.fetch_sub(1, Ordering::AcqRel) == 1 {
237+
self.tracker.released.notify_waiters();
238+
}
239+
}
240+
}
241+
242+
#[cfg(test)]
243+
impl McpConnectionLease {
244+
pub(crate) fn active_count(&self) -> usize {
245+
self.tracker.active.load(Ordering::Acquire)
246+
}
247+
}
248+
249+
impl McpConnectionLeaseTracker {
250+
fn new() -> Self {
251+
Self {
252+
active: AtomicUsize::new(0),
253+
released: Notify::new(),
254+
}
255+
}
256+
257+
fn acquire(self: &Arc<Self>) -> McpConnectionLease {
258+
self.active.fetch_add(1, Ordering::Relaxed);
259+
McpConnectionLease {
260+
tracker: Arc::clone(self),
261+
}
262+
}
263+
264+
async fn wait_until_released(&self) {
265+
loop {
266+
if self.active.load(Ordering::Acquire) == 0 {
267+
return;
268+
}
269+
let released = self.released.notified();
270+
if self.active.load(Ordering::Acquire) == 0 {
271+
return;
272+
}
273+
released.await;
274+
}
275+
}
195276
}
196277

197278
/// Connections removed from a publication and no longer shared by its
@@ -201,24 +282,52 @@ pub(crate) struct McpConnectionSet {
201282
/// hold additional strong references that act as in-flight leases.
202283
pub(crate) struct McpConnectionRetirement {
203284
pub(crate) connections: Vec<Arc<McpServerConnection>>,
285+
lease_tracker: Arc<McpConnectionLeaseTracker>,
286+
}
287+
288+
pub(crate) struct McpConnectionRetirementFailure {
289+
pub(crate) connections: Vec<Arc<McpServerConnection>>,
290+
message: String,
291+
}
292+
293+
impl std::fmt::Display for McpConnectionRetirementFailure {
294+
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
295+
formatter.write_str(&self.message)
296+
}
204297
}
205298

206299
impl McpConnectionRetirement {
207300
/// Waits for captured bindings to release each retired connection, then
208301
/// shuts all eligible connections down concurrently.
209-
pub(crate) async fn shutdown_when_unleased(self) {
210-
futures::future::join_all(self.connections.into_iter().map(|connection| async move {
211-
// This future owns one strong reference. Because the connection is
212-
// absent from the successor publication, any additional strong
213-
// references are binding leases that must finish before shutdown.
214-
// Final thread shutdown may upgrade a tracked Weak concurrently,
215-
// which is safe because process cleanup is shared and idempotent.
216-
while Arc::strong_count(&connection) > 1 {
217-
tokio::time::sleep(Duration::from_millis(10)).await;
302+
pub(crate) async fn shutdown_when_unleased(
303+
self,
304+
) -> std::result::Result<(), McpConnectionRetirementFailure> {
305+
self.lease_tracker.wait_until_released().await;
306+
let outcomes =
307+
futures::future::join_all(self.connections.into_iter().map(|connection| async move {
308+
let result = connection.shutdown().await;
309+
(connection, result)
310+
}))
311+
.await;
312+
let mut connections = Vec::new();
313+
let mut failures = Vec::new();
314+
for (connection, outcome) in outcomes {
315+
if let Err(error) = outcome {
316+
connections.push(connection);
317+
failures.push(format!("{error:#}"));
218318
}
219-
connection.shutdown().await;
220-
}))
221-
.await;
319+
}
320+
if failures.is_empty() {
321+
Ok(())
322+
} else {
323+
Err(McpConnectionRetirementFailure {
324+
connections,
325+
message: format!(
326+
"one or more retired MCP connections failed to shut down: {}",
327+
failures.join("; ")
328+
),
329+
})
330+
}
222331
}
223332
}
224333

@@ -240,7 +349,10 @@ impl McpConnectionSet {
240349
connections.push(Arc::clone(connection));
241350
}
242351
}
243-
(!connections.is_empty()).then_some(McpConnectionRetirement { connections })
352+
(!connections.is_empty()).then_some(McpConnectionRetirement {
353+
connections,
354+
lease_tracker: Arc::clone(&previous.lease_tracker),
355+
})
244356
}
245357

246358
/// Creates an MCP connection manager. Threadless callers can pass no `tx_event`; startup
@@ -723,6 +835,7 @@ impl McpConnectionSet {
723835
prefix_mcp_tool_names,
724836
non_prefixed_mcp_tool_servers,
725837
elicitation_requests: elicitation_requests.clone(),
838+
lease_tracker: Arc::new(McpConnectionLeaseTracker::new()),
726839
};
727840
let summary_publication_gate = publication_gate;
728841
tokio::spawn(async move {
@@ -788,9 +901,14 @@ impl McpConnectionSet {
788901
/*lifecycle*/ None,
789902
ElicitationRequestRouter::default(),
790903
),
904+
lease_tracker: Arc::new(McpConnectionLeaseTracker::new()),
791905
}
792906
}
793907

908+
pub(crate) fn acquire_lease(&self) -> McpConnectionLease {
909+
self.lease_tracker.acquire()
910+
}
911+
794912
pub fn has_servers(&self) -> bool {
795913
!self.servers.is_empty()
796914
}
@@ -861,26 +979,31 @@ impl McpConnectionSet {
861979
}
862980

863981
/// Stop all MCP clients owned by this manager and terminate stdio server processes.
864-
pub async fn shutdown(&self) {
982+
pub async fn shutdown(&self) -> Result<()> {
865983
let connections = self
866984
.servers
867-
.values()
868-
.map(|view| Arc::clone(&view.connection))
985+
.iter()
986+
.map(|(server_name, view)| (server_name.clone(), Arc::clone(&view.connection)))
869987
.collect::<Vec<_>>();
870988
// Keep cleanup alive if an interrupt cancels the refresh that requested it.
871989
let shutdown_task = tokio::spawn(async move {
872990
// A TERM grace period belongs to each process tree. Run them in
873991
// parallel so shutdown latency is bounded by the slowest tree,
874992
// rather than by the number of configured servers.
875-
futures::future::join_all(
876-
connections
877-
.into_iter()
878-
.map(|connection| async move { connection.shutdown().await }),
879-
)
993+
let outcomes = futures::future::join_all(connections.into_iter().map(
994+
|(server_name, connection)| async move {
995+
connection
996+
.shutdown()
997+
.await
998+
.with_context(|| format!("failed to shut down MCP server `{server_name}`"))
999+
},
1000+
))
8801001
.await;
1002+
collect_shutdown_failures(outcomes)
8811003
});
882-
if let Err(error) = shutdown_task.await {
883-
warn!("MCP client shutdown task failed: {error}");
1004+
match shutdown_task.await {
1005+
Ok(result) => result,
1006+
Err(error) => Err(anyhow!("MCP client shutdown task failed: {error}")),
8841007
}
8851008
}
8861009

0 commit comments

Comments
 (0)