supercode-harness 0.4.11

The optional native Supercode agent and tool harness
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
//! P5-2 (COMPOSABLE-HARNESS-DESIGN.md §2 module 15 D7 row 2 "remote
//! HTTP/SSE"): remote MCP transport tests. Every test spins up a minimal
//! raw-HTTP loopback server (the same idiom `provider.rs`/
//! `p4c_tool_new_smalls.rs` already use) — NEVER a real external MCP server
//! (`live-agent-test-safety`).

use std::collections::BTreeMap;

use supercode_harness::mcp::McpClient;

async fn spawn_http_server(
    handler: impl Fn(&str) -> String + Send + Sync + 'static,
) -> (std::net::SocketAddr, tokio::task::JoinHandle<()>) {
    use tokio::io::{AsyncReadExt, AsyncWriteExt};
    let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
    let addr = listener.local_addr().unwrap();
    let handler = std::sync::Arc::new(handler);
    let handle = tokio::spawn(async move {
        loop {
            let Ok((mut sock, _)) = listener.accept().await else {
                break;
            };
            let handler = handler.clone();
            tokio::spawn(async move {
                let mut buf = vec![0u8; 65536];
                let n = match sock.read(&mut buf).await {
                    Ok(n) => n,
                    Err(_) => return,
                };
                let text = String::from_utf8_lossy(&buf[..n]);
                let body = text.split("\r\n\r\n").nth(1).unwrap_or("");
                let response = handler(body);
                let _ = sock.write_all(response.as_bytes()).await;
                let _ = sock.flush().await;
            });
        }
    });
    (addr, handle)
}

fn http_json_200(body: &str) -> String {
    format!(
        "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
        body.len(),
        body
    )
}

fn json_rpc_id(body: &str) -> i64 {
    let v: serde_json::Value = serde_json::from_str(body).unwrap_or_default();
    v.get("id").and_then(serde_json::Value::as_i64).unwrap_or(0)
}

fn json_rpc_method(body: &str) -> String {
    let v: serde_json::Value = serde_json::from_str(body).unwrap_or_default();
    v.get("method")
        .and_then(serde_json::Value::as_str)
        .unwrap_or_default()
        .to_string()
}

// ---- http (streamable, non-streaming) transport ---------------------------

#[tokio::test]
async fn http_transport_connects_lists_and_calls_a_tool() {
    let (addr, _server) = spawn_http_server(|body| {
        let id = json_rpc_id(body);
        let method = json_rpc_method(body);
        let result = match method.as_str() {
            "initialize" => {
                serde_json::json!({"protocolVersion":"2025-06-18","serverInfo":{"name":"fake-http"},"instructions":"be nice"})
            }
            "notifications/initialized" => return http_json_200(""),
            "tools/list" => serde_json::json!({"tools":[
                {"name":"echo","description":"echo back","inputSchema":{"type":"object"}}
            ]}),
            "tools/call" => serde_json::json!({"content":[{"type":"text","text":"echo: hi"}],"isError":false}),
            _ => serde_json::json!({}),
        };
        http_json_200(&serde_json::json!({"jsonrpc":"2.0","id":id,"result":result}).to_string())
    })
    .await;

    let url = format!("http://127.0.0.1:{}/mcp", addr.port());
    let mut client = McpClient::connect_http(&url, &BTreeMap::new(), None)
        .await
        .unwrap();
    assert_eq!(client.instructions.as_deref(), Some("be nice"));

    let tools = client.list_tools().await.unwrap();
    assert_eq!(tools.len(), 1);
    assert_eq!(tools[0].name, "echo");

    let out = client
        .call_tool("echo", serde_json::json!({"text": "hi"}))
        .await
        .unwrap();
    assert_eq!(out, "echo: hi");
}

#[tokio::test]
async fn http_transport_sends_configured_headers() {
    let seen_auth: std::sync::Arc<std::sync::Mutex<Option<String>>> =
        std::sync::Arc::new(std::sync::Mutex::new(None));
    let seen_auth2 = seen_auth.clone();
    use tokio::io::{AsyncReadExt, AsyncWriteExt};
    let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
    let addr = listener.local_addr().unwrap();
    let _server = tokio::spawn(async move {
        loop {
            let Ok((mut sock, _)) = listener.accept().await else {
                break;
            };
            let seen_auth2 = seen_auth2.clone();
            tokio::spawn(async move {
                let mut buf = vec![0u8; 65536];
                let n = sock.read(&mut buf).await.unwrap_or(0);
                let text = String::from_utf8_lossy(&buf[..n]).to_string();
                for line in text.lines() {
                    // `HeaderName` always serializes lowercase on the wire
                    // regardless of the case it was constructed with — match
                    // the NAME case-insensitively, but keep the value as-is.
                    if let Some((name, value)) = line.split_once(':') {
                        if name.eq_ignore_ascii_case("authorization") {
                            *seen_auth2.lock().unwrap() = Some(value.trim().to_string());
                        }
                    }
                }
                let body = text.split("\r\n\r\n").nth(1).unwrap_or("");
                let id = json_rpc_id(body);
                let resp = http_json_200(
                    &serde_json::json!({"jsonrpc":"2.0","id":id,"result":{"protocolVersion":"2025-06-18","serverInfo":{"name":"f"}}}).to_string(),
                );
                let _ = sock.write_all(resp.as_bytes()).await;
                let _ = sock.flush().await;
            });
        }
    });
    let mut headers = BTreeMap::new();
    headers.insert(
        "Authorization".to_string(),
        "Bearer secret-token".to_string(),
    );
    let url = format!("http://127.0.0.1:{}/mcp", addr.port());
    let _client = McpClient::connect_http(&url, &headers, None).await.unwrap();
    assert_eq!(
        seen_auth.lock().unwrap().as_deref(),
        Some("Bearer secret-token"),
        "the configured Authorization header must reach the server"
    );
}

#[tokio::test]
async fn http_transport_reports_a_clean_error_on_embedded_server_request() {
    // A server that tries to elicit mid-call over the non-streaming http
    // transport — this client must fail closed with a clear error, never
    // hang or silently drop the elicitation.
    let (addr, _server) = spawn_http_server(|body| {
        let method = json_rpc_method(body);
        if method == "initialize" {
            let id = json_rpc_id(body);
            return http_json_200(
                &serde_json::json!({"jsonrpc":"2.0","id":id,"result":{"protocolVersion":"2025-06-18","serverInfo":{"name":"f"}}}).to_string(),
            );
        }
        if method == "notifications/initialized" {
            return http_json_200("");
        }
        // tools/call: respond with an embedded elicitation REQUEST instead
        // of the tool's result.
        http_json_200(
            &serde_json::json!({"jsonrpc":"2.0","id":999,"method":"elicitation/create","params":{"message":"need input"}}).to_string(),
        )
    })
    .await;
    let url = format!("http://127.0.0.1:{}/mcp", addr.port());
    let mut client = McpClient::connect_http(&url, &BTreeMap::new(), None)
        .await
        .unwrap();
    let err = client
        .call_tool("whatever", serde_json::json!({}))
        .await
        .unwrap_err();
    assert!(
        err.to_string().contains("stdio or sse"),
        "error should name the supported transports: {err}"
    );
}

#[tokio::test]
async fn network_policy_denies_a_disallowed_http_host_before_connecting() {
    use std::sync::atomic::{AtomicBool, Ordering};
    use tokio::io::AsyncReadExt;
    let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
    let addr = listener.local_addr().unwrap();
    let connected = std::sync::Arc::new(AtomicBool::new(false));
    let connected2 = connected.clone();
    tokio::spawn(async move {
        if let Ok((mut sock, _)) = listener.accept().await {
            connected2.store(true, Ordering::SeqCst);
            let mut buf = [0u8; 1024];
            let _ = sock.read(&mut buf).await;
        }
    });
    let policy = supercode_harness::tools::NetworkPolicy {
        enabled: true,
        allow_domains: vec![],
        deny_domains: vec!["127.0.0.1".to_string()],
    };
    let url = format!("http://127.0.0.1:{}/mcp", addr.port());
    let result = McpClient::connect_http(&url, &BTreeMap::new(), Some(&policy)).await;
    assert!(result.is_err(), "a denied host must not connect");
    tokio::time::sleep(std::time::Duration::from_millis(50)).await;
    assert!(
        !connected.load(Ordering::SeqCst),
        "the denied host must never even be contacted"
    );
}

#[tokio::test]
async fn reconnect_reapplies_the_original_network_policy_and_still_succeeds_when_allowed() {
    // No-over-block confirmation (Fable-5 review, latent-SSRF-landmine fix):
    // `reconnect()` now re-runs `connect_http`'s pre-connect NetworkPolicy
    // check using the client's OWN remembered policy instead of `None` —
    // this proves that doesn't regress the legitimate case: a reconnect to
    // a still-allowed host must keep working exactly as before. The
    // fail-closed half (a denied host must be refused on reconnect) is
    // pinned by `mcp::tests::reconnect_denies_a_disallowed_host_before_reconnecting`
    // in mcp.rs's own unit tests (needs private-field access to construct
    // an already-"connected" client under a denying policy, since a real
    // `connect_http` under a denying policy can never succeed in the first
    // place — see that test's doc comment for why it lives there).
    let (addr, _server) = spawn_http_server(|body| {
        let id = json_rpc_id(body);
        let method = json_rpc_method(body);
        let result = match method.as_str() {
            "initialize" => {
                serde_json::json!({"protocolVersion":"2025-06-18","serverInfo":{"name":"fake-http"}})
            }
            "notifications/initialized" => return http_json_200(""),
            _ => serde_json::json!({}),
        };
        http_json_200(&serde_json::json!({"jsonrpc":"2.0","id":id,"result":result}).to_string())
    })
    .await;
    let url = format!("http://127.0.0.1:{}/mcp", addr.port());
    let policy = supercode_harness::tools::NetworkPolicy {
        enabled: true,
        allow_domains: vec!["127.0.0.1".to_string()],
        deny_domains: vec![],
    };
    let client = McpClient::connect_http(&url, &BTreeMap::new(), Some(&policy))
        .await
        .unwrap();
    let _reconnected = client
        .reconnect()
        .await
        .expect("reconnect under an allowing policy must still succeed");
}

// ---- hardening: response/frame/resource size caps --------------------------

#[tokio::test]
async fn http_response_body_over_the_cap_errors_named_not_oom_or_hang() {
    // A hostile/misbehaving configured MCP server declares a Content-Length
    // far past MCP_MAX_RESPONSE_BYTES — this must be rejected by the fast
    // pre-check BEFORE this client tries to buffer anything close to that
    // size (never OOM, never hang).
    use tokio::io::{AsyncReadExt, AsyncWriteExt};
    let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
    let addr = listener.local_addr().unwrap();
    tokio::spawn(async move {
        loop {
            let Ok((mut sock, _)) = listener.accept().await else {
                break;
            };
            tokio::spawn(async move {
                let mut buf = vec![0u8; 65536];
                let n = sock.read(&mut buf).await.unwrap_or(0);
                let text = String::from_utf8_lossy(&buf[..n]).to_string();
                let body = text.split("\r\n\r\n").nth(1).unwrap_or("");
                let method = json_rpc_method(body);
                if method == "initialize" {
                    let id = json_rpc_id(body);
                    let resp = http_json_200(
                        &serde_json::json!({"jsonrpc":"2.0","id":id,"result":{"protocolVersion":"2025-06-18","serverInfo":{"name":"f"}}}).to_string(),
                    );
                    let _ = sock.write_all(resp.as_bytes()).await;
                    let _ = sock.flush().await;
                    return;
                }
                let oversized = supercode_harness::mcp::MCP_MAX_RESPONSE_BYTES + 1;
                let headers = format!(
                    "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {oversized}\r\nConnection: close\r\n\r\n"
                );
                let _ = sock.write_all(headers.as_bytes()).await;
                // Never actually send `oversized` bytes — the pre-check on
                // the declared Content-Length must reject this before this
                // client reads (or this server writes) anything close to
                // that much data.
                let _ = sock.write_all(b"{}").await;
                let _ = sock.flush().await;
            });
        }
    });
    let url = format!("http://127.0.0.1:{}/mcp", addr.port());
    let mut client = McpClient::connect_http(&url, &BTreeMap::new(), None)
        .await
        .unwrap();
    let result = tokio::time::timeout(
        std::time::Duration::from_secs(5),
        client.call_tool("whatever", serde_json::json!({})),
    )
    .await
    .expect("must not hang");
    let err = result.expect_err("an oversized declared body must error, never succeed");
    assert!(
        err.to_string().contains("exceeds max"),
        "error should name the cap: {err}"
    );
}

#[tokio::test]
async fn http_response_streamed_body_over_the_cap_errors_named_not_oom_or_hang() {
    // Same cap, but a hostile server that OMITS Content-Length (chunked,
    // unbounded from the client's perspective) and actually streams past
    // the cap — proves the streaming enforcement (not just the
    // Content-Length pre-check) also fails closed, without this client
    // ever buffering past MCP_MAX_RESPONSE_BYTES.
    use tokio::io::{AsyncReadExt, AsyncWriteExt};
    let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
    let addr = listener.local_addr().unwrap();
    tokio::spawn(async move {
        loop {
            let Ok((mut sock, _)) = listener.accept().await else {
                break;
            };
            tokio::spawn(async move {
                let mut buf = vec![0u8; 65536];
                let n = sock.read(&mut buf).await.unwrap_or(0);
                let text = String::from_utf8_lossy(&buf[..n]).to_string();
                let body = text.split("\r\n\r\n").nth(1).unwrap_or("");
                let method = json_rpc_method(body);
                if method == "initialize" {
                    let id = json_rpc_id(body);
                    let resp = http_json_200(
                        &serde_json::json!({"jsonrpc":"2.0","id":id,"result":{"protocolVersion":"2025-06-18","serverInfo":{"name":"f"}}}).to_string(),
                    );
                    let _ = sock.write_all(resp.as_bytes()).await;
                    let _ = sock.flush().await;
                    return;
                }
                let headers =
                    "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nTransfer-Encoding: chunked\r\n\r\n";
                let _ = sock.write_all(headers.as_bytes()).await;
                let chunk = vec![b'x'; 1024 * 1024]; // 1 MiB per chunk
                let mut framed = format!("{:x}\r\n", chunk.len()).into_bytes();
                framed.extend_from_slice(&chunk);
                framed.extend_from_slice(b"\r\n");
                let chunks_needed =
                    supercode_harness::mcp::MCP_MAX_RESPONSE_BYTES / (1024 * 1024) + 2;
                for _ in 0..chunks_needed {
                    if sock.write_all(&framed).await.is_err() {
                        break;
                    }
                }
                let _ = sock.write_all(b"0\r\n\r\n").await;
                let _ = sock.flush().await;
            });
        }
    });
    let url = format!("http://127.0.0.1:{}/mcp", addr.port());
    let mut client = McpClient::connect_http(&url, &BTreeMap::new(), None)
        .await
        .unwrap();
    let result = tokio::time::timeout(
        std::time::Duration::from_secs(30),
        client.call_tool("whatever", serde_json::json!({})),
    )
    .await
    .expect("must not hang");
    let err = result.expect_err("an oversized streamed body must error, never succeed");
    assert!(
        err.to_string().contains("exceeded max"),
        "error should name the cap: {err}"
    );
}

// ---- sse (legacy http+sse) transport ---------------------------------------

/// A raw SSE + message-post loopback server: the SSE `GET` connection
/// writes headers, the `endpoint` event, then relays whatever is pushed on
/// `push_rx` (chunk-framed) until the test drops the sender. Every `POST`
/// (a client->server message) is forwarded to `post_tx`. Returns the
/// listener address plus both channel handles so a test can drive a
/// request/response sequence, including injecting an out-of-band
/// notification or server-initiated request between a client request and
/// its eventual response.
async fn spawn_sse_server() -> (
    std::net::SocketAddr,
    tokio::sync::mpsc::UnboundedSender<String>,
    tokio::sync::mpsc::UnboundedReceiver<String>,
) {
    use tokio::io::{AsyncReadExt, AsyncWriteExt};
    let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
    let addr = listener.local_addr().unwrap();
    let (push_tx, push_rx) = tokio::sync::mpsc::unbounded_channel::<String>();
    let (post_tx, post_rx) = tokio::sync::mpsc::unbounded_channel::<String>();

    // A single accept loop that dispatches EACH connection to its own task —
    // the long-lived GET/SSE connection must never block accepting the
    // separate POST connections the client makes for its own requests.
    let post_tx = std::sync::Arc::new(post_tx);
    // `push_rx` is only ever consumed by the (single) GET/SSE connection —
    // move it into that connection's task the first time a GET arrives.
    let push_rx = std::sync::Arc::new(tokio::sync::Mutex::new(Some(push_rx)));
    tokio::spawn(async move {
        loop {
            let Ok((mut sock, _)) = listener.accept().await else {
                break;
            };
            let post_tx = post_tx.clone();
            let push_rx = push_rx.clone();
            tokio::spawn(async move {
                let mut buf = vec![0u8; 65536];
                let n = match sock.read(&mut buf).await {
                    Ok(n) => n,
                    Err(_) => return,
                };
                let text = String::from_utf8_lossy(&buf[..n]).to_string();
                let first_line = text.lines().next().unwrap_or("").to_string();
                if first_line.starts_with("GET") {
                    let Some(mut push_rx) = push_rx.lock().await.take() else {
                        return;
                    };
                    let headers = "HTTP/1.1 200 OK\r\nContent-Type: text/event-stream\r\nTransfer-Encoding: chunked\r\nConnection: close\r\n\r\n";
                    let _ = sock.write_all(headers.as_bytes()).await;
                    write_chunk(&mut sock, "event: endpoint\ndata: /messages\n\n").await;
                    while let Some(payload) = push_rx.recv().await {
                        write_chunk(&mut sock, &payload).await;
                    }
                } else if first_line.starts_with("POST") {
                    let body = text.split("\r\n\r\n").nth(1).unwrap_or("").to_string();
                    let _ = post_tx.send(body);
                    let resp =
                        "HTTP/1.1 202 Accepted\r\nContent-Length: 0\r\nConnection: close\r\n\r\n";
                    let _ = sock.write_all(resp.as_bytes()).await;
                    let _ = sock.flush().await;
                }
            });
        }
    });

    (addr, push_tx, post_rx)
}

async fn write_chunk(sock: &mut tokio::net::TcpStream, data: &str) {
    use tokio::io::AsyncWriteExt;
    let framed = format!("{:x}\r\n{data}\r\n", data.len());
    let _ = sock.write_all(framed.as_bytes()).await;
    let _ = sock.flush().await;
}

/// Complete the `initialize` handshake against a [`spawn_sse_server`]
/// backend: waits for the POST, replies over the push channel, and drains
/// the client's follow-up `notifications/initialized` notification.
async fn answer_initialize(
    push_tx: &tokio::sync::mpsc::UnboundedSender<String>,
    post_rx: &mut tokio::sync::mpsc::UnboundedReceiver<String>,
    instructions: Option<&str>,
) {
    let body = post_rx.recv().await.unwrap();
    assert_eq!(json_rpc_method(&body), "initialize");
    let id = json_rpc_id(&body);
    let mut result =
        serde_json::json!({"protocolVersion":"2025-06-18","serverInfo":{"name":"sse-fake"}});
    if let Some(instr) = instructions {
        result["instructions"] = serde_json::Value::String(instr.to_string());
    }
    let msg = serde_json::json!({"jsonrpc":"2.0","id":id,"result":result});
    push_tx
        .send(format!("event: message\ndata: {msg}\n\n"))
        .unwrap();
    let notif = post_rx.recv().await.unwrap();
    assert_eq!(json_rpc_method(&notif), "notifications/initialized");
}

#[tokio::test]
async fn sse_transport_discovers_endpoint_and_completes_initialize() {
    let (addr, push_tx, mut post_rx) = spawn_sse_server().await;
    let url = format!("http://127.0.0.1:{}/sse", addr.port());
    let connect_task =
        tokio::spawn(async move { McpClient::connect_sse(&url, &BTreeMap::new(), None).await });
    answer_initialize(&push_tx, &mut post_rx, Some("sse instructions")).await;
    let client = connect_task.await.unwrap().unwrap();
    assert_eq!(client.instructions.as_deref(), Some("sse instructions"));
}

#[tokio::test]
async fn sse_transport_lists_and_calls_a_tool() {
    let (addr, push_tx, mut post_rx) = spawn_sse_server().await;
    let url = format!("http://127.0.0.1:{}/sse", addr.port());
    let connect_task =
        tokio::spawn(async move { McpClient::connect_sse(&url, &BTreeMap::new(), None).await });
    answer_initialize(&push_tx, &mut post_rx, None).await;
    let mut client = connect_task.await.unwrap().unwrap();

    let list_task = tokio::spawn(async move {
        let tools = client.list_tools().await.unwrap();
        (client, tools)
    });
    let body = post_rx.recv().await.unwrap();
    assert_eq!(json_rpc_method(&body), "tools/list");
    let id = json_rpc_id(&body);
    let msg = serde_json::json!({"jsonrpc":"2.0","id":id,"result":{"tools":[{"name":"echo","description":"d","inputSchema":{"type":"object"}}]}});
    push_tx
        .send(format!("event: message\ndata: {msg}\n\n"))
        .unwrap();
    let (mut client, tools) = list_task.await.unwrap();
    assert_eq!(tools.len(), 1);
    assert_eq!(tools[0].name, "echo");

    let call_task =
        tokio::spawn(async move { client.call_tool("echo", serde_json::json!({})).await });
    let body = post_rx.recv().await.unwrap();
    let id = json_rpc_id(&body);
    let msg = serde_json::json!({"jsonrpc":"2.0","id":id,"result":{"content":[{"type":"text","text":"echoed"}],"isError":false}});
    push_tx
        .send(format!("event: message\ndata: {msg}\n\n"))
        .unwrap();
    let out = call_task.await.unwrap().unwrap();
    assert_eq!(out, "echoed");
}

#[tokio::test]
async fn sse_transport_answers_a_server_initiated_elicitation_request() {
    // The server sends an `elicitation/create` REQUEST (id + method) mid
    // `tools/call`; the client's headless-default handler must decline it
    // and keep waiting for the tool's own eventual response — proving the
    // bidirectional read loop handles a server->client request without
    // getting stuck or corrupting the pending client request's response.
    let (addr, push_tx, mut post_rx) = spawn_sse_server().await;
    let url = format!("http://127.0.0.1:{}/sse", addr.port());
    let connect_task =
        tokio::spawn(async move { McpClient::connect_sse(&url, &BTreeMap::new(), None).await });
    answer_initialize(&push_tx, &mut post_rx, None).await;
    let mut client = connect_task.await.unwrap().unwrap();

    let call_task = tokio::spawn(async move {
        let out = client.call_tool("needs_input", serde_json::json!({})).await;
        (client, out)
    });

    let body = post_rx.recv().await.unwrap();
    assert_eq!(json_rpc_method(&body), "tools/call");
    let call_id = json_rpc_id(&body);
    let elicit = serde_json::json!({"jsonrpc":"2.0","id":4242,"method":"elicitation/create","params":{"message":"need a value","requestedSchema":{}}});
    push_tx
        .send(format!("event: message\ndata: {elicit}\n\n"))
        .unwrap();

    // The client must reply to it (declining, headless-default) via a POST
    // BEFORE the original tools/call is answered.
    let reply_body = post_rx.recv().await.unwrap();
    let reply: serde_json::Value = serde_json::from_str(&reply_body).unwrap();
    assert_eq!(reply["id"], 4242);
    assert_eq!(reply["result"]["action"], "decline");

    let result = serde_json::json!({"jsonrpc":"2.0","id":call_id,"result":{"content":[{"type":"text","text":"done"}],"isError":false}});
    push_tx
        .send(format!("event: message\ndata: {result}\n\n"))
        .unwrap();
    let (_client, out) = call_task.await.unwrap();
    assert_eq!(out.unwrap(), "done");
}

#[tokio::test]
async fn sse_transport_logs_a_notification_and_keeps_waiting() {
    let (addr, push_tx, mut post_rx) = spawn_sse_server().await;
    let url = format!("http://127.0.0.1:{}/sse", addr.port());
    let connect_task =
        tokio::spawn(async move { McpClient::connect_sse(&url, &BTreeMap::new(), None).await });
    answer_initialize(&push_tx, &mut post_rx, None).await;
    let mut client = connect_task.await.unwrap().unwrap();

    let list_task = tokio::spawn(async move {
        let resources = client.list_resources().await.unwrap();
        (client, resources)
    });
    let body = post_rx.recv().await.unwrap();
    let id = json_rpc_id(&body);

    let notif = serde_json::json!({"jsonrpc":"2.0","method":"notifications/resources/updated","params":{"uri":"file:///a"}});
    push_tx
        .send(format!("event: message\ndata: {notif}\n\n"))
        .unwrap();
    let result = serde_json::json!({"jsonrpc":"2.0","id":id,"result":{"resources":[]}});
    push_tx
        .send(format!("event: message\ndata: {result}\n\n"))
        .unwrap();

    let (client, resources) = list_task.await.unwrap();
    assert!(resources.is_empty());
    let pending = client.take_pending_notifications();
    assert_eq!(pending.len(), 1);
    assert_eq!(pending[0]["method"], "notifications/resources/updated");
}

#[tokio::test]
async fn sse_stream_with_no_delimiter_over_the_cap_errors_named_not_unbounded() {
    // A hostile/misbehaving server pushes SSE bytes that never contain a
    // terminating blank line, well past MCP_MAX_SSE_FRAME_BYTES — the
    // reader task's SseLineAccumulator must error (fail-closed, named) and
    // tear the connection down instead of growing its buffer without
    // bound or hanging the pending request forever.
    let (addr, push_tx, mut post_rx) = spawn_sse_server().await;
    let url = format!("http://127.0.0.1:{}/sse", addr.port());
    let connect_task =
        tokio::spawn(async move { McpClient::connect_sse(&url, &BTreeMap::new(), None).await });
    answer_initialize(&push_tx, &mut post_rx, None).await;
    let mut client = connect_task.await.unwrap().unwrap();

    let call_task =
        tokio::spawn(async move { client.call_tool("whatever", serde_json::json!({})).await });
    let _tools_call_body = post_rx.recv().await.unwrap();

    // Never send "\n\n" — an ever-growing single un-terminated "frame".
    let chunk = "x".repeat(1024 * 1024); // 1 MiB, no blank-line terminator
    let chunks_needed = supercode_harness::mcp::MCP_MAX_SSE_FRAME_BYTES / (1024 * 1024) + 2;
    for _ in 0..chunks_needed {
        if push_tx.send(chunk.clone()).is_err() {
            break;
        }
    }

    let result = tokio::time::timeout(std::time::Duration::from_secs(30), call_task)
        .await
        .expect("must not hang")
        .unwrap();
    let err = result.expect_err("an oversized unterminated sse frame must error, not hang");
    assert!(
        err.to_string().contains("exceeded max"),
        "error should name the cap: {err}"
    );
}