adk-tool 0.8.0

Tool system for Rust Agent Development Kit (ADK-Rust) agents (FunctionTool, MCP, Google Search)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
//! McpServerManager implementation.
//!
//! This module contains the main [`McpServerManager`] struct and its
//! construction/builder methods, as well as lifecycle methods (start, stop,
//! restart) for individual servers.

use std::collections::HashMap;
use std::sync::Arc;
use std::time::Duration;

use adk_core::AdkError;
use tokio::sync::RwLock;
use tokio_util::sync::CancellationToken;

use super::super::elicitation::{AutoDeclineElicitationHandler, ElicitationHandler};
use super::super::toolset::McpToolset;
use super::config::McpServerConfig;
use super::entry::{BackoffState, McpServerEntry};
use super::status::ServerStatus;

/// Manages the full lifecycle of multiple local MCP server child processes.
///
/// `McpServerManager` spawns processes, connects them via `TokioChildProcess`
/// transport into [`McpToolset`](super::super::McpToolset) instances, monitors
/// health, auto-restarts on crash with exponential backoff, and aggregates tools
/// from all managed servers behind the [`Toolset`](adk_core::Toolset) trait.
///
/// # Construction
///
/// Use [`McpServerManager::new`] with a map of server configurations, then chain
/// builder methods to configure handlers and intervals:
///
/// ```rust,ignore
/// use adk_tool::mcp::manager::{McpServerConfig, McpServerManager};
/// use std::collections::HashMap;
/// use std::time::Duration;
///
/// let configs = HashMap::from([
///     ("my-server".to_string(), McpServerConfig {
///         command: "npx".to_string(),
///         args: vec!["-y".to_string(), "@modelcontextprotocol/server-filesystem".to_string()],
///         ..Default::default()
///     }),
/// ]);
///
/// let manager = McpServerManager::new(configs)
///     .with_health_check_interval(Duration::from_secs(15))
///     .with_grace_period(Duration::from_secs(3))
///     .with_name("my_manager");
/// ```
#[allow(dead_code)] // Fields used by lifecycle methods in later tasks
pub struct McpServerManager {
    /// Thread-safe map of server ID to per-server state.
    pub(crate) servers: Arc<RwLock<HashMap<String, McpServerEntry>>>,

    /// Optional elicitation handler shared across all managed server connections.
    pub(crate) elicitation_handler: Option<Arc<dyn ElicitationHandler>>,

    /// Optional sampling handler shared across all managed server connections.
    /// Only available when the `mcp-sampling` feature is enabled.
    #[cfg(feature = "mcp-sampling")]
    pub(crate) sampling_handler: Option<Arc<dyn crate::sampling::SamplingHandler>>,

    /// Interval between health check cycles. Default: 30 seconds.
    pub(crate) health_check_interval: Duration,

    /// Grace period to wait for a child process to exit before force-killing. Default: 5 seconds.
    pub(crate) grace_period: Duration,

    /// Cancellation token used to stop the health monitoring background task.
    pub(crate) monitor_cancel: CancellationToken,

    /// Name returned by the `Toolset::name()` implementation. Default: `"mcp_server_manager"`.
    pub(crate) name: String,
}

impl McpServerManager {
    /// Create a new `McpServerManager` from a map of server configurations.
    ///
    /// Each entry is keyed by a unique server ID. Servers with `disabled: true`
    /// are initialized with [`ServerStatus::Disabled`]; all others start as
    /// [`ServerStatus::Stopped`].
    ///
    /// No servers are started automatically — call [`start_server`](Self::start_server)
    /// or [`start_all`](Self::start_all) to begin spawning processes.
    pub fn new(configs: HashMap<String, McpServerConfig>) -> Self {
        let servers: HashMap<String, McpServerEntry> = configs
            .into_iter()
            .map(|(id, config)| {
                let status =
                    if config.disabled { ServerStatus::Disabled } else { ServerStatus::Stopped };
                let backoff = BackoffState::new(&config.restart_policy);
                let entry = McpServerEntry { config, status, toolset: None, child: None, backoff };
                (id, entry)
            })
            .collect();

        Self {
            servers: Arc::new(RwLock::new(servers)),
            elicitation_handler: None,
            #[cfg(feature = "mcp-sampling")]
            sampling_handler: None,
            health_check_interval: Duration::from_secs(30),
            grace_period: Duration::from_secs(5),
            monitor_cancel: CancellationToken::new(),
            name: "mcp_server_manager".to_string(),
        }
    }

    /// Create a new `McpServerManager` by parsing a JSON string in Kiro `mcp.json` format.
    ///
    /// The JSON must contain a top-level `mcpServers` object mapping server IDs
    /// to their configurations. CamelCase JSON field names are automatically
    /// mapped to snake_case Rust fields.
    ///
    /// # Errors
    ///
    /// Returns `AdkError::Tool` if the JSON is malformed or missing required fields.
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// let json = r#"{
    ///     "mcpServers": {
    ///         "filesystem": {
    ///             "command": "npx",
    ///             "args": ["-y", "@modelcontextprotocol/server-filesystem", "/tmp"]
    ///         }
    ///     }
    /// }"#;
    /// let manager = McpServerManager::from_json(json)?;
    /// ```
    pub fn from_json(json: &str) -> adk_core::Result<Self> {
        let file: super::config::McpJsonFile = serde_json::from_str(json)
            .map_err(|e| AdkError::tool(format!("failed to parse MCP server config: {e}")))?;
        Ok(Self::new(file.mcp_servers))
    }

    /// Create a new `McpServerManager` by reading and parsing a JSON file from disk.
    ///
    /// The file must contain JSON in Kiro `mcp.json` format (see [`from_json`](Self::from_json)).
    /// File reading is synchronous, which is acceptable for config loading at startup.
    ///
    /// # Errors
    ///
    /// Returns `AdkError::Tool` if the file cannot be read or the JSON is malformed.
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// let manager = McpServerManager::from_json_file("mcp.json")?;
    /// ```
    pub fn from_json_file(path: impl AsRef<std::path::Path>) -> adk_core::Result<Self> {
        let path = path.as_ref();
        let content = std::fs::read_to_string(path).map_err(|e| {
            AdkError::tool(format!("failed to read config file '{}': {e}", path.display()))
        })?;
        Self::from_json(&content)
    }

    /// Set the elicitation handler used for all managed server connections.
    ///
    /// The handler is preserved across server restarts via `Arc` sharing.
    pub fn with_elicitation_handler(mut self, handler: Arc<dyn ElicitationHandler>) -> Self {
        self.elicitation_handler = Some(handler);
        self
    }

    /// Set the sampling handler used for all managed server connections.
    ///
    /// The handler is preserved across server restarts via `Arc` sharing.
    /// Only available when the `mcp-sampling` feature is enabled.
    #[cfg(feature = "mcp-sampling")]
    pub fn with_sampling_handler(
        mut self,
        handler: Arc<dyn crate::sampling::SamplingHandler>,
    ) -> Self {
        self.sampling_handler = Some(handler);
        self
    }

    /// Set the interval between health check cycles.
    ///
    /// Default: 30 seconds.
    pub fn with_health_check_interval(mut self, interval: Duration) -> Self {
        self.health_check_interval = interval;
        self
    }

    /// Set the grace period to wait for a child process to exit before force-killing.
    ///
    /// Default: 5 seconds.
    pub fn with_grace_period(mut self, period: Duration) -> Self {
        self.grace_period = period;
        self
    }

    /// Set the name returned by the `Toolset::name()` implementation.
    ///
    /// Default: `"mcp_server_manager"`.
    pub fn with_name(mut self, name: impl Into<String>) -> Self {
        self.name = name.into();
        self
    }

    /// Start a managed MCP server by ID.
    ///
    /// Spawns the configured command as a child process, creates a
    /// `TokioChildProcess` transport, and connects via `McpToolset` with the
    /// configured elicitation (and optionally sampling) handler.
    ///
    /// If the server is already `Running`, this is a no-op and returns `Ok(())`.
    ///
    /// # Errors
    ///
    /// Returns `AdkError::Tool` if:
    /// - The server ID does not exist
    /// - The child process fails to spawn
    /// - The MCP handshake fails
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// manager.start_server("my-server").await?;
    /// ```
    pub async fn start_server(&self, id: &str) -> adk_core::Result<()> {
        let mut servers = self.servers.write().await;
        let entry = servers
            .get_mut(id)
            .ok_or_else(|| AdkError::tool(format!("unknown server ID: '{id}'")))?;

        Self::start_server_inner(
            id,
            entry,
            &self.elicitation_handler,
            #[cfg(feature = "mcp-sampling")]
            &self.sampling_handler,
        )
        .await
    }

    /// Internal start logic operating on a mutable entry reference.
    ///
    /// This avoids double-locking when called from `restart_server`.
    async fn start_server_inner(
        id: &str,
        entry: &mut McpServerEntry,
        elicitation_handler: &Option<Arc<dyn ElicitationHandler>>,
        #[cfg(feature = "mcp-sampling")] sampling_handler: &Option<
            Arc<dyn crate::sampling::SamplingHandler>,
        >,
    ) -> adk_core::Result<()> {
        // If already running, nothing to do
        if entry.status == ServerStatus::Running {
            return Ok(());
        }

        let config = &entry.config;

        // Build the command
        let mut cmd = tokio::process::Command::new(&config.command);
        cmd.args(&config.args);
        cmd.envs(&config.env);

        // Create transport — TokioChildProcess::new spawns the child internally
        let transport = rmcp::transport::TokioChildProcess::new(cmd).map_err(|e| {
            entry.status = ServerStatus::FailedToStart;
            AdkError::tool(format!(
                "failed to spawn server '{id}': command '{}' not found. Verify it is installed and on PATH: {e}",
                config.command
            ))
        })?;

        // Connect via McpToolset with the appropriate handler
        let handler: Arc<dyn ElicitationHandler> =
            elicitation_handler.clone().unwrap_or_else(|| Arc::new(AutoDeclineElicitationHandler));

        #[cfg(feature = "mcp-sampling")]
        let toolset_result = if let Some(sampling) = sampling_handler {
            McpToolset::with_sampling_handler(transport, handler, Arc::clone(sampling)).await
        } else {
            McpToolset::with_elicitation_handler(transport, handler).await
        };

        #[cfg(not(feature = "mcp-sampling"))]
        let toolset_result = McpToolset::with_elicitation_handler(transport, handler).await;

        let toolset = toolset_result.map_err(|e| {
            entry.status = ServerStatus::FailedToStart;
            AdkError::tool(format!("MCP handshake failed for server '{id}': {e}"))
        })?;

        // Success — update entry
        entry.status = ServerStatus::Running;
        entry.toolset = Some(toolset);
        entry.child = None; // Child is owned by the transport/toolset

        tracing::info!(
            server.id = id,
            server.command = config.command,
            server.args = ?config.args,
            "started MCP server"
        );

        Ok(())
    }

    /// Stop a managed MCP server by ID.
    ///
    /// Cancels the MCP session via the toolset's cancellation token, drops the
    /// `McpToolset` connection, and sets the status to `Stopped`.
    ///
    /// If the server is not running, this is a no-op and returns `Ok(())`.
    ///
    /// # Errors
    ///
    /// Returns `AdkError::Tool` if the server ID does not exist.
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// manager.stop_server("my-server").await?;
    /// ```
    pub async fn stop_server(&self, id: &str) -> adk_core::Result<()> {
        let mut servers = self.servers.write().await;
        let entry = servers
            .get_mut(id)
            .ok_or_else(|| AdkError::tool(format!("unknown server ID: '{id}'")))?;

        Self::stop_server_inner(id, entry, "manual").await;
        Ok(())
    }

    /// Internal stop logic operating on a mutable entry reference.
    ///
    /// This avoids double-locking when called from `restart_server`.
    async fn stop_server_inner(id: &str, entry: &mut McpServerEntry, reason: &str) {
        // If not running, nothing to do
        if entry.status != ServerStatus::Running && entry.status != ServerStatus::Restarting {
            return;
        }

        // Cancel the MCP session and drop the toolset
        if let Some(ref toolset) = entry.toolset {
            let cancel_token = toolset.cancellation_token().await;
            cancel_token.cancel();
        }

        // Drop the toolset — this cleans up the transport and child process
        entry.toolset = None;
        entry.child = None;

        // Only set to Stopped if we're not in a Restarting transition
        if entry.status != ServerStatus::Restarting {
            entry.status = ServerStatus::Stopped;
        }

        tracing::info!(server.id = id, stop.reason = reason, "stopped MCP server");
    }

    /// Restart a managed MCP server by ID.
    ///
    /// Sets the status to `Restarting`, stops the server, then starts it again.
    /// The same `ElicitationHandler` and `SamplingHandler` `Arc`s are preserved
    /// across the restart.
    ///
    /// # Errors
    ///
    /// Returns `AdkError::Tool` if:
    /// - The server ID does not exist
    /// - The start phase fails (status set to `FailedToStart`)
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// manager.restart_server("my-server").await?;
    /// ```
    pub async fn restart_server(&self, id: &str) -> adk_core::Result<()> {
        let mut servers = self.servers.write().await;
        let entry = servers
            .get_mut(id)
            .ok_or_else(|| AdkError::tool(format!("unknown server ID: '{id}'")))?;

        // Set status to Restarting
        entry.status = ServerStatus::Restarting;

        // Stop the server (inline to avoid double-locking)
        Self::stop_server_inner(id, entry, "restart").await;

        // Start the server again
        Self::start_server_inner(
            id,
            entry,
            &self.elicitation_handler,
            #[cfg(feature = "mcp-sampling")]
            &self.sampling_handler,
        )
        .await
    }

    /// Return the current [`ServerStatus`] for a given server ID.
    ///
    /// # Errors
    ///
    /// Returns `AdkError::Tool` if the server ID does not exist.
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// let status = manager.server_status("my-server").await?;
    /// assert_eq!(status, ServerStatus::Running);
    /// ```
    pub async fn server_status(&self, id: &str) -> adk_core::Result<ServerStatus> {
        let servers = self.servers.read().await;
        servers
            .get(id)
            .map(|entry| entry.status)
            .ok_or_else(|| AdkError::tool(format!("unknown server ID: '{id}'")))
    }

    /// Return a map of all server IDs to their current [`ServerStatus`].
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// let statuses = manager.all_statuses().await;
    /// for (id, status) in &statuses {
    ///     println!("{id}: {status:?}");
    /// }
    /// ```
    pub async fn all_statuses(&self) -> HashMap<String, ServerStatus> {
        let servers = self.servers.read().await;
        servers.iter().map(|(id, entry)| (id.clone(), entry.status)).collect()
    }

    /// Return the number of servers currently in [`ServerStatus::Running`] status.
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// let count = manager.running_server_count().await;
    /// println!("{count} servers running");
    /// ```
    pub async fn running_server_count(&self) -> usize {
        let servers = self.servers.read().await;
        servers.values().filter(|entry| entry.status == ServerStatus::Running).count()
    }

    /// Start the background health monitoring task.
    ///
    /// Spawns a `tokio::spawn` task that periodically checks each `Running`
    /// server by calling [`McpToolset::is_closed()`](super::super::McpToolset::is_closed).
    /// If a server's connection is closed, the monitor sets its status to
    /// `Crashed` and, if a [`RestartPolicy`] is configured, attempts auto-restart
    /// with exponential backoff.
    ///
    /// The monitoring loop runs until [`stop_monitoring`](Self::stop_monitoring)
    /// is called, which cancels the background task via the internal
    /// `CancellationToken`.
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// manager.start_monitoring();
    /// // ... later ...
    /// manager.stop_monitoring();
    /// ```
    pub fn start_monitoring(&self) {
        let servers = Arc::clone(&self.servers);
        let cancel = self.monitor_cancel.clone();
        let interval = self.health_check_interval;
        let elicitation_handler = self.elicitation_handler.clone();
        #[cfg(feature = "mcp-sampling")]
        let sampling_handler = self.sampling_handler.clone();

        tokio::spawn(async move {
            loop {
                tokio::select! {
                    _ = cancel.cancelled() => {
                        tracing::info!("health monitor stopped");
                        break;
                    }
                    _ = tokio::time::sleep(interval) => {
                        // Phase 1: Detect crashed servers under a read lock
                        let crashed_ids: Vec<String> = {
                            let servers = servers.read().await;
                            let mut crashed = Vec::new();
                            for (id, entry) in servers.iter() {
                                if entry.status != ServerStatus::Running {
                                    continue;
                                }
                                if let Some(ref toolset) = entry.toolset {
                                    if toolset.is_closed().await {
                                        crashed.push(id.clone());
                                    }
                                } else {
                                    // No toolset but status is Running — treat as crashed
                                    crashed.push(id.clone());
                                }
                            }
                            crashed
                        };

                        if crashed_ids.is_empty() {
                            continue;
                        }

                        // Phase 2: Mark crashed servers and attempt auto-restart
                        for id in crashed_ids {
                            // Mark as Crashed under write lock
                            let restart_info = {
                                let mut servers = servers.write().await;
                                if let Some(entry) = servers.get_mut(&id) {
                                    // Only process if still Running (could have been
                                    // stopped between read and write lock)
                                    if entry.status != ServerStatus::Running {
                                        continue;
                                    }

                                    tracing::warn!(
                                        server.id = id,
                                        failure.reason = "connection closed",
                                        "health check failed"
                                    );

                                    entry.status = ServerStatus::Crashed;
                                    entry.toolset = None;
                                    entry.child = None;

                                    // Check if auto-restart is configured
                                    entry.config.restart_policy.clone()
                                } else {
                                    continue;
                                }
                            };

                            // Attempt auto-restart if policy allows
                            if let Some(ref policy) = restart_info {
                                // Check if max attempts exceeded
                                let exceeded = {
                                    let servers = servers.read().await;
                                    servers.get(&id)
                                        .map(|e| e.backoff.exceeded_max_attempts(policy))
                                        .unwrap_or(true)
                                };

                                if exceeded {
                                    let mut servers = servers.write().await;
                                    if let Some(entry) = servers.get_mut(&id) {
                                        tracing::error!(
                                            server.id = id,
                                            restart.total_attempts = entry.backoff.consecutive_failures,
                                            "max restart attempts exceeded, giving up"
                                        );
                                        entry.status = ServerStatus::FailedToStart;
                                    }
                                    continue;
                                }

                                // Compute backoff delay and increment failure counter
                                let (delay_ms, attempt) = {
                                    let mut servers = servers.write().await;
                                    if let Some(entry) = servers.get_mut(&id) {
                                        let attempt = entry.backoff.consecutive_failures + 1;
                                        let delay = entry.backoff.next_delay(policy);
                                        (delay, attempt)
                                    } else {
                                        continue;
                                    }
                                };

                                tracing::info!(
                                    server.id = id,
                                    restart.attempt = attempt,
                                    restart.delay_ms = delay_ms,
                                    "auto-restarting crashed server after backoff"
                                );

                                // Wait for backoff delay (without holding any lock)
                                tokio::time::sleep(Duration::from_millis(delay_ms)).await;

                                // Check if monitoring was cancelled during the sleep
                                if cancel.is_cancelled() {
                                    break;
                                }

                                // Attempt restart under write lock
                                let restart_result = {
                                    let mut servers = servers.write().await;
                                    if let Some(entry) = servers.get_mut(&id) {
                                        entry.status = ServerStatus::Restarting;
                                        Self::start_server_inner(
                                            &id,
                                            entry,
                                            &elicitation_handler,
                                            #[cfg(feature = "mcp-sampling")]
                                            &sampling_handler,
                                        )
                                        .await
                                    } else {
                                        continue;
                                    }
                                };

                                match restart_result {
                                    Ok(()) => {
                                        // Reset backoff on success
                                        let mut servers = servers.write().await;
                                        if let Some(entry) = servers.get_mut(&id) {
                                            entry.backoff.reset(policy);
                                            tracing::info!(
                                                server.id = id,
                                                "auto-restart succeeded"
                                            );
                                        }
                                    }
                                    Err(e) => {
                                        tracing::warn!(
                                            server.id = id,
                                            error = %e,
                                            "auto-restart failed"
                                        );
                                        // Status already set to FailedToStart by start_server_inner
                                    }
                                }
                            }
                        }
                    }
                }
            }
        });
    }

    /// Stop the background health monitoring task.
    ///
    /// Cancels the monitoring loop spawned by [`start_monitoring`](Self::start_monitoring).
    /// This is a no-op if monitoring was never started or has already been stopped.
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// manager.stop_monitoring();
    /// ```
    pub fn stop_monitoring(&self) {
        self.monitor_cancel.cancel();
    }

    /// Register a new server configuration at runtime.
    ///
    /// The new server is initialized with [`ServerStatus::Disabled`] if
    /// `config.disabled` is `true`, or [`ServerStatus::Stopped`] otherwise.
    /// It will not be started automatically — call
    /// [`start_server`](Self::start_server) to begin spawning the process.
    ///
    /// # Errors
    ///
    /// Returns `AdkError::Tool` if a server with the given ID already exists.
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// let config = McpServerConfig {
    ///     command: "npx".to_string(),
    ///     args: vec!["-y".to_string(), "server".to_string()],
    ///     ..Default::default()
    /// };
    /// manager.add_server("new-server".to_string(), config).await?;
    /// ```
    pub async fn add_server(&self, id: String, config: McpServerConfig) -> adk_core::Result<()> {
        let mut servers = self.servers.write().await;
        if servers.contains_key(&id) {
            return Err(AdkError::tool(format!("server ID '{id}' already exists")));
        }
        let status = if config.disabled { ServerStatus::Disabled } else { ServerStatus::Stopped };
        let backoff = BackoffState::new(&config.restart_policy);
        let entry = McpServerEntry { config, status, toolset: None, child: None, backoff };
        servers.insert(id, entry);
        Ok(())
    }

    /// Remove a server configuration at runtime.
    ///
    /// If the server is currently running, it is stopped first using the
    /// graceful stop sequence before being removed from the manager.
    ///
    /// # Errors
    ///
    /// Returns `AdkError::Tool` if the server ID does not exist.
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// manager.remove_server("old-server").await?;
    /// ```
    pub async fn remove_server(&self, id: &str) -> adk_core::Result<()> {
        let mut servers = self.servers.write().await;
        let entry = servers
            .get_mut(id)
            .ok_or_else(|| AdkError::tool(format!("unknown server ID: '{id}'")))?;

        // If the server is running, stop it first
        Self::stop_server_inner(id, entry, "removal").await;

        servers.remove(id);
        Ok(())
    }

    /// Start all non-disabled servers concurrently.
    ///
    /// Collects all server IDs where `disabled == false`, then starts each one
    /// via [`start_server`](Self::start_server). Failures are logged but do not
    /// prevent other servers from starting.
    ///
    /// # Returns
    ///
    /// A `HashMap<String, Result<()>>` with per-server outcomes. Disabled servers
    /// are not included in the result.
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// let results = manager.start_all().await;
    /// for (id, result) in &results {
    ///     match result {
    ///         Ok(()) => println!("{id}: started"),
    ///         Err(e) => eprintln!("{id}: failed to start: {e}"),
    ///     }
    /// }
    /// ```
    pub async fn start_all(&self) -> HashMap<String, adk_core::Result<()>> {
        // Collect IDs of non-disabled servers under a read lock
        let ids_to_start: Vec<String> = {
            let servers = self.servers.read().await;
            servers
                .iter()
                .filter(|(_, entry)| !entry.config.disabled)
                .map(|(id, _)| id.clone())
                .collect()
        };

        // Start each server concurrently — each start_server call acquires
        // its own write lock internally
        let futures: Vec<_> = ids_to_start
            .iter()
            .map(|id| {
                let id = id.clone();
                async move {
                    let result = self.start_server(&id).await;
                    if let Err(ref e) = result {
                        tracing::error!(
                            server.id = id,
                            error = %e,
                            "failed to start server during start_all"
                        );
                    }
                    (id, result)
                }
            })
            .collect();

        futures::future::join_all(futures).await.into_iter().collect()
    }

    /// Shut down all managed servers and stop health monitoring.
    ///
    /// This method first stops the health monitoring task, then stops all
    /// running servers using the graceful stop sequence (cancel token → grace
    /// period → force-kill). After shutdown, all server statuses are set to
    /// `Stopped`.
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// manager.shutdown().await?;
    /// // All servers are now stopped, safe to drop the manager
    /// ```
    pub async fn shutdown(&self) -> adk_core::Result<()> {
        // Step 1: Stop health monitoring first
        self.stop_monitoring();

        // Step 2: Acquire write lock and stop all running servers
        let mut servers = self.servers.write().await;
        let ids: Vec<String> = servers
            .iter()
            .filter(|(_, entry)| entry.status == ServerStatus::Running)
            .map(|(id, _)| id.clone())
            .collect();

        for id in &ids {
            if let Some(entry) = servers.get_mut(id) {
                Self::stop_server_inner(id, entry, "shutdown").await;
            }
        }

        // Step 3: Set all server statuses to Stopped (except Disabled)
        for entry in servers.values_mut() {
            if entry.status != ServerStatus::Disabled {
                entry.status = ServerStatus::Stopped;
            }
        }

        Ok(())
    }
}

impl Drop for McpServerManager {
    fn drop(&mut self) {
        // Use try_read() to avoid blocking in Drop
        if let Ok(servers) = self.servers.try_read() {
            let running = servers.values().filter(|e| e.status == ServerStatus::Running).count();
            if running > 0 {
                tracing::warn!(
                    running_count = running,
                    "McpServerManager dropped with {running} servers still running. \
                     Call shutdown() before dropping to ensure clean process cleanup."
                );
            }
        }
    }
}

// Static assertions: McpServerManager must be Send + Sync so it can be
// shared across async tasks via Arc.
const _: () = {
    fn _assert_send<T: Send>() {}
    fn _assert_sync<T: Sync>() {}
    fn _assert_send_sync() {
        _assert_send::<McpServerManager>();
        _assert_sync::<McpServerManager>();
    }
};

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_new_empty_configs() {
        let manager = McpServerManager::new(HashMap::new());
        assert_eq!(manager.name, "mcp_server_manager");
        assert_eq!(manager.health_check_interval, Duration::from_secs(30));
        assert_eq!(manager.grace_period, Duration::from_secs(5));
        assert!(manager.elicitation_handler.is_none());
    }

    #[test]
    fn test_new_disabled_server_gets_disabled_status() {
        let configs = HashMap::from([(
            "disabled-server".to_string(),
            McpServerConfig {
                command: "echo".to_string(),
                args: vec![],
                env: HashMap::new(),
                disabled: true,
                auto_approve: vec![],
                restart_policy: None,
            },
        )]);
        let manager = McpServerManager::new(configs);
        let servers = manager.servers.try_read().unwrap();
        assert_eq!(servers["disabled-server"].status, ServerStatus::Disabled);
    }

    #[test]
    fn test_new_enabled_server_gets_stopped_status() {
        let configs = HashMap::from([(
            "enabled-server".to_string(),
            McpServerConfig {
                command: "echo".to_string(),
                args: vec![],
                env: HashMap::new(),
                disabled: false,
                auto_approve: vec![],
                restart_policy: None,
            },
        )]);
        let manager = McpServerManager::new(configs);
        let servers = manager.servers.try_read().unwrap();
        assert_eq!(servers["enabled-server"].status, ServerStatus::Stopped);
    }

    #[test]
    fn test_builder_with_name() {
        let manager = McpServerManager::new(HashMap::new()).with_name("custom_name");
        assert_eq!(manager.name, "custom_name");
    }

    #[test]
    fn test_builder_with_health_check_interval() {
        let manager = McpServerManager::new(HashMap::new())
            .with_health_check_interval(Duration::from_secs(10));
        assert_eq!(manager.health_check_interval, Duration::from_secs(10));
    }

    #[test]
    fn test_builder_with_grace_period() {
        let manager =
            McpServerManager::new(HashMap::new()).with_grace_period(Duration::from_secs(2));
        assert_eq!(manager.grace_period, Duration::from_secs(2));
    }

    #[test]
    fn test_builder_with_elicitation_handler() {
        use super::super::super::elicitation::AutoDeclineElicitationHandler;
        let handler: Arc<dyn ElicitationHandler> = Arc::new(AutoDeclineElicitationHandler);
        let manager = McpServerManager::new(HashMap::new()).with_elicitation_handler(handler);
        assert!(manager.elicitation_handler.is_some());
    }

    #[tokio::test]
    async fn test_server_status_returns_correct_status() {
        let configs = HashMap::from([(
            "server-a".to_string(),
            McpServerConfig {
                command: "echo".to_string(),
                args: vec![],
                env: HashMap::new(),
                disabled: false,
                auto_approve: vec![],
                restart_policy: None,
            },
        )]);
        let manager = McpServerManager::new(configs);
        let status = manager.server_status("server-a").await.unwrap();
        assert_eq!(status, ServerStatus::Stopped);
    }

    #[tokio::test]
    async fn test_server_status_unknown_id_returns_error() {
        let manager = McpServerManager::new(HashMap::new());
        let result = manager.server_status("nonexistent").await;
        assert!(result.is_err());
        let err_msg = format!("{}", result.unwrap_err());
        assert!(err_msg.contains("unknown server ID: 'nonexistent'"));
    }

    #[tokio::test]
    async fn test_all_statuses_returns_all_servers() {
        let configs = HashMap::from([
            (
                "server-a".to_string(),
                McpServerConfig {
                    command: "echo".to_string(),
                    args: vec![],
                    env: HashMap::new(),
                    disabled: false,
                    auto_approve: vec![],
                    restart_policy: None,
                },
            ),
            (
                "server-b".to_string(),
                McpServerConfig {
                    command: "echo".to_string(),
                    args: vec![],
                    env: HashMap::new(),
                    disabled: true,
                    auto_approve: vec![],
                    restart_policy: None,
                },
            ),
        ]);
        let manager = McpServerManager::new(configs);
        let statuses = manager.all_statuses().await;
        assert_eq!(statuses.len(), 2);
        assert_eq!(statuses["server-a"], ServerStatus::Stopped);
        assert_eq!(statuses["server-b"], ServerStatus::Disabled);
    }

    #[tokio::test]
    async fn test_all_statuses_empty_manager() {
        let manager = McpServerManager::new(HashMap::new());
        let statuses = manager.all_statuses().await;
        assert!(statuses.is_empty());
    }

    #[tokio::test]
    async fn test_running_server_count_no_running() {
        let configs = HashMap::from([(
            "server-a".to_string(),
            McpServerConfig {
                command: "echo".to_string(),
                args: vec![],
                env: HashMap::new(),
                disabled: false,
                auto_approve: vec![],
                restart_policy: None,
            },
        )]);
        let manager = McpServerManager::new(configs);
        assert_eq!(manager.running_server_count().await, 0);
    }

    #[tokio::test]
    async fn test_running_server_count_empty_manager() {
        let manager = McpServerManager::new(HashMap::new());
        assert_eq!(manager.running_server_count().await, 0);
    }

    #[tokio::test]
    async fn test_start_all_skips_disabled_servers() {
        let configs = HashMap::from([
            (
                "enabled".to_string(),
                McpServerConfig {
                    command: "nonexistent-command-xyz".to_string(),
                    args: vec![],
                    env: HashMap::new(),
                    disabled: false,
                    auto_approve: vec![],
                    restart_policy: None,
                },
            ),
            (
                "disabled".to_string(),
                McpServerConfig {
                    command: "echo".to_string(),
                    args: vec![],
                    env: HashMap::new(),
                    disabled: true,
                    auto_approve: vec![],
                    restart_policy: None,
                },
            ),
        ]);
        let manager = McpServerManager::new(configs);
        let results = manager.start_all().await;

        // Only the enabled server should be in the results
        assert!(results.contains_key("enabled"));
        assert!(!results.contains_key("disabled"));

        // The enabled server should fail (nonexistent command)
        assert!(results["enabled"].is_err());

        // The disabled server should still be Disabled
        let status = manager.server_status("disabled").await.unwrap();
        assert_eq!(status, ServerStatus::Disabled);
    }

    #[tokio::test]
    async fn test_start_all_empty_manager() {
        let manager = McpServerManager::new(HashMap::new());
        let results = manager.start_all().await;
        assert!(results.is_empty());
    }

    #[test]
    fn test_from_json_valid() {
        let json = r#"{
            "mcpServers": {
                "filesystem": {
                    "command": "npx",
                    "args": ["-y", "@modelcontextprotocol/server-filesystem", "/tmp"],
                    "env": { "NODE_ENV": "production" },
                    "disabled": false,
                    "autoApprove": ["read_file", "list_directory"]
                },
                "github": {
                    "command": "npx",
                    "args": ["-y", "@modelcontextprotocol/server-github"],
                    "env": { "GITHUB_TOKEN": "ghp_xxx" },
                    "disabled": true,
                    "autoApprove": []
                }
            }
        }"#;
        let manager = McpServerManager::from_json(json).unwrap();
        let servers = manager.servers.try_read().unwrap();
        assert_eq!(servers.len(), 2);

        let fs_entry = &servers["filesystem"];
        assert_eq!(fs_entry.config.command, "npx");
        assert_eq!(
            fs_entry.config.args,
            vec!["-y", "@modelcontextprotocol/server-filesystem", "/tmp"]
        );
        assert_eq!(fs_entry.config.env["NODE_ENV"], "production");
        assert!(!fs_entry.config.disabled);
        assert_eq!(fs_entry.config.auto_approve, vec!["read_file", "list_directory"]);
        assert_eq!(fs_entry.status, ServerStatus::Stopped);

        let gh_entry = &servers["github"];
        assert_eq!(gh_entry.config.command, "npx");
        assert!(gh_entry.config.disabled);
        assert_eq!(gh_entry.status, ServerStatus::Disabled);
    }

    #[test]
    fn test_from_json_malformed() {
        let json = r#"{ this is not valid json }"#;
        let result = McpServerManager::from_json(json);
        let err = result.err().expect("should fail on malformed JSON");
        let err_msg = format!("{err}");
        assert!(
            err_msg.contains("failed to parse MCP server config"),
            "error message was: {err_msg}"
        );
    }

    #[test]
    fn test_from_json_missing_command() {
        let json = r#"{
            "mcpServers": {
                "bad-server": {
                    "args": ["--flag"]
                }
            }
        }"#;
        let result = McpServerManager::from_json(json);
        let err = result.err().expect("should fail on missing command field");
        let err_msg = format!("{err}");
        assert!(
            err_msg.contains("failed to parse MCP server config"),
            "error message was: {err_msg}"
        );
    }

    #[test]
    fn test_from_json_file_not_found() {
        let result = McpServerManager::from_json_file("/nonexistent/path/mcp.json");
        let err = result.err().expect("should fail on nonexistent file");
        let err_msg = format!("{err}");
        assert!(err_msg.contains("failed to read config file"), "error message was: {err_msg}");
        assert!(
            err_msg.contains("/nonexistent/path/mcp.json"),
            "error message should contain the path: {err_msg}"
        );
    }

    #[test]
    fn test_mixed_disabled_and_enabled_servers() {
        let configs = HashMap::from([
            (
                "server-a".to_string(),
                McpServerConfig {
                    command: "cmd-a".to_string(),
                    args: vec![],
                    env: HashMap::new(),
                    disabled: false,
                    auto_approve: vec![],
                    restart_policy: None,
                },
            ),
            (
                "server-b".to_string(),
                McpServerConfig {
                    command: "cmd-b".to_string(),
                    args: vec![],
                    env: HashMap::new(),
                    disabled: true,
                    auto_approve: vec![],
                    restart_policy: None,
                },
            ),
            (
                "server-c".to_string(),
                McpServerConfig {
                    command: "cmd-c".to_string(),
                    args: vec![],
                    env: HashMap::new(),
                    disabled: false,
                    auto_approve: vec![],
                    restart_policy: None,
                },
            ),
        ]);
        let manager = McpServerManager::new(configs);
        let servers = manager.servers.try_read().unwrap();
        assert_eq!(servers["server-a"].status, ServerStatus::Stopped);
        assert_eq!(servers["server-b"].status, ServerStatus::Disabled);
        assert_eq!(servers["server-c"].status, ServerStatus::Stopped);
    }

    #[tokio::test]
    async fn test_add_server_success() {
        let manager = McpServerManager::new(HashMap::new());
        let config = McpServerConfig {
            command: "echo".to_string(),
            args: vec!["hello".to_string()],
            env: HashMap::new(),
            disabled: false,
            auto_approve: vec![],
            restart_policy: None,
        };
        let result = manager.add_server("new-server".to_string(), config).await;
        assert!(result.is_ok());

        let status = manager.server_status("new-server").await.unwrap();
        assert_eq!(status, ServerStatus::Stopped);
    }

    #[tokio::test]
    async fn test_add_server_duplicate_id() {
        let configs = HashMap::from([(
            "existing".to_string(),
            McpServerConfig {
                command: "echo".to_string(),
                args: vec![],
                env: HashMap::new(),
                disabled: false,
                auto_approve: vec![],
                restart_policy: None,
            },
        )]);
        let manager = McpServerManager::new(configs);

        let config = McpServerConfig {
            command: "echo".to_string(),
            args: vec![],
            env: HashMap::new(),
            disabled: false,
            auto_approve: vec![],
            restart_policy: None,
        };
        let result = manager.add_server("existing".to_string(), config).await;
        assert!(result.is_err());
        let err_msg = format!("{}", result.unwrap_err());
        assert!(err_msg.contains("server ID 'existing' already exists"));
    }

    #[tokio::test]
    async fn test_add_server_disabled() {
        let manager = McpServerManager::new(HashMap::new());
        let config = McpServerConfig {
            command: "echo".to_string(),
            args: vec![],
            env: HashMap::new(),
            disabled: true,
            auto_approve: vec![],
            restart_policy: None,
        };
        let result = manager.add_server("disabled-server".to_string(), config).await;
        assert!(result.is_ok());

        let status = manager.server_status("disabled-server").await.unwrap();
        assert_eq!(status, ServerStatus::Disabled);
    }

    #[tokio::test]
    async fn test_remove_server_success() {
        let configs = HashMap::from([(
            "to-remove".to_string(),
            McpServerConfig {
                command: "echo".to_string(),
                args: vec![],
                env: HashMap::new(),
                disabled: false,
                auto_approve: vec![],
                restart_policy: None,
            },
        )]);
        let manager = McpServerManager::new(configs);

        // Verify it exists first
        assert!(manager.server_status("to-remove").await.is_ok());

        // Remove it
        let result = manager.remove_server("to-remove").await;
        assert!(result.is_ok());

        // Verify it no longer exists
        let status_result = manager.server_status("to-remove").await;
        assert!(status_result.is_err());
    }

    #[tokio::test]
    async fn test_remove_server_unknown_id() {
        let manager = McpServerManager::new(HashMap::new());
        let result = manager.remove_server("nonexistent").await;
        assert!(result.is_err());
        let err_msg = format!("{}", result.unwrap_err());
        assert!(err_msg.contains("unknown server ID: 'nonexistent'"));
    }

    #[tokio::test]
    async fn test_shutdown_sets_all_to_stopped() {
        // Create a manager with a mix of statuses
        let configs = HashMap::from([
            (
                "server-a".to_string(),
                McpServerConfig {
                    command: "echo".to_string(),
                    args: vec![],
                    env: HashMap::new(),
                    disabled: false,
                    auto_approve: vec![],
                    restart_policy: None,
                },
            ),
            (
                "server-b".to_string(),
                McpServerConfig {
                    command: "echo".to_string(),
                    args: vec![],
                    env: HashMap::new(),
                    disabled: true,
                    auto_approve: vec![],
                    restart_policy: None,
                },
            ),
            (
                "server-c".to_string(),
                McpServerConfig {
                    command: "echo".to_string(),
                    args: vec![],
                    env: HashMap::new(),
                    disabled: false,
                    auto_approve: vec![],
                    restart_policy: None,
                },
            ),
        ]);
        let manager = McpServerManager::new(configs);

        // Manually set server-a to FailedToStart to test that shutdown
        // resets non-disabled statuses to Stopped
        {
            let mut servers = manager.servers.write().await;
            servers.get_mut("server-a").unwrap().status = ServerStatus::FailedToStart;
        }

        // Call shutdown
        let result = manager.shutdown().await;
        assert!(result.is_ok());

        // Verify all non-disabled servers are Stopped
        let statuses = manager.all_statuses().await;
        assert_eq!(statuses["server-a"], ServerStatus::Stopped);
        assert_eq!(statuses["server-b"], ServerStatus::Disabled); // Disabled stays Disabled
        assert_eq!(statuses["server-c"], ServerStatus::Stopped);
    }

    #[tokio::test]
    async fn test_shutdown_stops_monitoring() {
        let manager = McpServerManager::new(HashMap::new());

        // Start monitoring
        manager.start_monitoring();

        // Shutdown should cancel the monitoring token
        let result = manager.shutdown().await;
        assert!(result.is_ok());

        // Verify the cancellation token is cancelled
        assert!(manager.monitor_cancel.is_cancelled());
    }

    #[tokio::test]
    async fn test_shutdown_empty_manager() {
        let manager = McpServerManager::new(HashMap::new());
        let result = manager.shutdown().await;
        assert!(result.is_ok());
    }

    #[test]
    fn test_drop_no_warning_when_no_running_servers() {
        // This test verifies Drop doesn't panic when no servers are running.
        // The warning is only logged (not observable in test), but we verify
        // the Drop impl runs without error.
        let configs = HashMap::from([(
            "server-a".to_string(),
            McpServerConfig {
                command: "echo".to_string(),
                args: vec![],
                env: HashMap::new(),
                disabled: false,
                auto_approve: vec![],
                restart_policy: None,
            },
        )]);
        let manager = McpServerManager::new(configs);
        // Drop happens here — should not panic
        drop(manager);
    }
}