Skip to main content

adk_tool/mcp/manager/
manager.rs

1//! McpServerManager implementation.
2//!
3//! This module contains the main [`McpServerManager`] struct and its
4//! construction/builder methods, as well as lifecycle methods (start, stop,
5//! restart) for individual servers.
6
7use std::collections::{BTreeSet, HashMap};
8use std::sync::{
9    Arc, Mutex as StdMutex,
10    atomic::{AtomicBool, Ordering},
11};
12use std::time::Duration;
13
14use adk_core::AdkError;
15use tokio::sync::RwLock;
16use tokio_util::sync::CancellationToken;
17
18use super::super::discovery::McpDiscoveryLimits;
19use super::super::elicitation::{
20    AdkClientHandler, AutoDeclineElicitationHandler, ElicitationHandler,
21};
22use super::super::resource_notifications::ResourceNotificationHandler;
23use super::super::schema_limits::McpSchemaLimits;
24use super::super::toolset::McpToolset;
25use super::super::{GetPromptResult, Prompt, Resource, ResourceContents, ResourceTemplate};
26use super::config::McpServerConfig;
27use super::entry::{BackoffState, McpServerEntry};
28use super::status::{ServerStatus, ServerStatusTransition, StatusSender};
29
30/// Builds the command that starts a stdio server from its configuration (spec 3.2 §10 T1).
31type StdioLauncher =
32    Arc<dyn Fn(&McpServerConfig) -> adk_core::Result<tokio::process::Command> + Send + Sync>;
33
34/// Manages the full lifecycle of multiple local MCP server child processes.
35///
36/// `McpServerManager` spawns processes, connects them via `TokioChildProcess`
37/// transport into [`McpToolset`](super::super::McpToolset) instances, monitors
38/// health, auto-restarts on crash with exponential backoff, and aggregates tools
39/// from all managed servers behind the [`Toolset`](adk_core::Toolset) trait.
40///
41/// On Windows each server starts suspended and runs only once it is in a Job Object of its
42/// own, which closes with its connection: stopping, restarting or dropping a server, or the
43/// manager's process exiting, ends every process the server started (spec 3.2 §10 W1). On
44/// Unix each server leads a session and process group of its own, which closes with its
45/// connection: stopping, restarting or dropping a server sends the group `SIGTERM`, then
46/// `SIGKILL`, and returns once every process in it has exited (spec 3.2 §7.7, K-I5).
47///
48/// # Construction
49///
50/// Use [`McpServerManager::new`] with a map of server configurations, then chain
51/// builder methods to configure handlers and intervals:
52///
53/// ```rust,ignore
54/// use adk_tool::mcp::manager::{McpServerConfig, McpServerManager};
55/// use std::collections::HashMap;
56/// use std::time::Duration;
57///
58/// let configs = HashMap::from([
59///     ("my-server".to_string(), McpServerConfig {
60///         command: "/opt/company/bin/workspace-mcp".to_string(),
61///         args: vec!["--stdio".to_string(), "--root".to_string(), "/srv/workspace".to_string()],
62///         ..Default::default()
63///     }),
64/// ]);
65///
66/// let manager = McpServerManager::new(configs)
67///     .with_health_check_interval(Duration::from_secs(15))
68///     .with_grace_period(Duration::from_secs(3))
69///     .with_name("my_manager");
70/// ```
71#[allow(dead_code)] // Fields used by lifecycle methods in later tasks
72pub struct McpServerManager {
73    /// Thread-safe map of server ID to per-server state.
74    pub(crate) servers: Arc<RwLock<HashMap<String, McpServerEntry>>>,
75
76    /// Optional elicitation handler shared across all managed server connections.
77    pub(crate) elicitation_handler: Option<Arc<dyn ElicitationHandler>>,
78
79    /// Optional resource notification handler shared across all managed connections.
80    pub(crate) resource_notification_handler: Option<Arc<dyn ResourceNotificationHandler>>,
81
82    /// Resource subscriptions restored when a managed process reconnects.
83    pub(crate) resource_subscriptions: Arc<RwLock<HashMap<String, BTreeSet<String>>>>,
84
85    /// Optional sampling handler shared across all managed server connections.
86    /// Only available when the `mcp-sampling` feature is enabled.
87    #[cfg(feature = "mcp-sampling")]
88    pub(crate) sampling_handler: Option<Arc<dyn crate::sampling::SamplingHandler>>,
89
90    /// Elicitation handlers of single servers, preferred over the shared one
91    /// (spec 3.1 §10 T2).
92    pub(crate) server_elicitation_handlers: HashMap<String, Arc<dyn ElicitationHandler>>,
93
94    /// Sampling handlers of single servers, preferred over the shared one (spec 3.1 §10 T2).
95    #[cfg(feature = "mcp-sampling")]
96    pub(crate) server_sampling_handlers: HashMap<String, Arc<dyn crate::sampling::SamplingHandler>>,
97
98    /// Interval between health check cycles. Default: 30 seconds.
99    pub(crate) health_check_interval: Duration,
100
101    /// Grace period to wait for a cancelled MCP session and its child process before dropping its transport. Default: 5 seconds.
102    pub(crate) grace_period: Duration,
103
104    /// Cancellation token used to stop the health monitoring background task.
105    pub(crate) monitor_cancel: StdMutex<CancellationToken>,
106
107    /// Prevents duplicate health-monitor tasks and permits a stopped monitor to restart.
108    pub(crate) monitor_running: Arc<AtomicBool>,
109
110    /// Name returned by the `Toolset::name()` implementation. Default: `"mcp_server_manager"`.
111    pub(crate) name: String,
112
113    /// Size limits applied to the tool schemas of every managed server.
114    pub(crate) schema_limits: McpSchemaLimits,
115
116    /// Bounds on each catalog listing of every managed server.
117    pub(crate) discovery_limits: McpDiscoveryLimits,
118
119    /// Longest time a server's spawn and MCP handshake may take. Default: 30 seconds.
120    pub(crate) startup_timeout: Duration,
121
122    /// Publishes every status change as `(id, from, to)` (spec 3.2 §10 T1).
123    pub(crate) status_events: StatusSender,
124
125    /// Builds each stdio server's command in place of the configured one (spec 3.2 §10 T1).
126    pub(crate) stdio_launcher: Option<StdioLauncher>,
127}
128
129/// The limits every managed toolset is built with.
130#[derive(Clone, Copy)]
131struct ToolsetLimits {
132    schema: McpSchemaLimits,
133    discovery: McpDiscoveryLimits,
134}
135
136/// Everything a server start needs, detached from the manager so the health monitor's
137/// task can start servers too.
138#[derive(Clone)]
139struct Launcher {
140    servers: Arc<RwLock<HashMap<String, McpServerEntry>>>,
141    elicitation_handler: Option<Arc<dyn ElicitationHandler>>,
142    resource_notification_handler: Option<Arc<dyn ResourceNotificationHandler>>,
143    resource_subscriptions: Arc<RwLock<HashMap<String, BTreeSet<String>>>>,
144    limits: ToolsetLimits,
145    startup_timeout: Duration,
146    #[cfg(feature = "mcp-sampling")]
147    sampling_handler: Option<Arc<dyn crate::sampling::SamplingHandler>>,
148    server_elicitation_handlers: HashMap<String, Arc<dyn ElicitationHandler>>,
149    #[cfg(feature = "mcp-sampling")]
150    server_sampling_handlers: HashMap<String, Arc<dyn crate::sampling::SamplingHandler>>,
151    status_events: StatusSender,
152    stdio_launcher: Option<StdioLauncher>,
153}
154
155impl Launcher {
156    /// Starts server `id`.
157    ///
158    /// The registry lock is held only to read the configuration and to record the
159    /// outcome, never across the spawn and handshake, so a server that never answers
160    /// delays only its own start. Starts of one server are serialized by its gate.
161    async fn start(&self, id: &str) -> adk_core::Result<()> {
162        let unknown = || AdkError::tool(format!("unknown server ID: '{id}'"));
163        let gate = self.servers.read().await.get(id).map(|entry| entry.start_gate.clone());
164        let gate = gate.ok_or_else(unknown)?;
165        let _starting = gate.lock().await;
166
167        let (config, generation, cancel) = {
168            let mut servers = self.servers.write().await;
169            let entry = servers.get_mut(id).ok_or_else(unknown)?;
170            if entry.status == ServerStatus::Running {
171                return Ok(());
172            }
173            if entry.config.disabled {
174                entry.set_status(id, ServerStatus::Disabled, &self.status_events);
175                return Err(AdkError::tool(format!(
176                    "MCP server '{id}' is disabled; enable it before starting"
177                )));
178            }
179            if entry.config.command.trim().is_empty() {
180                entry.set_status(id, ServerStatus::FailedToStart, &self.status_events);
181                return Err(AdkError::tool(format!("MCP server '{id}' has an empty command")));
182            }
183            entry.set_status(id, ServerStatus::Starting, &self.status_events);
184            entry.generation += 1;
185            entry.startup_cancel = CancellationToken::new();
186            (entry.config.clone(), entry.generation, entry.startup_cancel.clone())
187        };
188
189        let connected = tokio::select! {
190            connected = tokio::time::timeout(self.startup_timeout, self.connect(id, &config)) => {
191                connected.unwrap_or_else(|_| {
192                    Err(AdkError::tool(format!(
193                        "MCP server '{id}' did not complete its handshake within {:?}; raise \
194                         McpServerManager::with_startup_timeout if it starts this slowly",
195                        self.startup_timeout
196                    )))
197                })
198            }
199            // Dropping the handshake drops its transport, which ends the child.
200            () = cancel.cancelled() => Err(AdkError::tool(format!(
201                "MCP server '{id}' was stopped while it was starting"
202            ))),
203        };
204
205        let mut servers = self.servers.write().await;
206        let Some(entry) = servers.get_mut(id).filter(|entry| entry.generation == generation) else {
207            // Stopped, updated or removed meanwhile: a new connection is dropped here,
208            // which ends its child process.
209            return Err(AdkError::tool(format!(
210                "MCP server '{id}' was stopped while it was starting"
211            )));
212        };
213        match connected {
214            Ok(toolset) => {
215                entry.set_status(id, ServerStatus::Running, &self.status_events);
216                entry.toolset = Some(toolset);
217                entry.child = None; // Child is owned by the transport/toolset
218                tracing::info!(
219                    server.id = id,
220                    server.command = config.command,
221                    server.args = ?config.args,
222                    "started MCP server"
223                );
224                Ok(())
225            }
226            Err(error) => {
227                entry.set_status(id, ServerStatus::FailedToStart, &self.status_events);
228                Err(error)
229            }
230        }
231    }
232
233    /// Spawns the server's command and completes the MCP handshake with it.
234    ///
235    /// The command is the stdio launcher's when one is set, else the configured one.
236    async fn connect(
237        &self,
238        id: &str,
239        config: &McpServerConfig,
240    ) -> adk_core::Result<McpToolset<AdkClientHandler>> {
241        let cmd = match &self.stdio_launcher {
242            Some(launch) => launch(config)?,
243            None => {
244                let mut cmd = tokio::process::Command::new(&config.command);
245                cmd.args(&config.args);
246                cmd.envs(&config.env);
247                cmd
248            }
249        };
250        // What holds the server's process tree — a Job Object on Windows, a process group on
251        // Unix — closes with the transport, ending the whole tree (spec 3.2 §10 W1, K-I5).
252        let transport = super::process_tree::spawn(id, cmd)?;
253
254        // Build one handler for both lifecycle negotiation and later MRTR/task input.
255        // A handler set for this server wins over the shared one (spec 3.1 §10 T2).
256        let handler: Arc<dyn ElicitationHandler> = self
257            .server_elicitation_handlers
258            .get(id)
259            .cloned()
260            .or_else(|| self.elicitation_handler.clone())
261            .unwrap_or_else(|| Arc::new(AutoDeclineElicitationHandler));
262
263        let mut adk_handler = AdkClientHandler::new(handler);
264        // Servers may give their tools apps, which a host shows sandboxed (spec 3.3 §6.1).
265        #[cfg(feature = "mcp-apps")]
266        {
267            adk_handler = adk_handler.with_apps();
268        }
269        if config.task_config.enable_tasks {
270            adk_handler = adk_handler.with_tasks();
271        }
272        if let Some(resource_handler) = &self.resource_notification_handler {
273            adk_handler =
274                adk_handler.with_resource_notification_handler(Arc::clone(resource_handler));
275        }
276        #[cfg(feature = "mcp-sampling")]
277        if let Some(sampling) =
278            self.server_sampling_handlers.get(id).or(self.sampling_handler.as_ref())
279        {
280            adk_handler = adk_handler.with_sampling_handler(Arc::clone(sampling));
281        }
282
283        let input_handler = adk_handler.clone();
284        use rmcp::ClientServiceExt;
285        let client = adk_handler
286            .serve_with_lifecycle(transport, config.lifecycle.to_rmcp())
287            .await
288            .map_err(|error| {
289                AdkError::tool(format!(
290                    "MCP handshake failed for server '{id}': failed to connect MCP server: {error}"
291                ))
292            })?;
293        let toolset = McpToolset::new(client)
294            .with_name(id)
295            .with_schema_limits(self.limits.schema)
296            .with_discovery_limits(self.limits.discovery)
297            .with_task_support(config.task_config.clone())
298            .with_mrtr_handler(input_handler);
299
300        let subscriptions =
301            self.resource_subscriptions.read().await.get(id).cloned().unwrap_or_default();
302        for uri in subscriptions {
303            if let Err(error) = toolset.subscribe_resource(&uri).await {
304                tracing::warn!(server.id = id, %uri, %error, "failed to restore MCP resource subscription");
305            }
306        }
307        Ok(toolset)
308    }
309}
310
311impl McpServerManager {
312    fn validate_server_id(id: &str) -> adk_core::Result<()> {
313        if id.is_empty()
314            || !id.chars().all(|character| {
315                character.is_ascii_alphanumeric() || matches!(character, '-' | '_')
316            })
317        {
318            return Err(AdkError::tool(
319                "MCP server IDs must contain only ASCII letters, numbers, '-' or '_'",
320            ));
321        }
322        Ok(())
323    }
324
325    /// Create a new `McpServerManager` from a map of server configurations.
326    ///
327    /// Each entry is keyed by a unique server ID. Servers with `disabled: true`
328    /// are initialized with [`ServerStatus::Disabled`]; all others start as
329    /// [`ServerStatus::Stopped`].
330    ///
331    /// No servers are started automatically — call [`start_server`](Self::start_server)
332    /// or [`start_all`](Self::start_all) to begin spawning processes.
333    pub fn new(configs: HashMap<String, McpServerConfig>) -> Self {
334        let servers: HashMap<String, McpServerEntry> =
335            configs.into_iter().map(|(id, config)| (id, McpServerEntry::new(config))).collect();
336
337        Self {
338            servers: Arc::new(RwLock::new(servers)),
339            elicitation_handler: None,
340            resource_notification_handler: None,
341            resource_subscriptions: Arc::new(RwLock::new(HashMap::new())),
342            #[cfg(feature = "mcp-sampling")]
343            sampling_handler: None,
344            server_elicitation_handlers: HashMap::new(),
345            #[cfg(feature = "mcp-sampling")]
346            server_sampling_handlers: HashMap::new(),
347            health_check_interval: Duration::from_secs(30),
348            grace_period: Duration::from_secs(5),
349            monitor_cancel: StdMutex::new(CancellationToken::new()),
350            monitor_running: Arc::new(AtomicBool::new(false)),
351            name: "mcp_server_manager".to_string(),
352            schema_limits: McpSchemaLimits::default(),
353            discovery_limits: McpDiscoveryLimits::default(),
354            startup_timeout: Self::DEFAULT_STARTUP_TIMEOUT,
355            status_events: tokio::sync::broadcast::channel(Self::STATUS_CHANNEL_CAPACITY).0,
356            stdio_launcher: None,
357        }
358    }
359
360    /// Create a new `McpServerManager` by parsing a JSON string in Kiro `mcp.json` format.
361    ///
362    /// The JSON must contain a top-level `mcpServers` object mapping server IDs
363    /// to their configurations. CamelCase JSON field names are automatically
364    /// mapped to snake_case Rust fields.
365    ///
366    /// # Errors
367    ///
368    /// Returns `AdkError::Tool` if the JSON is malformed or missing required fields.
369    ///
370    /// # Example
371    ///
372    /// ```rust,ignore
373    /// let json = r#"{
374    ///     "mcpServers": {
375    ///         "workspace": {
376    ///             "command": "/opt/company/bin/workspace-mcp",
377    ///             "args": ["--stdio", "--root", "/srv/workspace"]
378    ///         }
379    ///     }
380    /// }"#;
381    /// let manager = McpServerManager::from_json(json)?;
382    /// ```
383    pub fn from_json(json: &str) -> adk_core::Result<Self> {
384        let file: super::config::McpJsonFile = serde_json::from_str(json)
385            .map_err(|e| AdkError::tool(format!("failed to parse MCP server config: {e}")))?;
386        for id in file.mcp_servers.keys() {
387            Self::validate_server_id(id)?;
388        }
389        Ok(Self::new(file.mcp_servers))
390    }
391
392    /// Create a new `McpServerManager` by reading and parsing a JSON file from disk.
393    ///
394    /// The file must contain JSON in Kiro `mcp.json` format (see [`from_json`](Self::from_json)).
395    /// File reading is synchronous, which is acceptable for config loading at startup.
396    ///
397    /// # Errors
398    ///
399    /// Returns `AdkError::Tool` if the file cannot be read or the JSON is malformed.
400    ///
401    /// # Example
402    ///
403    /// ```rust,ignore
404    /// let manager = McpServerManager::from_json_file("mcp.json")?;
405    /// ```
406    pub fn from_json_file(path: impl AsRef<std::path::Path>) -> adk_core::Result<Self> {
407        let path = path.as_ref();
408        let content = std::fs::read_to_string(path).map_err(|e| {
409            AdkError::tool(format!("failed to read config file '{}': {e}", path.display()))
410        })?;
411        Self::from_json(&content)
412    }
413
414    /// Set the elicitation handler used for all managed server connections.
415    ///
416    /// The handler is preserved across server restarts via `Arc` sharing.
417    pub fn with_elicitation_handler(mut self, handler: Arc<dyn ElicitationHandler>) -> Self {
418        self.elicitation_handler = Some(handler);
419        self
420    }
421
422    /// Set the resource notification handler used for all managed connections.
423    ///
424    /// The handler is retained across manual and automatic server restarts.
425    pub fn with_resource_notification_handler(
426        mut self,
427        handler: Arc<dyn ResourceNotificationHandler>,
428    ) -> Self {
429        self.resource_notification_handler = Some(handler);
430        self
431    }
432
433    /// Set the sampling handler used for all managed server connections.
434    ///
435    /// The handler is preserved across server restarts via `Arc` sharing.
436    /// Only available when the `mcp-sampling` feature is enabled.
437    #[cfg(feature = "mcp-sampling")]
438    pub fn with_sampling_handler(
439        mut self,
440        handler: Arc<dyn crate::sampling::SamplingHandler>,
441    ) -> Self {
442        self.sampling_handler = Some(handler);
443        self
444    }
445
446    /// Sets the elicitation handler of server `id` alone, preferred over the shared one
447    /// (spec 3.1 §10 T2).
448    ///
449    /// A server without its own handler uses the shared one, or declines.
450    ///
451    /// # Example
452    ///
453    /// ```rust
454    /// use std::collections::HashMap;
455    /// use std::sync::Arc;
456    /// use adk_tool::mcp::{AutoDeclineElicitationHandler, McpServerManager};
457    ///
458    /// let manager = McpServerManager::new(HashMap::new())
459    ///     .with_server_elicitation_handler("fs", Arc::new(AutoDeclineElicitationHandler));
460    /// assert!(manager.server_elicitation_handler("fs").is_some());
461    /// assert!(manager.server_elicitation_handler("other").is_none());
462    /// ```
463    pub fn with_server_elicitation_handler(
464        mut self,
465        id: impl Into<String>,
466        handler: Arc<dyn ElicitationHandler>,
467    ) -> Self {
468        self.server_elicitation_handlers.insert(id.into(), handler);
469        self
470    }
471
472    /// The elicitation handler set for server `id` alone, if any.
473    pub fn server_elicitation_handler(&self, id: &str) -> Option<Arc<dyn ElicitationHandler>> {
474        self.server_elicitation_handlers.get(id).cloned()
475    }
476
477    /// Sets the sampling handler of server `id` alone, preferred over the shared one
478    /// (spec 3.1 §10 T2), so one server may sample while another cannot.
479    ///
480    /// # Example
481    ///
482    /// ```rust,ignore
483    /// let manager = McpServerManager::new(configs)
484    ///     .with_server_sampling_handler("summarizer", Arc::new(LlmSamplingHandler::new(model)));
485    /// ```
486    #[cfg(feature = "mcp-sampling")]
487    pub fn with_server_sampling_handler(
488        mut self,
489        id: impl Into<String>,
490        handler: Arc<dyn crate::sampling::SamplingHandler>,
491    ) -> Self {
492        self.server_sampling_handlers.insert(id.into(), handler);
493        self
494    }
495
496    /// The sampling handler set for server `id` alone, if any.
497    #[cfg(feature = "mcp-sampling")]
498    pub fn server_sampling_handler(
499        &self,
500        id: &str,
501    ) -> Option<Arc<dyn crate::sampling::SamplingHandler>> {
502        self.server_sampling_handlers.get(id).cloned()
503    }
504
505    /// Set the interval between health check cycles.
506    ///
507    /// Default: 30 seconds.
508    pub fn with_health_check_interval(mut self, interval: Duration) -> Self {
509        self.health_check_interval = interval;
510        self
511    }
512
513    /// Set the grace period reserved for managed-session shutdown.
514    ///
515    /// The period covers cancelling the server's pending MCP tasks and closing
516    /// its session. Default: 5 seconds.
517    pub fn with_grace_period(mut self, period: Duration) -> Self {
518        self.grace_period = period;
519        self
520    }
521
522    /// Set the name returned by the `Toolset::name()` implementation.
523    ///
524    /// Default: `"mcp_server_manager"`.
525    pub fn with_name(mut self, name: impl Into<String>) -> Self {
526        self.name = name.into();
527        self
528    }
529
530    /// Set the size limits applied to the tool schemas of every managed server.
531    ///
532    /// Each managed toolset is named after its server ID, so the warning for a
533    /// skipped tool names the server. Default: [`McpSchemaLimits::default`].
534    ///
535    /// # Example
536    ///
537    /// ```
538    /// use adk_tool::mcp::{McpSchemaLimits, McpServerManager};
539    /// use std::collections::HashMap;
540    ///
541    /// let manager = McpServerManager::new(HashMap::new())
542    ///     .with_schema_limits(McpSchemaLimits::default().with_max_nodes(20_000));
543    /// ```
544    pub fn with_schema_limits(mut self, limits: McpSchemaLimits) -> Self {
545        self.schema_limits = limits;
546        self
547    }
548
549    /// Set the bounds on each catalog listing of every managed server.
550    ///
551    /// [`Toolset::tools`](adk_core::Toolset::tools) lists every running server
552    /// concurrently, so a server that pages without end or never answers costs
553    /// at most `timeout` and the other servers' tools still resolve. Default:
554    /// [`McpDiscoveryLimits::default`].
555    ///
556    /// # Example
557    ///
558    /// ```
559    /// use adk_tool::mcp::{McpDiscoveryLimits, McpServerManager};
560    /// use std::collections::HashMap;
561    /// use std::time::Duration;
562    ///
563    /// let manager = McpServerManager::new(HashMap::new())
564    ///     .with_discovery_limits(McpDiscoveryLimits::default().with_timeout(Duration::from_secs(5)));
565    /// ```
566    pub fn with_discovery_limits(mut self, limits: McpDiscoveryLimits) -> Self {
567        self.discovery_limits = limits;
568        self
569    }
570
571    /// Default for [`with_startup_timeout`](Self::with_startup_timeout): 30 seconds.
572    pub const DEFAULT_STARTUP_TIMEOUT: Duration = Duration::from_secs(30);
573
574    /// Set the longest time a server's spawn and MCP handshake may take.
575    ///
576    /// A server that has not completed its handshake by then is stopped and marked
577    /// [`ServerStatus::FailedToStart`]. The other servers' tools, statuses and
578    /// lifecycle calls are not held up while one server starts. Default:
579    /// [`DEFAULT_STARTUP_TIMEOUT`](Self::DEFAULT_STARTUP_TIMEOUT).
580    ///
581    /// # Example
582    ///
583    /// ```
584    /// use adk_tool::mcp::McpServerManager;
585    /// use std::collections::HashMap;
586    /// use std::time::Duration;
587    ///
588    /// // `npx` may download its package on first start.
589    /// let manager = McpServerManager::new(HashMap::new())
590    ///     .with_startup_timeout(Duration::from_secs(120));
591    /// ```
592    pub fn with_startup_timeout(mut self, timeout: Duration) -> Self {
593        self.startup_timeout = timeout;
594        self
595    }
596
597    /// Transitions the status channel retains for a receiver that has not read them
598    /// (spec 3.2 §10 T1): 256.
599    pub const STATUS_CHANNEL_CAPACITY: usize = 256;
600
601    /// Subscribes to every [`ServerStatus`] transition of every managed server
602    /// (spec 3.2 §10 T1).
603    ///
604    /// The manager publishes a [`ServerStatusTransition`] `(id, from, to)` wherever it
605    /// changes a server's status — starts, stops, restarts, the health monitor's crash and
606    /// auto-restart handling, `update_server`, `enable_server`, `disable_server` and
607    /// `shutdown` — while it holds the registry lock, so a receiver sees each server's
608    /// changes in the order they happened. The receiver sees only transitions published
609    /// after it subscribed; read [`all_statuses`](Self::all_statuses) after subscribing to
610    /// learn the state they start from. A receiver more than
611    /// [`STATUS_CHANNEL_CAPACITY`](Self::STATUS_CHANNEL_CAPACITY) transitions behind gets
612    /// [`RecvError::Lagged`](tokio::sync::broadcast::error::RecvError::Lagged) and resumes at
613    /// the oldest one retained.
614    ///
615    /// `FailedToStart` is the exhausted state: the monitor retries a `FailedToStart` or
616    /// `Crashed` server only while its [`RestartPolicy`](super::RestartPolicy) has attempts
617    /// left, so a `FailedToStart` that a server without a policy enters, or that follows
618    /// `max_restart_attempts` failed restarts since the server last ran, is followed by no
619    /// further transition until the application starts the server again.
620    ///
621    /// # Example
622    ///
623    /// ```rust
624    /// use adk_tool::mcp::{McpServerConfig, McpServerManager, ServerStatus};
625    /// use std::collections::HashMap;
626    ///
627    /// # #[tokio::main(flavor = "current_thread")]
628    /// # async fn main() {
629    /// let configs = HashMap::from([("email".to_string(), McpServerConfig::default())]);
630    /// let manager = McpServerManager::new(configs);
631    /// let mut transitions = manager.subscribe_status_transitions();
632    ///
633    /// manager.disable_server("email").await.unwrap();
634    ///
635    /// let transition = transitions.recv().await.unwrap();
636    /// assert_eq!(
637    ///     (transition.id.as_str(), transition.from, transition.to),
638    ///     ("email", ServerStatus::Stopped, ServerStatus::Disabled)
639    /// );
640    /// # }
641    /// ```
642    pub fn subscribe_status_transitions(
643        &self,
644    ) -> tokio::sync::broadcast::Receiver<ServerStatusTransition> {
645        self.status_events.subscribe()
646    }
647
648    /// Sets the stdio launcher, which builds the command of every start of every managed
649    /// server in place of `Command::new(&config.command)` with the configured arguments and
650    /// environment (spec 3.2 §10 T1).
651    ///
652    /// The launcher receives the server's [`McpServerConfig`] on each start, auto-restarts
653    /// included, and returns the [`tokio::process::Command`] to spawn — for example the
654    /// configured server wrapped in an OS sandbox. rmcp pipes the command's stdin and stdout
655    /// for the MCP connection. An error from the launcher fails that start with the error
656    /// unchanged and leaves the server `FailedToStart`. Without a launcher the manager
657    /// spawns the configured command, arguments and environment. On Windows the manager
658    /// replaces the command's creation flags with `CREATE_SUSPENDED`, so the server runs only
659    /// once it is in its Job Object (spec 3.2 §10 W1).
660    ///
661    /// # Example
662    ///
663    /// ```rust
664    /// use adk_tool::mcp::McpServerManager;
665    /// use std::collections::HashMap;
666    ///
667    /// let manager = McpServerManager::new(HashMap::new()).with_stdio_launcher(|config| {
668    ///     let mut command = tokio::process::Command::new("/usr/bin/nice");
669    ///     command.arg(&config.command).args(&config.args).envs(&config.env);
670    ///     Ok(command)
671    /// });
672    /// ```
673    pub fn with_stdio_launcher<F>(mut self, launcher: F) -> Self
674    where
675        F: Fn(&McpServerConfig) -> adk_core::Result<tokio::process::Command>
676            + Send
677            + Sync
678            + 'static,
679    {
680        self.stdio_launcher = Some(Arc::new(launcher));
681        self
682    }
683
684    fn toolset_limits(&self) -> ToolsetLimits {
685        ToolsetLimits { schema: self.schema_limits, discovery: self.discovery_limits }
686    }
687
688    fn launcher(&self) -> Launcher {
689        Launcher {
690            servers: Arc::clone(&self.servers),
691            elicitation_handler: self.elicitation_handler.clone(),
692            resource_notification_handler: self.resource_notification_handler.clone(),
693            resource_subscriptions: Arc::clone(&self.resource_subscriptions),
694            limits: self.toolset_limits(),
695            startup_timeout: self.startup_timeout,
696            #[cfg(feature = "mcp-sampling")]
697            sampling_handler: self.sampling_handler.clone(),
698            server_elicitation_handlers: self.server_elicitation_handlers.clone(),
699            #[cfg(feature = "mcp-sampling")]
700            server_sampling_handlers: self.server_sampling_handlers.clone(),
701            status_events: self.status_events.clone(),
702            stdio_launcher: self.stdio_launcher.clone(),
703        }
704    }
705
706    /// Start a managed MCP server by ID.
707    ///
708    /// Spawns the configured command as a child process, creates a
709    /// `TokioChildProcess` transport, and connects via `McpToolset` with the
710    /// configured elicitation (and optionally sampling) handler. While the
711    /// handshake runs the server is [`ServerStatus::Starting`]; the registry is not
712    /// locked, so other servers keep serving tools and status.
713    ///
714    /// If the server is already `Running`, this is a no-op and returns `Ok(())`.
715    ///
716    /// # Errors
717    ///
718    /// Returns `AdkError::Tool` if:
719    /// - The server ID does not exist
720    /// - The child process fails to spawn
721    /// - The MCP handshake fails or does not finish within the
722    ///   [startup timeout](Self::with_startup_timeout)
723    /// - The server is stopped, updated or removed before its handshake finishes
724    ///
725    /// # Example
726    ///
727    /// ```rust,ignore
728    /// manager.start_server("my-server").await?;
729    /// ```
730    pub async fn start_server(&self, id: &str) -> adk_core::Result<()> {
731        self.launcher().start(id).await
732    }
733
734    /// Stop a managed MCP server by ID.
735    ///
736    /// Cancels the server's pending MCP tasks (see
737    /// [`McpToolset::cancel_pending_tasks`]) and then its MCP session, both within
738    /// the grace period, waits within it for the child process to exit, drops the
739    /// `McpToolset` connection, and sets the status to `Stopped`. Tools the server's
740    /// toolset produced fail from then on, and a restart serves new ones.
741    ///
742    /// If the server is not running, this is a no-op and returns `Ok(())`.
743    ///
744    /// # Errors
745    ///
746    /// Returns `AdkError::Tool` if the server ID does not exist.
747    ///
748    /// # Example
749    ///
750    /// ```rust,ignore
751    /// manager.stop_server("my-server").await?;
752    /// ```
753    pub async fn stop_server(&self, id: &str) -> adk_core::Result<()> {
754        let mut servers = self.servers.write().await;
755        let entry = servers
756            .get_mut(id)
757            .ok_or_else(|| AdkError::tool(format!("unknown server ID: '{id}'")))?;
758
759        Self::stop_server_inner(id, entry, "manual", self.grace_period, &self.status_events).await;
760        Ok(())
761    }
762
763    /// Internal stop logic operating on a mutable entry reference.
764    ///
765    /// This avoids double-locking when called from `restart_server`.
766    async fn stop_server_inner(
767        id: &str,
768        entry: &mut McpServerEntry,
769        reason: &str,
770        grace_period: Duration,
771        events: &StatusSender,
772    ) {
773        // A handshake still in progress is cancelled, and discarded should it finish.
774        entry.generation += 1;
775        entry.startup_cancel.cancel();
776        if entry.status == ServerStatus::Starting {
777            entry.set_status(id, ServerStatus::Stopped, events);
778            tracing::info!(
779                server.id = id,
780                stop.reason = reason,
781                "stopped MCP server during startup"
782            );
783            return;
784        }
785
786        // If not running, nothing to do
787        if entry.status != ServerStatus::Running && entry.status != ServerStatus::Restarting {
788            return;
789        }
790
791        // Cancel remote tasks, then the MCP session, and wait for the child to exit
792        if let Some(ref toolset) = entry.toolset {
793            toolset.close_within(grace_period).await;
794        }
795
796        // A transport still closing after the grace period ends its child when dropped
797        entry.toolset = None;
798        entry.child = None;
799
800        // Only set to Stopped if we're not in a Restarting transition
801        if entry.status != ServerStatus::Restarting {
802            entry.set_status(id, ServerStatus::Stopped, events);
803        }
804
805        tracing::info!(server.id = id, stop.reason = reason, "stopped MCP server");
806    }
807
808    /// Restart a managed MCP server by ID.
809    ///
810    /// Sets the status to `Restarting`, stops the server, then starts it again.
811    /// The same `ElicitationHandler` and `SamplingHandler` `Arc`s are preserved
812    /// across the restart.
813    ///
814    /// # Errors
815    ///
816    /// Returns `AdkError::Tool` if:
817    /// - The server ID does not exist
818    /// - The start phase fails (status set to `FailedToStart`)
819    ///
820    /// # Example
821    ///
822    /// ```rust,ignore
823    /// manager.restart_server("my-server").await?;
824    /// ```
825    pub async fn restart_server(&self, id: &str) -> adk_core::Result<()> {
826        {
827            let mut servers = self.servers.write().await;
828            let entry = servers
829                .get_mut(id)
830                .ok_or_else(|| AdkError::tool(format!("unknown server ID: '{id}'")))?;
831            if entry.status != ServerStatus::Starting {
832                entry.set_status(id, ServerStatus::Restarting, &self.status_events);
833            }
834            Self::stop_server_inner(id, entry, "restart", self.grace_period, &self.status_events)
835                .await;
836        }
837        self.launcher().start(id).await
838    }
839
840    /// Return the current [`ServerStatus`] for a given server ID.
841    ///
842    /// # Errors
843    ///
844    /// Returns `AdkError::Tool` if the server ID does not exist.
845    ///
846    /// # Example
847    ///
848    /// ```rust,ignore
849    /// let status = manager.server_status("my-server").await?;
850    /// assert_eq!(status, ServerStatus::Running);
851    /// ```
852    pub async fn server_status(&self, id: &str) -> adk_core::Result<ServerStatus> {
853        let servers = self.servers.read().await;
854        servers
855            .get(id)
856            .map(|entry| entry.status)
857            .ok_or_else(|| AdkError::tool(format!("unknown server ID: '{id}'")))
858    }
859
860    async fn running_toolset(
861        &self,
862        id: &str,
863    ) -> adk_core::Result<McpToolset<super::super::elicitation::AdkClientHandler>> {
864        let servers = self.servers.read().await;
865        let entry =
866            servers.get(id).ok_or_else(|| AdkError::tool(format!("MCP server not found: {id}")))?;
867        if entry.status != ServerStatus::Running {
868            return Err(AdkError::tool(format!("MCP server is not running: {id}")));
869        }
870        entry
871            .toolset
872            .clone()
873            .ok_or_else(|| AdkError::tool(format!("MCP server has no active connection: {id}")))
874    }
875
876    /// List static resources published by one running managed server.
877    pub async fn list_server_resources(&self, id: &str) -> adk_core::Result<Vec<Resource>> {
878        self.running_toolset(id).await?.list_resources().await
879    }
880
881    /// List URI templates published by one running managed server.
882    pub async fn list_server_resource_templates(
883        &self,
884        id: &str,
885    ) -> adk_core::Result<Vec<ResourceTemplate>> {
886        self.running_toolset(id).await?.list_resource_templates().await
887    }
888
889    /// List prompt templates published by one running managed server.
890    pub async fn list_server_prompts(&self, id: &str) -> adk_core::Result<Vec<Prompt>> {
891        self.running_toolset(id).await?.list_prompts().await
892    }
893
894    /// Read one resource from a running managed server.
895    pub async fn read_server_resource(
896        &self,
897        id: &str,
898        uri: &str,
899    ) -> adk_core::Result<Vec<ResourceContents>> {
900        self.running_toolset(id).await?.read_resource(uri).await
901    }
902
903    /// The apps one running managed server's tools show, including the tools only an app may
904    /// call (spec 3.3 §6.1 `genui-apps`; see [`McpToolset::ui_bindings`](crate::mcp::McpToolset::ui_bindings)).
905    ///
906    /// # Errors
907    ///
908    /// Returns `AdkError::Tool` when the server is unknown or not running, or cannot list its
909    /// tools.
910    #[cfg(feature = "mcp-apps")]
911    pub async fn server_ui_bindings(
912        &self,
913        id: &str,
914    ) -> adk_core::Result<Vec<crate::mcp::McpUiBinding>> {
915        self.running_toolset(id).await?.ui_bindings().await
916    }
917
918    /// Who may call each tool one running managed server publishes (spec 3.3 §6.1
919    /// `genui-apps`; see [`McpToolset::tool_visibility`](crate::mcp::McpToolset::tool_visibility)).
920    ///
921    /// # Errors
922    ///
923    /// Returns `AdkError::Tool` when the server is unknown or not running, or cannot list its
924    /// tools.
925    #[cfg(feature = "mcp-apps")]
926    pub async fn server_tool_visibility(
927        &self,
928        id: &str,
929    ) -> adk_core::Result<Vec<(String, crate::mcp::McpUiVisibility)>> {
930        self.running_toolset(id).await?.tool_visibility().await
931    }
932
933    /// The name this manager's [`tools`](adk_core::Toolset::tools) give server `id`'s tool
934    /// `tool`: `tool` itself, `{id}__{tool}` when another running server publishes the same
935    /// name, or `None` when the tool is not among them — left out, renamed past the length
936    /// limit, or its name taken by another server's tool (spec 3.3 §6.1 `genui-apps`). A host
937    /// asks for an app's tool call by this name, so it never reaches another server's tool.
938    ///
939    /// # Example
940    ///
941    /// ```rust,ignore
942    /// // `weather` and `forecast` both publish `weather_show`; only `weather` publishes `set_rain_alert`.
943    /// assert_eq!(manager.agent_tool_name("weather", "weather_show").await?.as_deref(), Some("weather__weather_show"));
944    /// assert_eq!(manager.agent_tool_name("weather", "set_rain_alert").await?.as_deref(), Some("set_rain_alert"));
945    /// ```
946    ///
947    /// # Errors
948    ///
949    /// Returns `AdkError::Tool` when the server is unknown or not running.
950    #[cfg(feature = "mcp-apps")]
951    pub async fn agent_tool_name(&self, id: &str, tool: &str) -> adk_core::Result<Option<String>> {
952        self.running_toolset(id).await?;
953        let listing: Arc<dyn adk_core::ReadonlyContext> =
954            Arc::new(crate::SimpleToolContext::new(self.name.clone()));
955        let origin = format!("mcp:{id}");
956        let prefixed = format!("{id}__{tool}");
957        let tools = adk_core::Toolset::tools(self, listing).await?;
958        Ok(tools
959            .iter()
960            .find(|known| {
961                known.origin() == origin && (known.name() == tool || known.name() == prefixed)
962            })
963            .map(|known| known.name().to_string()))
964    }
965
966    /// Reads the app at `uri` from one running managed server (spec 3.3 §6.1 `genui-apps`; see
967    /// [`McpToolset::read_app`](crate::mcp::McpToolset::read_app)).
968    ///
969    /// # Errors
970    ///
971    /// Returns `AdkError::Tool` when the server is unknown or not running, or the resource is
972    /// not an MCP App.
973    #[cfg(feature = "mcp-apps")]
974    pub async fn read_server_app(
975        &self,
976        id: &str,
977        uri: &str,
978    ) -> adk_core::Result<crate::mcp::McpAppResource> {
979        self.running_toolset(id).await?.read_app(uri).await
980    }
981
982    /// Subscribe to updates for one resource on a running managed server.
983    pub async fn subscribe_server_resource(&self, id: &str, uri: &str) -> adk_core::Result<()> {
984        self.running_toolset(id).await?.subscribe_resource(uri).await?;
985        self.resource_subscriptions
986            .write()
987            .await
988            .entry(id.to_string())
989            .or_default()
990            .insert(uri.to_string());
991        Ok(())
992    }
993
994    /// Remove a resource subscription from one running managed server.
995    pub async fn unsubscribe_server_resource(&self, id: &str, uri: &str) -> adk_core::Result<()> {
996        self.running_toolset(id).await?.unsubscribe_resource(uri).await?;
997        let mut subscriptions = self.resource_subscriptions.write().await;
998        if let Some(server_subscriptions) = subscriptions.get_mut(id) {
999            server_subscriptions.remove(uri);
1000            if server_subscriptions.is_empty() {
1001                subscriptions.remove(id);
1002            }
1003        }
1004        Ok(())
1005    }
1006
1007    /// Resolve one prompt from a running managed server.
1008    pub async fn get_server_prompt(
1009        &self,
1010        id: &str,
1011        name: &str,
1012        arguments: Option<serde_json::Map<String, serde_json::Value>>,
1013    ) -> adk_core::Result<GetPromptResult> {
1014        self.running_toolset(id).await?.get_prompt(name, arguments).await
1015    }
1016
1017    /// Re-issues a parked call on the running server it names (spec 3.2 §7.7, §10 T2).
1018    ///
1019    /// The call's [`server_id`](super::super::ParkedMcpCall::server_id) is the managed
1020    /// server's ID; see [`McpToolset::reissue`] for what happens per kind.
1021    ///
1022    /// # Errors
1023    ///
1024    /// Returns `AdkError::Tool` when the server is unknown or not running, and as
1025    /// [`McpToolset::reissue`] does.
1026    ///
1027    /// # Example
1028    ///
1029    /// ```rust,ignore
1030    /// let parked: ParkedMcpCall = serde_json::from_str(&checkpoint)?;
1031    /// let outcome = manager.reissue_parked_call(&parked, responses).await?;
1032    /// ```
1033    pub async fn reissue_parked_call(
1034        &self,
1035        parked: &super::super::ParkedMcpCall,
1036        responses: rmcp::model::InputResponses,
1037    ) -> adk_core::Result<super::super::McpCallOutcome> {
1038        self.running_toolset(&parked.server_id).await?.reissue(parked, responses).await
1039    }
1040
1041    /// Calls tool `name` on running server `id` for an agent's call, ending it with its
1042    /// parked form when the server needs input (spec 3.2 §7.7, §10 T2).
1043    ///
1044    /// This is [`McpToolset::call_tool_resumable`] on the server's connection, run in the
1045    /// scopes the call's tool would enter: sampling requests the server sends meanwhile
1046    /// count against `ctx`'s run, and elicitations belong to the call. The call id is
1047    /// `ctx`'s function call id.
1048    ///
1049    /// # Errors
1050    ///
1051    /// Returns `AdkError::Tool` when the server is unknown or not running, and as
1052    /// [`McpToolset::call_tool_resumable`] does.
1053    ///
1054    /// # Example
1055    ///
1056    /// ```rust,ignore
1057    /// match manager.call_tool_resumable("email", ctx, "send_draft", arguments).await? {
1058    ///     McpCallOutcome::Completed(value) => Ok(value),
1059    ///     McpCallOutcome::Parked(parked) => park(parked).await,
1060    /// }
1061    /// ```
1062    pub async fn call_tool_resumable(
1063        &self,
1064        id: &str,
1065        ctx: Arc<dyn adk_core::ToolContext>,
1066        name: &str,
1067        arguments: serde_json::Map<String, serde_json::Value>,
1068    ) -> adk_core::Result<super::super::McpCallOutcome> {
1069        let toolset = self.running_toolset(id).await?;
1070        let _scopes = toolset.enter_call_scopes(ctx.as_ref());
1071        let call_id = Some(ctx.function_call_id()).filter(|call_id| !call_id.is_empty());
1072        toolset.call_tool_resumable(call_id, name, arguments).await
1073    }
1074
1075    /// [`reissue_parked_call`](Self::reissue_parked_call) for an agent's call, run in the
1076    /// scopes the call's tool would enter, as
1077    /// [`call_tool_resumable`](Self::call_tool_resumable) runs (spec 3.2 §7.7, §10 T2).
1078    ///
1079    /// # Errors
1080    ///
1081    /// As [`reissue_parked_call`](Self::reissue_parked_call).
1082    ///
1083    /// # Example
1084    ///
1085    /// ```rust,ignore
1086    /// let outcome = manager.reissue_parked_call_for(ctx, &parked, responses).await?;
1087    /// ```
1088    pub async fn reissue_parked_call_for(
1089        &self,
1090        ctx: Arc<dyn adk_core::ToolContext>,
1091        parked: &super::super::ParkedMcpCall,
1092        responses: rmcp::model::InputResponses,
1093    ) -> adk_core::Result<super::super::McpCallOutcome> {
1094        let toolset = self.running_toolset(&parked.server_id).await?;
1095        let _scopes = toolset.enter_call_scopes(ctx.as_ref());
1096        toolset.reissue(parked, responses).await
1097    }
1098
1099    /// Return a map of all server IDs to their current [`ServerStatus`].
1100    ///
1101    /// # Example
1102    ///
1103    /// ```rust,ignore
1104    /// let statuses = manager.all_statuses().await;
1105    /// for (id, status) in &statuses {
1106    ///     println!("{id}: {status:?}");
1107    /// }
1108    /// ```
1109    pub async fn all_statuses(&self) -> HashMap<String, ServerStatus> {
1110        let servers = self.servers.read().await;
1111        servers.iter().map(|(id, entry)| (id.clone(), entry.status)).collect()
1112    }
1113
1114    /// Return the number of servers currently in [`ServerStatus::Running`] status.
1115    ///
1116    /// # Example
1117    ///
1118    /// ```rust,ignore
1119    /// let count = manager.running_server_count().await;
1120    /// println!("{count} servers running");
1121    /// ```
1122    pub async fn running_server_count(&self) -> usize {
1123        let servers = self.servers.read().await;
1124        servers.values().filter(|entry| entry.status == ServerStatus::Running).count()
1125    }
1126
1127    /// Start the background health monitoring task.
1128    ///
1129    /// Spawns a `tokio::spawn` task that periodically checks each `Running`
1130    /// server by calling [`McpToolset::is_closed()`](super::super::McpToolset::is_closed).
1131    /// If a server's connection is closed, the monitor sets its status to
1132    /// `Crashed` and, if a [`RestartPolicy`](super::config::RestartPolicy) is configured, attempts auto-restart
1133    /// with exponential backoff.
1134    ///
1135    /// The monitoring loop runs until [`stop_monitoring`](Self::stop_monitoring)
1136    /// is called, which cancels the background task via the internal
1137    /// `CancellationToken`.
1138    ///
1139    /// # Example
1140    ///
1141    /// ```rust,ignore
1142    /// manager.start_monitoring();
1143    /// // ... later ...
1144    /// manager.stop_monitoring();
1145    /// ```
1146    pub fn start_monitoring(&self) {
1147        if self.monitor_running.swap(true, Ordering::AcqRel) {
1148            return;
1149        }
1150        let servers = Arc::clone(&self.servers);
1151        let cancel = {
1152            let mut cancel =
1153                self.monitor_cancel.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
1154            if cancel.is_cancelled() {
1155                *cancel = CancellationToken::new();
1156            }
1157            cancel.clone()
1158        };
1159        let monitor_running = Arc::clone(&self.monitor_running);
1160        let interval = self.health_check_interval;
1161        let launcher = self.launcher();
1162        let events = self.status_events.clone();
1163
1164        tokio::spawn(async move {
1165            loop {
1166                tokio::select! {
1167                    _ = cancel.cancelled() => {
1168                        tracing::info!("health monitor stopped");
1169                        break;
1170                    }
1171                    _ = tokio::time::sleep(interval) => {
1172                        // Snapshot candidates without retaining the map lock across
1173                        // asynchronous connection checks.
1174                        let candidates = {
1175                            let servers = servers.read().await;
1176                            servers
1177                                .iter()
1178                                .filter_map(|(id, entry)| match entry.status {
1179                                    ServerStatus::Running => {
1180                                        Some((id.clone(), entry.status, entry.toolset.clone()))
1181                                    }
1182                                    ServerStatus::Crashed | ServerStatus::FailedToStart => entry
1183                                        .config
1184                                        .restart_policy
1185                                        .as_ref()
1186                                        .filter(|policy| {
1187                                            !entry.backoff.exceeded_max_attempts(policy)
1188                                        })
1189                                        .map(|_| (id.clone(), entry.status, None)),
1190                                    _ => None,
1191                                })
1192                                .collect::<Vec<_>>()
1193                        };
1194
1195                        let mut crashed_ids = Vec::new();
1196                        for (id, status, toolset) in candidates {
1197                            let closed = match toolset {
1198                                Some(toolset) => toolset.is_closed().await,
1199                                None => true,
1200                            };
1201                            if status != ServerStatus::Running || closed {
1202                                crashed_ids.push(id);
1203                            }
1204                        }
1205
1206                        if crashed_ids.is_empty() {
1207                            continue;
1208                        }
1209
1210                        // Phase 2: Mark crashed servers and attempt auto-restart
1211                        for id in crashed_ids {
1212                            // Mark as Crashed under write lock
1213                            let restart_info = {
1214                                let mut servers = servers.write().await;
1215                                if let Some(entry) = servers.get_mut(&id) {
1216                                    if entry.status == ServerStatus::Running {
1217                                        tracing::warn!(
1218                                            server.id = id,
1219                                            failure.reason = "connection closed",
1220                                            "health check failed"
1221                                        );
1222                                        entry.set_status(&id, ServerStatus::Crashed, &events);
1223                                        entry.toolset = None;
1224                                        entry.child = None;
1225                                    } else if !matches!(
1226                                        entry.status,
1227                                        ServerStatus::Crashed | ServerStatus::FailedToStart
1228                                    ) {
1229                                        continue;
1230                                    }
1231
1232                                    // Check if auto-restart is configured
1233                                    entry.config.restart_policy.clone()
1234                                } else {
1235                                    continue;
1236                                }
1237                            };
1238
1239                            // Attempt auto-restart if policy allows
1240                            if let Some(ref policy) = restart_info {
1241                                // Check if max attempts exceeded
1242                                let exceeded = {
1243                                    let servers = servers.read().await;
1244                                    servers.get(&id)
1245                                        .map(|e| e.backoff.exceeded_max_attempts(policy))
1246                                        .unwrap_or(true)
1247                                };
1248
1249                                if exceeded {
1250                                    let mut servers = servers.write().await;
1251                                    if let Some(entry) = servers.get_mut(&id) {
1252                                        tracing::error!(
1253                                            server.id = id,
1254                                            restart.total_attempts = entry.backoff.consecutive_failures,
1255                                            "max restart attempts exceeded, giving up"
1256                                        );
1257                                        entry.set_status(&id, ServerStatus::FailedToStart, &events);
1258                                    }
1259                                    continue;
1260                                }
1261
1262                                // Compute backoff delay and increment failure counter
1263                                let (delay_ms, attempt) = {
1264                                    let mut servers = servers.write().await;
1265                                    if let Some(entry) = servers.get_mut(&id) {
1266                                        let attempt = entry.backoff.consecutive_failures + 1;
1267                                        let delay = entry.backoff.next_delay(policy);
1268                                        (delay, attempt)
1269                                    } else {
1270                                        continue;
1271                                    }
1272                                };
1273
1274                                tracing::info!(
1275                                    server.id = id,
1276                                    restart.attempt = attempt,
1277                                    restart.delay_ms = delay_ms,
1278                                    "auto-restarting crashed server after backoff"
1279                                );
1280
1281                                // Wait for backoff delay (without holding any lock)
1282                                tokio::time::sleep(Duration::from_millis(delay_ms)).await;
1283
1284                                // Check if monitoring was cancelled during the sleep
1285                                if cancel.is_cancelled() {
1286                                    break;
1287                                }
1288
1289                                {
1290                                    let mut servers = servers.write().await;
1291                                    match servers.get_mut(&id) {
1292                                        Some(entry) if matches!(
1293                                            entry.status,
1294                                            ServerStatus::Crashed | ServerStatus::FailedToStart
1295                                        ) => entry.set_status(&id, ServerStatus::Restarting, &events),
1296                                        // Stopped, restarted or removed during the backoff.
1297                                        _ => continue,
1298                                    }
1299                                }
1300                                let restart_result = launcher.start(&id).await;
1301
1302                                match restart_result {
1303                                    Ok(()) => {
1304                                        // Reset backoff on success
1305                                        let mut servers = servers.write().await;
1306                                        if let Some(entry) = servers.get_mut(&id) {
1307                                            entry.backoff.reset(policy);
1308                                            tracing::info!(
1309                                                server.id = id,
1310                                                "auto-restart succeeded"
1311                                            );
1312                                        }
1313                                    }
1314                                    Err(e) => {
1315                                        tracing::warn!(
1316                                            server.id = id,
1317                                            error = %e,
1318                                            "auto-restart failed"
1319                                        );
1320                                        // Status already set to FailedToStart by the launcher
1321                                    }
1322                                }
1323                            }
1324                        }
1325                    }
1326                }
1327            }
1328            monitor_running.store(false, Ordering::Release);
1329        });
1330    }
1331
1332    /// Stop the background health monitoring task.
1333    ///
1334    /// Cancels the monitoring loop spawned by [`start_monitoring`](Self::start_monitoring).
1335    /// This is a no-op if monitoring was never started or has already been stopped.
1336    ///
1337    /// # Example
1338    ///
1339    /// ```rust,ignore
1340    /// manager.stop_monitoring();
1341    /// ```
1342    pub fn stop_monitoring(&self) {
1343        self.monitor_cancel.lock().unwrap_or_else(std::sync::PoisonError::into_inner).cancel();
1344    }
1345
1346    /// Register a new server configuration at runtime.
1347    ///
1348    /// The new server is initialized with [`ServerStatus::Disabled`] if
1349    /// `config.disabled` is `true`, or [`ServerStatus::Stopped`] otherwise.
1350    /// It will not be started automatically — call
1351    /// [`start_server`](Self::start_server) to begin spawning the process.
1352    ///
1353    /// # Errors
1354    ///
1355    /// Returns `AdkError::Tool` if a server with the given ID already exists.
1356    ///
1357    /// # Example
1358    ///
1359    /// ```rust,ignore
1360    /// let config = McpServerConfig {
1361    ///     command: "/opt/company/bin/billing-mcp".to_string(),
1362    ///     args: vec!["--stdio".to_string()],
1363    ///     ..Default::default()
1364    /// };
1365    /// manager.add_server("new-server".to_string(), config).await?;
1366    /// ```
1367    pub async fn add_server(&self, id: String, config: McpServerConfig) -> adk_core::Result<()> {
1368        Self::validate_server_id(&id)?;
1369        let mut servers = self.servers.write().await;
1370        if servers.contains_key(&id) {
1371            return Err(AdkError::tool(format!("server ID '{id}' already exists")));
1372        }
1373        servers.insert(id, McpServerEntry::new(config));
1374        Ok(())
1375    }
1376
1377    /// Return a copy of one server's current configuration.
1378    pub async fn server_config(&self, id: &str) -> adk_core::Result<McpServerConfig> {
1379        let servers = self.servers.read().await;
1380        servers
1381            .get(id)
1382            .map(|entry| entry.config.clone())
1383            .ok_or_else(|| AdkError::tool(format!("unknown server ID: '{id}'")))
1384    }
1385
1386    /// Return a snapshot of every managed server configuration.
1387    pub async fn all_configs(&self) -> HashMap<String, McpServerConfig> {
1388        let servers = self.servers.read().await;
1389        servers.iter().map(|(id, entry)| (id.clone(), entry.config.clone())).collect()
1390    }
1391
1392    /// Replace a server configuration at runtime.
1393    ///
1394    /// A running server is stopped and restarted with the new configuration.
1395    /// If the replacement fails to start, the previous configuration is restored
1396    /// and restarted before the error is returned.
1397    pub async fn update_server(&self, id: &str, config: McpServerConfig) -> adk_core::Result<()> {
1398        Self::validate_server_id(id)?;
1399        let (previous, was_running) = {
1400            let mut servers = self.servers.write().await;
1401            let entry = servers
1402                .get_mut(id)
1403                .ok_or_else(|| AdkError::tool(format!("unknown server ID: '{id}'")))?;
1404            let previous = entry.config.clone();
1405            let was_running = entry.status == ServerStatus::Running;
1406            Self::stop_server_inner(
1407                id,
1408                entry,
1409                "configuration update",
1410                self.grace_period,
1411                &self.status_events,
1412            )
1413            .await;
1414            entry.config = config.clone();
1415            entry.backoff = BackoffState::new(&config.restart_policy);
1416            let status =
1417                if config.disabled { ServerStatus::Disabled } else { ServerStatus::Stopped };
1418            entry.set_status(id, status, &self.status_events);
1419            (previous, was_running)
1420        };
1421
1422        if !was_running || config.disabled {
1423            return Ok(());
1424        }
1425
1426        if let Err(replacement_error) = self.start_server(id).await {
1427            {
1428                let mut servers = self.servers.write().await;
1429                let entry = servers
1430                    .get_mut(id)
1431                    .ok_or_else(|| AdkError::tool(format!("unknown server ID: '{id}'")))?;
1432                entry.config = previous.clone();
1433                entry.backoff = BackoffState::new(&previous.restart_policy);
1434                entry.set_status(id, ServerStatus::Stopped, &self.status_events);
1435            }
1436            self.start_server(id).await.map_err(|rollback_error| {
1437                AdkError::tool(format!(
1438                    "replacement for MCP server '{id}' failed ({replacement_error}); restoring the previous server also failed ({rollback_error})"
1439                ))
1440            })?;
1441            return Err(AdkError::tool(format!(
1442                "replacement for MCP server '{id}' failed and the previous configuration was restored: {replacement_error}"
1443            )));
1444        }
1445        Ok(())
1446    }
1447
1448    /// Enable a disabled server without starting it.
1449    pub async fn enable_server(&self, id: &str) -> adk_core::Result<()> {
1450        let mut servers = self.servers.write().await;
1451        let entry = servers
1452            .get_mut(id)
1453            .ok_or_else(|| AdkError::tool(format!("unknown server ID: '{id}'")))?;
1454        entry.config.disabled = false;
1455        if entry.status == ServerStatus::Disabled {
1456            entry.set_status(id, ServerStatus::Stopped, &self.status_events);
1457        }
1458        Ok(())
1459    }
1460
1461    /// Stop and disable a server until it is explicitly enabled again.
1462    pub async fn disable_server(&self, id: &str) -> adk_core::Result<()> {
1463        let mut servers = self.servers.write().await;
1464        let entry = servers
1465            .get_mut(id)
1466            .ok_or_else(|| AdkError::tool(format!("unknown server ID: '{id}'")))?;
1467        Self::stop_server_inner(id, entry, "disabled", self.grace_period, &self.status_events)
1468            .await;
1469        entry.config.disabled = true;
1470        entry.set_status(id, ServerStatus::Disabled, &self.status_events);
1471        Ok(())
1472    }
1473
1474    /// Serialize the current in-memory configuration as compatible `mcp.json`.
1475    pub async fn to_json(&self) -> adk_core::Result<String> {
1476        let file = super::config::McpJsonFile { mcp_servers: self.all_configs().await };
1477        serde_json::to_string_pretty(&file)
1478            .map_err(|error| AdkError::tool(format!("failed to serialize MCP config: {error}")))
1479    }
1480
1481    /// Persist the current configuration using an atomic temporary-file rename.
1482    pub async fn save_json_file(&self, path: impl AsRef<std::path::Path>) -> adk_core::Result<()> {
1483        let path = path.as_ref();
1484        let parent = path.parent().unwrap_or_else(|| std::path::Path::new("."));
1485        let file_name = path
1486            .file_name()
1487            .and_then(|name| name.to_str())
1488            .ok_or_else(|| AdkError::tool("MCP config path must have a UTF-8 file name"))?;
1489        let temporary = parent.join(format!(".{file_name}.tmp"));
1490        tokio::fs::write(&temporary, self.to_json().await?)
1491            .await
1492            .map_err(|error| AdkError::tool(format!("failed to write MCP config: {error}")))?;
1493        tokio::fs::rename(&temporary, path).await.map_err(|error| {
1494            AdkError::tool(format!("failed to replace MCP config atomically: {error}"))
1495        })
1496    }
1497
1498    /// Remove a server configuration at runtime.
1499    ///
1500    /// If the server is currently running, it is stopped first using the
1501    /// graceful stop sequence before being removed from the manager.
1502    ///
1503    /// # Errors
1504    ///
1505    /// Returns `AdkError::Tool` if the server ID does not exist.
1506    ///
1507    /// # Example
1508    ///
1509    /// ```rust,ignore
1510    /// manager.remove_server("old-server").await?;
1511    /// ```
1512    pub async fn remove_server(&self, id: &str) -> adk_core::Result<()> {
1513        let mut servers = self.servers.write().await;
1514        let entry = servers
1515            .get_mut(id)
1516            .ok_or_else(|| AdkError::tool(format!("unknown server ID: '{id}'")))?;
1517
1518        // If the server is running, stop it first
1519        Self::stop_server_inner(id, entry, "removal", self.grace_period, &self.status_events).await;
1520
1521        servers.remove(id);
1522        Ok(())
1523    }
1524
1525    /// Start all non-disabled servers and report each result independently.
1526    ///
1527    /// Collects all server IDs where `disabled == false`, then starts each one
1528    /// via [`start_server`](Self::start_server). Failures are logged but do not
1529    /// prevent other servers from starting. The servers complete their MCP
1530    /// handshakes concurrently, each bounded by the
1531    /// [startup timeout](Self::with_startup_timeout).
1532    ///
1533    /// # Returns
1534    ///
1535    /// A `HashMap<String, Result<()>>` with per-server outcomes. Disabled servers
1536    /// are not included in the result.
1537    ///
1538    /// # Example
1539    ///
1540    /// ```rust,ignore
1541    /// let results = manager.start_all().await;
1542    /// for (id, result) in &results {
1543    ///     match result {
1544    ///         Ok(()) => println!("{id}: started"),
1545    ///         Err(e) => eprintln!("{id}: failed to start: {e}"),
1546    ///     }
1547    /// }
1548    /// ```
1549    pub async fn start_all(&self) -> HashMap<String, adk_core::Result<()>> {
1550        // Collect IDs of non-disabled servers under a read lock
1551        let ids_to_start: Vec<String> = {
1552            let servers = self.servers.read().await;
1553            servers
1554                .iter()
1555                .filter(|(_, entry)| !entry.config.disabled)
1556                .map(|(id, _)| id.clone())
1557                .collect()
1558        };
1559
1560        // Each start locks the registry only to read its configuration and record
1561        // its outcome, so the handshakes run concurrently.
1562        let futures: Vec<_> = ids_to_start
1563            .iter()
1564            .map(|id| {
1565                let id = id.clone();
1566                async move {
1567                    let result = self.start_server(&id).await;
1568                    if let Err(ref e) = result {
1569                        tracing::error!(
1570                            server.id = id,
1571                            error = %e,
1572                            "failed to start server during start_all"
1573                        );
1574                    }
1575                    (id, result)
1576                }
1577            })
1578            .collect();
1579
1580        futures::future::join_all(futures).await.into_iter().collect()
1581    }
1582
1583    /// Shut down all managed servers and stop health monitoring.
1584    ///
1585    /// This method first stops the health monitoring task, then stops all
1586    /// running servers by cancelling their pending MCP tasks and MCP sessions
1587    /// and dropping the child transports. After shutdown, all server statuses
1588    /// are set to `Stopped`.
1589    ///
1590    /// # Example
1591    ///
1592    /// ```rust,ignore
1593    /// manager.shutdown().await?;
1594    /// // All servers are now stopped, safe to drop the manager
1595    /// ```
1596    pub async fn shutdown(&self) -> adk_core::Result<()> {
1597        // Step 1: Stop health monitoring first
1598        self.stop_monitoring();
1599
1600        // Step 2: Acquire write lock and stop all running servers
1601        let mut servers = self.servers.write().await;
1602        let ids: Vec<String> = servers
1603            .iter()
1604            .filter(|(_, entry)| {
1605                matches!(entry.status, ServerStatus::Running | ServerStatus::Starting)
1606            })
1607            .map(|(id, _)| id.clone())
1608            .collect();
1609
1610        for id in &ids {
1611            if let Some(entry) = servers.get_mut(id) {
1612                Self::stop_server_inner(
1613                    id,
1614                    entry,
1615                    "shutdown",
1616                    self.grace_period,
1617                    &self.status_events,
1618                )
1619                .await;
1620            }
1621        }
1622
1623        // Step 3: Set all server statuses to Stopped (except Disabled)
1624        for (id, entry) in servers.iter_mut() {
1625            if entry.status != ServerStatus::Disabled {
1626                entry.set_status(id, ServerStatus::Stopped, &self.status_events);
1627            }
1628        }
1629
1630        Ok(())
1631    }
1632}
1633
1634impl Drop for McpServerManager {
1635    fn drop(&mut self) {
1636        // Use try_read() to avoid blocking in Drop
1637        if let Ok(servers) = self.servers.try_read() {
1638            let running = servers.values().filter(|e| e.status == ServerStatus::Running).count();
1639            if running > 0 {
1640                tracing::warn!(
1641                    running_count = running,
1642                    "McpServerManager dropped with {running} servers still running. \
1643                     Call shutdown() before dropping to ensure clean process cleanup."
1644                );
1645            }
1646        }
1647    }
1648}
1649
1650// Static assertions: McpServerManager must be Send + Sync so it can be
1651// shared across async tasks via Arc.
1652const _: () = {
1653    fn _assert_send<T: Send>() {}
1654    fn _assert_sync<T: Sync>() {}
1655    fn _assert_send_sync() {
1656        _assert_send::<McpServerManager>();
1657        _assert_sync::<McpServerManager>();
1658    }
1659};
1660
1661#[cfg(test)]
1662mod tests {
1663    use super::*;
1664
1665    #[test]
1666    fn test_new_empty_configs() {
1667        let manager = McpServerManager::new(HashMap::new());
1668        assert_eq!(manager.name, "mcp_server_manager");
1669        assert_eq!(manager.health_check_interval, Duration::from_secs(30));
1670        assert_eq!(manager.grace_period, Duration::from_secs(5));
1671        assert!(manager.elicitation_handler.is_none());
1672    }
1673
1674    #[test]
1675    fn test_new_disabled_server_gets_disabled_status() {
1676        let configs = HashMap::from([(
1677            "disabled-server".to_string(),
1678            McpServerConfig {
1679                command: "echo".to_string(),
1680                args: vec![],
1681                env: HashMap::new(),
1682                disabled: true,
1683                auto_approve: vec![],
1684                restart_policy: None,
1685                lifecycle: Default::default(),
1686                task_config: Default::default(),
1687            },
1688        )]);
1689        let manager = McpServerManager::new(configs);
1690        let servers = manager.servers.try_read().unwrap();
1691        assert_eq!(servers["disabled-server"].status, ServerStatus::Disabled);
1692    }
1693
1694    #[test]
1695    fn test_new_enabled_server_gets_stopped_status() {
1696        let configs = HashMap::from([(
1697            "enabled-server".to_string(),
1698            McpServerConfig {
1699                command: "echo".to_string(),
1700                args: vec![],
1701                env: HashMap::new(),
1702                disabled: false,
1703                auto_approve: vec![],
1704                restart_policy: None,
1705                lifecycle: Default::default(),
1706                task_config: Default::default(),
1707            },
1708        )]);
1709        let manager = McpServerManager::new(configs);
1710        let servers = manager.servers.try_read().unwrap();
1711        assert_eq!(servers["enabled-server"].status, ServerStatus::Stopped);
1712    }
1713
1714    #[test]
1715    fn test_builder_with_name() {
1716        let manager = McpServerManager::new(HashMap::new()).with_name("custom_name");
1717        assert_eq!(manager.name, "custom_name");
1718    }
1719
1720    #[test]
1721    fn test_builder_with_health_check_interval() {
1722        let manager = McpServerManager::new(HashMap::new())
1723            .with_health_check_interval(Duration::from_secs(10));
1724        assert_eq!(manager.health_check_interval, Duration::from_secs(10));
1725    }
1726
1727    #[test]
1728    fn test_builder_with_grace_period() {
1729        let manager =
1730            McpServerManager::new(HashMap::new()).with_grace_period(Duration::from_secs(2));
1731        assert_eq!(manager.grace_period, Duration::from_secs(2));
1732    }
1733
1734    #[test]
1735    fn test_builder_with_schema_limits() {
1736        let limits = McpSchemaLimits::default().with_max_bytes(4096).with_max_nodes(64);
1737        let manager = McpServerManager::new(HashMap::new()).with_schema_limits(limits);
1738        assert_eq!(manager.schema_limits, limits);
1739        assert_eq!(McpServerManager::new(HashMap::new()).schema_limits, McpSchemaLimits::default());
1740    }
1741
1742    #[test]
1743    fn test_builder_with_elicitation_handler() {
1744        use super::super::super::elicitation::AutoDeclineElicitationHandler;
1745        let handler: Arc<dyn ElicitationHandler> = Arc::new(AutoDeclineElicitationHandler);
1746        let manager = McpServerManager::new(HashMap::new()).with_elicitation_handler(handler);
1747        assert!(manager.elicitation_handler.is_some());
1748    }
1749
1750    #[tokio::test]
1751    async fn test_server_status_returns_correct_status() {
1752        let configs = HashMap::from([(
1753            "server-a".to_string(),
1754            McpServerConfig {
1755                command: "echo".to_string(),
1756                args: vec![],
1757                env: HashMap::new(),
1758                disabled: false,
1759                auto_approve: vec![],
1760                restart_policy: None,
1761                lifecycle: Default::default(),
1762                task_config: Default::default(),
1763            },
1764        )]);
1765        let manager = McpServerManager::new(configs);
1766        let status = manager.server_status("server-a").await.unwrap();
1767        assert_eq!(status, ServerStatus::Stopped);
1768    }
1769
1770    #[tokio::test]
1771    async fn test_server_status_unknown_id_returns_error() {
1772        let manager = McpServerManager::new(HashMap::new());
1773        let result = manager.server_status("nonexistent").await;
1774        assert!(result.is_err());
1775        let err_msg = format!("{}", result.unwrap_err());
1776        assert!(err_msg.contains("unknown server ID: 'nonexistent'"));
1777    }
1778
1779    #[tokio::test]
1780    async fn test_all_statuses_returns_all_servers() {
1781        let configs = HashMap::from([
1782            (
1783                "server-a".to_string(),
1784                McpServerConfig {
1785                    command: "echo".to_string(),
1786                    args: vec![],
1787                    env: HashMap::new(),
1788                    disabled: false,
1789                    auto_approve: vec![],
1790                    restart_policy: None,
1791                    lifecycle: Default::default(),
1792                    task_config: Default::default(),
1793                },
1794            ),
1795            (
1796                "server-b".to_string(),
1797                McpServerConfig {
1798                    command: "echo".to_string(),
1799                    args: vec![],
1800                    env: HashMap::new(),
1801                    disabled: true,
1802                    auto_approve: vec![],
1803                    restart_policy: None,
1804                    lifecycle: Default::default(),
1805                    task_config: Default::default(),
1806                },
1807            ),
1808        ]);
1809        let manager = McpServerManager::new(configs);
1810        let statuses = manager.all_statuses().await;
1811        assert_eq!(statuses.len(), 2);
1812        assert_eq!(statuses["server-a"], ServerStatus::Stopped);
1813        assert_eq!(statuses["server-b"], ServerStatus::Disabled);
1814    }
1815
1816    #[tokio::test]
1817    async fn test_all_statuses_empty_manager() {
1818        let manager = McpServerManager::new(HashMap::new());
1819        let statuses = manager.all_statuses().await;
1820        assert!(statuses.is_empty());
1821    }
1822
1823    #[tokio::test]
1824    async fn test_running_server_count_no_running() {
1825        let configs = HashMap::from([(
1826            "server-a".to_string(),
1827            McpServerConfig {
1828                command: "echo".to_string(),
1829                args: vec![],
1830                env: HashMap::new(),
1831                disabled: false,
1832                auto_approve: vec![],
1833                restart_policy: None,
1834                lifecycle: Default::default(),
1835                task_config: Default::default(),
1836            },
1837        )]);
1838        let manager = McpServerManager::new(configs);
1839        assert_eq!(manager.running_server_count().await, 0);
1840    }
1841
1842    #[tokio::test]
1843    async fn test_running_server_count_empty_manager() {
1844        let manager = McpServerManager::new(HashMap::new());
1845        assert_eq!(manager.running_server_count().await, 0);
1846    }
1847
1848    #[tokio::test]
1849    async fn test_start_all_skips_disabled_servers() {
1850        let configs = HashMap::from([
1851            (
1852                "enabled".to_string(),
1853                McpServerConfig {
1854                    command: "nonexistent-command-xyz".to_string(),
1855                    args: vec![],
1856                    env: HashMap::new(),
1857                    disabled: false,
1858                    auto_approve: vec![],
1859                    restart_policy: None,
1860                    lifecycle: Default::default(),
1861                    task_config: Default::default(),
1862                },
1863            ),
1864            (
1865                "disabled".to_string(),
1866                McpServerConfig {
1867                    command: "echo".to_string(),
1868                    args: vec![],
1869                    env: HashMap::new(),
1870                    disabled: true,
1871                    auto_approve: vec![],
1872                    restart_policy: None,
1873                    lifecycle: Default::default(),
1874                    task_config: Default::default(),
1875                },
1876            ),
1877        ]);
1878        let manager = McpServerManager::new(configs);
1879        let results = manager.start_all().await;
1880
1881        // Only the enabled server should be in the results
1882        assert!(results.contains_key("enabled"));
1883        assert!(!results.contains_key("disabled"));
1884
1885        // The enabled server should fail (nonexistent command)
1886        assert!(results["enabled"].is_err());
1887
1888        // The disabled server should still be Disabled
1889        let status = manager.server_status("disabled").await.unwrap();
1890        assert_eq!(status, ServerStatus::Disabled);
1891    }
1892
1893    #[tokio::test]
1894    async fn test_start_all_empty_manager() {
1895        let manager = McpServerManager::new(HashMap::new());
1896        let results = manager.start_all().await;
1897        assert!(results.is_empty());
1898    }
1899
1900    #[test]
1901    fn test_from_json_valid() {
1902        let json = r#"{
1903            "mcpServers": {
1904                "filesystem": {
1905                    "command": "npx",
1906                    "args": ["-y", "@modelcontextprotocol/server-filesystem", "/tmp"],
1907                    "env": { "NODE_ENV": "production" },
1908                    "disabled": false,
1909                    "autoApprove": ["read_file", "list_directory"]
1910                },
1911                "github": {
1912                    "command": "npx",
1913                    "args": ["-y", "@modelcontextprotocol/server-github"],
1914                    "env": { "GITHUB_TOKEN": "ghp_xxx" },
1915                    "disabled": true,
1916                    "autoApprove": []
1917                }
1918            }
1919        }"#;
1920        let manager = McpServerManager::from_json(json).unwrap();
1921        let servers = manager.servers.try_read().unwrap();
1922        assert_eq!(servers.len(), 2);
1923
1924        let fs_entry = &servers["filesystem"];
1925        assert_eq!(fs_entry.config.command, "npx");
1926        assert_eq!(
1927            fs_entry.config.args,
1928            vec!["-y", "@modelcontextprotocol/server-filesystem", "/tmp"]
1929        );
1930        assert_eq!(fs_entry.config.env["NODE_ENV"], "production");
1931        assert!(!fs_entry.config.disabled);
1932        assert_eq!(fs_entry.config.auto_approve, vec!["read_file", "list_directory"]);
1933        assert_eq!(fs_entry.status, ServerStatus::Stopped);
1934
1935        let gh_entry = &servers["github"];
1936        assert_eq!(gh_entry.config.command, "npx");
1937        assert!(gh_entry.config.disabled);
1938        assert_eq!(gh_entry.status, ServerStatus::Disabled);
1939    }
1940
1941    #[test]
1942    fn test_from_json_malformed() {
1943        let json = r#"{ this is not valid json }"#;
1944        let result = McpServerManager::from_json(json);
1945        let err = result.err().expect("should fail on malformed JSON");
1946        let err_msg = format!("{err}");
1947        assert!(
1948            err_msg.contains("failed to parse MCP server config"),
1949            "error message was: {err_msg}"
1950        );
1951    }
1952
1953    #[test]
1954    fn test_from_json_missing_command() {
1955        let json = r#"{
1956            "mcpServers": {
1957                "bad-server": {
1958                    "args": ["--flag"]
1959                }
1960            }
1961        }"#;
1962        let result = McpServerManager::from_json(json);
1963        let err = result.err().expect("should fail on missing command field");
1964        let err_msg = format!("{err}");
1965        assert!(
1966            err_msg.contains("failed to parse MCP server config"),
1967            "error message was: {err_msg}"
1968        );
1969    }
1970
1971    #[test]
1972    fn test_from_json_file_not_found() {
1973        let result = McpServerManager::from_json_file("/nonexistent/path/mcp.json");
1974        let err = result.err().expect("should fail on nonexistent file");
1975        let err_msg = format!("{err}");
1976        assert!(err_msg.contains("failed to read config file"), "error message was: {err_msg}");
1977        assert!(
1978            err_msg.contains("/nonexistent/path/mcp.json"),
1979            "error message should contain the path: {err_msg}"
1980        );
1981    }
1982
1983    #[test]
1984    fn test_mixed_disabled_and_enabled_servers() {
1985        let configs = HashMap::from([
1986            (
1987                "server-a".to_string(),
1988                McpServerConfig {
1989                    command: "cmd-a".to_string(),
1990                    args: vec![],
1991                    env: HashMap::new(),
1992                    disabled: false,
1993                    auto_approve: vec![],
1994                    restart_policy: None,
1995                    lifecycle: Default::default(),
1996                    task_config: Default::default(),
1997                },
1998            ),
1999            (
2000                "server-b".to_string(),
2001                McpServerConfig {
2002                    command: "cmd-b".to_string(),
2003                    args: vec![],
2004                    env: HashMap::new(),
2005                    disabled: true,
2006                    auto_approve: vec![],
2007                    restart_policy: None,
2008                    lifecycle: Default::default(),
2009                    task_config: Default::default(),
2010                },
2011            ),
2012            (
2013                "server-c".to_string(),
2014                McpServerConfig {
2015                    command: "cmd-c".to_string(),
2016                    args: vec![],
2017                    env: HashMap::new(),
2018                    disabled: false,
2019                    auto_approve: vec![],
2020                    restart_policy: None,
2021                    lifecycle: Default::default(),
2022                    task_config: Default::default(),
2023                },
2024            ),
2025        ]);
2026        let manager = McpServerManager::new(configs);
2027        let servers = manager.servers.try_read().unwrap();
2028        assert_eq!(servers["server-a"].status, ServerStatus::Stopped);
2029        assert_eq!(servers["server-b"].status, ServerStatus::Disabled);
2030        assert_eq!(servers["server-c"].status, ServerStatus::Stopped);
2031    }
2032
2033    #[tokio::test]
2034    async fn test_add_server_success() {
2035        let manager = McpServerManager::new(HashMap::new());
2036        let config = McpServerConfig {
2037            command: "echo".to_string(),
2038            args: vec!["hello".to_string()],
2039            env: HashMap::new(),
2040            disabled: false,
2041            auto_approve: vec![],
2042            restart_policy: None,
2043            lifecycle: Default::default(),
2044            task_config: Default::default(),
2045        };
2046        let result = manager.add_server("new-server".to_string(), config).await;
2047        assert!(result.is_ok());
2048
2049        let status = manager.server_status("new-server").await.unwrap();
2050        assert_eq!(status, ServerStatus::Stopped);
2051    }
2052
2053    #[tokio::test]
2054    async fn test_add_server_duplicate_id() {
2055        let configs = HashMap::from([(
2056            "existing".to_string(),
2057            McpServerConfig {
2058                command: "echo".to_string(),
2059                args: vec![],
2060                env: HashMap::new(),
2061                disabled: false,
2062                auto_approve: vec![],
2063                restart_policy: None,
2064                lifecycle: Default::default(),
2065                task_config: Default::default(),
2066            },
2067        )]);
2068        let manager = McpServerManager::new(configs);
2069
2070        let config = McpServerConfig {
2071            command: "echo".to_string(),
2072            args: vec![],
2073            env: HashMap::new(),
2074            disabled: false,
2075            auto_approve: vec![],
2076            restart_policy: None,
2077            lifecycle: Default::default(),
2078            task_config: Default::default(),
2079        };
2080        let result = manager.add_server("existing".to_string(), config).await;
2081        assert!(result.is_err());
2082        let err_msg = format!("{}", result.unwrap_err());
2083        assert!(err_msg.contains("server ID 'existing' already exists"));
2084    }
2085
2086    #[tokio::test]
2087    async fn test_add_server_disabled() {
2088        let manager = McpServerManager::new(HashMap::new());
2089        let config = McpServerConfig {
2090            command: "echo".to_string(),
2091            args: vec![],
2092            env: HashMap::new(),
2093            disabled: true,
2094            auto_approve: vec![],
2095            restart_policy: None,
2096            lifecycle: Default::default(),
2097            task_config: Default::default(),
2098        };
2099        let result = manager.add_server("disabled-server".to_string(), config).await;
2100        assert!(result.is_ok());
2101
2102        let status = manager.server_status("disabled-server").await.unwrap();
2103        assert_eq!(status, ServerStatus::Disabled);
2104    }
2105
2106    #[tokio::test]
2107    async fn rejects_unsafe_dynamic_server_ids() {
2108        let manager = McpServerManager::new(HashMap::new());
2109        let result =
2110            manager.add_server("../../server".to_string(), McpServerConfig::default()).await;
2111        assert!(result.is_err());
2112    }
2113
2114    #[tokio::test]
2115    async fn disabled_server_must_be_enabled_before_start() {
2116        let manager = McpServerManager::new(HashMap::from([(
2117            "disabled".to_string(),
2118            McpServerConfig { command: "unused".to_string(), disabled: true, ..Default::default() },
2119        )]));
2120
2121        let error = manager.start_server("disabled").await.unwrap_err();
2122        assert!(error.to_string().contains("enable it before starting"));
2123        assert_eq!(manager.server_status("disabled").await.unwrap(), ServerStatus::Disabled);
2124    }
2125
2126    #[tokio::test]
2127    async fn enable_disable_and_update_change_the_live_registry() {
2128        let manager = McpServerManager::new(HashMap::from([(
2129            "catalog".to_string(),
2130            McpServerConfig { command: "old-command".to_string(), ..Default::default() },
2131        )]));
2132
2133        manager.disable_server("catalog").await.unwrap();
2134        assert_eq!(manager.server_status("catalog").await.unwrap(), ServerStatus::Disabled);
2135        manager.enable_server("catalog").await.unwrap();
2136        assert_eq!(manager.server_status("catalog").await.unwrap(), ServerStatus::Stopped);
2137
2138        let replacement = McpServerConfig {
2139            command: "new-command".to_string(),
2140            args: vec!["--safe".to_string()],
2141            ..Default::default()
2142        };
2143        manager.update_server("catalog", replacement.clone()).await.unwrap();
2144        assert_eq!(manager.server_config("catalog").await.unwrap(), replacement);
2145    }
2146
2147    #[tokio::test]
2148    async fn registry_json_can_be_exported_and_reloaded() {
2149        let config = McpServerConfig {
2150            command: "fixture".to_string(),
2151            args: vec!["--stdio".to_string()],
2152            auto_approve: vec!["read".to_string()],
2153            ..Default::default()
2154        };
2155        let manager = McpServerManager::new(HashMap::from([("catalog".to_string(), config)]));
2156        let json = manager.to_json().await.unwrap();
2157        let reloaded = McpServerManager::from_json(&json).unwrap();
2158        assert_eq!(manager.all_configs().await, reloaded.all_configs().await);
2159
2160        let path = std::env::temp_dir()
2161            .join(format!("adk-rust-mcp-manager-test-{}.json", std::process::id()));
2162        manager.save_json_file(&path).await.unwrap();
2163        let from_disk = McpServerManager::from_json_file(&path).unwrap();
2164        assert_eq!(manager.all_configs().await, from_disk.all_configs().await);
2165        std::fs::remove_file(path).unwrap();
2166    }
2167
2168    #[tokio::test]
2169    async fn test_remove_server_success() {
2170        let configs = HashMap::from([(
2171            "to-remove".to_string(),
2172            McpServerConfig {
2173                command: "echo".to_string(),
2174                args: vec![],
2175                env: HashMap::new(),
2176                disabled: false,
2177                auto_approve: vec![],
2178                restart_policy: None,
2179                lifecycle: Default::default(),
2180                task_config: Default::default(),
2181            },
2182        )]);
2183        let manager = McpServerManager::new(configs);
2184
2185        // Verify it exists first
2186        assert!(manager.server_status("to-remove").await.is_ok());
2187
2188        // Remove it
2189        let result = manager.remove_server("to-remove").await;
2190        assert!(result.is_ok());
2191
2192        // Verify it no longer exists
2193        let status_result = manager.server_status("to-remove").await;
2194        assert!(status_result.is_err());
2195    }
2196
2197    #[tokio::test]
2198    async fn test_remove_server_unknown_id() {
2199        let manager = McpServerManager::new(HashMap::new());
2200        let result = manager.remove_server("nonexistent").await;
2201        assert!(result.is_err());
2202        let err_msg = format!("{}", result.unwrap_err());
2203        assert!(err_msg.contains("unknown server ID: 'nonexistent'"));
2204    }
2205
2206    #[tokio::test]
2207    async fn test_shutdown_sets_all_to_stopped() {
2208        // Create a manager with a mix of statuses
2209        let configs = HashMap::from([
2210            (
2211                "server-a".to_string(),
2212                McpServerConfig {
2213                    command: "echo".to_string(),
2214                    args: vec![],
2215                    env: HashMap::new(),
2216                    disabled: false,
2217                    auto_approve: vec![],
2218                    restart_policy: None,
2219                    lifecycle: Default::default(),
2220                    task_config: Default::default(),
2221                },
2222            ),
2223            (
2224                "server-b".to_string(),
2225                McpServerConfig {
2226                    command: "echo".to_string(),
2227                    args: vec![],
2228                    env: HashMap::new(),
2229                    disabled: true,
2230                    auto_approve: vec![],
2231                    restart_policy: None,
2232                    lifecycle: Default::default(),
2233                    task_config: Default::default(),
2234                },
2235            ),
2236            (
2237                "server-c".to_string(),
2238                McpServerConfig {
2239                    command: "echo".to_string(),
2240                    args: vec![],
2241                    env: HashMap::new(),
2242                    disabled: false,
2243                    auto_approve: vec![],
2244                    restart_policy: None,
2245                    lifecycle: Default::default(),
2246                    task_config: Default::default(),
2247                },
2248            ),
2249        ]);
2250        let manager = McpServerManager::new(configs);
2251
2252        // Manually set server-a to FailedToStart to test that shutdown
2253        // resets non-disabled statuses to Stopped
2254        {
2255            let mut servers = manager.servers.write().await;
2256            servers.get_mut("server-a").unwrap().status = ServerStatus::FailedToStart;
2257        }
2258
2259        // Call shutdown
2260        let result = manager.shutdown().await;
2261        assert!(result.is_ok());
2262
2263        // Verify all non-disabled servers are Stopped
2264        let statuses = manager.all_statuses().await;
2265        assert_eq!(statuses["server-a"], ServerStatus::Stopped);
2266        assert_eq!(statuses["server-b"], ServerStatus::Disabled); // Disabled stays Disabled
2267        assert_eq!(statuses["server-c"], ServerStatus::Stopped);
2268    }
2269
2270    #[tokio::test]
2271    async fn test_shutdown_stops_monitoring() {
2272        let manager = McpServerManager::new(HashMap::new());
2273
2274        // Start monitoring
2275        manager.start_monitoring();
2276
2277        // Shutdown should cancel the monitoring token
2278        let result = manager.shutdown().await;
2279        assert!(result.is_ok());
2280
2281        // Verify the cancellation token is cancelled
2282        assert!(
2283            manager
2284                .monitor_cancel
2285                .lock()
2286                .unwrap_or_else(std::sync::PoisonError::into_inner)
2287                .is_cancelled()
2288        );
2289    }
2290
2291    #[tokio::test]
2292    async fn test_shutdown_empty_manager() {
2293        let manager = McpServerManager::new(HashMap::new());
2294        let result = manager.shutdown().await;
2295        assert!(result.is_ok());
2296    }
2297
2298    #[test]
2299    fn test_drop_no_warning_when_no_running_servers() {
2300        // This test verifies Drop doesn't panic when no servers are running.
2301        // The warning is only logged (not observable in test), but we verify
2302        // the Drop impl runs without error.
2303        let configs = HashMap::from([(
2304            "server-a".to_string(),
2305            McpServerConfig {
2306                command: "echo".to_string(),
2307                args: vec![],
2308                env: HashMap::new(),
2309                disabled: false,
2310                auto_approve: vec![],
2311                restart_policy: None,
2312                lifecycle: Default::default(),
2313                task_config: Default::default(),
2314            },
2315        )]);
2316        let manager = McpServerManager::new(configs);
2317        // Drop happens here — should not panic
2318        drop(manager);
2319    }
2320
2321    /// Materializes one task that never finishes and counts `tasks/get` and
2322    /// `tasks/cancel` requests.
2323    #[derive(Clone, Default)]
2324    struct HeldTaskServer {
2325        gets: Arc<std::sync::atomic::AtomicUsize>,
2326        cancels: Arc<std::sync::atomic::AtomicUsize>,
2327    }
2328
2329    impl rmcp::ServerHandler for HeldTaskServer {
2330        fn get_info(&self) -> rmcp::model::InitializeResult {
2331            rmcp::model::InitializeResult::new(
2332                rmcp::model::ServerCapabilities::builder().enable_tools().enable_tasks().build(),
2333            )
2334        }
2335
2336        async fn call_tool(
2337            &self,
2338            params: rmcp::model::CallToolRequestParams,
2339            _context: rmcp::service::RequestContext<rmcp::RoleServer>,
2340        ) -> Result<rmcp::model::CallToolResponse, rmcp::ErrorData> {
2341            if params.name == "hang" {
2342                std::future::pending::<()>().await;
2343            }
2344            Ok(rmcp::model::CreateTaskResult::new(held_task()).into())
2345        }
2346
2347        async fn get_task(
2348            &self,
2349            _params: rmcp::model::GetTaskParams,
2350            _context: rmcp::service::RequestContext<rmcp::RoleServer>,
2351        ) -> Result<rmcp::model::GetTaskResult, rmcp::ErrorData> {
2352            self.gets.fetch_add(1, Ordering::SeqCst);
2353            Ok(rmcp::model::GetTaskResult::new(rmcp::model::DetailedTask::new(
2354                held_task(),
2355                rmcp::model::TaskPayload::Working,
2356            )))
2357        }
2358
2359        async fn cancel_task(
2360            &self,
2361            _params: rmcp::model::CancelTaskParams,
2362            _context: rmcp::service::RequestContext<rmcp::RoleServer>,
2363        ) -> Result<(), rmcp::ErrorData> {
2364            self.cancels.fetch_add(1, Ordering::SeqCst);
2365            Ok(())
2366        }
2367    }
2368
2369    fn held_task() -> rmcp::model::Task {
2370        let now = "2026-10-08T00:00:00Z";
2371        rmcp::model::Task::new("held", rmcp::model::TaskStatus::Working, now, now)
2372    }
2373
2374    #[tokio::test]
2375    async fn stop_server_cancels_pending_tasks_within_the_grace_period() {
2376        use rmcp::ServiceExt;
2377
2378        let server = HeldTaskServer::default();
2379        let (gets, cancels) = (server.gets.clone(), server.cancels.clone());
2380        let (server_io, client_io) = tokio::io::duplex(4096);
2381        tokio::spawn(async move {
2382            if let Ok(running) = server.serve(server_io).await {
2383                let _ = running.waiting().await;
2384            }
2385        });
2386        let client = AdkClientHandler::new(Arc::new(AutoDeclineElicitationHandler))
2387            .with_tasks()
2388            .serve(client_io)
2389            .await
2390            .unwrap();
2391        let toolset = McpToolset::new(client).with_task_support(
2392            crate::mcp::McpTaskConfig::enabled().poll_interval(Duration::from_millis(1)),
2393        );
2394        // Dropping the call once it polls sends one `tasks/cancel`; the held task keeps
2395        // running, so the toolset still tracks it.
2396        tokio::select! {
2397            result = toolset.call_tool_value("job", Default::default()) => {
2398                panic!("a held task must not finish: {result:?}");
2399            }
2400            () = async {
2401                while gets.load(Ordering::SeqCst) == 0 {
2402                    tokio::time::sleep(Duration::from_millis(1)).await;
2403                }
2404            } => {}
2405        }
2406        tokio::time::timeout(Duration::from_secs(10), async {
2407            while cancels.load(Ordering::SeqCst) == 0 {
2408                tokio::time::sleep(Duration::from_millis(1)).await;
2409            }
2410        })
2411        .await
2412        .expect("the dropped call never sent tasks/cancel");
2413
2414        let manager = McpServerManager::new(HashMap::from([(
2415            "tasks".to_string(),
2416            McpServerConfig { command: "unused".to_string(), ..Default::default() },
2417        )]))
2418        .with_grace_period(Duration::from_secs(2));
2419        {
2420            let mut servers = manager.servers.write().await;
2421            let entry = servers.get_mut("tasks").unwrap();
2422            entry.status = ServerStatus::Running;
2423            entry.toolset = Some(toolset);
2424        }
2425        manager.stop_server("tasks").await.unwrap();
2426
2427        assert_eq!(cancels.load(Ordering::SeqCst), 2, "shutdown must cancel the pending task");
2428        assert_eq!(manager.server_status("tasks").await.unwrap(), ServerStatus::Stopped);
2429    }
2430
2431    /// Never answers `tools/list`, or publishes one `lookup` tool.
2432    #[derive(Clone)]
2433    struct ListingServer {
2434        hang: bool,
2435    }
2436
2437    impl rmcp::ServerHandler for ListingServer {
2438        fn get_info(&self) -> rmcp::model::InitializeResult {
2439            rmcp::model::InitializeResult::new(
2440                rmcp::model::ServerCapabilities::builder().enable_tools().build(),
2441            )
2442        }
2443
2444        async fn list_tools(
2445            &self,
2446            _params: Option<rmcp::model::PaginatedRequestParams>,
2447            _context: rmcp::service::RequestContext<rmcp::RoleServer>,
2448        ) -> Result<rmcp::model::ListToolsResult, rmcp::ErrorData> {
2449            if self.hang {
2450                std::future::pending::<()>().await;
2451            }
2452            let schema = Arc::new(serde_json::Map::new());
2453            Ok(rmcp::model::ListToolsResult::with_all_items(vec![rmcp::model::Tool::new(
2454                "lookup",
2455                "Looks up.",
2456                schema,
2457            )]))
2458        }
2459    }
2460
2461    #[tokio::test(start_paused = true)]
2462    async fn a_server_that_never_lists_does_not_hold_the_other_servers() {
2463        use adk_core::Toolset;
2464        use rmcp::ServiceExt;
2465
2466        let limits = McpDiscoveryLimits::default().with_timeout(Duration::from_secs(5));
2467        let servers = [("stuck_a", true), ("stuck_b", true), ("healthy", false)];
2468        let manager = McpServerManager::new(
2469            servers
2470                .iter()
2471                .map(|(id, _)| {
2472                    (
2473                        id.to_string(),
2474                        McpServerConfig { command: "unused".to_string(), ..Default::default() },
2475                    )
2476                })
2477                .collect(),
2478        );
2479        for (id, hang) in servers {
2480            let (server_io, client_io) = tokio::io::duplex(4096);
2481            tokio::spawn(async move {
2482                if let Ok(running) = (ListingServer { hang }).serve(server_io).await {
2483                    let _ = running.waiting().await;
2484                }
2485            });
2486            let client = AdkClientHandler::new(Arc::new(AutoDeclineElicitationHandler))
2487                .serve(client_io)
2488                .await
2489                .unwrap();
2490            let toolset = McpToolset::new(client).with_name(id).with_discovery_limits(limits);
2491            let mut entries = manager.servers.write().await;
2492            let entry = entries.get_mut(id).unwrap();
2493            entry.status = ServerStatus::Running;
2494            entry.toolset = Some(toolset);
2495        }
2496
2497        let started = tokio::time::Instant::now();
2498        let tools =
2499            manager.tools(Arc::new(crate::SimpleToolContext::new("manager-test"))).await.unwrap();
2500
2501        let names: Vec<_> = tools.iter().map(|tool| tool.name().to_string()).collect();
2502        assert_eq!(names, vec!["lookup"]);
2503        // Listed one after another, the two stuck servers would take twice the timeout.
2504        let elapsed = started.elapsed();
2505        assert!(elapsed >= limits.timeout && elapsed < limits.timeout * 2, "{elapsed:?}");
2506    }
2507
2508    #[test]
2509    fn test_builder_with_discovery_limits() {
2510        let limits = McpDiscoveryLimits::default().with_max_pages(4);
2511        let manager = McpServerManager::new(HashMap::new()).with_discovery_limits(limits);
2512        assert_eq!(manager.discovery_limits, limits);
2513        assert_eq!(
2514            McpServerManager::new(HashMap::new()).discovery_limits,
2515            McpDiscoveryLimits::default()
2516        );
2517    }
2518
2519    #[tokio::test]
2520    async fn stop_server_is_bounded_while_a_call_holds_the_connection() {
2521        use rmcp::ServiceExt;
2522
2523        let (server_io, client_io) = tokio::io::duplex(4096);
2524        tokio::spawn(async move {
2525            if let Ok(running) = HeldTaskServer::default().serve(server_io).await {
2526                let _ = running.waiting().await;
2527            }
2528        });
2529        let client = AdkClientHandler::new(Arc::new(AutoDeclineElicitationHandler))
2530            .serve(client_io)
2531            .await
2532            .unwrap();
2533        let toolset = McpToolset::new(client);
2534        // The server never answers, so this call keeps the connection lock.
2535        let hung = toolset.clone();
2536        tokio::spawn(async move { hung.call_tool_value("hang", Default::default()).await });
2537        tokio::time::sleep(Duration::from_millis(20)).await;
2538
2539        let manager = McpServerManager::new(HashMap::from([(
2540            "hung".to_string(),
2541            McpServerConfig { command: "unused".to_string(), ..Default::default() },
2542        )]))
2543        .with_grace_period(Duration::from_millis(100));
2544        {
2545            let mut servers = manager.servers.write().await;
2546            let entry = servers.get_mut("hung").unwrap();
2547            entry.status = ServerStatus::Running;
2548            entry.toolset = Some(toolset);
2549        }
2550        tokio::time::timeout(Duration::from_secs(5), manager.stop_server("hung"))
2551            .await
2552            .expect("stopping a server must not wait on a hung call")
2553            .unwrap();
2554        assert_eq!(manager.server_status("hung").await.unwrap(), ServerStatus::Stopped);
2555    }
2556
2557    /// A server that reads its stdin and never answers the `initialize` request.
2558    #[cfg(unix)]
2559    fn silent_server() -> McpServerConfig {
2560        McpServerConfig {
2561            command: "sh".to_string(),
2562            args: vec!["-c".to_string(), "cat > /dev/null".to_string()],
2563            ..Default::default()
2564        }
2565    }
2566
2567    #[cfg(unix)]
2568    #[tokio::test]
2569    async fn a_hung_handshake_times_out_without_holding_the_registry() {
2570        let manager = Arc::new(
2571            McpServerManager::new(HashMap::from([
2572                ("silent".to_string(), silent_server()),
2573                (
2574                    "other".to_string(),
2575                    McpServerConfig { command: "echo".into(), ..Default::default() },
2576                ),
2577            ]))
2578            .with_startup_timeout(Duration::from_millis(500)),
2579        );
2580        let starting = {
2581            let manager = manager.clone();
2582            tokio::spawn(async move { manager.start_server("silent").await })
2583        };
2584        tokio::time::sleep(Duration::from_millis(100)).await;
2585
2586        let prompt = Duration::from_millis(200);
2587        let statuses = tokio::time::timeout(prompt, manager.all_statuses()).await.unwrap();
2588        assert_eq!(statuses["silent"], ServerStatus::Starting);
2589        assert_eq!(statuses["other"], ServerStatus::Stopped);
2590        let ctx = Arc::new(crate::SimpleToolContext::new("manager-test"));
2591        let tools = tokio::time::timeout(prompt, adk_core::Toolset::tools(&*manager, ctx)).await;
2592        assert!(tools.unwrap().unwrap().is_empty());
2593
2594        let error = starting.await.unwrap().unwrap_err();
2595        assert!(error.message.contains("did not complete its handshake"), "{}", error.message);
2596        assert_eq!(manager.server_status("silent").await.unwrap(), ServerStatus::FailedToStart);
2597    }
2598
2599    #[cfg(unix)]
2600    #[tokio::test]
2601    async fn stopping_a_server_during_its_handshake_cancels_the_start() {
2602        let manager = Arc::new(McpServerManager::new(HashMap::from([(
2603            "silent".to_string(),
2604            silent_server(),
2605        )])));
2606        let starting = {
2607            let manager = manager.clone();
2608            tokio::spawn(async move { manager.start_server("silent").await })
2609        };
2610        tokio::time::sleep(Duration::from_millis(100)).await;
2611
2612        tokio::time::timeout(Duration::from_millis(200), manager.stop_server("silent"))
2613            .await
2614            .unwrap()
2615            .unwrap();
2616        let error = tokio::time::timeout(Duration::from_secs(2), starting)
2617            .await
2618            .expect("the start returns once the server is stopped")
2619            .unwrap()
2620            .unwrap_err();
2621        assert!(error.message.contains("stopped while it was starting"), "{}", error.message);
2622        assert_eq!(manager.server_status("silent").await.unwrap(), ServerStatus::Stopped);
2623    }
2624
2625    fn transition(id: &str, from: ServerStatus, to: ServerStatus) -> ServerStatusTransition {
2626        ServerStatusTransition { id: id.to_string(), from, to }
2627    }
2628
2629    #[tokio::test]
2630    async fn every_status_change_is_published_once_in_order() {
2631        use ServerStatus::{Disabled, FailedToStart, Stopped};
2632        let blank = McpServerConfig { command: " ".to_string(), ..Default::default() };
2633        let manager = McpServerManager::new(HashMap::from([("a".to_string(), blank.clone())]));
2634        let mut transitions = manager.subscribe_status_transitions();
2635
2636        manager.start_server("a").await.unwrap_err();
2637        manager.disable_server("a").await.unwrap();
2638        manager.disable_server("a").await.unwrap();
2639        manager.enable_server("a").await.unwrap();
2640        manager
2641            .update_server("a", McpServerConfig { disabled: true, ..blank.clone() })
2642            .await
2643            .unwrap();
2644        manager.update_server("a", blank).await.unwrap();
2645        manager.start_server("a").await.unwrap_err();
2646        manager.shutdown().await.unwrap();
2647
2648        let mut seen = Vec::new();
2649        while let Ok(transition) = transitions.try_recv() {
2650            seen.push(transition);
2651        }
2652        assert_eq!(
2653            seen,
2654            vec![
2655                transition("a", Stopped, FailedToStart),
2656                transition("a", FailedToStart, Disabled),
2657                transition("a", Disabled, Stopped),
2658                transition("a", Stopped, Disabled),
2659                transition("a", Disabled, Stopped),
2660                transition("a", Stopped, FailedToStart),
2661                transition("a", FailedToStart, Stopped),
2662            ]
2663        );
2664    }
2665
2666    #[tokio::test]
2667    async fn a_launcher_error_fails_the_start_unchanged() {
2668        let config = McpServerConfig { command: "server".to_string(), ..Default::default() };
2669        let manager = McpServerManager::new(HashMap::from([("a".to_string(), config)]))
2670            .with_stdio_launcher(|config| {
2671                Err(AdkError::tool(format!("no sandbox for '{}'", config.command)))
2672            });
2673        let mut transitions = manager.subscribe_status_transitions();
2674
2675        let error = manager.start_server("a").await.unwrap_err();
2676
2677        assert_eq!(error.message, "no sandbox for 'server'");
2678        assert_eq!(manager.server_status("a").await.unwrap(), ServerStatus::FailedToStart);
2679        assert_eq!(
2680            transitions.try_recv().unwrap(),
2681            transition("a", ServerStatus::Stopped, ServerStatus::Starting)
2682        );
2683        assert_eq!(
2684            transitions.try_recv().unwrap(),
2685            transition("a", ServerStatus::Starting, ServerStatus::FailedToStart)
2686        );
2687    }
2688}