tower-mcp 0.10.1

Tower-native Model Context Protocol (MCP) implementation
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
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
#[cfg(test)]
mod proxy_tests {
    use std::collections::HashMap;
    use std::time::Duration;

    use serde_json::json;
    use tower::Layer;
    use tower::timeout::TimeoutLayer;
    use tower_service::Service;

    use crate::client::{ChannelTransport, McpClient};
    use crate::context::notification_channel;
    use crate::protocol::{McpRequest, McpResponse, RequestId};
    use crate::proxy::McpProxy;
    use crate::router::{Extensions, RouterRequest};
    use crate::{
        CallToolResult, GetPromptResult, McpRouter, PromptBuilder, ReadResourceResult,
        ResourceBuilder, ResourceContent, ResourceTemplateBuilder, ToolBuilder,
    };

    use schemars::JsonSchema;
    use serde::Deserialize;

    #[derive(Debug, Deserialize, JsonSchema)]
    struct AddInput {
        a: i64,
        b: i64,
    }

    #[derive(Debug, Deserialize, JsonSchema)]
    struct EchoInput {
        message: String,
    }

    /// Create a "math" backend router with an `add` tool.
    fn math_router() -> McpRouter {
        let add = ToolBuilder::new("add")
            .description("Add two numbers")
            .handler(|input: AddInput| async move {
                Ok(CallToolResult::text(format!("{}", input.a + input.b)))
            })
            .build();

        McpRouter::new()
            .server_info("math-server", "1.0.0")
            .tool(add)
    }

    /// Create a "text" backend router with an `echo` tool and a `greet` prompt.
    fn text_router() -> McpRouter {
        let echo = ToolBuilder::new("echo")
            .description("Echo a message")
            .handler(|input: EchoInput| async move { Ok(CallToolResult::text(input.message)) })
            .build();

        let readme = ResourceBuilder::new("file:///README.md")
            .name("README")
            .description("Project readme")
            .text("# Hello");

        let file_template = ResourceTemplateBuilder::new("file:///{path}")
            .name("File Template")
            .description("Read a file by path")
            .handler(|uri: String, vars: HashMap<String, String>| async move {
                let path = vars.get("path").cloned().unwrap_or_default();
                Ok(ReadResourceResult {
                    contents: vec![ResourceContent {
                        uri,
                        mime_type: Some("text/plain".to_string()),
                        text: Some(format!("contents of {}", path)),
                        blob: None,
                        meta: None,
                    }],
                    meta: None,
                })
            });

        let greet = PromptBuilder::new("greet")
            .description("Greet someone")
            .required_arg("name", "Name to greet")
            .handler(|args: HashMap<String, String>| async move {
                let name = args.get("name").map(|s| s.as_str()).unwrap_or("World");
                Ok(GetPromptResult::user_message(format!("Hello, {}!", name)))
            })
            .build();

        McpRouter::new()
            .server_info("text-server", "1.0.0")
            .tool(echo)
            .resource(readme)
            .resource_template(file_template)
            .prompt(greet)
    }

    /// Build a proxy with two in-process backends.
    async fn build_test_proxy() -> McpProxy {
        let math_transport = ChannelTransport::new(math_router());
        let text_transport = ChannelTransport::new(text_router());

        McpProxy::builder("test-proxy", "1.0.0")
            .backend("math", math_transport)
            .await
            .backend("text", text_transport)
            .await
            .build_strict()
            .await
            .expect("proxy should build")
    }

    /// Helper: send an McpRequest through the proxy and get the McpResponse.
    async fn call_proxy(
        proxy: &mut McpProxy,
        request: McpRequest,
    ) -> Result<McpResponse, tower_mcp_types::JsonRpcError> {
        let req = RouterRequest {
            id: RequestId::Number(1),
            inner: request,
            extensions: Extensions::new(),
        };
        let resp = proxy.call(req).await.expect("infallible");
        resp.inner
    }

    // ========================================================================
    // Initialize
    // ========================================================================

    #[tokio::test]
    async fn test_proxy_initialize() {
        let mut proxy = build_test_proxy().await;

        let resp = call_proxy(
            &mut proxy,
            McpRequest::Initialize(crate::protocol::InitializeParams {
                protocol_version: "2025-11-25".to_string(),
                capabilities: Default::default(),
                client_info: crate::protocol::Implementation {
                    name: "test".to_string(),
                    version: "1.0".to_string(),
                    title: None,
                    description: None,
                    icons: None,
                    website_url: None,
                    meta: None,
                },
                meta: None,
            }),
        )
        .await
        .expect("initialize should succeed");

        match resp {
            McpResponse::Initialize(init) => {
                assert_eq!(init.server_info.name, "test-proxy");
                assert_eq!(init.server_info.version, "1.0.0");
                assert!(init.capabilities.tools.is_some());
            }
            other => panic!("expected Initialize response, got: {:?}", other),
        }
    }

    // ========================================================================
    // List tools
    // ========================================================================

    #[tokio::test]
    async fn test_proxy_list_tools() {
        let mut proxy = build_test_proxy().await;

        let resp = call_proxy(&mut proxy, McpRequest::ListTools(Default::default()))
            .await
            .expect("list tools should succeed");

        match resp {
            McpResponse::ListTools(result) => {
                let names: Vec<&str> = result.tools.iter().map(|t| t.name.as_str()).collect();
                assert!(
                    names.contains(&"math_add"),
                    "expected math_add, got: {:?}",
                    names
                );
                assert!(
                    names.contains(&"text_echo"),
                    "expected text_echo, got: {:?}",
                    names
                );
                assert_eq!(result.tools.len(), 2);
            }
            other => panic!("expected ListTools response, got: {:?}", other),
        }
    }

    // ========================================================================
    // Call tool - routing
    // ========================================================================

    #[tokio::test]
    async fn test_proxy_call_tool_routes_to_correct_backend() {
        let mut proxy = build_test_proxy().await;

        // Call math_add
        let resp = call_proxy(
            &mut proxy,
            McpRequest::CallTool(crate::protocol::CallToolParams {
                name: "math_add".to_string(),
                arguments: json!({"a": 10, "b": 32}),
                meta: None,
                task: None,
            }),
        )
        .await
        .expect("call tool should succeed");

        match resp {
            McpResponse::CallTool(result) => {
                assert_eq!(result.all_text(), "42");
            }
            other => panic!("expected CallTool response, got: {:?}", other),
        }

        // Call text_echo
        let resp = call_proxy(
            &mut proxy,
            McpRequest::CallTool(crate::protocol::CallToolParams {
                name: "text_echo".to_string(),
                arguments: json!({"message": "hello"}),
                meta: None,
                task: None,
            }),
        )
        .await
        .expect("call tool should succeed");

        match resp {
            McpResponse::CallTool(result) => {
                assert_eq!(result.all_text(), "hello");
            }
            other => panic!("expected CallTool response, got: {:?}", other),
        }
    }

    // ========================================================================
    // Call tool - unknown tool
    // ========================================================================

    #[tokio::test]
    async fn test_proxy_call_unknown_tool_returns_error() {
        let mut proxy = build_test_proxy().await;

        let result = call_proxy(
            &mut proxy,
            McpRequest::CallTool(crate::protocol::CallToolParams {
                name: "nonexistent_tool".to_string(),
                arguments: json!({}),
                meta: None,
                task: None,
            }),
        )
        .await;

        assert!(result.is_err(), "should return error for unknown tool");
        let err = result.unwrap_err();
        assert!(err.message.contains("Unknown tool"));
    }

    // ========================================================================
    // List resources
    // ========================================================================

    #[tokio::test]
    async fn test_proxy_call_unknown_resource_returns_error() {
        let mut proxy = build_test_proxy().await;

        let result = call_proxy(
            &mut proxy,
            McpRequest::ReadResource(crate::protocol::ReadResourceParams {
                uri: "unknown://resource".to_string(),
                meta: None,
            }),
        )
        .await;

        assert!(result.is_err(), "should return error for unknown resource");
        let err = result.unwrap_err();
        assert!(
            err.message.contains("Unknown resource"),
            "error should mention unknown resource, got: {}",
            err.message
        );
    }

    #[tokio::test]
    async fn test_proxy_call_unknown_prompt_returns_error() {
        let mut proxy = build_test_proxy().await;

        let result = call_proxy(
            &mut proxy,
            McpRequest::GetPrompt(crate::protocol::GetPromptParams {
                name: "nonexistent_prompt".to_string(),
                arguments: Default::default(),
                meta: None,
            }),
        )
        .await;

        assert!(result.is_err(), "should return error for unknown prompt");
        let err = result.unwrap_err();
        assert!(
            err.message.contains("Unknown prompt"),
            "error should mention unknown prompt, got: {}",
            err.message
        );
    }

    #[tokio::test]
    async fn test_proxy_list_resources() {
        let mut proxy = build_test_proxy().await;

        let resp = call_proxy(&mut proxy, McpRequest::ListResources(Default::default()))
            .await
            .expect("list resources should succeed");

        match resp {
            McpResponse::ListResources(result) => {
                assert_eq!(result.resources.len(), 1);
                // URI should be namespaced
                assert!(
                    result.resources[0].uri.starts_with("text_"),
                    "expected text_ prefix on URI, got: {}",
                    result.resources[0].uri
                );
            }
            other => panic!("expected ListResources response, got: {:?}", other),
        }
    }

    // ========================================================================
    // Read resource - routing
    // ========================================================================

    #[tokio::test]
    async fn test_proxy_read_resource_routes_correctly() {
        let mut proxy = build_test_proxy().await;

        let resp = call_proxy(
            &mut proxy,
            McpRequest::ReadResource(crate::protocol::ReadResourceParams {
                uri: "text_file:///README.md".to_string(),
                meta: None,
            }),
        )
        .await
        .expect("read resource should succeed");

        match resp {
            McpResponse::ReadResource(result) => {
                assert_eq!(result.first_text(), Some("# Hello"));
            }
            other => panic!("expected ReadResource response, got: {:?}", other),
        }
    }

    // ========================================================================
    // List resource templates
    // ========================================================================

    #[tokio::test]
    async fn test_proxy_list_resource_templates() {
        let mut proxy = build_test_proxy().await;

        let resp = call_proxy(
            &mut proxy,
            McpRequest::ListResourceTemplates(Default::default()),
        )
        .await
        .expect("list resource templates should succeed");

        match resp {
            McpResponse::ListResourceTemplates(result) => {
                // text backend has one resource template
                assert_eq!(result.resource_templates.len(), 1);
                let template = &result.resource_templates[0];
                // Should be namespaced
                assert!(
                    template.name.starts_with("text_"),
                    "template name should be namespaced, got: {}",
                    template.name
                );
                assert!(
                    template.uri_template.starts_with("text_"),
                    "template URI should be namespaced, got: {}",
                    template.uri_template
                );
            }
            other => panic!("expected ListResourceTemplates, got: {:?}", other),
        }
    }

    // ========================================================================
    // List prompts
    // ========================================================================

    #[tokio::test]
    async fn test_proxy_list_prompts() {
        let mut proxy = build_test_proxy().await;

        let resp = call_proxy(&mut proxy, McpRequest::ListPrompts(Default::default()))
            .await
            .expect("list prompts should succeed");

        match resp {
            McpResponse::ListPrompts(result) => {
                assert_eq!(result.prompts.len(), 1);
                assert_eq!(result.prompts[0].name, "text_greet");
            }
            other => panic!("expected ListPrompts response, got: {:?}", other),
        }
    }

    // ========================================================================
    // Get prompt - routing
    // ========================================================================

    #[tokio::test]
    async fn test_proxy_get_prompt_routes_correctly() {
        let mut proxy = build_test_proxy().await;

        let resp = call_proxy(
            &mut proxy,
            McpRequest::GetPrompt(crate::protocol::GetPromptParams {
                name: "text_greet".to_string(),
                arguments: HashMap::from([("name".to_string(), "Alice".to_string())]),
                meta: None,
            }),
        )
        .await
        .expect("get prompt should succeed");

        match resp {
            McpResponse::GetPrompt(result) => {
                let text = result.first_message_text().unwrap();
                assert!(
                    text.contains("Alice"),
                    "expected Alice in prompt, got: {}",
                    text
                );
            }
            other => panic!("expected GetPrompt response, got: {:?}", other),
        }
    }

    // ========================================================================
    // Ping
    // ========================================================================

    #[tokio::test]
    async fn test_proxy_ping() {
        let mut proxy = build_test_proxy().await;

        let resp = call_proxy(&mut proxy, McpRequest::Ping)
            .await
            .expect("ping should succeed");

        assert!(matches!(resp, McpResponse::Pong(_)));
    }

    // ========================================================================
    // Custom separator
    // ========================================================================

    #[tokio::test]
    async fn test_proxy_custom_separator() {
        let math_transport = ChannelTransport::new(math_router());

        let mut proxy = McpProxy::builder("sep-proxy", "1.0.0")
            .separator(".")
            .backend("math", math_transport)
            .await
            .build_strict()
            .await
            .expect("proxy should build");

        // List tools with dot separator
        let resp = call_proxy(&mut proxy, McpRequest::ListTools(Default::default()))
            .await
            .expect("list tools should succeed");

        match resp {
            McpResponse::ListTools(result) => {
                assert_eq!(result.tools[0].name, "math.add");
            }
            other => panic!("expected ListTools response, got: {:?}", other),
        }

        // Call tool with dot separator
        let resp = call_proxy(
            &mut proxy,
            McpRequest::CallTool(crate::protocol::CallToolParams {
                name: "math.add".to_string(),
                arguments: json!({"a": 1, "b": 2}),
                meta: None,
                task: None,
            }),
        )
        .await
        .expect("call tool should succeed");

        match resp {
            McpResponse::CallTool(result) => {
                assert_eq!(result.all_text(), "3");
            }
            other => panic!("expected CallTool response, got: {:?}", other),
        }
    }

    // ========================================================================
    // Builder validation
    // ========================================================================

    #[tokio::test]
    async fn test_proxy_builder_rejects_empty_backends() {
        let result = McpProxy::builder("empty", "1.0.0").build().await;
        assert!(result.is_err());
    }

    #[tokio::test]
    async fn test_proxy_builder_rejects_duplicate_namespaces() {
        let t1 = ChannelTransport::new(math_router());
        let t2 = ChannelTransport::new(text_router());

        let result = McpProxy::builder("dup", "1.0.0")
            .backend("same", t1)
            .await
            .backend("same", t2)
            .await
            .build()
            .await;

        assert!(result.is_err());
    }

    #[tokio::test]
    async fn test_proxy_builder_rejects_ambiguous_namespace_prefixes() {
        // With separator "_", "redis" produces prefix "redis_" and "redis_ft"
        // produces prefix "redis_ft_". Since "redis_ft_" starts with "redis_",
        // routing "redis_ft_search" is ambiguous.
        let t1 = ChannelTransport::new(math_router());
        let t2 = ChannelTransport::new(text_router());

        let result = McpProxy::builder("ambiguous", "1.0.0")
            .backend("redis", t1)
            .await
            .backend("redis_ft", t2)
            .await
            .build()
            .await;

        let err = result.err().expect("should fail with ambiguous prefixes");
        assert!(
            err.to_string().contains("Ambiguous namespace prefixes"),
            "Expected ambiguous prefix error, got: {}",
            err
        );
    }

    #[tokio::test]
    async fn test_proxy_builder_allows_non_ambiguous_prefixes_with_dot_separator() {
        // With separator ".", "redis" -> "redis." and "redis_ft" -> "redis_ft."
        // Neither is a prefix of the other, so this is fine.
        let t1 = ChannelTransport::new(math_router());
        let t2 = ChannelTransport::new(text_router());

        let result = McpProxy::builder("dot-sep", "1.0.0")
            .separator(".")
            .backend("redis", t1)
            .await
            .backend("redis_ft", t2)
            .await
            .build()
            .await;

        assert!(result.is_ok());
    }

    #[tokio::test]
    async fn test_proxy_unsupported_method_returns_error() {
        let mut proxy = build_test_proxy().await;

        let result = call_proxy(
            &mut proxy,
            McpRequest::SetLoggingLevel(crate::protocol::SetLogLevelParams {
                level: crate::protocol::LogLevel::Info,
                meta: None,
            }),
        )
        .await;

        assert!(result.is_err(), "unsupported method should return error");
        let err = result.unwrap_err();
        assert!(
            err.message.contains("not supported"),
            "error should mention not supported, got: {}",
            err.message
        );
    }

    #[tokio::test]
    async fn test_proxy_backend_client_path() {
        let transport = ChannelTransport::new(math_router());
        let client = McpClient::connect(transport).await.expect("should connect");

        // Use backend_client (pre-connected McpClient) instead of backend (transport)
        let mut proxy = McpProxy::builder("client-proxy", "1.0.0")
            .backend_client("math", client)
            .build_strict()
            .await
            .expect("proxy should build");

        // Should still be able to list and call tools
        let resp = call_proxy(&mut proxy, McpRequest::ListTools(Default::default()))
            .await
            .expect("list tools should succeed");

        match resp {
            McpResponse::ListTools(result) => {
                assert_eq!(result.tools.len(), 1);
                assert_eq!(result.tools[0].name, "math_add");
            }
            other => panic!("expected ListTools, got: {:?}", other),
        }

        let resp = call_proxy(
            &mut proxy,
            McpRequest::CallTool(crate::protocol::CallToolParams {
                name: "math_add".to_string(),
                arguments: json!({"a": 5, "b": 7}),
                meta: None,
                task: None,
            }),
        )
        .await
        .expect("call tool should succeed");

        match resp {
            McpResponse::CallTool(result) => assert_eq!(result.all_text(), "12"),
            other => panic!("expected CallTool, got: {:?}", other),
        }
    }

    // ========================================================================
    // Clone
    // ========================================================================

    #[tokio::test]
    async fn test_proxy_is_clone() {
        let proxy = build_test_proxy().await;
        let mut proxy2 = proxy.clone();

        // Both should work independently
        let resp = call_proxy(&mut proxy2, McpRequest::Ping)
            .await
            .expect("ping should succeed");
        assert!(matches!(resp, McpResponse::Pong(_)));
    }

    // ========================================================================
    // ChannelTransport basics
    // ========================================================================

    #[tokio::test]
    async fn test_channel_transport_basic_roundtrip() {
        let router = math_router();
        let transport = ChannelTransport::new(router);

        let client = McpClient::connect(transport).await.expect("should connect");
        client
            .initialize("test-client", "1.0.0")
            .await
            .expect("should initialize");

        let tools = client.list_all_tools().await.expect("should list tools");
        assert_eq!(tools.len(), 1);
        assert_eq!(tools[0].name, "add");

        let result = client
            .call_tool("add", json!({"a": 100, "b": 200}))
            .await
            .expect("should call tool");
        assert_eq!(result.all_text(), "300");
    }

    #[tokio::test]
    async fn test_channel_transport_with_resources_and_prompts() {
        let router = text_router();
        let transport = ChannelTransport::new(router);

        let client = McpClient::connect(transport).await.expect("should connect");
        client
            .initialize("test-client", "1.0.0")
            .await
            .expect("should initialize");

        // Tools
        let tools = client.list_all_tools().await.expect("should list tools");
        assert_eq!(tools.len(), 1);
        assert_eq!(tools[0].name, "echo");

        // Resources
        let resources = client
            .list_all_resources()
            .await
            .expect("should list resources");
        assert_eq!(resources.len(), 1);

        let content = client
            .read_resource("file:///README.md")
            .await
            .expect("should read resource");
        assert_eq!(content.first_text(), Some("# Hello"));

        // Prompts
        let prompts = client
            .list_all_prompts()
            .await
            .expect("should list prompts");
        assert_eq!(prompts.len(), 1);
        assert_eq!(prompts[0].name, "greet");

        let prompt = client
            .get_prompt(
                "greet",
                Some(HashMap::from([("name".to_string(), "Bob".to_string())])),
            )
            .await
            .expect("should get prompt");
        assert!(prompt.first_message_text().unwrap().contains("Bob"));
    }

    /// A transport that immediately returns EOF, causing initialization to fail.
    struct BrokenTransport;

    #[async_trait::async_trait]
    impl crate::client::ClientTransport for BrokenTransport {
        async fn send(&mut self, _message: &str) -> crate::error::Result<()> {
            Err(crate::error::Error::internal("broken transport"))
        }

        async fn recv(&mut self) -> crate::error::Result<Option<String>> {
            Ok(None) // EOF
        }

        fn is_connected(&self) -> bool {
            false
        }

        async fn close(&mut self) -> crate::error::Result<()> {
            Ok(())
        }
    }

    #[tokio::test]
    async fn test_proxy_skips_failed_backend_initialization() {
        let good_transport = ChannelTransport::new(math_router());

        // Build with one broken and one good backend
        let result = McpProxy::builder("mixed-init", "1.0.0")
            .backend("broken", BrokenTransport)
            .await
            .backend("math", good_transport)
            .await
            .build()
            .await
            .expect("proxy should build with at least one good backend");

        // The broken backend should be in the skipped list
        assert_eq!(result.skipped.len(), 1);
        assert_eq!(result.skipped[0].namespace, "broken");
        let mut proxy = result.proxy;

        // Only the math backend should be available
        let resp = call_proxy(&mut proxy, McpRequest::ListTools(Default::default()))
            .await
            .expect("list tools should succeed");

        match resp {
            McpResponse::ListTools(result) => {
                assert_eq!(result.tools.len(), 1);
                assert_eq!(result.tools[0].name, "math_add");
            }
            other => panic!("expected ListTools, got: {:?}", other),
        }
    }

    // ========================================================================
    // Per-backend middleware
    // ========================================================================

    #[derive(Debug, Deserialize, JsonSchema)]
    struct SlowInput {
        delay_ms: u64,
    }

    /// Create a "slow" backend router with a tool that sleeps.
    fn slow_router() -> McpRouter {
        let slow = ToolBuilder::new("slow_op")
            .description("A slow operation")
            .handler(|input: SlowInput| async move {
                tokio::time::sleep(Duration::from_millis(input.delay_ms)).await;
                Ok(CallToolResult::text("done"))
            })
            .build();

        McpRouter::new()
            .server_info("slow-server", "1.0.0")
            .tool(slow)
    }

    #[tokio::test]
    async fn test_backend_layer_timeout_triggers() {
        let slow_transport = ChannelTransport::new(slow_router());

        let mut proxy = McpProxy::builder("timeout-proxy", "1.0.0")
            .backend("slow", slow_transport)
            .await
            .backend_layer(TimeoutLayer::new(Duration::from_millis(50)))
            .build_strict()
            .await
            .expect("proxy should build");

        // Call with a delay that exceeds the timeout
        let result = call_proxy(
            &mut proxy,
            McpRequest::CallTool(crate::protocol::CallToolParams {
                name: "slow_slow_op".to_string(),
                arguments: json!({"delay_ms": 500}),
                meta: None,
                task: None,
            }),
        )
        .await;

        // Should get a JSON-RPC error from the CatchError wrapper
        assert!(result.is_err(), "should timeout");
        let err = result.unwrap_err();
        assert!(
            err.message.to_lowercase().contains("timed out")
                || err.message.to_lowercase().contains("timeout"),
            "error should mention timeout, got: {}",
            err.message
        );
    }

    #[tokio::test]
    async fn test_backend_layer_timeout_allows_fast_requests() {
        let slow_transport = ChannelTransport::new(slow_router());

        let mut proxy = McpProxy::builder("timeout-proxy", "1.0.0")
            .backend("slow", slow_transport)
            .await
            .backend_layer(TimeoutLayer::new(Duration::from_secs(5)))
            .build_strict()
            .await
            .expect("proxy should build");

        // Call with no delay -- should succeed
        let resp = call_proxy(
            &mut proxy,
            McpRequest::CallTool(crate::protocol::CallToolParams {
                name: "slow_slow_op".to_string(),
                arguments: json!({"delay_ms": 0}),
                meta: None,
                task: None,
            }),
        )
        .await
        .expect("fast call should succeed");

        match resp {
            McpResponse::CallTool(result) => {
                assert_eq!(result.all_text(), "done");
            }
            other => panic!("expected CallTool response, got: {:?}", other),
        }
    }

    #[tokio::test]
    async fn test_backend_layer_only_affects_target_backend() {
        let math_transport = ChannelTransport::new(math_router());
        let slow_transport = ChannelTransport::new(slow_router());

        let mut proxy = McpProxy::builder("mixed-proxy", "1.0.0")
            // math backend: no middleware
            .backend("math", math_transport)
            .await
            // slow backend: tight timeout
            .backend("slow", slow_transport)
            .await
            .backend_layer(TimeoutLayer::new(Duration::from_millis(50)))
            .build_strict()
            .await
            .expect("proxy should build");

        // math backend should work fine (no timeout layer)
        let resp = call_proxy(
            &mut proxy,
            McpRequest::CallTool(crate::protocol::CallToolParams {
                name: "math_add".to_string(),
                arguments: json!({"a": 1, "b": 2}),
                meta: None,
                task: None,
            }),
        )
        .await
        .expect("math should succeed");

        match resp {
            McpResponse::CallTool(result) => assert_eq!(result.all_text(), "3"),
            other => panic!("expected CallTool, got: {:?}", other),
        }

        // slow backend should timeout
        let result = call_proxy(
            &mut proxy,
            McpRequest::CallTool(crate::protocol::CallToolParams {
                name: "slow_slow_op".to_string(),
                arguments: json!({"delay_ms": 500}),
                meta: None,
                task: None,
            }),
        )
        .await;

        assert!(result.is_err(), "slow backend should timeout");
    }

    // ========================================================================
    // Health check
    // ========================================================================

    #[tokio::test]
    async fn test_proxy_health_check_all_healthy() {
        let proxy = build_test_proxy().await;

        let health = proxy.health_check().await;
        assert_eq!(health.len(), 2);
        assert!(
            health.iter().all(|h| h.healthy),
            "all backends should be healthy"
        );

        let namespaces: Vec<&str> = health.iter().map(|h| h.namespace.as_str()).collect();
        assert!(namespaces.contains(&"math"));
        assert!(namespaces.contains(&"text"));
    }

    // ========================================================================
    // Notification forwarding
    // ========================================================================

    #[tokio::test]
    async fn test_proxy_notification_sender_configured() {
        let (notif_tx, _notif_rx) = notification_channel(32);
        let math_transport = ChannelTransport::new(math_router());

        let proxy = McpProxy::builder("notif-proxy", "1.0.0")
            .notification_sender(notif_tx)
            .backend("math", math_transport)
            .await
            .build_strict()
            .await
            .expect("proxy should build");

        // Verify proxy built successfully with notification sender
        assert!(proxy.shared.notification_tx.is_some());
    }

    // ========================================================================
    // Instructions aggregation (#605)
    // ========================================================================

    #[tokio::test]
    async fn test_proxy_aggregates_backend_instructions() {
        // Create routers with instructions
        let math = McpRouter::new()
            .server_info("math-server", "1.0.0")
            .instructions("Provides arithmetic operations")
            .tool(
                ToolBuilder::new("add")
                    .description("Add two numbers")
                    .handler(|input: AddInput| async move {
                        Ok(CallToolResult::text(format!("{}", input.a + input.b)))
                    })
                    .build(),
            );

        let text = McpRouter::new()
            .server_info("text-server", "1.0.0")
            .instructions("Provides text manipulation tools")
            .tool(
                ToolBuilder::new("echo")
                    .description("Echo a message")
                    .handler(
                        |input: EchoInput| async move { Ok(CallToolResult::text(input.message)) },
                    )
                    .build(),
            );

        let math_transport = ChannelTransport::new(math);
        let text_transport = ChannelTransport::new(text);

        let mut proxy = McpProxy::builder("instructions-proxy", "1.0.0")
            .backend("math", math_transport)
            .await
            .backend("text", text_transport)
            .await
            .build_strict()
            .await
            .expect("proxy should build");

        let req = RouterRequest {
            id: RequestId::Number(1),
            inner: McpRequest::Initialize(crate::protocol::InitializeParams {
                protocol_version: "2025-11-25".to_string(),
                capabilities: Default::default(),
                client_info: crate::protocol::Implementation {
                    name: "test".to_string(),
                    version: "1.0".to_string(),
                    ..Default::default()
                },
                meta: None,
            }),
            extensions: Extensions::new(),
        };

        let resp = proxy.call(req).await.unwrap();
        let result = resp.inner.unwrap();

        if let McpResponse::Initialize(init) = result {
            let instructions = init.instructions.expect("should have instructions");
            assert!(
                instructions.contains("[math] Provides arithmetic operations"),
                "should contain math instructions: {instructions}"
            );
            assert!(
                instructions.contains("[text] Provides text manipulation tools"),
                "should contain text instructions: {instructions}"
            );
        } else {
            panic!("expected Initialize response");
        }
    }

    #[tokio::test]
    async fn test_proxy_custom_instructions_override() {
        let math_transport = ChannelTransport::new(math_router());

        let mut proxy = McpProxy::builder("custom-proxy", "1.0.0")
            .instructions("Custom proxy description")
            .backend("math", math_transport)
            .await
            .build_strict()
            .await
            .expect("proxy should build");

        let req = RouterRequest {
            id: RequestId::Number(1),
            inner: McpRequest::Initialize(crate::protocol::InitializeParams {
                protocol_version: "2025-11-25".to_string(),
                capabilities: Default::default(),
                client_info: crate::protocol::Implementation {
                    name: "test".to_string(),
                    version: "1.0".to_string(),
                    ..Default::default()
                },
                meta: None,
            }),
            extensions: Extensions::new(),
        };

        let resp = proxy.call(req).await.unwrap();
        let result = resp.inner.unwrap();

        if let McpResponse::Initialize(init) = result {
            assert_eq!(
                init.instructions.as_deref(),
                Some("Custom proxy description")
            );
        } else {
            panic!("expected Initialize response");
        }
    }

    #[tokio::test]
    async fn test_proxy_no_backend_instructions_gives_default() {
        // math_router doesn't set instructions
        let math_transport = ChannelTransport::new(math_router());

        let mut proxy = McpProxy::builder("default-proxy", "1.0.0")
            .backend("math", math_transport)
            .await
            .build_strict()
            .await
            .expect("proxy should build");

        let req = RouterRequest {
            id: RequestId::Number(1),
            inner: McpRequest::Initialize(crate::protocol::InitializeParams {
                protocol_version: "2025-11-25".to_string(),
                capabilities: Default::default(),
                client_info: crate::protocol::Implementation {
                    name: "test".to_string(),
                    version: "1.0".to_string(),
                    ..Default::default()
                },
                meta: None,
            }),
            extensions: Extensions::new(),
        };

        let resp = proxy.call(req).await.unwrap();
        let result = resp.inner.unwrap();

        if let McpResponse::Initialize(init) = result {
            let instructions = init.instructions.expect("should have instructions");
            assert_eq!(instructions, "MCP proxy aggregating 1 backend servers.");
            // Should NOT contain any [namespace] section
            assert!(!instructions.contains('['));
        } else {
            panic!("expected Initialize response");
        }
    }

    // ========================================================================
    // CoalesceLayer integration
    // ========================================================================

    // ========================================================================
    // ConcurrencyLimit integration (#604)
    // ========================================================================

    #[tokio::test]
    async fn test_backend_concurrency_limit_serializes_requests() {
        use tower::limit::ConcurrencyLimitLayer;

        let slow_transport = ChannelTransport::new(slow_router());

        let proxy = McpProxy::builder("concurrency-proxy", "1.0.0")
            .backend("slow", slow_transport)
            .await
            .backend_layer(ConcurrencyLimitLayer::new(1))
            .build_strict()
            .await
            .expect("proxy should build");

        // Fire two concurrent requests. With ConcurrencyLimitLayer(1),
        // they should be serialized (second waits for first to complete).
        // Both should succeed -- backpressure is handled internally by
        // BoxCloneService which calls poll_ready before dispatch.
        let req1 = RouterRequest {
            id: RequestId::Number(1),
            inner: McpRequest::CallTool(crate::protocol::CallToolParams {
                name: "slow_slow_op".to_string(),
                arguments: json!({"delay_ms": 10}),
                meta: None,
                task: None,
            }),
            extensions: Extensions::new(),
        };
        let req2 = RouterRequest {
            id: RequestId::Number(2),
            inner: McpRequest::CallTool(crate::protocol::CallToolParams {
                name: "slow_slow_op".to_string(),
                arguments: json!({"delay_ms": 10}),
                meta: None,
                task: None,
            }),
            extensions: Extensions::new(),
        };

        let mut p1 = proxy.clone();
        let mut p2 = proxy.clone();
        let h1 = tokio::spawn(async move { p1.call(req1).await });
        let h2 = tokio::spawn(async move { p2.call(req2).await });

        let r1 = h1.await.unwrap().unwrap();
        let r2 = h2.await.unwrap().unwrap();

        // Both should succeed
        assert!(r1.inner.is_ok(), "first request should succeed");
        assert!(r2.inner.is_ok(), "second request should succeed");
    }

    #[tokio::test]
    async fn test_coalesce_layer_deduplicates_concurrent_list_tools() {
        use std::mem::discriminant;
        use tower::ServiceExt;
        use tower_resilience::coalesce::{CoalesceError, CoalesceLayer};

        type CoalesceResult =
            Result<crate::router::RouterResponse, CoalesceError<std::convert::Infallible>>;

        let proxy = build_test_proxy().await;

        // Wrap the proxy in CoalesceLayer keyed by McpRequest discriminant.
        // This means concurrent list_tools calls share a single execution.
        let coalesced =
            CoalesceLayer::new(|req: &RouterRequest| discriminant(&req.inner)).layer(proxy);

        // Fire 5 concurrent list_tools requests
        let mut handles = vec![];
        for _ in 0..5 {
            let mut svc = coalesced.clone();
            handles.push(tokio::spawn(async move {
                let req = RouterRequest {
                    id: RequestId::Number(1),
                    inner: McpRequest::ListTools(Default::default()),
                    extensions: Extensions::new(),
                };
                let result: CoalesceResult = svc.ready().await.unwrap().call(req).await;
                result
            }));
        }

        // All should succeed with identical tool lists
        let mut tool_lists: Vec<Vec<String>> = Vec::new();
        for handle in handles {
            let resp = handle.await.unwrap().unwrap();
            let mcp_resp = resp.inner.expect("should be Ok");
            match mcp_resp {
                McpResponse::ListTools(list) => {
                    let names: Vec<String> = list.tools.iter().map(|t| t.name.clone()).collect();
                    tool_lists.push(names);
                }
                other => panic!("expected ListTools, got: {:?}", other),
            }
        }

        // All responses should be identical (coalesced from the same execution)
        assert_eq!(tool_lists.len(), 5);
        for list in &tool_lists {
            assert_eq!(list, &tool_lists[0], "all responses should match");
        }
        // Should contain tools from both backends
        assert!(tool_lists[0].contains(&"math_add".to_string()));
        assert!(tool_lists[0].contains(&"text_echo".to_string()));
    }

    // ========================================================================
    // Dynamic backend addition (#628)
    // ========================================================================

    #[tokio::test]
    async fn test_add_backend_dynamically() {
        // Start with just the math backend
        let math_transport = ChannelTransport::new(math_router());
        let mut proxy = McpProxy::builder("dynamic-proxy", "1.0.0")
            .backend("math", math_transport)
            .await
            .build_strict()
            .await
            .expect("proxy should build");

        // Initially only 1 backend with 1 tool
        assert_eq!(proxy.backend_count(), 1);
        let resp = call_proxy(&mut proxy, McpRequest::ListTools(Default::default()))
            .await
            .expect("list tools should succeed");
        match &resp {
            McpResponse::ListTools(result) => assert_eq!(result.tools.len(), 1),
            other => panic!("expected ListTools, got: {:?}", other),
        }

        // Add text backend dynamically
        let text_transport = ChannelTransport::new(text_router());
        proxy
            .add_backend("text", text_transport)
            .await
            .expect("add_backend should succeed");

        // Now 2 backends
        assert_eq!(proxy.backend_count(), 2);

        // List tools should show tools from both backends
        let resp = call_proxy(&mut proxy, McpRequest::ListTools(Default::default()))
            .await
            .expect("list tools should succeed");
        match resp {
            McpResponse::ListTools(result) => {
                assert_eq!(result.tools.len(), 2);
                let names: Vec<&str> = result.tools.iter().map(|t| t.name.as_str()).collect();
                assert!(names.contains(&"math_add"));
                assert!(names.contains(&"text_echo"));
            }
            other => panic!("expected ListTools, got: {:?}", other),
        }

        // Call tool on the dynamically-added backend
        let resp = call_proxy(
            &mut proxy,
            McpRequest::CallTool(crate::protocol::CallToolParams {
                name: "text_echo".to_string(),
                arguments: json!({"message": "dynamic!"}),
                meta: None,
                task: None,
            }),
        )
        .await
        .expect("call tool should succeed");

        match resp {
            McpResponse::CallTool(result) => assert_eq!(result.all_text(), "dynamic!"),
            other => panic!("expected CallTool, got: {:?}", other),
        }
    }

    #[tokio::test]
    async fn test_add_backend_visible_to_clones() {
        let math_transport = ChannelTransport::new(math_router());
        let proxy = McpProxy::builder("clone-proxy", "1.0.0")
            .backend("math", math_transport)
            .await
            .build_strict()
            .await
            .expect("proxy should build");

        // Clone the proxy before adding a backend
        let mut clone = proxy.clone();

        // Add text backend to the original
        let text_transport = ChannelTransport::new(text_router());
        proxy
            .add_backend("text", text_transport)
            .await
            .expect("add_backend should succeed");

        // The clone should also see the new backend (shared entries)
        assert_eq!(clone.backend_count(), 2);

        let resp = call_proxy(&mut clone, McpRequest::ListTools(Default::default()))
            .await
            .expect("list tools should succeed");
        match resp {
            McpResponse::ListTools(result) => {
                assert_eq!(result.tools.len(), 2);
            }
            other => panic!("expected ListTools, got: {:?}", other),
        }
    }

    #[tokio::test]
    async fn test_add_backend_rejects_duplicate_namespace() {
        let math_transport = ChannelTransport::new(math_router());
        let proxy = McpProxy::builder("dup-proxy", "1.0.0")
            .backend("math", math_transport)
            .await
            .build_strict()
            .await
            .expect("proxy should build");

        let text_transport = ChannelTransport::new(text_router());
        let result = proxy.add_backend("math", text_transport).await;
        assert!(result.is_err());
        match result.unwrap_err() {
            crate::proxy::AddBackendError::DuplicateNamespace(ns) => {
                assert_eq!(ns, "math");
            }
            other => panic!("expected DuplicateNamespace, got: {:?}", other),
        }
    }

    #[tokio::test]
    async fn test_add_backend_rejects_ambiguous_prefix() {
        let t1 = ChannelTransport::new(math_router());
        let proxy = McpProxy::builder("ambig-proxy", "1.0.0")
            .backend("redis", t1)
            .await
            .build_strict()
            .await
            .expect("proxy should build");

        let t2 = ChannelTransport::new(text_router());
        let result = proxy.add_backend("redis_ft", t2).await;
        assert!(result.is_err());
        assert!(
            matches!(
                result.unwrap_err(),
                crate::proxy::AddBackendError::AmbiguousPrefix { .. }
            ),
            "should be AmbiguousPrefix error"
        );
    }

    #[tokio::test]
    async fn test_add_backend_with_layer() {
        let math_transport = ChannelTransport::new(math_router());
        let mut proxy = McpProxy::builder("layered-proxy", "1.0.0")
            .backend("math", math_transport)
            .await
            .build_strict()
            .await
            .expect("proxy should build");

        // Add slow backend with a tight timeout
        let slow_transport = ChannelTransport::new(slow_router());
        proxy
            .add_backend_with_layer(
                "slow",
                slow_transport,
                TimeoutLayer::new(Duration::from_millis(50)),
            )
            .await
            .expect("add_backend_with_layer should succeed");

        // The slow backend should timeout
        let result = call_proxy(
            &mut proxy,
            McpRequest::CallTool(crate::protocol::CallToolParams {
                name: "slow_slow_op".to_string(),
                arguments: json!({"delay_ms": 500}),
                meta: None,
                task: None,
            }),
        )
        .await;

        assert!(result.is_err(), "should timeout");

        // The math backend should still work
        let resp = call_proxy(
            &mut proxy,
            McpRequest::CallTool(crate::protocol::CallToolParams {
                name: "math_add".to_string(),
                arguments: json!({"a": 3, "b": 4}),
                meta: None,
                task: None,
            }),
        )
        .await
        .expect("math should succeed");

        match resp {
            McpResponse::CallTool(result) => assert_eq!(result.all_text(), "7"),
            other => panic!("expected CallTool, got: {:?}", other),
        }
    }

    #[tokio::test]
    async fn test_add_backend_health_check_includes_new_backend() {
        let math_transport = ChannelTransport::new(math_router());
        let proxy = McpProxy::builder("health-proxy", "1.0.0")
            .backend("math", math_transport)
            .await
            .build_strict()
            .await
            .expect("proxy should build");

        let text_transport = ChannelTransport::new(text_router());
        proxy
            .add_backend("text", text_transport)
            .await
            .expect("add_backend should succeed");

        let health = proxy.health_check().await;
        assert_eq!(health.len(), 2);
        let namespaces: Vec<&str> = health.iter().map(|h| h.namespace.as_str()).collect();
        assert!(namespaces.contains(&"math"));
        assert!(namespaces.contains(&"text"));
        assert!(health.iter().all(|h| h.healthy));
    }

    #[tokio::test]
    async fn test_coalesce_layer_does_not_affect_different_methods() {
        use std::mem::discriminant;
        use tower::ServiceExt;
        use tower_resilience::coalesce::{CoalesceError, CoalesceLayer};

        type CoalesceResult =
            Result<crate::router::RouterResponse, CoalesceError<std::convert::Infallible>>;

        let proxy = build_test_proxy().await;

        let coalesced =
            CoalesceLayer::new(|req: &RouterRequest| discriminant(&req.inner)).layer(proxy);

        // Fire list_tools and call_tool concurrently -- they have different
        // discriminants so they should NOT be coalesced.
        let mut list_svc = coalesced.clone();
        let mut call_svc = coalesced.clone();

        let list_handle: tokio::task::JoinHandle<CoalesceResult> = tokio::spawn(async move {
            let req = RouterRequest {
                id: RequestId::Number(1),
                inner: McpRequest::ListTools(Default::default()),
                extensions: Extensions::new(),
            };
            list_svc.ready().await.unwrap().call(req).await
        });

        let call_handle: tokio::task::JoinHandle<CoalesceResult> = tokio::spawn(async move {
            let req = RouterRequest {
                id: RequestId::Number(2),
                inner: McpRequest::CallTool(crate::protocol::CallToolParams {
                    name: "math_add".to_string(),
                    arguments: json!({"a": 10, "b": 20}),
                    meta: None,
                    task: None,
                }),
                extensions: Extensions::new(),
            };
            call_svc.ready().await.unwrap().call(req).await
        });

        let list_resp = list_handle.await.unwrap().unwrap();
        let call_resp = call_handle.await.unwrap().unwrap();

        // list_tools should return tool definitions
        match list_resp.inner.unwrap() {
            McpResponse::ListTools(list) => {
                assert!(!list.tools.is_empty());
            }
            other => panic!("expected ListTools, got: {:?}", other),
        }

        // call_tool should return the computation result
        match call_resp.inner.unwrap() {
            McpResponse::CallTool(result) => {
                assert_eq!(result.all_text(), "30");
            }
            other => panic!("expected CallTool, got: {:?}", other),
        }
    }

    // Static assertions: McpProxy must be Send + Sync so that &McpProxy is Send
    // and methods like health_check() can be called from tokio::spawn.
    #[allow(dead_code)]
    const _: () = {
        fn assert_send<T: Send>() {}
        fn assert_sync<T: Sync>() {}
        fn assert_send_sync() {
            assert_send::<McpProxy>();
            assert_sync::<McpProxy>();
        }
    };

    #[tokio::test]
    async fn test_health_check_is_spawnable() {
        // Verify that health_check future can be spawned (requires Send)
        let proxy = std::sync::Arc::new(build_test_proxy().await);
        let proxy_clone = proxy.clone();
        let handle = tokio::spawn(async move { proxy_clone.health_check().await });
        let results = handle.await.unwrap();
        assert!(!results.is_empty());
    }

    // ========================================================================
    // Remove / replace / namespaces
    // ========================================================================

    #[tokio::test]
    async fn test_remove_backend() {
        let proxy = build_test_proxy().await;
        assert_eq!(proxy.backend_count(), 2);
        assert!(proxy.backend_namespaces().contains(&"math".to_string()));

        // Remove the math backend
        assert!(proxy.remove_backend("math").await);
        assert_eq!(proxy.backend_count(), 1);
        assert!(!proxy.backend_namespaces().contains(&"math".to_string()));
        assert!(proxy.backend_namespaces().contains(&"text".to_string()));
    }

    #[tokio::test]
    async fn test_remove_backend_not_found() {
        let proxy = build_test_proxy().await;
        assert!(!proxy.remove_backend("nonexistent").await);
        assert_eq!(proxy.backend_count(), 2);
    }

    #[tokio::test]
    async fn test_remove_backend_tools_no_longer_listed() {
        let mut proxy = build_test_proxy().await;

        // Before removal: math/add should be listed
        let resp = call_proxy(&mut proxy, McpRequest::ListTools(Default::default()))
            .await
            .unwrap();
        let tools = match resp {
            McpResponse::ListTools(r) => r.tools,
            _ => panic!("expected ListTools"),
        };
        assert!(tools.iter().any(|t| t.name.contains("math")));

        // Remove math
        proxy.remove_backend("math").await;

        // After removal: math tools should be gone
        let resp = call_proxy(&mut proxy, McpRequest::ListTools(Default::default()))
            .await
            .unwrap();
        let tools = match resp {
            McpResponse::ListTools(r) => r.tools,
            _ => panic!("expected ListTools"),
        };
        assert!(!tools.iter().any(|t| t.name.contains("math")));
        // text tools should still be there
        assert!(tools.iter().any(|t| t.name.contains("text")));
    }

    #[tokio::test]
    async fn test_remove_backend_tool_calls_fail() {
        let mut proxy = build_test_proxy().await;
        proxy.remove_backend("math").await;

        // Calling a removed backend's tool should fail
        let resp = call_proxy(
            &mut proxy,
            McpRequest::CallTool(crate::protocol::CallToolParams {
                name: "math_add".to_string(),
                arguments: json!({"a": 1, "b": 2}),
                meta: None,
                task: None,
            }),
        )
        .await;

        assert!(resp.is_err());
    }

    #[tokio::test]
    async fn test_replace_backend() {
        let mut proxy = build_test_proxy().await;

        // Replace math with a new math backend
        let new_math_transport = ChannelTransport::new(math_router());
        proxy
            .replace_backend("math", new_math_transport)
            .await
            .expect("replace should succeed");

        assert_eq!(proxy.backend_count(), 2);

        // The replaced backend should still work
        let resp = call_proxy(
            &mut proxy,
            McpRequest::CallTool(crate::protocol::CallToolParams {
                name: "math_add".to_string(),
                arguments: json!({"a": 10, "b": 20}),
                meta: None,
                task: None,
            }),
        )
        .await
        .unwrap();

        match resp {
            McpResponse::CallTool(r) => {
                let text = r.content[0].as_text().unwrap();
                assert_eq!(text, "30");
            }
            _ => panic!("expected CallTool"),
        }
    }

    #[tokio::test]
    async fn test_backend_namespaces() {
        let proxy = build_test_proxy().await;
        let mut namespaces = proxy.backend_namespaces();
        namespaces.sort();
        assert_eq!(namespaces, vec!["math", "text"]);
    }

    #[tokio::test]
    async fn test_remove_all_backends() {
        let proxy = build_test_proxy().await;
        proxy.remove_backend("math").await;
        proxy.remove_backend("text").await;
        assert_eq!(proxy.backend_count(), 0);
        assert!(proxy.backend_namespaces().is_empty());
    }
}