stdio2http 0.3.1

MCP stdio -> Streamable HTTP proxy
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
//! End-to-end: a real stdio child behind the real HTTP proxy.
//!
//! The upstream is the deterministic fixture in `tests/fixtures/mock-mcp-server`
//! and the HTTP side is a real rmcp Streamable HTTP client, so these exercise
//! session ids, SSE framing, and protocol negotiation rather than stubbing them.

use std::net::SocketAddr;
use std::path::PathBuf;
use std::sync::Arc;

use clap::Parser;
use rmcp::ClientHandler;
use rmcp::model::{CallToolRequestParams, CallToolResponse, ContentBlock, JsonObject, Tool};
use rmcp::service::{Peer, RoleClient, RunningService, ServiceExt as _};
use rmcp::transport::StreamableHttpClientTransport;
use serde_json::{Value, json};
use stdio2http::config::Config;
use stdio2http::http;
use stdio2http::upstream::Upstream;

const KEY_ALICE: &str = "k-alice-secret";
const KEY_BOB: &str = "k-bob-secret";

/// Locate the fixture binary through cargo rather than assuming a target dir.
fn fixture_binary() -> PathBuf {
    let manifest =
        PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/mock-mcp-server/Cargo.toml");

    let output = std::process::Command::new(env!("CARGO"))
        .args([
            "metadata",
            "--manifest-path",
            manifest.to_str().expect("utf-8 manifest path"),
            "--format-version",
            "1",
            "--no-deps",
        ])
        .output()
        .expect("cargo metadata runs");

    assert!(
        output.status.success(),
        "cargo metadata failed: {}",
        String::from_utf8_lossy(&output.stderr)
    );

    let metadata: serde_json::Value =
        serde_json::from_slice(&output.stdout).expect("metadata is JSON");
    let target_dir = metadata["target_directory"]
        .as_str()
        .expect("metadata carries a target_directory");
    let profile = if cfg!(debug_assertions) {
        "debug"
    } else {
        "release"
    };

    PathBuf::from(target_dir)
        .join(profile)
        .join("mock-mcp-server")
}

/// Install a stderr subscriber once so `upstream_error`'s diagnostic is visible.
fn init_tracing() {
    use std::sync::Once;
    static ONCE: Once = Once::new();
    ONCE.call_once(|| {
        let filter = tracing_subscriber::EnvFilter::try_from_default_env()
            .unwrap_or_else(|_| tracing_subscriber::EnvFilter::new("info"));
        let _ = tracing_subscriber::fmt()
            .with_env_filter(filter)
            .with_writer(std::io::stderr)
            .try_init();
    });
}

fn test_config(extra: &[&str]) -> Config {
    let binary = fixture_binary();
    assert!(
        binary.exists(),
        "fixture not built at {}; run: cargo build --manifest-path tests/fixtures/mock-mcp-server/Cargo.toml",
        binary.display()
    );

    let mut flags = vec![
        "--command".to_string(),
        binary.to_string_lossy().into_owned(),
        "--port".to_string(),
        "0".to_string(),
    ];
    flags.extend(extra.iter().map(|flag| (*flag).to_string()));

    let mut full = vec!["stdio2http".to_string()];
    full.extend(flags);
    let cfg = Config::parse_from(full.iter().map(String::as_str));
    cfg.validate().expect("test config is valid");
    cfg
}

/// A running proxy: the shared child plus the HTTP listener in front of it.
///
/// The `Upstream` handle is kept alive for the harness's lifetime on purpose:
/// it owns the child's transport, so dropping it would close the pipe under the
/// proxy and make every session fail.
struct Harness {
    addr: SocketAddr,
    child_pid: Option<u32>,
    _upstream: Arc<Upstream>,
}

async fn start(extra: &[&str]) -> Harness {
    init_tracing();
    let cfg = test_config(extra);

    let upstream = Arc::new(Upstream::spawn(&cfg).await.expect("upstream spawns"));
    let child_pid = upstream.child_pid();
    assert!(child_pid.is_some(), "the proxy must own a child pid");

    let listener = http::bind(&cfg).await.expect("proxy binds");
    let addr = listener.local_addr().expect("listener has an address");
    let router = http::router(&cfg, &upstream, tokio_util::sync::CancellationToken::new());
    tokio::spawn(async move {
        let _ = axum::serve(listener, router).await;
    });

    Harness {
        addr,
        child_pid,
        _upstream: upstream,
    }
}

struct TestClient;

impl ClientHandler for TestClient {}

type Client = RunningService<RoleClient, TestClient>;

/// Connect a real MCP client over Streamable HTTP, optionally with a credential.
async fn connect_at(uri: &str, api_key: Option<&str>) -> std::result::Result<Client, String> {
    use rmcp::transport::streamable_http_client::StreamableHttpClientTransportConfig as TransportConfig;

    let mut config = TransportConfig::with_uri(uri);
    if let Some(key) = api_key {
        // rmcp expects the token without the `Bearer ` prefix; it adds the scheme.
        config = config.auth_header(key.to_string());
    }

    let transport = StreamableHttpClientTransport::with_client(reqwest::Client::new(), config);

    TestClient
        .serve(transport)
        .await
        .map_err(|error| format!("{error}"))
}

async fn connect(harness: &Harness, api_key: Option<&str>) -> std::result::Result<Client, String> {
    connect_at(&format!("http://{}/mcp", harness.addr), api_key).await
}

/// Connect, treating a failed handshake as a test failure.
async fn connect_ok(harness: &Harness, api_key: Option<&str>) -> Client {
    connect(harness, api_key)
        .await
        .unwrap_or_else(|error| panic!("handshake failed: {error}"))
}

fn tool_names(tools: &[Tool]) -> Vec<&str> {
    let mut names: Vec<&str> = tools.iter().map(|tool| tool.name.as_ref()).collect();
    names.sort_unstable();
    names
}

/// The fixture always answers with text; anything else is a test bug.
fn text_of(result: &rmcp::model::CallToolResult) -> String {
    result
        .content
        .iter()
        .map(|block| match block {
            ContentBlock::Text(text) => text.text.clone(),
            other => panic!("expected a text block, got {other:?}"),
        })
        .collect()
}

fn echo_args(message: &str) -> JsonObject {
    let mut args = JsonObject::new();
    args.insert("message".to_string(), json!(message));
    args
}

/// Unwrap a completed tool call, failing loudly on any other shape.
fn completed(response: CallToolResponse) -> rmcp::model::CallToolResult {
    match response {
        CallToolResponse::Complete(result) => result,
        other => panic!("expected a completed call, got {other:?}"),
    }
}

async fn call_echo(client: &Client, message: &str) -> String {
    let response = client
        .call_tool_once(CallToolRequestParams::new("echo").with_arguments(echo_args(message)))
        .await
        .expect("tools/call succeeds");
    text_of(&completed(response))
}

async fn call_whoami(client: &Client) -> String {
    let response = client
        .call_tool_once(CallToolRequestParams::new("whoami"))
        .await
        .expect("tools/call succeeds");
    text_of(&completed(response))
}

#[tokio::test]
async fn tools_list_over_http_matches_the_stub() {
    let harness = start(&[]).await;
    let client = connect_ok(&harness, None).await;

    let listed = client.list_all_tools().await.expect("tools/list succeeds");

    assert_eq!(tool_names(&listed), ["echo", "whoami"]);

    let echo = listed
        .iter()
        .find(|tool| tool.name == "echo")
        .expect("echo is advertised");
    assert_eq!(
        echo.input_schema.get("required"),
        Some(&json!(["message"])),
        "echo keeps its required argument: {:?}",
        echo.input_schema
    );
}

#[tokio::test]
async fn a_tool_call_round_trips() {
    let harness = start(&[]).await;
    let client = connect_ok(&harness, None).await;

    let response = client
        .call_tool_once(CallToolRequestParams::new("echo").with_arguments(echo_args("hello")))
        .await
        .expect("tools/call succeeds");
    let result = completed(response);

    assert!(!result.is_error.unwrap_or(false), "echo must succeed");
    assert_eq!(text_of(&result), "hello");
}

#[tokio::test]
async fn a_tool_error_reaches_the_client_as_a_tool_error() {
    let harness = start(&[]).await;
    let client = connect_ok(&harness, None).await;

    // Omitting `message` makes the fixture answer isError, not a JSON-RPC error.
    let response = client
        .call_tool_once(CallToolRequestParams::new("echo"))
        .await
        .expect("the request itself is well-formed");
    let result = completed(response);

    assert!(
        result.is_error.unwrap_or(false),
        "a missing argument must surface as a tool error: {result:?}"
    );
    assert!(text_of(&result).contains("message"), "{result:?}");
}

#[tokio::test]
async fn two_sessions_share_one_child() {
    let harness = start(&[]).await;

    let first = connect_ok(&harness, None).await;
    let second = connect_ok(&harness, None).await;

    assert_eq!(call_echo(&first, "first").await, "first");
    assert_eq!(call_echo(&second, "second").await, "second");

    // Re-reading from the first session proves both answers came from one child
    // rather than a per-session one: the value is not tied to the caller.
    assert_eq!(call_echo(&first, "again").await, "again");
    assert!(harness.child_pid.is_some());
}

#[tokio::test]
async fn concurrent_sessions_interleave_over_one_child() {
    let harness = start(&[]).await;
    let client = connect_ok(&harness, None).await;
    let peer: Peer<RoleClient> = client.peer().clone();

    let mut calls = Vec::new();
    for index in 0..8 {
        let peer = peer.clone();
        calls.push(tokio::spawn(async move {
            let message = format!("call-{index}");
            let response = peer
                .call_tool_once(
                    CallToolRequestParams::new("echo").with_arguments(echo_args(&message)),
                )
                .await;
            response.map(completed).map(|result| text_of(&result))
        }));
    }

    for (index, call) in calls.into_iter().enumerate() {
        let text = call
            .await
            .expect("task does not panic")
            .expect("call succeeds");
        assert_eq!(
            text,
            format!("call-{index}"),
            "rmcp multiplexes by request id"
        );
    }
}

#[tokio::test]
async fn bearer_mode_rejects_an_unauthenticated_handshake() {
    let harness = start(&["--auth-mode", "bearer", "--api-key", KEY_ALICE]).await;

    let uri = format!("http://{}/mcp", harness.addr);
    assert_401(&uri, None).await;
    assert!(
        connect(&harness, None).await.is_err(),
        "an unauthenticated handshake must fail"
    );
}

#[tokio::test]
async fn bearer_mode_accepts_a_configured_key() {
    let harness = start(&["--auth-mode", "bearer", "--api-key", KEY_ALICE]).await;

    let client = connect_ok(&harness, Some(KEY_ALICE)).await;
    let tools = client
        .list_all_tools()
        .await
        .expect("authenticated list succeeds");
    assert_eq!(tool_names(&tools), ["echo", "whoami"]);
}

#[tokio::test]
async fn bearer_mode_rejects_a_wrong_key() {
    let harness = start(&["--auth-mode", "bearer", "--api-key", KEY_ALICE]).await;

    let uri = format!("http://{}/mcp", harness.addr);
    assert_401(&uri, Some(KEY_BOB)).await;
    assert!(
        connect(&harness, Some(KEY_BOB)).await.is_err(),
        "a wrong key must fail"
    );
}

#[tokio::test]
async fn x_api_key_header_accepts_a_configured_key() {
    let harness = start(&["--auth-mode", "bearer", "--api-key", KEY_ALICE]).await;

    let session = raw_handshake_with_x_api_key(&harness, Some(KEY_ALICE)).await;
    let result = raw_rpc_with_x_api_key(
        &harness,
        &session,
        2,
        "tools/list",
        json!({}),
        Some(KEY_ALICE),
    )
    .await;
    assert!(
        result.get("tools").is_some(),
        "tools/list over X-API-Key must succeed: {result:?}"
    );
}

#[tokio::test]
async fn x_api_key_header_rejects_a_wrong_key() {
    let harness = start(&["--auth-mode", "bearer", "--api-key", KEY_ALICE]).await;

    let uri = format!("http://{}/mcp", harness.addr);
    assert_401_x_api_key(&uri, Some(KEY_BOB)).await;
}

#[tokio::test]
async fn identity_forward_yields_distinct_callers() {
    let harness = start(&[
        "--auth-mode",
        "identity-forward",
        "--api-key",
        &format!("{KEY_ALICE}=alice"),
        "--api-key",
        &format!("{KEY_BOB}=bob"),
    ])
    .await;

    let alice = connect_ok(&harness, Some(KEY_ALICE)).await;
    let bob = connect_ok(&harness, Some(KEY_BOB)).await;

    assert_eq!(call_whoami(&alice).await, "alice");
    assert_eq!(call_whoami(&bob).await, "bob");

    // Re-reading as alice shows the identity is per-request, not a one-time
    // label attached to the shared child.
    assert_eq!(call_whoami(&alice).await, "alice");
}

#[tokio::test]
async fn bearer_mode_authenticates_without_forwarding_identity() {
    let harness = start(&["--auth-mode", "bearer", "--api-key", KEY_ALICE]).await;
    let client = connect_ok(&harness, Some(KEY_ALICE)).await;

    assert_eq!(
        call_whoami(&client).await,
        "<none>",
        "bearer mode authenticates but forwards no identity"
    );
}

#[tokio::test]
async fn healthz_is_reachable_without_credentials() {
    let harness = start(&["--auth-mode", "bearer", "--api-key", KEY_ALICE]).await;

    let response = reqwest::get(format!("http://{}/healthz", harness.addr))
        .await
        .expect("healthz answers");

    assert_eq!(response.status(), 200);
    assert_eq!(response.text().await.expect("body reads"), "ok");
}

#[tokio::test]
async fn the_mount_path_is_configurable() {
    let harness = start(&["--mcp-path", "/rpc"]).await;
    let uri = format!("http://{}/rpc", harness.addr);

    let client = connect_at(&uri, None)
        .await
        .expect("connecting to the configured path must work");
    let tools = client.list_all_tools().await.expect("tools/list succeeds");
    assert_eq!(tool_names(&tools), ["echo", "whoami"]);

    // The default path is gone once remapped.
    let default_uri = format!("http://{}/mcp", harness.addr);
    assert!(
        connect_at(&default_uri, None).await.is_err(),
        "the default mount must not answer after remapping"
    );
}

#[tokio::test]
async fn an_upstream_failure_does_not_leak_child_stderr() {
    let harness = start(&[]).await;
    let client = connect_ok(&harness, None).await;

    let pid = harness.child_pid.expect("child pid recorded");
    let killed = std::process::Command::new("kill")
        .args(["-9", &pid.to_string()])
        .status()
        .expect("kill runs");
    assert!(killed.success(), "killing the child must succeed");

    let outcome = client
        .call_tool_once(CallToolRequestParams::new("echo").with_arguments(echo_args("gone")))
        .await;

    match outcome {
        Ok(response) => panic!(
            "a dead child must not answer: {}",
            text_of(&completed(response))
        ),
        Err(error) => {
            let rendered = format!("{error} {error:?}");
            for leak in [
                "panicked",
                "backtrace",
                "RUST_BACKTRACE",
                "mock-mcp-server",
                env!("CARGO_MANIFEST_DIR"),
            ] {
                assert!(
                    !rendered.contains(leak),
                    "error leaked {leak:?}: {rendered}"
                );
            }
            assert!(
                rendered.contains("internal_error") || rendered.contains("-32603"),
                "an upstream failure must map to internal_error: {rendered}"
            );
        }
    }

    let health = reqwest::get(format!("http://{}/healthz", harness.addr))
        .await
        .expect("healthz answers after upstream death");
    assert_eq!(health.status(), 503, "a dead child must surface as 503");
    assert_eq!(
        health.text().await.expect("body reads"),
        "upstream unavailable"
    );
}

#[tokio::test]
async fn a_child_that_exits_before_initializing_is_fatal() {
    let cfg = Config::parse_from([
        "stdio2http",
        "--command",
        "true",
        "--init-timeout-ms",
        "2000",
    ]);
    cfg.validate().expect("valid config");

    let error = Upstream::spawn(&cfg)
        .await
        .expect_err("a child that exits before initializing is fatal");
    let rendered = format!("{error:#}");

    assert!(
        rendered.contains("true"),
        "the error must name the program: {rendered}"
    );
}

#[tokio::test]
async fn spoofed_caller_meta_never_reaches_the_child() {
    let harness = start(&[]).await;
    let session = raw_handshake(&harness).await;

    let result = raw_rpc(
        &harness,
        &session,
        2,
        "tools/call",
        json!({
            "name": "whoami",
            "arguments": {},
            "_meta": {
                "io.stdio2http/caller": "mallory",
                "custom": "keep-me",
            },
        }),
    )
    .await;
    let text = result
        .get("content")
        .and_then(Value::as_array)
        .and_then(|content| content.first())
        .and_then(|block| block.get("text"))
        .and_then(Value::as_str)
        .unwrap_or_else(|| panic!("whoami result has no text content: {result}"));
    assert_eq!(
        text, "<none>",
        "a client-set caller must never reach the child"
    );
}

/// A raw MCP session over plain HTTP: the id the server issued plus the
/// protocol version it negotiated.
struct RawSession {
    id: String,
    version: String,
}

/// Parse a Streamable HTTP POST body: either one JSON object or SSE `data:` lines.
fn response_events(body: &str) -> Vec<Value> {
    if body.trim_start().starts_with('{') {
        return vec![serde_json::from_str(body).expect("response body is JSON")];
    }
    body.lines()
        .filter_map(|line| line.strip_prefix("data:"))
        .map(str::trim)
        .filter(|data| !data.is_empty())
        .map(|data| serde_json::from_str(data).expect("SSE data is JSON"))
        .collect()
}

fn post_raw(uri: &str, body: &Value, session: Option<&RawSession>) -> reqwest::RequestBuilder {
    let client = reqwest::Client::new();
    let request = client
        .post(uri)
        .header("content-type", "application/json")
        .header("accept", "application/json, text/event-stream")
        .json(body);
    match session {
        Some(session) => request
            .header("mcp-session-id", &session.id)
            .header("mcp-protocol-version", &session.version),
        None => request,
    }
}

fn with_auth(builder: reqwest::RequestBuilder, key: Option<&str>) -> reqwest::RequestBuilder {
    if let Some(key) = key {
        builder.header("authorization", format!("Bearer {key}"))
    } else {
        builder
    }
}

/// Full handshake over raw HTTP with an optional credential.
async fn raw_handshake_with_key(harness: &Harness, key: Option<&str>) -> RawSession {
    let uri = format!("http://{}/mcp", harness.addr);
    let body = json!({
        "jsonrpc": "2.0",
        "id": 1,
        "method": "initialize",
        "params": {
            "protocolVersion": "2025-11-25",
            "capabilities": {},
            "clientInfo": {"name": "raw-e2e", "version": "0.0.0"},
        },
    });
    let response = with_auth(post_raw(&uri, &body, None), key)
        .send()
        .await
        .expect("initialize is answered");
    assert_eq!(response.status(), 200, "initialize must succeed");
    let id = response
        .headers()
        .get("mcp-session-id")
        .expect("initialize issues a session id")
        .to_str()
        .expect("session id is ascii")
        .to_owned();
    let text = response.text().await.expect("body reads");
    let version = response_events(&text)
        .iter()
        .find(|event| event.get("id") == Some(&json!(1)))
        .and_then(|event| event.get("result"))
        .and_then(|result| result.get("protocolVersion"))
        .and_then(Value::as_str)
        .unwrap_or_else(|| panic!("no initialize result in {text:?}"))
        .to_owned();
    let session = RawSession { id, version };

    let initialized = json!({"jsonrpc": "2.0", "method": "notifications/initialized"});
    let response = with_auth(post_raw(&uri, &initialized, Some(&session)), key)
        .send()
        .await
        .expect("initialized is accepted");
    assert_eq!(response.status(), 202, "initialized must be accepted");
    session
}

/// Full handshake over raw HTTP: `initialize` (id 1), then `notifications/initialized`.
async fn raw_handshake(harness: &Harness) -> RawSession {
    raw_handshake_with_key(harness, None).await
}

/// One request/response round-trip inside `session`, returning the `result`.
async fn raw_rpc(
    harness: &Harness,
    session: &RawSession,
    id: i64,
    method: &str,
    params: Value,
) -> Value {
    raw_rpc_with_key(harness, session, id, method, params, None).await
}

/// Same as [`raw_rpc`] with an optional credential.
async fn raw_rpc_with_key(
    harness: &Harness,
    session: &RawSession,
    id: i64,
    method: &str,
    params: Value,
    key: Option<&str>,
) -> Value {
    let uri = format!("http://{}/mcp", harness.addr);
    let body = json!({"jsonrpc": "2.0", "id": id, "method": method, "params": params});
    let response = with_auth(post_raw(&uri, &body, Some(session)), key)
        .send()
        .await
        .unwrap_or_else(|error| panic!("{method} is answered: {error}"));
    assert_eq!(response.status(), 200, "{method} must succeed");
    let text = response.text().await.expect("body reads");
    let event = response_events(&text)
        .into_iter()
        .find(|event| event.get("id") == Some(&json!(id)))
        .unwrap_or_else(|| panic!("no {method} event in {text:?}"));
    if let Some(error) = event.get("error") {
        panic!("server answered with a JSON-RPC error: {error}");
    }
    event
        .get("result")
        .cloned()
        .unwrap_or_else(|| panic!("response has neither result nor error: {event}"))
}

/// POST inside `session` with a credential, returning status and body for
/// negative assertions.
async fn raw_post_status(
    harness: &Harness,
    session: &RawSession,
    id: i64,
    method: &str,
    params: Value,
    key: Option<&str>,
) -> (reqwest::StatusCode, String) {
    let uri = format!("http://{}/mcp", harness.addr);
    let body = json!({"jsonrpc": "2.0", "id": id, "method": method, "params": params});
    let response = with_auth(post_raw(&uri, &body, Some(session)), key)
        .send()
        .await
        .expect("proxy answers");
    let status = response.status();
    let text = response.text().await.expect("body reads");
    (status, text)
}

fn bearer_harness_args() -> Vec<&'static str> {
    vec![
        "--auth-mode",
        "bearer",
        "--api-key",
        KEY_ALICE,
        "--api-key",
        KEY_BOB,
    ]
}

#[tokio::test]
async fn another_key_cannot_delete_a_session() {
    let harness = start(&bearer_harness_args()).await;
    let alice = raw_handshake_with_key(&harness, Some(KEY_ALICE)).await;

    let uri = format!("http://{}/mcp", harness.addr);
    let response = reqwest::Client::new()
        .delete(&uri)
        .header("mcp-session-id", &alice.id)
        .header("mcp-protocol-version", &alice.version)
        .header("authorization", format!("Bearer {KEY_BOB}"))
        .send()
        .await
        .expect("proxy answers");
    assert_eq!(response.status(), 404);
    assert_eq!(
        response.text().await.expect("body reads"),
        "Not Found: Session not found"
    );

    let result = raw_rpc_with_key(
        &harness,
        &alice,
        2,
        "tools/list",
        json!({}),
        Some(KEY_ALICE),
    )
    .await;
    assert!(
        result.get("tools").is_some(),
        "owner session still works: {result:?}"
    );
}

#[tokio::test]
async fn another_key_cannot_resume_a_session() {
    let harness = start(&bearer_harness_args()).await;
    let alice = raw_handshake_with_key(&harness, Some(KEY_ALICE)).await;

    let uri = format!("http://{}/mcp", harness.addr);
    let response = reqwest::Client::new()
        .get(&uri)
        .header("mcp-session-id", &alice.id)
        .header("mcp-protocol-version", &alice.version)
        .header("last-event-id", "0/0")
        .header("accept", "application/json, text/event-stream")
        .header("authorization", format!("Bearer {KEY_BOB}"))
        .send()
        .await
        .expect("proxy answers");
    assert_eq!(response.status(), 404);
    assert_eq!(
        response.text().await.expect("body reads"),
        "Not Found: Session not found"
    );
}

#[tokio::test]
async fn another_key_cannot_post_to_a_session() {
    let harness = start(&bearer_harness_args()).await;
    let alice = raw_handshake_with_key(&harness, Some(KEY_ALICE)).await;

    let (status, body) =
        raw_post_status(&harness, &alice, 2, "tools/list", json!({}), Some(KEY_BOB)).await;
    assert_eq!(status, 404);
    assert_eq!(body, "Not Found: Session not found");
}

#[tokio::test]
async fn owner_can_delete_own_session() {
    let harness = start(&bearer_harness_args()).await;
    let alice = raw_handshake_with_key(&harness, Some(KEY_ALICE)).await;

    let uri = format!("http://{}/mcp", harness.addr);
    let response = reqwest::Client::new()
        .delete(&uri)
        .header("mcp-session-id", &alice.id)
        .header("mcp-protocol-version", &alice.version)
        .header("authorization", format!("Bearer {KEY_ALICE}"))
        .send()
        .await
        .expect("proxy answers");
    assert_eq!(response.status(), 202);

    let (status, body) = raw_post_status(
        &harness,
        &alice,
        2,
        "tools/list",
        json!({}),
        Some(KEY_ALICE),
    )
    .await;
    assert_eq!(status, 404);
    assert_eq!(body, "Not Found: Session not found");
}

fn with_x_api_key(builder: reqwest::RequestBuilder, key: Option<&str>) -> reqwest::RequestBuilder {
    if let Some(key) = key {
        builder.header("x-api-key", key)
    } else {
        builder
    }
}

/// Full handshake over raw HTTP with the `X-API-Key` header.
async fn raw_handshake_with_x_api_key(harness: &Harness, key: Option<&str>) -> RawSession {
    let uri = format!("http://{}/mcp", harness.addr);
    let body = json!({
        "jsonrpc": "2.0",
        "id": 1,
        "method": "initialize",
        "params": {
            "protocolVersion": "2025-11-25",
            "capabilities": {},
            "clientInfo": {"name": "raw-e2e", "version": "0.0.0"},
        },
    });
    let response = with_x_api_key(post_raw(&uri, &body, None), key)
        .send()
        .await
        .expect("initialize is answered");
    assert_eq!(response.status(), 200, "initialize must succeed");
    let id = response
        .headers()
        .get("mcp-session-id")
        .expect("initialize issues a session id")
        .to_str()
        .expect("session id is ascii")
        .to_owned();
    let text = response.text().await.expect("body reads");
    let version = response_events(&text)
        .iter()
        .find(|event| event.get("id") == Some(&json!(1)))
        .and_then(|event| event.get("result"))
        .and_then(|result| result.get("protocolVersion"))
        .and_then(Value::as_str)
        .unwrap_or_else(|| panic!("no initialize result in {text:?}"))
        .to_owned();
    let session = RawSession { id, version };

    let initialized = json!({"jsonrpc": "2.0", "method": "notifications/initialized"});
    let response = with_x_api_key(post_raw(&uri, &initialized, Some(&session)), key)
        .send()
        .await
        .expect("initialized is accepted");
    assert_eq!(response.status(), 202, "initialized must be accepted");
    session
}

/// One request/response round-trip inside `session` with the `X-API-Key` header.
async fn raw_rpc_with_x_api_key(
    harness: &Harness,
    session: &RawSession,
    id: i64,
    method: &str,
    params: Value,
    key: Option<&str>,
) -> Value {
    let uri = format!("http://{}/mcp", harness.addr);
    let body = json!({"jsonrpc": "2.0", "id": id, "method": method, "params": params});
    let response = with_x_api_key(post_raw(&uri, &body, Some(session)), key)
        .send()
        .await
        .unwrap_or_else(|error| panic!("{method} is answered: {error}"));
    assert_eq!(response.status(), 200, "{method} must succeed");
    let text = response.text().await.expect("body reads");
    let event = response_events(&text)
        .into_iter()
        .find(|event| event.get("id") == Some(&json!(id)))
        .unwrap_or_else(|| panic!("no {method} event in {text:?}"));
    if let Some(error) = event.get("error") {
        panic!("server answered with a JSON-RPC error: {error}");
    }
    event
        .get("result")
        .cloned()
        .unwrap_or_else(|| panic!("response has neither result nor error: {event}"))
}

/// Assert the proxy answers 401 with a challenge for the `X-API-Key` header.
async fn assert_401_x_api_key(uri: &str, api_key: Option<&str>) {
    let mut request = reqwest::Client::new()
        .post(uri)
        .header("content-type", "application/json")
        .body(r#"{"jsonrpc":"2.0","id":0,"method":"initialize"}"#);
    if let Some(key) = api_key {
        request = request.header("x-api-key", key);
    }

    let response = request.send().await.expect("proxy answers");
    assert_eq!(response.status(), 401, "expected a 401 for {api_key:?}");

    let challenge = response
        .headers()
        .get("www-authenticate")
        .expect("a challenge header is required")
        .to_str()
        .expect("challenge is ascii");
    assert_eq!(challenge, "Bearer realm=\"mcp\"", "unexpected challenge");

    let body = response.text().await.expect("body reads");
    for leak in [KEY_ALICE, KEY_BOB] {
        assert!(!body.contains(leak), "401 body leaked a key: {body}");
    }
}

/// Assert the proxy answers 401 with a challenge, and echoes no key.
async fn assert_401(uri: &str, api_key: Option<&str>) {
    let mut request = reqwest::Client::new()
        .post(uri)
        .header("content-type", "application/json")
        .body(r#"{"jsonrpc":"2.0","id":0,"method":"initialize"}"#);
    if let Some(key) = api_key {
        request = request.header("authorization", format!("Bearer {key}"));
    }

    let response = request.send().await.expect("proxy answers");
    assert_eq!(response.status(), 401, "expected a 401 for {api_key:?}");

    let challenge = response
        .headers()
        .get("www-authenticate")
        .expect("a challenge header is required")
        .to_str()
        .expect("challenge is ascii");
    assert_eq!(challenge, "Bearer realm=\"mcp\"", "unexpected challenge");

    let body = response.text().await.expect("body reads");
    for leak in [KEY_ALICE, KEY_BOB] {
        assert!(!body.contains(leak), "401 body leaked a key: {body}");
    }
}