mcp-proxy 0.3.1

Standalone MCP proxy -- config-driven reverse proxy with auth, rate limiting, and observability
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
//! Integration tests for the proxy middleware stack.
//!
//! Uses in-process MCP backends via `ChannelTransport` to test the full
//! middleware composition without external processes.

use std::convert::Infallible;

use schemars::JsonSchema;
use serde::Deserialize;
use tower::Service;

use tower_mcp::client::ChannelTransport;
use tower_mcp::protocol::{CallToolParams, McpRequest, McpResponse, RequestId};
use tower_mcp::proxy::McpProxy;
use tower_mcp::router::{Extensions, RouterRequest, RouterResponse};
use tower_mcp::{CallToolResult, McpRouter, ToolBuilder};

use mcp_proxy::alias::{AliasMap, AliasService};
use mcp_proxy::cache::CacheService;
use mcp_proxy::canary::CanaryService;
use mcp_proxy::coalesce::CoalesceService;
use mcp_proxy::config::{BackendCacheConfig, CacheBackendConfig};
use mcp_proxy::config::{BackendFilter, InjectArgsConfig, NameFilter};
use mcp_proxy::filter::CapabilityFilterService;
use mcp_proxy::inject::{InjectArgsService, InjectionRules};
use mcp_proxy::mirror::MirrorService;
use mcp_proxy::validation::{ValidationConfig, ValidationService};

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

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

/// A tool that echoes back all arguments as JSON, for testing argument injection.
#[derive(Debug, Deserialize, JsonSchema)]
struct ArgsInput {
    #[serde(flatten)]
    args: serde_json::Map<String, serde_json::Value>,
}

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();

    let echo_args = ToolBuilder::new("echo_args")
        .description("Echo back all arguments as JSON")
        .handler(|input: ArgsInput| async move {
            Ok(CallToolResult::text(
                serde_json::to_string(&input.args).unwrap(),
            ))
        })
        .build();

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

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 upper = ToolBuilder::new("upper")
        .description("Uppercase a message")
        .handler(|input: EchoInput| async move {
            Ok(CallToolResult::text(input.message.to_uppercase()))
        })
        .build();

    McpRouter::new()
        .server_info("text-server", "1.0.0")
        .tool(echo)
        .tool(upper)
}

async fn build_proxy() -> McpProxy {
    let math_transport = ChannelTransport::new(math_router());
    let text_transport = ChannelTransport::new(text_router());

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

async fn call<S>(svc: &mut S, request: McpRequest) -> RouterResponse
where
    S: Service<RouterRequest, Response = RouterResponse, Error = Infallible>,
{
    let req = RouterRequest {
        id: RequestId::Number(1),
        inner: request,
        extensions: Extensions::new(),
    };
    svc.call(req).await.expect("infallible")
}

fn tool_call(name: &str, args: serde_json::Value) -> McpRequest {
    McpRequest::CallTool(CallToolParams {
        name: name.to_string(),
        arguments: args,
        meta: None,
        task: None,
    })
}

// --- End-to-end proxy tests ---

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

    let resp = call(&mut proxy, McpRequest::ListTools(Default::default())).await;
    match resp.inner.unwrap() {
        McpResponse::ListTools(result) => {
            let names: Vec<&str> = result.tools.iter().map(|t| t.name.as_str()).collect();
            assert!(names.contains(&"math/add"), "tools: {:?}", names);
            assert!(names.contains(&"math/echo_args"), "tools: {:?}", names);
            assert!(names.contains(&"text/echo"), "tools: {:?}", names);
            assert!(names.contains(&"text/upper"), "tools: {:?}", names);
            assert_eq!(names.len(), 4);
        }
        other => panic!("expected ListTools, got: {:?}", other),
    }
}

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

    let resp = call(
        &mut proxy,
        tool_call("math/add", serde_json::json!({"a": 3, "b": 4})),
    )
    .await;

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

// --- Proxy + filter ---

#[tokio::test]
async fn test_proxy_with_filter_hides_tools() {
    let proxy = build_proxy().await;
    let filters = vec![BackendFilter {
        namespace: "text/".to_string(),
        tool_filter: NameFilter::deny_list(["upper".to_string()]).unwrap(),
        resource_filter: NameFilter::PassAll,
        prompt_filter: NameFilter::PassAll,
        hide_destructive: false,
        read_only_only: false,
    }];
    let mut svc = CapabilityFilterService::new(proxy, filters);

    let resp = call(&mut svc, McpRequest::ListTools(Default::default())).await;
    match resp.inner.unwrap() {
        McpResponse::ListTools(result) => {
            let names: Vec<&str> = result.tools.iter().map(|t| t.name.as_str()).collect();
            assert!(names.contains(&"math/add"));
            assert!(names.contains(&"text/echo"));
            assert!(!names.contains(&"text/upper"), "upper should be hidden");
        }
        other => panic!("expected ListTools, got: {:?}", other),
    }
}

#[tokio::test]
async fn test_proxy_with_filter_denies_call() {
    let proxy = build_proxy().await;
    let filters = vec![BackendFilter {
        namespace: "text/".to_string(),
        tool_filter: NameFilter::allow_list(["echo".to_string()]).unwrap(),
        resource_filter: NameFilter::PassAll,
        prompt_filter: NameFilter::PassAll,
        hide_destructive: false,
        read_only_only: false,
    }];
    let mut svc = CapabilityFilterService::new(proxy, filters);

    let resp = call(
        &mut svc,
        tool_call("text/upper", serde_json::json!({"message": "hi"})),
    )
    .await;

    assert!(resp.inner.is_err(), "calling hidden tool should fail");
}

// --- Proxy + alias ---

#[tokio::test]
async fn test_proxy_with_alias_renames_tools() {
    let proxy = build_proxy().await;
    let aliases = AliasMap::new(vec![(
        "math/".to_string(),
        "add".to_string(),
        "sum".to_string(),
    )])
    .unwrap();
    let mut svc = AliasService::new(proxy, aliases);

    // List should show aliased name
    let resp = call(&mut svc, McpRequest::ListTools(Default::default())).await;
    match resp.inner.unwrap() {
        McpResponse::ListTools(result) => {
            let names: Vec<&str> = result.tools.iter().map(|t| t.name.as_str()).collect();
            assert!(
                names.contains(&"math/sum"),
                "should be aliased: {:?}",
                names
            );
            assert!(
                !names.contains(&"math/add"),
                "original should be gone: {:?}",
                names
            );
        }
        other => panic!("expected ListTools, got: {:?}", other),
    }

    // Call aliased name should work
    let resp = call(
        &mut svc,
        tool_call("math/sum", serde_json::json!({"a": 10, "b": 20})),
    )
    .await;

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

// --- Proxy + validation ---

#[tokio::test]
async fn test_proxy_with_validation_rejects_oversized() {
    let proxy = build_proxy().await;
    let config = ValidationConfig {
        max_argument_size: Some(10),
    };
    let mut svc = ValidationService::new(proxy, config);

    let resp = call(
        &mut svc,
        tool_call(
            "text/echo",
            serde_json::json!({"message": "this is a very long message that exceeds the size limit"}),
        ),
    )
    .await;

    let err = resp.inner.unwrap_err();
    assert!(err.message.contains("exceed maximum size"));
}

// --- Proxy + cache ---

#[tokio::test]
async fn test_proxy_with_cache_returns_cached_result() {
    let proxy = build_proxy().await;
    let cfg = BackendCacheConfig {
        resource_ttl_seconds: 60,
        tool_ttl_seconds: 60,
        max_entries: 100,
    };
    let (mut svc, _handle) = CacheService::new(
        proxy,
        vec![("math/".to_string(), &cfg)],
        &CacheBackendConfig::default(),
    );

    let req = tool_call("math/add", serde_json::json!({"a": 5, "b": 5}));

    let resp1 = call(&mut svc, req.clone()).await;
    let resp2 = call(&mut svc, req).await;

    match (resp1.inner.unwrap(), resp2.inner.unwrap()) {
        (McpResponse::CallTool(r1), McpResponse::CallTool(r2)) => {
            assert_eq!(r1.all_text(), "10");
            assert_eq!(r2.all_text(), "10");
        }
        _ => panic!("expected CallTool responses"),
    }
}

// --- Admin tools via proxy ---

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

    // Register admin tools as a proxy/ backend
    let admin_router = tower_mcp::McpRouter::new()
        .server_info("admin", "1.0.0")
        .tool(
            ToolBuilder::new("list_backends")
                .description("List backends")
                .handler(
                    |_: tower_mcp::NoParams| async move { Ok(CallToolResult::text("math,text")) },
                )
                .build(),
        );
    let admin_transport = ChannelTransport::new(admin_router);
    proxy
        .add_backend("proxy", admin_transport)
        .await
        .expect("add proxy backend");

    // List tools should include proxy/list_backends
    let resp = call(&mut proxy, McpRequest::ListTools(Default::default())).await;
    match resp.inner.unwrap() {
        McpResponse::ListTools(result) => {
            let names: Vec<&str> = result.tools.iter().map(|t| t.name.as_str()).collect();
            assert!(
                names.contains(&"proxy/list_backends"),
                "should have admin tool: {:?}",
                names
            );
            assert!(names.contains(&"math/add"), "original tools present");
        }
        other => panic!("expected ListTools, got: {:?}", other),
    }

    // Call admin tool
    let resp = call(
        &mut proxy,
        tool_call("proxy/list_backends", serde_json::json!({})),
    )
    .await;
    match resp.inner.unwrap() {
        McpResponse::CallTool(result) => {
            assert_eq!(result.all_text(), "math,text");
        }
        other => panic!("expected CallTool, got: {:?}", other),
    }
}

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

    // Verify we start with 4 tools (math/add, math/echo_args, text/echo, text/upper)
    let resp = call(&mut proxy, McpRequest::ListTools(Default::default())).await;
    let initial_count = match resp.inner.unwrap() {
        McpResponse::ListTools(result) => result.tools.len(),
        _ => panic!("expected ListTools"),
    };
    assert_eq!(initial_count, 4);

    // Dynamically add another backend
    let extra_router = McpRouter::new().server_info("extra", "1.0.0").tool(
        ToolBuilder::new("ping")
            .description("Ping")
            .handler(|_: tower_mcp::NoParams| async move { Ok(CallToolResult::text("pong")) })
            .build(),
    );
    let extra_transport = ChannelTransport::new(extra_router);
    proxy
        .add_backend("extra", extra_transport)
        .await
        .expect("add extra backend");

    // Should now have 5 tools
    let resp = call(&mut proxy, McpRequest::ListTools(Default::default())).await;
    match resp.inner.unwrap() {
        McpResponse::ListTools(result) => {
            let names: Vec<&str> = result.tools.iter().map(|t| t.name.as_str()).collect();
            assert_eq!(names.len(), 5, "should have 5 tools: {:?}", names);
            assert!(names.contains(&"extra/ping"));
        }
        other => panic!("expected ListTools, got: {:?}", other),
    }

    // Call the new tool
    let resp = call(&mut proxy, tool_call("extra/ping", serde_json::json!({}))).await;
    match resp.inner.unwrap() {
        McpResponse::CallTool(result) => assert_eq!(result.all_text(), "pong"),
        other => panic!("expected CallTool, got: {:?}", other),
    }
}

// --- Cache stats ---

#[tokio::test]
async fn test_cache_stats_through_proxy() {
    let proxy = build_proxy().await;
    let cfg = BackendCacheConfig {
        resource_ttl_seconds: 60,
        tool_ttl_seconds: 60,
        max_entries: 100,
    };
    let (mut svc, handle) = CacheService::new(
        proxy,
        vec![("math/".to_string(), &cfg)],
        &CacheBackendConfig::default(),
    );

    // Miss
    let _ = call(
        &mut svc,
        tool_call("math/add", serde_json::json!({"a": 1, "b": 2})),
    )
    .await;
    // Hit
    let _ = call(
        &mut svc,
        tool_call("math/add", serde_json::json!({"a": 1, "b": 2})),
    )
    .await;
    // Miss (different args)
    let _ = call(
        &mut svc,
        tool_call("math/add", serde_json::json!({"a": 3, "b": 4})),
    )
    .await;

    let stats = handle.stats().await;
    assert_eq!(stats.len(), 1);
    assert_eq!(stats[0].namespace, "math/");
    assert_eq!(stats[0].hits, 1);
    assert_eq!(stats[0].misses, 2);

    // Clear and verify counters reset
    handle.clear().await;
    let stats = handle.stats().await;
    assert_eq!(stats[0].hits, 0);
    assert_eq!(stats[0].misses, 0);
}

// --- Stacked middleware ---

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

    // Validation -> Filter -> Proxy
    let validation = ValidationConfig {
        max_argument_size: Some(1024),
    };
    let filters = vec![BackendFilter {
        namespace: "text/".to_string(),
        tool_filter: NameFilter::deny_list(["upper".to_string()]).unwrap(),
        resource_filter: NameFilter::PassAll,
        prompt_filter: NameFilter::PassAll,
        hide_destructive: false,
        read_only_only: false,
    }];

    let filtered = CapabilityFilterService::new(proxy, filters);
    let mut svc = ValidationService::new(filtered, validation);

    // Normal call works
    let resp = call(
        &mut svc,
        tool_call("text/echo", serde_json::json!({"message": "hello"})),
    )
    .await;
    match resp.inner.unwrap() {
        McpResponse::CallTool(result) => assert_eq!(result.all_text(), "hello"),
        other => panic!("expected CallTool, got: {:?}", other),
    }

    // Filtered tool is denied
    let resp = call(
        &mut svc,
        tool_call("text/upper", serde_json::json!({"message": "hello"})),
    )
    .await;
    assert!(resp.inner.is_err(), "filtered tool should be denied");

    // List shows filtered view
    let resp = call(&mut svc, McpRequest::ListTools(Default::default())).await;
    match resp.inner.unwrap() {
        McpResponse::ListTools(result) => {
            let names: Vec<&str> = result.tools.iter().map(|t| t.name.as_str()).collect();
            assert_eq!(
                names.len(),
                3,
                "should have math/add + math/echo_args + text/echo: {:?}",
                names
            );
        }
        other => panic!("expected ListTools, got: {:?}", other),
    }
}

// --- Proxy + inject args ---

#[tokio::test]
async fn test_proxy_with_inject_default_args() {
    let proxy = build_proxy().await;
    let mut defaults = serde_json::Map::new();
    defaults.insert("timeout".to_string(), serde_json::json!(30));

    let rules = vec![InjectionRules::new("math/".to_string(), defaults, vec![])];
    let mut svc = InjectArgsService::new(proxy, rules);

    // Call echo_args with just "query" -- should get "timeout" injected
    let resp = call(
        &mut svc,
        tool_call("math/echo_args", serde_json::json!({"query": "SELECT 1"})),
    )
    .await;

    match resp.inner.unwrap() {
        McpResponse::CallTool(result) => {
            let args: serde_json::Value = serde_json::from_str(&result.all_text()).unwrap();
            assert_eq!(args["query"], "SELECT 1");
            assert_eq!(args["timeout"], 30, "default arg should be injected");
        }
        other => panic!("expected CallTool, got: {:?}", other),
    }
}

#[tokio::test]
async fn test_proxy_with_inject_does_not_overwrite() {
    let proxy = build_proxy().await;
    let mut defaults = serde_json::Map::new();
    defaults.insert("timeout".to_string(), serde_json::json!(30));

    let rules = vec![InjectionRules::new("math/".to_string(), defaults, vec![])];
    let mut svc = InjectArgsService::new(proxy, rules);

    // Call with timeout already set -- should NOT be overwritten
    let resp = call(
        &mut svc,
        tool_call(
            "math/echo_args",
            serde_json::json!({"query": "SELECT 1", "timeout": 60}),
        ),
    )
    .await;

    match resp.inner.unwrap() {
        McpResponse::CallTool(result) => {
            let args: serde_json::Value = serde_json::from_str(&result.all_text()).unwrap();
            assert_eq!(args["timeout"], 60, "existing value should be preserved");
        }
        other => panic!("expected CallTool, got: {:?}", other),
    }
}

#[tokio::test]
async fn test_proxy_with_inject_per_tool_overwrite() {
    let proxy = build_proxy().await;
    let tool_rules = vec![InjectArgsConfig {
        tool: "echo_args".to_string(),
        args: {
            let mut m = serde_json::Map::new();
            m.insert("forced".to_string(), serde_json::json!(true));
            m
        },
        overwrite: true,
    }];

    let rules = vec![InjectionRules::new(
        "math/".to_string(),
        serde_json::Map::new(),
        tool_rules,
    )];
    let mut svc = InjectArgsService::new(proxy, rules);

    // Call with forced=false -- should be overwritten to true
    let resp = call(
        &mut svc,
        tool_call(
            "math/echo_args",
            serde_json::json!({"data": "hi", "forced": false}),
        ),
    )
    .await;

    match resp.inner.unwrap() {
        McpResponse::CallTool(result) => {
            let args: serde_json::Value = serde_json::from_str(&result.all_text()).unwrap();
            assert_eq!(args["forced"], true, "should be overwritten");
            assert_eq!(args["data"], "hi", "other args preserved");
        }
        other => panic!("expected CallTool, got: {:?}", other),
    }
}

#[tokio::test]
async fn test_proxy_with_inject_skips_other_namespace() {
    let proxy = build_proxy().await;
    let mut defaults = serde_json::Map::new();
    defaults.insert("injected".to_string(), serde_json::json!(true));

    // Only inject into math/ namespace
    let rules = vec![InjectionRules::new("math/".to_string(), defaults, vec![])];
    let mut svc = InjectArgsService::new(proxy, rules);

    // Call text/echo -- should NOT get injected args
    let resp = call(
        &mut svc,
        tool_call("text/echo", serde_json::json!({"message": "hello"})),
    )
    .await;

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

// --- Proxy + mirror ---

#[tokio::test]
async fn test_proxy_with_mirror_primary_response_returned() {
    // Mirror sends a fire-and-forget copy; primary response is returned to caller.
    let math_transport = ChannelTransport::new(math_router());
    let text_transport = ChannelTransport::new(text_router());
    let text_v2_transport = ChannelTransport::new(text_router());

    let proxy = McpProxy::builder("mirror-proxy", "1.0.0")
        .separator("/")
        .backend("math", math_transport)
        .await
        .backend("text", text_transport)
        .await
        .backend("text-v2", text_v2_transport)
        .await
        .build_strict()
        .await
        .expect("proxy should build");

    let mirror_mappings = [("text".to_string(), ("text-v2".to_string(), 100u32))]
        .into_iter()
        .collect();

    let mut svc = MirrorService::new(proxy, mirror_mappings, "/");

    // Call primary -- should get normal response
    let resp = call(
        &mut svc,
        tool_call("text/echo", serde_json::json!({"message": "hello"})),
    )
    .await;

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

    // List tools should show all backends
    let resp = call(&mut svc, McpRequest::ListTools(Default::default())).await;
    match resp.inner.unwrap() {
        McpResponse::ListTools(result) => {
            let names: Vec<&str> = result.tools.iter().map(|t| t.name.as_str()).collect();
            assert!(names.contains(&"text/echo"));
            assert!(names.contains(&"text-v2/echo"));
            assert!(names.contains(&"math/add"));
        }
        other => panic!("expected ListTools, got: {:?}", other),
    }
}

// --- Proxy + coalesce ---

#[tokio::test]
async fn test_proxy_with_coalesce() {
    let proxy = build_proxy().await;
    let mut svc = CoalesceService::new(proxy);

    // Sequential calls with same args should both succeed
    let resp1 = call(
        &mut svc,
        tool_call("math/add", serde_json::json!({"a": 7, "b": 8})),
    )
    .await;
    let resp2 = call(
        &mut svc,
        tool_call("math/add", serde_json::json!({"a": 7, "b": 8})),
    )
    .await;

    match (resp1.inner.unwrap(), resp2.inner.unwrap()) {
        (McpResponse::CallTool(r1), McpResponse::CallTool(r2)) => {
            assert_eq!(r1.all_text(), "15");
            assert_eq!(r2.all_text(), "15");
        }
        _ => panic!("expected CallTool responses"),
    }
}

// --- Proxy + canary ---

#[tokio::test]
async fn test_canary_routes_all_traffic_when_primary_weight_zero() {
    // Two backends with the same tools: primary "api" and canary "api-canary"
    let api_router = {
        let tool = ToolBuilder::new("search")
            .description("Search")
            .handler(|_: tower_mcp::NoParams| async move { Ok(CallToolResult::text("primary")) })
            .build();
        McpRouter::new().server_info("api", "1.0.0").tool(tool)
    };

    let canary_router = {
        let tool = ToolBuilder::new("search")
            .description("Search")
            .handler(|_: tower_mcp::NoParams| async move { Ok(CallToolResult::text("canary")) })
            .build();
        McpRouter::new()
            .server_info("api-canary", "1.0.0")
            .tool(tool)
    };

    let proxy = McpProxy::builder("canary-proxy", "1.0.0")
        .separator("/")
        .backend("api", ChannelTransport::new(api_router))
        .await
        .backend("api-canary", ChannelTransport::new(canary_router))
        .await
        .build_strict()
        .await
        .expect("proxy should build");

    // 0 primary weight = 100% canary
    let canaries = [("api".to_string(), ("api-canary".to_string(), 0u32, 100u32))]
        .into_iter()
        .collect();
    let mut svc = CanaryService::new(proxy, canaries, "/");

    // All requests to api/search should be rewritten to api-canary/search
    let resp = call(&mut svc, tool_call("api/search", serde_json::json!({}))).await;

    match resp.inner.unwrap() {
        McpResponse::CallTool(result) => {
            assert_eq!(result.all_text(), "canary", "should route to canary");
        }
        other => panic!("expected CallTool, got: {:?}", other),
    }
}

#[tokio::test]
async fn test_canary_passes_through_when_primary_weight_full() {
    let api_router = {
        let tool = ToolBuilder::new("search")
            .description("Search")
            .handler(|_: tower_mcp::NoParams| async move { Ok(CallToolResult::text("primary")) })
            .build();
        McpRouter::new().server_info("api", "1.0.0").tool(tool)
    };

    let canary_router = {
        let tool = ToolBuilder::new("search")
            .description("Search")
            .handler(|_: tower_mcp::NoParams| async move { Ok(CallToolResult::text("canary")) })
            .build();
        McpRouter::new()
            .server_info("api-canary", "1.0.0")
            .tool(tool)
    };

    let proxy = McpProxy::builder("canary-proxy", "1.0.0")
        .separator("/")
        .backend("api", ChannelTransport::new(api_router))
        .await
        .backend("api-canary", ChannelTransport::new(canary_router))
        .await
        .build_strict()
        .await
        .expect("proxy should build");

    // 100 primary / 0 canary -- but total_weight would be 100, so all go to primary
    let canaries = [("api".to_string(), ("api-canary".to_string(), 100u32, 0u32))]
        .into_iter()
        .collect();
    let mut svc = CanaryService::new(proxy, canaries, "/");

    let resp = call(&mut svc, tool_call("api/search", serde_json::json!({}))).await;

    match resp.inner.unwrap() {
        McpResponse::CallTool(result) => {
            assert_eq!(result.all_text(), "primary", "should route to primary");
        }
        other => panic!("expected CallTool, got: {:?}", other),
    }
}

#[tokio::test]
async fn test_canary_with_filter_hides_canary_tools() {
    let api_router = {
        let tool = ToolBuilder::new("search")
            .description("Search")
            .handler(|_: tower_mcp::NoParams| async move { Ok(CallToolResult::text("primary")) })
            .build();
        McpRouter::new().server_info("api", "1.0.0").tool(tool)
    };

    let canary_router = {
        let tool = ToolBuilder::new("search")
            .description("Search")
            .handler(|_: tower_mcp::NoParams| async move { Ok(CallToolResult::text("canary")) })
            .build();
        McpRouter::new()
            .server_info("api-canary", "1.0.0")
            .tool(tool)
    };

    let proxy = McpProxy::builder("canary-proxy", "1.0.0")
        .separator("/")
        .backend("api", ChannelTransport::new(api_router))
        .await
        .backend("api-canary", ChannelTransport::new(canary_router))
        .await
        .build_strict()
        .await
        .expect("proxy should build");

    // Canary middleware (0 primary = all canary)
    let canaries = [("api".to_string(), ("api-canary".to_string(), 0u32, 100u32))]
        .into_iter()
        .collect();
    let canary_svc = CanaryService::new(proxy, canaries, "/");

    // Filter to hide canary tools (empty AllowList = hide everything)
    let filters = vec![BackendFilter {
        namespace: "api-canary/".to_string(),
        tool_filter: NameFilter::allow_list(std::iter::empty::<String>()).unwrap(),
        resource_filter: NameFilter::allow_list(std::iter::empty::<String>()).unwrap(),
        prompt_filter: NameFilter::allow_list(std::iter::empty::<String>()).unwrap(),
        hide_destructive: false,
        read_only_only: false,
    }];
    let mut svc = CapabilityFilterService::new(canary_svc, filters);

    // ListTools should only show api/search, not api-canary/search
    let resp = call(&mut svc, McpRequest::ListTools(Default::default())).await;
    match resp.inner.unwrap() {
        McpResponse::ListTools(result) => {
            let names: Vec<&str> = result.tools.iter().map(|t| t.name.as_str()).collect();
            assert!(
                names.contains(&"api/search"),
                "primary visible: {:?}",
                names
            );
            assert!(
                !names.contains(&"api-canary/search"),
                "canary hidden: {:?}",
                names
            );
            assert_eq!(names.len(), 1, "only primary tool: {:?}", names);
        }
        other => panic!("expected ListTools, got: {:?}", other),
    }

    // But CallTool to api/search should still route to canary and succeed
    let resp = call(&mut svc, tool_call("api/search", serde_json::json!({}))).await;

    match resp.inner.unwrap() {
        McpResponse::CallTool(result) => {
            assert_eq!(result.all_text(), "canary", "should route to canary");
        }
        other => panic!("expected CallTool, got: {:?}", other),
    }
}

// --- Full middleware stack composition ---

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

    // Build a realistic middleware stack:
    // validation -> alias -> filter -> inject -> proxy
    let mut defaults = serde_json::Map::new();
    defaults.insert("timeout".to_string(), serde_json::json!(30));
    let inject_rules = vec![InjectionRules::new("math/".to_string(), defaults, vec![])];

    let filters = vec![BackendFilter {
        namespace: "text/".to_string(),
        tool_filter: NameFilter::deny_list(["upper".to_string()]).unwrap(),
        resource_filter: NameFilter::PassAll,
        prompt_filter: NameFilter::PassAll,
        hide_destructive: false,
        read_only_only: false,
    }];

    let aliases = AliasMap::new(vec![(
        "math/".to_string(),
        "add".to_string(),
        "sum".to_string(),
    )])
    .unwrap();

    let validation = ValidationConfig {
        max_argument_size: Some(4096),
    };

    // Stack: outermost -> innermost
    let injected = InjectArgsService::new(proxy, inject_rules);
    let filtered = CapabilityFilterService::new(injected, filters);
    let aliased = AliasService::new(filtered, aliases);
    let mut svc = ValidationService::new(aliased, validation);

    // math/add is aliased to math/sum
    let resp = call(
        &mut svc,
        tool_call("math/sum", serde_json::json!({"a": 100, "b": 200})),
    )
    .await;
    match resp.inner.unwrap() {
        McpResponse::CallTool(result) => assert_eq!(result.all_text(), "300"),
        other => panic!("expected CallTool, got: {:?}", other),
    }

    // text/upper is filtered out
    let resp = call(
        &mut svc,
        tool_call("text/upper", serde_json::json!({"message": "hi"})),
    )
    .await;
    assert!(resp.inner.is_err());

    // text/echo works normally
    let resp = call(
        &mut svc,
        tool_call("text/echo", serde_json::json!({"message": "world"})),
    )
    .await;
    match resp.inner.unwrap() {
        McpResponse::CallTool(result) => assert_eq!(result.all_text(), "world"),
        other => panic!("expected CallTool, got: {:?}", other),
    }

    // List tools shows aliased + filtered view
    let resp = call(&mut svc, McpRequest::ListTools(Default::default())).await;
    match resp.inner.unwrap() {
        McpResponse::ListTools(result) => {
            let names: Vec<&str> = result.tools.iter().map(|t| t.name.as_str()).collect();
            assert!(names.contains(&"math/sum"), "aliased name: {:?}", names);
            assert!(!names.contains(&"math/add"), "original hidden: {:?}", names);
            assert!(names.contains(&"text/echo"), "echo visible: {:?}", names);
            assert!(
                !names.contains(&"text/upper"),
                "upper filtered: {:?}",
                names
            );
        }
        other => panic!("expected ListTools, got: {:?}", other),
    }
}