monoloop-loop 0.1.2

Minimal extensible Loop: lossless canonical subscription, empty-capable tools
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
//! WP-07: MCP capability lifecycle, list/call parity, isolation.

use futures_util::stream;
use monoloop_contracts::{
    CanonicalToolOutput, ChannelId, ExchangeId, JsonSchema, SessionId, SessionKey, ToolActionId,
    ToolCompletion, ToolExecutionClass, ToolId, ToolLimits, ToolName, ToolOutputContract, ToolSpec,
    ToolSuccessContract, TransactionId,
};
use monoloop_loop::{
    dispatch_ready_tool, tool_definitions_from_resolved, CapabilityToken, DispatchOutcome,
    HostToolRegistry, ImmediateToolHandler, McpBindingState, McpGateway, McpGatewayHandle,
    McpGatewayLimits, RegisteredTool, ResolvedToolSet, SharedToolCapacity, ToolHandler,
    TransactionToolDispatcher,
};
use std::ops::Deref;
use std::sync::Arc;
use std::time::Duration;
use tokio::task::JoinHandle;
use tokio_util::sync::CancellationToken;

/// Test-owned loopback gateway (ambient spawn stays in the test harness, not product src).
struct BoundGateway {
    handle: McpGatewayHandle,
    cancel: CancellationToken,
    join: JoinHandle<()>,
}

impl BoundGateway {
    async fn bind(max_routes: usize) -> Self {
        Self::bind_with_limits(max_routes, McpGatewayLimits::default()).await
    }

    async fn bind_with_limits(max_routes: usize, limits: McpGatewayLimits) -> Self {
        let listener = tokio::net::TcpListener::bind("127.0.0.1:0")
            .await
            .expect("loopback bind");
        let prepared =
            McpGateway::prepare_from_tokio_listener_with_limits(listener, max_routes, None, limits)
                .expect("prepare gateway");
        let handle = prepared.handle();
        let cancel = prepared.cancel_token();
        let join = tokio::spawn(prepared.serve());
        Self {
            handle,
            cancel,
            join,
        }
    }

    async fn shutdown(self) {
        self.handle.revoke_all_services();
        self.cancel.cancel();
        let _ = self.join.await;
    }
}

impl Deref for BoundGateway {
    type Target = McpGatewayHandle;
    fn deref(&self) -> &Self::Target {
        &self.handle
    }
}

fn object_schema() -> JsonSchema {
    JsonSchema::try_new(serde_json::json!({
        "type": "object",
        "properties": { "q": { "type": "string" } },
        "required": ["q"],
        "additionalProperties": false
    }))
    .unwrap()
}

fn success_schema() -> JsonSchema {
    JsonSchema::try_new(serde_json::json!({
        "type": "object",
        "properties": { "ok": { "type": "boolean" } },
        "required": ["ok"],
        "additionalProperties": false
    }))
    .unwrap()
}

fn make_spec(id: &str, name: &str) -> ToolSpec {
    ToolSpec::try_new(
        ToolId::try_new(id).unwrap(),
        ToolName::try_new(name).unwrap(),
        "echo tool",
        object_schema(),
        ToolOutputContract {
            success: ToolSuccessContract::json(success_schema()),
            error_data_schema: None,
        },
        ToolLimits {
            max_concurrent: 4,
            max_input_bytes: 1024,
            max_output_bytes: 1024,
            execution_deadline: Duration::from_secs(5),
        },
        ToolExecutionClass::CooperativeInProcess {
            grace: std::time::Duration::from_millis(50),
        },
    )
    .unwrap()
}

fn ok_handler() -> Arc<dyn ToolHandler> {
    Arc::new(ImmediateToolHandler::new(|_call, _ctx| {
        Ok(ToolCompletion::Succeeded(CanonicalToolOutput::Json(
            serde_json::json!({"ok": true}),
        )))
    }))
}

fn session_key() -> SessionKey {
    SessionKey::new(
        ChannelId::try_new("ch").unwrap(),
        SessionId::try_new("s1").unwrap(),
    )
}

fn build_dispatcher(tools: ResolvedToolSet) -> Arc<TransactionToolDispatcher> {
    TransactionToolDispatcher::new(
        TransactionId::generate(),
        session_key(),
        tools,
        SharedToolCapacity::unlimited(),
        8,
        16,
    )
}

fn resolved_echo() -> (HostToolRegistry, ResolvedToolSet) {
    let host = HostToolRegistry::build(vec![RegisteredTool::new(
        make_spec("echo", "echo"),
        ok_handler(),
    )])
    .unwrap();
    let tool = host.get(&ToolId::try_new("echo").unwrap()).unwrap().clone();
    (host, ResolvedToolSet::from_registered(vec![tool]))
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn bind_loopback_and_shutdown_revokes_routes() {
    let gw = BoundGateway::bind(32).await;
    assert!(gw.local_addr().ip().is_loopback());
    let (_, tools) = resolved_echo();
    let d = build_dispatcher(tools.clone());
    let pending = gw
        .install_pending(TransactionId::generate(), tools, d, ExchangeId::generate())
        .unwrap();
    assert!(gw.routes().get(&pending.token).is_some());
    gw.shutdown().await;
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn pending_rejects_list_and_call_until_active() {
    let gw = BoundGateway::bind(32).await;
    let (_, tools) = resolved_echo();
    let d = build_dispatcher(tools.clone());
    let pending = gw
        .install_pending(TransactionId::generate(), tools, d, ExchangeId::generate())
        .unwrap();
    let binding = gw.routes().get(&pending.token).unwrap();
    assert_eq!(binding.state(), McpBindingState::Pending);
    assert!(binding.handler.list_tool_defs().is_err());
    let mut args = serde_json::Map::new();
    args.insert("q".into(), serde_json::json!("hi"));
    assert!(binding
        .handler
        .call_tool_direct("echo", Some(args))
        .await
        .is_err());

    gw.activate(&pending.token).unwrap();
    assert_eq!(
        gw.routes().state_of(&pending.token),
        Some(McpBindingState::Active)
    );
    let listed = binding.handler.list_tool_defs().unwrap();
    assert_eq!(listed.len(), 1);
    assert_eq!(listed[0].name, "echo");

    let mut args = serde_json::Map::new();
    args.insert("q".into(), serde_json::json!("hi"));
    let result = binding
        .handler
        .call_tool_direct("echo", Some(args))
        .await
        .unwrap();
    assert_eq!(result.is_error, Some(false));

    gw.shutdown().await;
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn empty_resolved_set_lists_no_tools() {
    let gw = BoundGateway::bind(8).await;
    let tools = ResolvedToolSet::empty();
    let d = build_dispatcher(tools.clone());
    let pending = gw
        .install_pending(TransactionId::generate(), tools, d, ExchangeId::generate())
        .unwrap();
    gw.activate(&pending.token).unwrap();
    let binding = gw.routes().get(&pending.token).unwrap();
    let listed = binding.handler.list_tool_defs().unwrap();
    assert!(listed.is_empty());
    gw.shutdown().await;
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn unknown_revoked_cross_transaction_isolation() {
    let gw = BoundGateway::bind(16).await;
    let (_, tools_a) = resolved_echo();
    let d_a = build_dispatcher(tools_a.clone());
    let a = gw
        .install_pending(
            TransactionId::generate(),
            tools_a,
            d_a,
            ExchangeId::generate(),
        )
        .unwrap();
    gw.activate(&a.token).unwrap();

    // Unknown token
    assert!(gw.routes().get_by_hex(&"00".repeat(32)).is_none());

    // Revoke A
    assert!(gw.revoke(&a.token));
    assert!(gw.routes().get(&a.token).is_none());
    // Second revoke is idempotent false
    assert!(!gw.revoke(&a.token));

    // Transaction B cannot use A's token
    let (_, tools_b) = resolved_echo();
    let d_b = build_dispatcher(tools_b.clone());
    let b = gw
        .install_pending(
            TransactionId::generate(),
            tools_b,
            d_b,
            ExchangeId::generate(),
        )
        .unwrap();
    assert_ne!(a.token, b.token);
    assert!(gw.routes().get(&a.token).is_none());
    gw.activate(&b.token).unwrap();
    // Stale A hex still unknown
    assert!(gw.routes().get(&a.token).is_none());

    gw.shutdown().await;
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn delayed_capability_a_cannot_enter_b() {
    let gw = BoundGateway::bind(16).await;
    let (_, tools) = resolved_echo();
    let d1 = build_dispatcher(tools.clone());
    let a = gw
        .install_pending(
            TransactionId::generate(),
            tools.clone(),
            d1,
            ExchangeId::generate(),
        )
        .unwrap();
    gw.activate(&a.token).unwrap();
    let token_a = a.token.clone();
    gw.revoke(&token_a);

    let d2 = build_dispatcher(tools);
    let b = gw
        .install_pending(
            TransactionId::generate(),
            ResolvedToolSet::empty(),
            d2,
            ExchangeId::generate(),
        )
        .unwrap();
    gw.activate(&b.token).unwrap();

    // Late use of A after B is active
    assert!(gw.routes().get(&token_a).is_none());
    assert!(gw.routes().get(&b.token).is_some());
    gw.shutdown().await;
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn capability_redacted_in_debug() {
    let token = CapabilityToken::generate().unwrap();
    let dbg = format!("{token:?}");
    assert!(dbg.contains("redacted"));
    assert!(!dbg.contains(&token.to_hex()));

    let gw = BoundGateway::bind(4).await;
    let (_, tools) = resolved_echo();
    let d = build_dispatcher(tools.clone());
    let pending = gw
        .install_pending(TransactionId::generate(), tools, d, ExchangeId::generate())
        .unwrap();
    let desc_dbg = format!("{:?}", pending.descriptor);
    assert!(desc_dbg.contains("redacted") || desc_dbg.contains("<redacted>"));
    assert!(!desc_dbg.contains(&pending.token.to_hex()));
    // Descriptor Debug must not include full capability URL path token
    assert!(!desc_dbg.contains("/mcp/"));
    gw.shutdown().await;
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn mcp_and_local_paths_same_handler_and_definitions() {
    let host = HostToolRegistry::build(vec![RegisteredTool::new(
        make_spec("echo", "echo"),
        ok_handler(),
    )])
    .unwrap();
    let registered = host.get(&ToolId::try_new("echo").unwrap()).unwrap().clone();
    let tools = ResolvedToolSet::from_registered(vec![registered]);
    let mcp_defs = tool_definitions_from_resolved(&tools);
    assert_eq!(mcp_defs.len(), 1);
    assert_eq!(mcp_defs[0].name, "echo");
    // Encoder projection uses the same specs()
    assert_eq!(tools.specs()[0].name.as_str(), mcp_defs[0].name.as_ref());

    let dispatcher = build_dispatcher(tools.clone());
    let gw = BoundGateway::bind(8).await;
    let pending = gw
        .install_pending(
            TransactionId::generate(),
            tools.clone(),
            Arc::clone(&dispatcher),
            ExchangeId::generate(),
        )
        .unwrap();
    gw.activate(&pending.token).unwrap();

    // Local path
    let local = dispatch_ready_tool(
        &dispatcher,
        ExchangeId::generate(),
        ToolActionId::new("local-1"),
        "echo",
        "p1",
        0,
        r#"{"q":"hi"}"#,
    )
    .await;
    assert!(matches!(local, DispatchOutcome::Canonical { .. }));

    // MCP path (same dispatcher Arc)
    let binding = gw.routes().get(&pending.token).unwrap();
    let mut args = serde_json::Map::new();
    args.insert("q".into(), serde_json::json!("hi"));
    let mcp = binding
        .handler
        .call_tool_direct("echo", Some(args))
        .await
        .unwrap();
    assert_eq!(mcp.is_error, Some(false));

    // Disallowed tool on MCP
    let bad = binding.handler.call_tool_direct("nope", None).await;
    assert!(bad.is_err());

    gw.shutdown().await;
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn disallowed_tool_and_schema_invalid_on_mcp() {
    let gw = BoundGateway::bind(8).await;
    let (_, tools) = resolved_echo();
    let d = build_dispatcher(tools.clone());
    let pending = gw
        .install_pending(TransactionId::generate(), tools, d, ExchangeId::generate())
        .unwrap();
    gw.activate(&pending.token).unwrap();
    let binding = gw.routes().get(&pending.token).unwrap();

    let mut bad_args = serde_json::Map::new();
    bad_args.insert("q".into(), serde_json::json!(1));
    let invalid = binding
        .handler
        .call_tool_direct("echo", Some(bad_args))
        .await
        .unwrap();
    assert_eq!(invalid.is_error, Some(true));

    gw.shutdown().await;
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn http_unknown_capability_is_404() {
    let gw = BoundGateway::bind(4).await;
    let addr = gw.local_addr();
    let client = reqwest::Client::new();
    let url = format!("http://{addr}/mcp/{}", "ab".repeat(32));
    let resp = client.get(&url).send().await.unwrap();
    assert_eq!(resp.status(), reqwest::StatusCode::NOT_FOUND);
    gw.shutdown().await;
}

/// D-018: oversized HTTP body is rejected before protocol dispatch.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn http_oversized_body_fails_closed() {
    let gw = BoundGateway::bind(4).await;
    let (_, tools) = resolved_echo();
    let d = build_dispatcher(tools.clone());
    let pending = gw
        .install_pending(TransactionId::generate(), tools, d, ExchangeId::generate())
        .unwrap();
    gw.activate(&pending.token).unwrap();
    let url = format!("{}/mcp/{}", gw.base_url(), pending.token.to_hex());
    let client = reqwest::Client::new();
    let big = vec![b'x'; 1024 * 1024 + 64];
    let resp = client
        .post(&url)
        .header("content-type", "application/json")
        .body(big)
        .send()
        .await
        .unwrap();
    assert_eq!(resp.status(), reqwest::StatusCode::PAYLOAD_TOO_LARGE);
    gw.shutdown().await;
}

/// Never-yielding body stream — used by duration plus-one (single request).
fn hanging_body() -> reqwest::Body {
    reqwest::Body::wrap_stream(stream::pending::<Result<bytes::Bytes, std::io::Error>>())
}

/// Open an HTTP/1.1 chunked POST and leave the body unfinished so the gateway
/// holds concurrency permits inside `to_bytes` (server-side only — no client
/// body-stream poll race).
async fn hold_incomplete_chunked_post(
    addr: std::net::SocketAddr,
    token_hex: &str,
) -> tokio::net::TcpStream {
    use tokio::io::AsyncWriteExt;

    let mut stream = tokio::net::TcpStream::connect(addr)
        .await
        .expect("connect hold socket");
    let req = format!(
        "POST /mcp/{token_hex} HTTP/1.1\r\n\
         Host: {addr}\r\n\
         Content-Type: application/json\r\n\
         Transfer-Encoding: chunked\r\n\
         Connection: keep-alive\r\n\
         \r\n"
    );
    stream
        .write_all(req.as_bytes())
        .await
        .expect("write hold headers");
    // No chunks, no terminating 0-chunk — server waits in body read with permits held.
    stream
}

async fn probe_until_status(
    client: &reqwest::Client,
    url: &str,
    want: reqwest::StatusCode,
    budget: Duration,
) -> reqwest::Response {
    let deadline = tokio::time::Instant::now() + budget;
    let mut last = None;
    while tokio::time::Instant::now() < deadline {
        let resp = client
            .post(url)
            .header("content-type", "application/json")
            .body("{}")
            .send()
            .await
            .expect("probe send");
        if resp.status() == want {
            return resp;
        }
        last = Some(resp.status());
        tokio::time::sleep(Duration::from_millis(10)).await;
    }
    panic!("probe did not reach {want} within {budget:?}; last={last:?}");
}

/// D-034: per-capability concurrency exact limit held; plus-one fails closed (429).
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn mcp_per_capability_concurrency_plus_one_rejects() {
    let limits = McpGatewayLimits {
        max_global_requests: 8,
        max_per_capability_requests: 1,
        request_duration: Duration::from_secs(5),
    };
    let gw = BoundGateway::bind_with_limits(4, limits).await;
    let (_, tools) = resolved_echo();
    let d = build_dispatcher(tools.clone());
    let pending = gw
        .install_pending(TransactionId::generate(), tools, d, ExchangeId::generate())
        .unwrap();
    gw.activate(&pending.token).unwrap();
    let url = format!("{}/mcp/{}", gw.base_url(), pending.token.to_hex());
    let client = reqwest::Client::new();

    let _hold = hold_incomplete_chunked_post(gw.local_addr(), &pending.token.to_hex()).await;

    let resp = probe_until_status(
        &client,
        &url,
        reqwest::StatusCode::TOO_MANY_REQUESTS,
        Duration::from_secs(2),
    )
    .await;
    let body = resp.text().await.unwrap_or_default();
    assert!(
        body.contains("mcp capability concurrency exceeded"),
        "expected per-capability concurrency body, got {body:?}"
    );

    gw.shutdown().await;
}

/// D-034: global concurrency exact limit held; plus-one fails closed (429).
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn mcp_global_concurrency_plus_one_rejects() {
    let limits = McpGatewayLimits {
        max_global_requests: 1,
        max_per_capability_requests: 8,
        request_duration: Duration::from_secs(5),
    };
    let gw = BoundGateway::bind_with_limits(4, limits).await;
    let (_, tools) = resolved_echo();
    let d = build_dispatcher(tools.clone());
    let pending = gw
        .install_pending(TransactionId::generate(), tools, d, ExchangeId::generate())
        .unwrap();
    gw.activate(&pending.token).unwrap();
    let url = format!("{}/mcp/{}", gw.base_url(), pending.token.to_hex());
    let client = reqwest::Client::new();

    let _hold = hold_incomplete_chunked_post(gw.local_addr(), &pending.token.to_hex()).await;

    let resp = probe_until_status(
        &client,
        &url,
        reqwest::StatusCode::TOO_MANY_REQUESTS,
        Duration::from_secs(2),
    )
    .await;
    let body = resp.text().await.unwrap_or_default();
    assert!(
        body.contains("mcp gateway concurrency exceeded"),
        "expected global concurrency body, got {body:?}"
    );

    gw.shutdown().await;
}

/// D-034: request duration plus-one (hanging body past budget) fails closed (504).
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn mcp_request_duration_plus_one_fails_closed() {
    let limits = McpGatewayLimits {
        max_global_requests: 4,
        max_per_capability_requests: 4,
        request_duration: Duration::from_millis(80),
    };
    let gw = BoundGateway::bind_with_limits(4, limits).await;
    let (_, tools) = resolved_echo();
    let d = build_dispatcher(tools.clone());
    let pending = gw
        .install_pending(TransactionId::generate(), tools, d, ExchangeId::generate())
        .unwrap();
    gw.activate(&pending.token).unwrap();
    let url = format!("{}/mcp/{}", gw.base_url(), pending.token.to_hex());
    let client = reqwest::Client::builder()
        .timeout(Duration::from_secs(5))
        .build()
        .unwrap();

    let resp = client
        .post(&url)
        .header("content-type", "application/json")
        .body(hanging_body())
        .send()
        .await
        .unwrap();
    assert_eq!(resp.status(), reqwest::StatusCode::GATEWAY_TIMEOUT);
    let body = resp.text().await.unwrap_or_default();
    assert!(
        body.contains("mcp request deadline exceeded"),
        "expected duration fail-closed body, got {body:?}"
    );
    gw.shutdown().await;
}

/// D-018: same capability token reuses HTTP service across requests (session manager).
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn http_active_capability_accepts_repeated_posts() {
    let gw = BoundGateway::bind(8).await;
    let (_, tools) = resolved_echo();
    let d = build_dispatcher(tools.clone());
    let pending = gw
        .install_pending(TransactionId::generate(), tools, d, ExchangeId::generate())
        .unwrap();
    gw.activate(&pending.token).unwrap();
    let url = format!("{}/mcp/{}", gw.base_url(), pending.token.to_hex());
    let client = reqwest::Client::new();
    // Minimal JSON-RPC-shaped posts; Streamable HTTP may reject protocol-incomplete
    // bodies, but must not 404 the active capability, and must stay consistent across calls.
    let body = r#"{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-03-26","capabilities":{},"clientInfo":{"name":"t","version":"0"}}}"#;
    let mut statuses = Vec::new();
    for _ in 0..3 {
        let resp = client
            .post(&url)
            .header("content-type", "application/json")
            .header("accept", "application/json, text/event-stream")
            .body(body)
            .send()
            .await
            .unwrap();
        statuses.push(resp.status());
    }
    assert!(
        statuses
            .iter()
            .all(|s| *s != reqwest::StatusCode::NOT_FOUND),
        "active capability must not 404: {statuses:?}"
    );
    // All three requests hit the same route (stable non-404 outcomes).
    assert_eq!(statuses[0], statuses[1]);
    assert_eq!(statuses[1], statuses[2]);
    gw.shutdown().await;
}

const MCP_PROTOCOL: &str = "2025-03-26";

fn mcp_init_body(id: u64) -> String {
    format!(
        r#"{{"jsonrpc":"2.0","id":{id},"method":"initialize","params":{{"protocolVersion":"{MCP_PROTOCOL}","capabilities":{{}},"clientInfo":{{"name":"monoloop-e2e","version":"0"}}}}}}"#
    )
}

/// Extract first JSON-RPC object from a JSON body or SSE `data:` frames.
fn first_jsonrpc_value(body: &str) -> Option<serde_json::Value> {
    let trimmed = body.trim();
    if trimmed.starts_with('{') {
        return serde_json::from_str(trimmed).ok();
    }
    for line in body.lines() {
        let line = line.trim();
        if let Some(data) = line.strip_prefix("data:") {
            let data = data.trim();
            if data.is_empty() || data == "[DONE]" {
                continue;
            }
            if let Ok(v) = serde_json::from_str::<serde_json::Value>(data) {
                return Some(v);
            }
        }
    }
    None
}

/// D-018: real Streamable HTTP initialize → initialized → tools/list → tools/call.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn http_mcp_initialize_list_call_sequence() {
    let gw = BoundGateway::bind(8).await;
    let (_, tools) = resolved_echo();
    let d = build_dispatcher(tools.clone());
    let pending = gw
        .install_pending(TransactionId::generate(), tools, d, ExchangeId::generate())
        .unwrap();
    gw.activate(&pending.token).unwrap();
    let url = format!("{}/mcp/{}", gw.base_url(), pending.token.to_hex());
    let client = reqwest::Client::new();

    // 1) initialize
    let init_resp = client
        .post(&url)
        .header("content-type", "application/json")
        .header("accept", "application/json, text/event-stream")
        .header("mcp-protocol-version", MCP_PROTOCOL)
        .body(mcp_init_body(1))
        .send()
        .await
        .unwrap();
    assert!(
        init_resp.status().is_success(),
        "initialize status={}",
        init_resp.status()
    );
    let session_id = init_resp
        .headers()
        .get("mcp-session-id")
        .and_then(|v| v.to_str().ok())
        .map(|s| s.to_string())
        .expect("Mcp-Session-Id on initialize response");
    let init_body = init_resp.text().await.unwrap();
    let init_msg = first_jsonrpc_value(&init_body)
        .unwrap_or_else(|| panic!("initialize JSON-RPC body missing; body={init_body:?}"));
    assert!(
        init_msg.get("result").is_some(),
        "initialize must return result, got {init_msg}"
    );

    // 2) notifications/initialized (same session)
    let notify_resp = client
        .post(&url)
        .header("content-type", "application/json")
        .header("accept", "application/json, text/event-stream")
        .header("mcp-session-id", &session_id)
        .header("mcp-protocol-version", MCP_PROTOCOL)
        .body(r#"{"jsonrpc":"2.0","method":"notifications/initialized"}"#)
        .send()
        .await
        .unwrap();
    assert!(
        notify_resp.status().is_success() || notify_resp.status() == reqwest::StatusCode::ACCEPTED,
        "initialized notification status={}",
        notify_resp.status()
    );

    // 3) tools/list
    let list_resp = client
        .post(&url)
        .header("content-type", "application/json")
        .header("accept", "application/json, text/event-stream")
        .header("mcp-session-id", &session_id)
        .header("mcp-protocol-version", MCP_PROTOCOL)
        .body(r#"{"jsonrpc":"2.0","id":2,"method":"tools/list","params":{}}"#)
        .send()
        .await
        .unwrap();
    assert!(
        list_resp.status().is_success(),
        "tools/list status={}",
        list_resp.status()
    );
    let list_body = list_resp.text().await.unwrap();
    let list_msg = first_jsonrpc_value(&list_body).expect("tools/list JSON-RPC body");
    let tools = list_msg
        .pointer("/result/tools")
        .and_then(|t| t.as_array())
        .expect("result.tools array");
    assert!(
        tools
            .iter()
            .any(|t| t.get("name").and_then(|n| n.as_str()) == Some("echo")),
        "tools/list must include echo: {list_msg}"
    );

    // 4) tools/call
    let call_resp = client
        .post(&url)
        .header("content-type", "application/json")
        .header("accept", "application/json, text/event-stream")
        .header("mcp-session-id", &session_id)
        .header("mcp-protocol-version", MCP_PROTOCOL)
        .body(
            r#"{"jsonrpc":"2.0","id":3,"method":"tools/call","params":{"name":"echo","arguments":{"q":"hi"}}}"#,
        )
        .send()
        .await
        .unwrap();
    assert!(
        call_resp.status().is_success(),
        "tools/call status={}",
        call_resp.status()
    );
    let call_body = call_resp.text().await.unwrap();
    let call_msg = first_jsonrpc_value(&call_body).expect("tools/call JSON-RPC body");
    assert!(
        call_msg.get("result").is_some() && call_msg.get("error").is_none(),
        "tools/call must succeed: {call_msg}"
    );
    // Echo handler returns JSON {"ok": true} as text content block.
    let content_text = call_msg
        .pointer("/result/content")
        .and_then(|c| c.as_array())
        .and_then(|arr| arr.first())
        .and_then(|block| block.get("text"))
        .and_then(|t| t.as_str())
        .unwrap_or("");
    assert!(
        content_text.contains("ok")
            || call_msg.pointer("/result/isError") == Some(&serde_json::json!(false)),
        "tools/call content unexpected: {call_msg}"
    );

    gw.shutdown().await;
}

/// D-018: pending (not activated) capability rejects tools/list after initialize.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn http_mcp_pending_token_rejects_tools_list() {
    let gw = BoundGateway::bind(4).await;
    let (_, tools) = resolved_echo();
    let d = build_dispatcher(tools.clone());
    let pending = gw
        .install_pending(TransactionId::generate(), tools, d, ExchangeId::generate())
        .unwrap();
    // deliberately not activated
    let url = format!("{}/mcp/{}", gw.base_url(), pending.token.to_hex());
    let client = reqwest::Client::new();

    let init_resp = client
        .post(&url)
        .header("content-type", "application/json")
        .header("accept", "application/json, text/event-stream")
        .header("mcp-protocol-version", MCP_PROTOCOL)
        .body(mcp_init_body(1))
        .send()
        .await
        .unwrap();
    assert!(init_resp.status().is_success());
    let session_id = init_resp
        .headers()
        .get("mcp-session-id")
        .and_then(|v| v.to_str().ok())
        .map(|s| s.to_string())
        .expect("session id");
    let _ = init_resp.text().await;

    let _ = client
        .post(&url)
        .header("content-type", "application/json")
        .header("accept", "application/json, text/event-stream")
        .header("mcp-session-id", &session_id)
        .header("mcp-protocol-version", MCP_PROTOCOL)
        .body(r#"{"jsonrpc":"2.0","method":"notifications/initialized"}"#)
        .send()
        .await
        .unwrap();

    let list_resp = client
        .post(&url)
        .header("content-type", "application/json")
        .header("accept", "application/json, text/event-stream")
        .header("mcp-session-id", &session_id)
        .header("mcp-protocol-version", MCP_PROTOCOL)
        .body(r#"{"jsonrpc":"2.0","id":2,"method":"tools/list","params":{}}"#)
        .send()
        .await
        .unwrap();
    let list_body = list_resp.text().await.unwrap();
    let list_msg = first_jsonrpc_value(&list_body).expect("tools/list body");
    assert!(
        list_msg.get("error").is_some(),
        "pending capability must error tools/list: {list_msg}"
    );

    gw.shutdown().await;
}

/// D-018: revoked capability 404s subsequent HTTP traffic.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn http_mcp_revoked_token_is_404() {
    let gw = BoundGateway::bind(4).await;
    let (_, tools) = resolved_echo();
    let d = build_dispatcher(tools.clone());
    let pending = gw
        .install_pending(TransactionId::generate(), tools, d, ExchangeId::generate())
        .unwrap();
    gw.activate(&pending.token).unwrap();
    let url = format!("{}/mcp/{}", gw.base_url(), pending.token.to_hex());
    assert!(gw.revoke(&pending.token));

    let client = reqwest::Client::new();
    let resp = client
        .post(&url)
        .header("content-type", "application/json")
        .header("accept", "application/json, text/event-stream")
        .header("mcp-protocol-version", MCP_PROTOCOL)
        .body(mcp_init_body(1))
        .send()
        .await
        .unwrap();
    assert_eq!(resp.status(), reqwest::StatusCode::NOT_FOUND);
    gw.shutdown().await;
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn token_hex_roundtrip() {
    let t = CapabilityToken::generate().unwrap();
    let hex = t.to_hex();
    assert_eq!(hex.len(), 64);
    let back = CapabilityToken::from_hex(&hex).unwrap();
    assert_eq!(t, back);
    assert!(CapabilityToken::from_hex("short").is_none());
    assert!(CapabilityToken::from_hex(&"zz".repeat(32)).is_none());
}