@@ -24,6 +24,7 @@ pub use tool_catalog::tool_is_model_visible;
2424use std:: collections:: HashMap ;
2525use std:: sync:: Arc ;
2626use std:: sync:: OnceLock ;
27+ use std:: sync:: atomic:: AtomicUsize ;
2728use std:: sync:: atomic:: Ordering ;
2829use std:: time:: Duration ;
2930
@@ -69,13 +70,30 @@ use codex_protocol::protocol::McpStartupStatus;
6970use codex_protocol:: protocol:: McpStartupUpdateEvent ;
7071use codex_rmcp_client:: determine_streamable_http_auth_status_from_credentials;
7172use tokio:: sync:: Mutex ;
73+ use tokio:: sync:: Notify ;
7274use tokio:: sync:: RwLock ;
7375use tokio:: sync:: watch;
7476use tokio:: task:: JoinSet ;
7577use tracing:: warn;
7678
7779static 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+
7997pub ( 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.
202283pub ( 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
206299impl 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