mcp-repl 0.2.0

Interactive MCP client REPL: connects to any MCP server and turns its tools, prompts, and resources into the command set
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
//! Black-box coverage for the published `mcp-repl` process boundary.

use std::io::{Read, Seek};
use std::path::{Path, PathBuf};
use std::process::Output;
use std::time::Duration;

use tempfile::TempDir;
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::process::{Child, Command};

// Each process normally finishes in well under a second, but beta and Windows
// runners can be CPU-starved while the all-target workspace job is active.
// Keep hangs bounded without treating scheduler stalls as product failures.
const CASE_TIMEOUT: Duration = Duration::from_secs(60);
const BUILD_TIMEOUT: Duration = Duration::from_secs(180);
const SUITE_TIMEOUT: Duration = Duration::from_secs(600);

fn repo_root() -> PathBuf {
    Path::new(env!("CARGO_MANIFEST_DIR"))
        .canonicalize()
        .expect("repository root")
}

async fn run(mut command: Command, label: &str, timeout: Duration) -> Output {
    // Capture through files rather than `Child::wait_with_output`. On Windows,
    // a server grandchild can retain an inherited pipe handle after mcp-repl
    // exits, which makes waiting for pipe EOF look like a hung parent process.
    let mut stdout = tempfile::tempfile().expect("create stdout capture");
    let mut stderr = tempfile::tempfile().expect("create stderr capture");
    command
        .stdin(std::process::Stdio::null())
        .stdout(stdout.try_clone().expect("clone stdout capture"))
        .stderr(stderr.try_clone().expect("clone stderr capture"))
        .kill_on_drop(true);
    let mut child = command
        .spawn()
        .unwrap_or_else(|error| panic!("spawn {label}: {error}"));
    let status = match tokio::time::timeout(timeout, child.wait()).await {
        Ok(result) => result.unwrap_or_else(|error| panic!("wait for {label}: {error}")),
        Err(_) => {
            let _ = child.kill().await;
            let stdout = read_capture(&mut stdout, label, "stdout");
            let stderr = read_capture(&mut stderr, label, "stderr");
            panic!(
                "{label} exceeded {timeout:?}\nstdout:\n{}\nstderr:\n{}",
                String::from_utf8_lossy(&stdout),
                String::from_utf8_lossy(&stderr)
            );
        }
    };
    Output {
        status,
        stdout: read_capture(&mut stdout, label, "stdout"),
        stderr: read_capture(&mut stderr, label, "stderr"),
    }
}

fn read_capture(file: &mut std::fs::File, label: &str, stream: &str) -> Vec<u8> {
    file.rewind()
        .unwrap_or_else(|error| panic!("rewind {label} {stream}: {error}"));
    let mut bytes = Vec::new();
    file.read_to_end(&mut bytes)
        .unwrap_or_else(|error| panic!("read {label} {stream}: {error}"));
    bytes
}

fn assert_success(output: &Output, label: &str) {
    assert!(
        output.status.success(),
        "{label} failed with {}\nstdout:\n{}\nstderr:\n{}",
        output.status,
        String::from_utf8_lossy(&output.stdout),
        String::from_utf8_lossy(&output.stderr)
    );
}

fn assert_status(output: &Output, expected: i32, label: &str) {
    assert_eq!(
        output.status.code(),
        Some(expected),
        "{label} had unexpected status {}\nstdout:\n{}\nstderr:\n{}",
        output.status,
        String::from_utf8_lossy(&output.stdout),
        String::from_utf8_lossy(&output.stderr)
    );
}

fn json_lines(output: &Output, label: &str) -> Vec<serde_json::Value> {
    String::from_utf8_lossy(&output.stdout)
        .lines()
        .enumerate()
        .map(|(index, line)| {
            serde_json::from_str(line).unwrap_or_else(|error| {
                panic!(
                    "{label} stdout line {} is not JSON: {error}: {line}",
                    index + 1
                )
            })
        })
        .collect()
}

async fn build_fixture() -> PathBuf {
    let mut command = Command::new(env!("CARGO"));
    command.current_dir(repo_root()).args([
        "build",
        "--quiet",
        "--example",
        "mcp_repl_fixture",
        "--message-format=json-render-diagnostics",
    ]);
    // Coverage and beta jobs may need to compile the repository-only fixture
    // with a distinct target configuration. Keep that budget independent of
    // the much tighter timeout used to detect hung mcp-repl processes.
    let output = run(command, "fixture build", BUILD_TIMEOUT).await;
    assert_success(&output, "fixture build");

    // The outer test runner may select a different target directory (notably
    // cargo-llvm-cov). Cargo's artifact record is authoritative; deriving the
    // fixture path from the integration-test executable only works when both
    // Cargo invocations happen to share a target directory.
    let fixture = String::from_utf8_lossy(&output.stdout)
        .lines()
        .filter_map(|line| serde_json::from_str::<serde_json::Value>(line).ok())
        .find_map(|message| {
            (message["reason"] == "compiler-artifact"
                && message["target"]["name"] == "mcp_repl_fixture")
                .then(|| message["executable"].as_str().map(PathBuf::from))
                .flatten()
        })
        .expect("Cargo did not report the mcp_repl_fixture executable");
    assert!(
        fixture.is_file(),
        "fixture was not built at {}",
        fixture.display()
    );
    fixture
}

fn repl_command() -> Command {
    let mut command = Command::new(env!("CARGO_BIN_EXE_mcp-repl"));
    command.current_dir(repo_root());
    command
}

async fn wait_for_file(path: &Path, label: &str) -> String {
    tokio::time::timeout(Duration::from_secs(10), async {
        loop {
            match std::fs::read_to_string(path) {
                Ok(contents) => break contents,
                Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
                    tokio::time::sleep(Duration::from_millis(20)).await;
                }
                Err(error) => panic!("read {label}: {error}"),
            }
        }
    })
    .await
    .unwrap_or_else(|_| panic!("timed out waiting for {label}"))
}

async fn run_stdio(fixture: &Path, temp: &TempDir, case: &str, repl_args: &[&str]) -> Output {
    let exit_file = temp.path().join(format!("{case}.exit"));
    let mut command = repl_command();
    command
        .args(repl_args)
        .arg(fixture)
        .env("MCP_REPL_FIXTURE_EXIT_FILE", &exit_file);
    let output = run(command, case, CASE_TIMEOUT).await;
    assert_eq!(
        wait_for_file(&exit_file, "stdio fixture shutdown").await,
        "clean",
        "mcp-repl left its stdio child running"
    );
    output
}

struct HttpFixture {
    child: Option<Child>,
    url: String,
    subscription_file: PathBuf,
}

impl HttpFixture {
    async fn start(fixture: &Path, temp: &TempDir) -> Self {
        let ready_file = temp.path().join("http.ready");
        let subscription_file = temp.path().join("http.subscription");
        let mut command = Command::new(fixture);
        command
            .arg("--http")
            .env("MCP_REPL_FIXTURE_READY_FILE", &ready_file)
            .env("MCP_REPL_FIXTURE_SUBSCRIPTION_FILE", &subscription_file)
            .stdin(std::process::Stdio::null())
            .stdout(std::process::Stdio::null())
            .stderr(std::process::Stdio::null())
            .kill_on_drop(true);
        let child = command.spawn().expect("spawn HTTP fixture");
        let url = wait_for_file(&ready_file, "HTTP fixture readiness").await;
        Self {
            child: Some(child),
            url,
            subscription_file,
        }
    }

    async fn shutdown(mut self) {
        let mut child = self.child.take().expect("HTTP fixture child");
        child.start_kill().expect("stop HTTP fixture");
        tokio::time::timeout(Duration::from_secs(5), child.wait())
            .await
            .expect("HTTP fixture did not exit")
            .expect("wait for HTTP fixture");
    }
}

impl Drop for HttpFixture {
    fn drop(&mut self) {
        if let Some(child) = &mut self.child {
            let _ = child.start_kill();
        }
    }
}

async fn run_http(url: &str, case: &str, repl_args: &[&str]) -> Output {
    let mut command = repl_command();
    command.args(repl_args).args(["--http", url]);
    run(command, case, CASE_TIMEOUT).await
}

async fn auth_failure_server() -> (String, tokio::task::JoinHandle<()>) {
    let listener = tokio::net::TcpListener::bind("127.0.0.1:0")
        .await
        .expect("bind auth failure server");
    let url = format!(
        "http://{}/",
        listener.local_addr().expect("auth server address")
    );
    let task = tokio::spawn(async move {
        while let Ok((mut stream, _)) = listener.accept().await {
            tokio::spawn(async move {
                let mut request = [0_u8; 8 * 1024];
                let _ = stream.read(&mut request).await;
                let _ = stream
                    .write_all(
                        b"HTTP/1.1 401 Unauthorized\r\n\
                          Content-Length: 0\r\n\
                          WWW-Authenticate: Bearer\r\n\
                          Connection: close\r\n\r\n",
                    )
                    .await;
            });
        }
    });
    (url, task)
}

async fn exercise_json_contract(fixture: &Path, temp: &TempDir) {
    // Keep one round trip after `announce` so the asynchronous notification
    // handler drains before the one-shot process exits, including on Windows.
    let multiple = run_stdio(
        fixture,
        temp,
        "json-multiple",
        &[
            "--json",
            "--verbose",
            "--trace",
            "--exec",
            "tools",
            "--exec",
            "announce",
            "--exec",
            "add a=20 b=22",
        ],
    )
    .await;
    assert_success(&multiple, "multiple JSON commands");
    let values = json_lines(&multiple, "multiple JSON commands");
    assert_eq!(values.len(), 3, "one JSON line must be emitted per command");
    assert!(
        values[0].is_array(),
        "tools returns the raw MCP list: {values:?}"
    );
    assert_eq!(
        values[1].pointer("/content/0/text"),
        Some(&serde_json::json!("announced"))
    );
    assert_eq!(
        values[2].pointer("/content/0/text"),
        Some(&serde_json::json!("42"))
    );
    assert!(
        !String::from_utf8_lossy(&multiple.stdout).contains("connected:"),
        "--verbose must not contaminate JSON stdout"
    );
    let stderr = String::from_utf8_lossy(&multiple.stderr);
    assert!(stderr.contains("fixture announcement"), "{stderr}");
    assert!(
        stderr.contains("tools/list"),
        "wire tracing stayed off: {stderr}"
    );

    let no_match = run_stdio(
        fixture,
        temp,
        "json-no-match",
        &["--json", "--exec", "find definitely-not-on-the-surface"],
    )
    .await;
    assert_status(&no_match, 1, "no-match outcome");
    assert_eq!(
        json_lines(&no_match, "no-match outcome"),
        [serde_json::json!([])]
    );

    let continued = run_stdio(
        fixture,
        temp,
        "json-continued",
        &[
            "--json",
            "--exec",
            "no_such_command",
            "--exec",
            "add a=20 b=22",
        ],
    )
    .await;
    assert_status(&continued, 2, "usage error");
    let values = json_lines(&continued, "continued JSON commands");
    assert_eq!(values.len(), 2, "later commands must run after a failure");
    assert_eq!(values[0]["kind"], "usage");
    assert_eq!(values[0]["exitStatus"], 2);
    assert_eq!(
        values[1].pointer("/content/0/text"),
        Some(&serde_json::json!("42"))
    );

    let server_error = run_stdio(
        fixture,
        temp,
        "json-server-error",
        &["--json", "--exec", "fail"],
    )
    .await;
    assert_status(&server_error, 3, "tool error");
    let values = json_lines(&server_error, "tool error");
    assert_eq!(values.len(), 1);
    assert_eq!(values[0]["isError"], true);

    let unavailable = tokio::net::TcpListener::bind("127.0.0.1:0")
        .await
        .expect("reserve unavailable endpoint");
    let unavailable_url = format!(
        "http://{}/",
        unavailable.local_addr().expect("unavailable address")
    );
    drop(unavailable);
    let transport_error = run_http(
        &unavailable_url,
        "JSON transport error",
        &["--json", "--exec", "tools"],
    )
    .await;
    assert_status(&transport_error, 4, "transport error");
    let values = json_lines(&transport_error, "transport error");
    assert_eq!(values.len(), 1);
    assert_eq!(values[0]["kind"], "transport");

    let (auth_url, auth_server) = auth_failure_server().await;
    let auth_error = run_http(&auth_url, "JSON auth error", &["--json", "--exec", "tools"]).await;
    auth_server.abort();
    assert_status(&auth_error, 5, "authentication error");
    let values = json_lines(&auth_error, "authentication error");
    assert_eq!(values.len(), 1);
    assert_eq!(values[0]["kind"], "auth");
}

async fn exercise_imported_stdio_config(fixture: &Path, temp: &TempDir) {
    let workspace = temp.path().join("import-workspace");
    let cwd = workspace.join("work");
    std::fs::create_dir_all(&cwd).expect("create imported fixture cwd");
    let config = workspace.join(".mcp.json");
    std::fs::write(
        &config,
        serde_json::json!({
            "mcpServers": {
                "fixture": {
                    "command": fixture,
                    "env": {
                        "MCP_REPL_IMPORTED_VALUE": "${env:MCP_REPL_HOST_VALUE}"
                    },
                    "cwd": "${workspaceFolder}/work"
                }
            }
        })
        .to_string(),
    )
    .expect("write imported stdio config");
    let exit_file = temp.path().join("import-stdio.exit");
    let selector = format!("{}:fixture", config.display());

    // An imported entry names a command to execute, so a session with nobody
    // to ask refuses instead of spawning it.
    let mut unapproved = repl_command();
    unapproved
        .args(["--json", "--exec", "process_info", &selector])
        .env("MCP_REPL_HOST_VALUE", "from-host");
    let refused = run(unapproved, "unapproved imported stdio config", CASE_TIMEOUT).await;
    assert_status(&refused, 2, "unapproved imported stdio config");
    let refusal = json_lines(&refused, "unapproved imported stdio config");
    assert_eq!(refusal.len(), 1);
    assert_eq!(refusal[0]["kind"], "usage");
    let message = refusal[0]["error"]
        .as_str()
        .expect("refusal carries a message");
    assert!(
        message.contains("--trust-import"),
        "the refusal must say how to proceed, got: {message}"
    );

    let mut command = repl_command();
    command
        .args([
            "--json",
            "--trust-import",
            "--exec",
            "process_info",
            &selector,
        ])
        .env("MCP_REPL_HOST_VALUE", "from-host")
        // An HTTP credential in the environment must not be handed to a
        // spawned child.
        .env("MCP_BEARER", "http-only-secret")
        .env("MCP_REPL_FIXTURE_EXIT_FILE", &exit_file);
    let output = run(command, "imported stdio config", CASE_TIMEOUT).await;
    assert_success(&output, "imported stdio config");
    assert_eq!(
        wait_for_file(&exit_file, "imported stdio fixture shutdown").await,
        "clean"
    );
    let values = json_lines(&output, "imported stdio config");
    assert_eq!(values.len(), 1);
    let process: serde_json::Value = serde_json::from_str(
        values[0]
            .pointer("/content/0/text")
            .and_then(serde_json::Value::as_str)
            .expect("process_info text result"),
    )
    .expect("process_info JSON");
    assert_eq!(process["imported"], "from-host");
    assert_eq!(
        process["bearer"],
        serde_json::Value::Null,
        "MCP_BEARER must not reach a spawned stdio child"
    );
    assert_eq!(
        PathBuf::from(process["cwd"].as_str().expect("process cwd"))
            .canonicalize()
            .expect("canonical process cwd"),
        cwd.canonicalize().expect("canonical expected cwd")
    );

    // The same selector under `RUST_LOG`. Which file and entry a selector
    // resolved to, and which approval let the spawn happen, are decisions
    // that never become a frame, so `wire on` cannot answer them.
    let mut logged = repl_command();
    logged
        .args([
            "--json",
            "--trust-import",
            "--exec",
            "process_info",
            &selector,
        ])
        .env("MCP_REPL_HOST_VALUE", "from-host")
        .env("RUST_LOG", "mcp_repl=debug")
        .env("MCP_REPL_FIXTURE_EXIT_FILE", &exit_file);
    let logged = run(logged, "imported stdio config with logging", CASE_TIMEOUT).await;
    assert_success(&logged, "imported stdio config with logging");
    let records = String::from_utf8_lossy(&logged.stderr);
    assert!(
        records.contains("resolved a client config entry") && records.contains("entry=fixture"),
        "the records name the entry a selector resolved to:\n{records}"
    );
    assert!(
        records.contains("spawn approved by --trust-import"),
        "and which approval let the spawn happen:\n{records}"
    );

    // stdout is the data stream either way: records go to stderr, so the
    // NDJSON contract survives having logging on.
    let values = json_lines(&logged, "imported stdio config with logging");
    assert_eq!(values.len(), 1, "one value per command, with logging on");

    // And none of it appears without being asked for.
    assert!(
        !String::from_utf8_lossy(&output.stderr).contains("resolved a client config entry"),
        "the default level stays quiet:\n{}",
        String::from_utf8_lossy(&output.stderr)
    );
}

async fn exercise_schema_contracts(fixture: &Path, temp: &TempDir) {
    let snapshot_path = temp.path().join("add.schema.json");
    let snapshot_command = format!("snapshot add '{}'", snapshot_path.display());
    let exported = run_stdio(
        fixture,
        temp,
        "schema-export",
        &["--json", "--exec", &snapshot_command],
    )
    .await;
    assert_success(&exported, "schema snapshot export");
    let snapshot: serde_json::Value = serde_json::from_str(
        &std::fs::read_to_string(&snapshot_path).expect("read exported schema snapshot"),
    )
    .expect("exported schema snapshot JSON");
    assert_eq!(snapshot["formatVersion"], 1);
    assert_eq!(snapshot["kind"], "tool");
    assert_eq!(snapshot["name"], "add");

    let validate_command = format!("validate '{}' strict", snapshot_path.display());
    let validated = run_stdio(
        fixture,
        temp,
        "schema-validate",
        &["--json", "--exec", &validate_command],
    )
    .await;
    assert_success(&validated, "strict schema validation");
    let values = json_lines(&validated, "strict schema validation");
    assert_eq!(values.len(), 1);
    assert_eq!(values[0]["compatible"], true);
    assert_eq!(values[0]["mode"], "strict");

    let mut incompatible = snapshot;
    incompatible["inputSchema"]["properties"]["a"]["type"] = serde_json::json!("string");
    std::fs::write(
        &snapshot_path,
        serde_json::to_string_pretty(&incompatible).unwrap(),
    )
    .expect("write incompatible schema snapshot");
    let snapshot_path = snapshot_path.to_string_lossy().into_owned();
    let blocked = run_stdio(
        fixture,
        temp,
        "schema-preflight",
        &[
            "--json",
            "--schema-contract",
            &snapshot_path,
            "--exec",
            "add a=20 b=22",
        ],
    )
    .await;
    assert_status(&blocked, 1, "incompatible schema preflight");
    let values = json_lines(&blocked, "incompatible schema preflight");
    assert_eq!(values.len(), 1, "the blocked tool must not emit a result");
    assert_eq!(values[0]["compatible"], false);
    assert!(
        values[0]["issues"]
            .as_array()
            .unwrap()
            .iter()
            .any(|issue| issue["code"] == "schema_retyped")
    );

    let human_validate = format!("validate '{}' compatible", snapshot_path);
    let explained = run_stdio(
        fixture,
        temp,
        "schema-human-report",
        &["--exec", &human_validate],
    )
    .await;
    assert_status(&explained, 1, "human schema validation");
    let stdout = String::from_utf8_lossy(&explained.stdout);
    assert!(stdout.contains("incompatible"), "{stdout}");
    assert!(stdout.contains("schema_retyped"), "{stdout}");
    assert!(
        stdout.contains("$.inputSchema.properties.a.type"),
        "{stdout}"
    );

    let prompt_path = temp.path().join("greet.schema.json");
    let snapshot_prompt = format!("snapshot prompt:greet '{}'", prompt_path.display());
    let exported = run_stdio(
        fixture,
        temp,
        "prompt-schema-export",
        &["--json", "--exec", &snapshot_prompt],
    )
    .await;
    assert_success(&exported, "prompt schema snapshot export");
    let mut prompt_snapshot: serde_json::Value = serde_json::from_str(
        &std::fs::read_to_string(&prompt_path).expect("read prompt schema snapshot"),
    )
    .expect("prompt schema snapshot JSON");
    prompt_snapshot["arguments"][0]["required"] = serde_json::json!(false);
    std::fs::write(
        &prompt_path,
        serde_json::to_string_pretty(&prompt_snapshot).unwrap(),
    )
    .expect("write incompatible prompt snapshot");
    let prompt_path = prompt_path.to_string_lossy().into_owned();
    let blocked = run_stdio(
        fixture,
        temp,
        "prompt-schema-preflight",
        &[
            "--json",
            "--schema-contract",
            &prompt_path,
            "--exec",
            "prompt greet name=Ada",
        ],
    )
    .await;
    assert_status(&blocked, 1, "incompatible prompt schema preflight");
    let values = json_lines(&blocked, "incompatible prompt schema preflight");
    assert_eq!(values.len(), 1, "the blocked prompt must not emit a result");
    assert!(
        values[0]["issues"]
            .as_array()
            .unwrap()
            .iter()
            .any(|issue| issue["code"] == "argument_newly_required")
    );
}

async fn exercise_imported_http_config(http: &HttpFixture, temp: &TempDir) {
    let config = temp.path().join("vscode-mcp.json");
    std::fs::write(
        &config,
        serde_json::json!({
            "servers": {
                "fixture": {
                    "type": "http",
                    "url": "http://127.0.0.1:1/"
                }
            }
        })
        .to_string(),
    )
    .expect("write imported HTTP config");
    let selector = format!("{}:fixture", config.display());
    let mut command = repl_command();
    command.args([
        "--json",
        "--exec",
        "add a=20 b=22",
        "--http",
        &http.url,
        &selector,
    ]);
    let output = run(command, "imported HTTP config", CASE_TIMEOUT).await;
    assert_success(&output, "imported HTTP config");
    let values = json_lines(&output, "imported HTTP config");
    assert_eq!(values.len(), 1);
    assert_eq!(
        values[0].pointer("/content/0/text"),
        Some(&serde_json::json!("42"))
    );
}

async fn exercise_stdio(fixture: &Path, temp: &TempDir) {
    let stable = run_stdio(
        fixture,
        temp,
        "stable-stdio",
        &[
            "--protocol",
            "stable",
            "--verbose",
            "--exec",
            "add a=20 b=22",
        ],
    )
    .await;
    assert_success(&stable, "stable stdio");
    let stdout = String::from_utf8_lossy(&stable.stdout);
    let stderr = String::from_utf8_lossy(&stable.stderr);
    assert!(stdout.contains("protocol 2025-11-25"), "{stdout}");
    assert!(stdout.contains("42"), "{stdout}");
    assert!(stderr.contains("mcp-repl fixture ready"), "{stderr}");

    let final_ = run_stdio(
        fixture,
        temp,
        "final-stdio",
        &[
            "--protocol",
            "2026-07-28",
            "--verbose",
            "--exec",
            "add a=20 b=22",
            "--exec",
            "prompt greet name=Ada",
            "--exec",
            "read fixture://guide",
        ],
    )
    .await;
    assert_success(&final_, "final stdio");
    let stdout = String::from_utf8_lossy(&final_.stdout);
    assert!(stdout.contains("protocol 2026-07-28"), "{stdout}");
    assert!(stdout.contains("42"), "{stdout}");
    assert!(stdout.contains("Please greet Ada warmly."), "{stdout}");
    assert!(stdout.contains("fixture resource body"), "{stdout}");

    let error = run_stdio(
        fixture,
        temp,
        "json-error",
        &["--json", "--exec", "no_such_command"],
    )
    .await;
    assert!(!error.status.success(), "unknown command should fail");
    let stdout = String::from_utf8_lossy(&error.stdout);
    let stderr = String::from_utf8_lossy(&error.stderr);
    assert!(stdout.contains("\"error\""), "{stdout}");
    assert!(!stdout.contains("fixture ready"), "{stdout}");
    assert!(stderr.contains("mcp-repl fixture ready"), "{stderr}");
}

/// An `--exec` script cannot name a task it started: the id is generated by
/// the command that starts it, and the `-e` list is fixed before any of it
/// runs. Without a way to wait, the process exits and takes the connection
/// with it, abandoning work the server already began.
async fn exercise_exec_waits_for_its_own_tasks(fixture: &Path, temp: &TempDir) {
    let waited = run_stdio(
        fixture,
        temp,
        "exec-wait-all",
        &[
            "--protocol",
            "2026-07-28",
            "--no-history",
            "--color",
            "never",
            "--exec",
            "slow_add a=1 b=2 &",
            "--exec",
            "wait",
        ],
    )
    .await;
    assert_success(&waited, "exec wait all");
    let stdout = String::from_utf8_lossy(&waited.stdout);
    assert!(
        stdout.contains("status=completed"),
        "a bare wait settles the task started earlier in the same run:\n{stdout}"
    );
    assert!(
        stdout.contains("\n3\n"),
        "and reports its result, so the work was not abandoned:\n{stdout}"
    );

    // `last` names it without knowing the id, for a script that wants one
    // specific task rather than all of them.
    let last = run_stdio(
        fixture,
        temp,
        "exec-wait-last",
        &[
            "--protocol",
            "2026-07-28",
            "--no-history",
            "--color",
            "never",
            "--exec",
            "slow_add a=20 b=22 &",
            "--exec",
            "wait last",
        ],
    )
    .await;
    assert_success(&last, "exec wait last");
    assert!(
        String::from_utf8_lossy(&last.stdout).contains("\n42\n"),
        "`last` names the most recently started task:\n{}",
        String::from_utf8_lossy(&last.stdout)
    );

    // The point of waiting is to learn whether the work succeeded, so a
    // failed task has to reach the exit status. The fixture's failure arrives
    // as a *completed* task carrying an error, which is the shape a handler
    // returning `Err` produces, so judging on status alone would call it a
    // success.
    let failed = run_stdio(
        fixture,
        temp,
        "exec-wait-failure",
        &[
            "--protocol",
            "2026-07-28",
            "--no-history",
            "--color",
            "never",
            "--exec",
            "fail_slowly &",
            "--exec",
            "wait",
        ],
    )
    .await;
    assert_status(&failed, 3, "exec wait failure");
    assert!(
        String::from_utf8_lossy(&failed.stdout).contains("fixture task failure"),
        "the failure is reported, not only counted:\n{}",
        String::from_utf8_lossy(&failed.stdout)
    );

    // The other failure shape, and the one a server is most likely to send:
    // an `isError` result rather than a handler error. The demo's `fail` is
    // task-capable so this is reachable without a server of your own, which
    // is the whole point of it being there.
    let error_result = run_demo_answering(
        "",
        "demo task tool error",
        &["--exec", "fail &", "--exec", "wait"],
    )
    .await;
    assert_status(&error_result, 3, "demo task tool error");
    let stdout = String::from_utf8_lossy(&error_result.stdout);
    assert!(
        stdout.contains("tool error"),
        "a failed task settles as `completed`, so the error needs saying:\n{stdout}"
    );

    // Nothing to wait for is a distinct outcome from a task that failed.
    let empty = run_stdio(
        fixture,
        temp,
        "exec-wait-empty",
        &["--no-history", "--color", "never", "--exec", "wait"],
    )
    .await;
    assert_status(&empty, 1, "exec wait with no tasks");
}

/// `--login`/`--logout` under `--json` speak the same NDJSON contract.
///
/// The success path of `--login` needs a real authorization server, so what
/// is reachable here is everything around it: that `--json` is accepted at
/// all, that a failure is the standard envelope rather than prose, and that
/// `--logout` reports what it removed. The shape of a saved profile is
/// covered by a unit test.
async fn exercise_login_json(temp: &TempDir) {
    let config = temp.path().join("login.toml");
    std::fs::write(&config, "").expect("write empty config");
    let config = config.display().to_string();

    // A usage failure is the same envelope every other command emits, on
    // stdout, so it occupies that invocation's one output line.
    let mut missing_url = repl_command();
    missing_url.args(["--login", "work", "--json", "--config", &config]);
    let missing_url = run(missing_url, "login without a url", CASE_TIMEOUT).await;
    assert_status(&missing_url, 2, "login without a url");
    let values = json_lines(&missing_url, "login without a url");
    assert_eq!(values.len(), 1);
    assert_eq!(values[0]["kind"], "usage");
    assert_eq!(values[0]["exitStatus"], 2);

    // `--json` is now allowed, but the genuinely incompatible combinations
    // are still refused.
    let mut with_exec = repl_command();
    with_exec.args([
        "--login", "work", "--json", "--exec", "tools", "--config", &config,
    ]);
    let with_exec = run(with_exec, "login with exec", CASE_TIMEOUT).await;
    assert_status(&with_exec, 2, "login with exec");
    assert!(
        String::from_utf8_lossy(&with_exec.stdout).contains("standalone credential"),
        "{}",
        String::from_utf8_lossy(&with_exec.stdout)
    );

    // Removing a profile touches the operating-system credential store, which
    // a headless runner does not have. Both outcomes are correct, and the
    // contract is what this pins: exactly one parseable value either way,
    // the success shape or the standard auth envelope. The failure branch is
    // worth covering in its own right, since "a script gets an envelope
    // rather than prose when it fails" is half the point of the flag.
    let mut logout = repl_command();
    logout.args(["--logout", "work", "--json", "--config", &config]);
    let logout = run(logout, "logout json", CASE_TIMEOUT).await;
    let values = json_lines(&logout, "logout json");
    assert_eq!(values.len(), 1, "one value per invocation");
    match logout.status.code() {
        Some(0) => {
            assert_eq!(values[0]["profile"], "work");
            assert_eq!(values[0]["removed"], true);
        }
        Some(5) => {
            assert_eq!(values[0]["kind"], "auth");
            assert_eq!(values[0]["exitStatus"], 5);
        }
        other => panic!("unexpected logout status {other:?}: {}", values[0]),
    }

    // Without `--json`, the human wording is unchanged. Same split: the
    // message goes to stdout on success and stderr on failure, because
    // stdout is the data stream.
    let mut human = repl_command();
    human.args(["--logout", "work", "--config", &config]);
    let human = run(human, "logout human", CASE_TIMEOUT).await;
    let stdout = String::from_utf8_lossy(&human.stdout);
    let stderr = String::from_utf8_lossy(&human.stderr);
    if human.status.success() {
        assert!(stdout.contains("removed OAuth profile"), "{stdout}");
    } else {
        assert!(
            stderr.contains("credential store"),
            "a failure explains itself on stderr:\n{stderr}"
        );
        assert!(
            stdout.is_empty(),
            "and stdout stays the data stream: {stdout}"
        );
    }
}

/// `[repl] request_timeout` supplies the default `--timeout` uses.
///
/// The precedence is what matters and what a unit test cannot see: the flag
/// beats the config, the config beats the built-in default, and an explicit
/// `--timeout 0` still means "wait indefinitely" rather than "unset".
async fn exercise_repl_config(temp: &TempDir) {
    let config = temp.path().join("repl-config.toml");
    std::fs::write(&config, "[repl]\nrequest_timeout = 1\n").expect("write repl config");
    let config = config.display().to_string();

    // `slow_add` sleeps three seconds, so a one-second budget must expire.
    let mut timed_out = repl_command();
    timed_out.args([
        "--demo",
        "--no-history",
        "--color",
        "never",
        "--config",
        &config,
        "--exec",
        "slow_add a=1 b=2",
    ]);
    let timed_out = run(timed_out, "config timeout", CASE_TIMEOUT).await;
    assert_status(&timed_out, 4, "config timeout");

    // The flag overrides it.
    let mut flag_wins = repl_command();
    flag_wins.args([
        "--demo",
        "--no-history",
        "--color",
        "never",
        "--config",
        &config,
        "--timeout",
        "30",
        "--exec",
        "slow_add a=1 b=2",
    ]);
    let flag_wins = run(flag_wins, "flag over config", CASE_TIMEOUT).await;
    assert_success(&flag_wins, "flag over config");
    assert!(
        String::from_utf8_lossy(&flag_wins.stdout).contains('3'),
        "the call completes when the flag allows it"
    );

    // A typo is refused rather than ignored, since a setting that appears to
    // apply and does not is worse than one that fails loudly.
    let typo = temp.path().join("repl-typo.toml");
    std::fs::write(&typo, "[repl]\nrequest_timeoutt = 1\n").expect("write typo config");
    let mut refused = repl_command();
    refused.args([
        "--demo",
        "--no-history",
        "--color",
        "never",
        "--config",
        &typo.display().to_string(),
        "--exec",
        "echo message=hi",
    ]);
    let refused = run(refused, "config typo", CASE_TIMEOUT).await;
    assert_status(&refused, 2, "config typo");
    assert!(
        String::from_utf8_lossy(&refused.stderr).contains("request_timeout"),
        "the refusal names the key that was meant:\n{}",
        String::from_utf8_lossy(&refused.stderr)
    );
}

/// `loglevel` must actually change what the server sends.
///
/// The fixture's `announce` emits one Info log. Asserting only that the
/// request went out would pass against a server that ignored it, so this
/// checks the observable consequence: the same call, quiet afterwards.
async fn exercise_loglevel(fixture: &Path, temp: &TempDir) {
    let before = run_stdio(
        fixture,
        temp,
        "loglevel-default",
        &["--no-history", "--color", "never", "--exec", "announce"],
    )
    .await;
    assert_success(&before, "loglevel default");
    // Notifications go to stderr: stdout is the data stream, and a log line
    // arriving mid-command is not part of any command's result.
    assert!(
        String::from_utf8_lossy(&before.stderr).contains("log info"),
        "the fixture logs at info by default:\n{}",
        String::from_utf8_lossy(&before.stderr)
    );

    let after = run_stdio(
        fixture,
        temp,
        "loglevel-raised",
        &[
            "--no-history",
            "--color",
            "never",
            "--exec",
            "loglevel emergency",
            "--exec",
            "announce",
        ],
    )
    .await;
    assert_success(&after, "loglevel raised");
    let stdout = String::from_utf8_lossy(&after.stdout);
    let stderr = String::from_utf8_lossy(&after.stderr);
    assert!(
        stdout.contains("announced"),
        "the tool still runs:\n{stdout}"
    );
    assert!(
        !stderr.contains("log info"),
        "and its log is below the level that was set:\n{stderr}"
    );

    // A server that never declared the capability is told so, rather than
    // being sent a request it will only reject.
    let mut undeclared = repl_command();
    undeclared
        .args([
            "--no-history",
            "--color",
            "never",
            "--exec",
            "loglevel debug",
        ])
        .arg(fixture)
        .arg("--tools-only")
        .env(
            "MCP_REPL_FIXTURE_EXIT_FILE",
            temp.path().join("loglevel-undeclared.exit"),
        );
    let undeclared = run(undeclared, "loglevel undeclared", CASE_TIMEOUT).await;
    assert_status(&undeclared, 3, "loglevel undeclared");
    assert!(
        String::from_utf8_lossy(&undeclared.stderr).contains("does not declare"),
        "{}",
        String::from_utf8_lossy(&undeclared.stderr)
    );
}

/// Sampling is a feature the README leads with, so something must exercise it.
///
/// `canned` rather than `prompt`, so the case is deterministic and needs no
/// stdin: what is being checked is that the request reaches the client and
/// the answer reaches the tool, not how a human types.
async fn exercise_sampling() {
    let answered = run_demo_answering(
        "",
        "sampling canned",
        &[
            "--sampling",
            "canned",
            "--exec",
            "summarize text=\"the quick brown fox\"",
        ],
    )
    .await;
    assert_success(&answered, "sampling canned");
    let stdout = String::from_utf8_lossy(&answered.stdout);
    assert!(
        stdout.contains("summary (mcp-repl/canned)"),
        "the tool receives what the client answered:\n{stdout}"
    );

    // Declining is an answer too, and the tool has to cope with it rather
    // than the REPL pretending it succeeded.
    let declined = run_demo_answering(
        "",
        "sampling declined",
        &[
            "--sampling",
            "decline",
            "--exec",
            "summarize text=\"the quick brown fox\"",
        ],
    )
    .await;
    assert_ne!(
        declined.status.code(),
        Some(0),
        "a declined request is not a success:\nstdout:\n{}\nstderr:\n{}",
        String::from_utf8_lossy(&declined.stdout),
        String::from_utf8_lossy(&declined.stderr)
    );
}

/// A server that serves only tools must not be greeted with warnings.
///
/// Real servers declare exactly this: GitMCP's `initialize` result is
/// `{"tools":{"listChanged":true}}`. The REPL used to ask for prompts and
/// resources anyway, and report the correct "Method not found" it got back as
/// a failure, so connecting to a healthy server opened with two warnings
/// about nothing.
async fn exercise_tools_only_server(fixture: &Path, temp: &TempDir) {
    let exit_file = temp.path().join("tools-only.exit");
    let mut command = repl_command();
    command
        .args(["--no-history", "--color", "never", "--exec", "tools"])
        .arg(fixture)
        .arg("--tools-only")
        .env("MCP_REPL_FIXTURE_EXIT_FILE", &exit_file);
    let output = run(command, "tools only", CASE_TIMEOUT).await;
    assert_success(&output, "tools only");

    let stdout = String::from_utf8_lossy(&output.stdout);
    assert!(stdout.contains("add"), "the tools still list:\n{stdout}");
    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(
        !stderr.contains("warning:"),
        "a server that declares only tools is not broken:\n{stderr}"
    );
}

/// The protocol version reported is the one the server returned.
///
/// A server may answer `initialize` with a version other than the one asked
/// for, and real ones do. Echoing the request back would be the easy mistake
/// and would tell the operator something false: the banner is the only place
/// the negotiated version appears, so it has to be the negotiated one.
async fn exercise_downgraded_protocol(fixture: &Path, temp: &TempDir) {
    let exit_file = temp.path().join("downgrade.exit");
    let mut command = repl_command();
    command
        .args([
            "--no-history",
            "--color",
            "never",
            "--verbose",
            "--exec",
            "quit",
        ])
        .arg(fixture)
        .args(["--tools-only", "--downgrade-protocol"])
        .env("MCP_REPL_FIXTURE_EXIT_FILE", &exit_file);
    let output = run(command, "downgraded protocol", CASE_TIMEOUT).await;
    assert_success(&output, "downgraded protocol");

    let stdout = String::from_utf8_lossy(&output.stdout);
    assert!(
        stdout.contains("protocol 2025-06-18"),
        "the version the server chose is the one reported:\n{stdout}"
    );
    assert!(
        !stdout.contains("2025-11-25"),
        "and the version mcp-repl asked for is not:\n{stdout}"
    );
}

/// An absent pagination cursor must be absent, not null.
///
/// `cursor` is optional in the schema, and a server that generates its
/// validators from that schema types it `string | undefined`. Context7 and
/// the Hugging Face server both reject an explicit null, correctly: absent
/// and null are not the same thing. Sending one made every listing they
/// serve fail.
///
/// The fixture rejects a null on any listing rather than a chosen one,
/// because which method carries it is not the point and has already moved:
/// the null rode on `resources/templates/list` and never on `tools/list`.
async fn exercise_absent_cursor(fixture: &Path, temp: &TempDir) {
    let mut command = repl_command();
    command
        .args(["--no-history", "--color", "never", "--exec", "tools"])
        .arg(fixture)
        .args(["--tools-only", "--strict-cursor"])
        .env(
            "MCP_REPL_FIXTURE_EXIT_FILE",
            temp.path().join("strict-cursor.exit"),
        );
    let output = run(command, "strict cursor", CASE_TIMEOUT).await;
    assert_success(&output, "strict cursor");
    assert!(
        String::from_utf8_lossy(&output.stdout).contains("add"),
        "the listing survives a server that types cursor as string|undefined:\n{}",
        String::from_utf8_lossy(&output.stdout)
    );
    assert!(
        !String::from_utf8_lossy(&output.stderr).contains("cursor"),
        "and no listing is refused over one:\n{}",
        String::from_utf8_lossy(&output.stderr)
    );
}

/// A listing that could not be read must not be reported as an empty one.
///
/// The same raw server, now declaring the tools capability and then failing
/// to serve it. Found against DeepWiki, where the listing failed to
/// deserialize and `--json -e tools | jq length` read 0 for a server with 18
/// tools. The original fixture reproduced that exact cause, a `_meta`
/// key tower-mcp refused; upstream now drops such keys instead, so the cause
/// had to become one that does not depend on someone else's bug. What is
/// being pinned is the REPL's response to an unreadable listing, not the
/// reason it was unreadable.
async fn exercise_unreadable_listing(fixture: &Path, temp: &TempDir) {
    let exit_file = temp.path().join("failing-list.exit");
    let mut command = repl_command();
    command
        .args(["--no-history", "--color", "never", "--exec", "tools"])
        .arg(fixture)
        .args(["--tools-only", "--failing-list"])
        .env("MCP_REPL_FIXTURE_EXIT_FILE", &exit_file);
    let output = run(command, "unreadable listing", CASE_TIMEOUT).await;

    let stdout = String::from_utf8_lossy(&output.stdout);
    let stderr = String::from_utf8_lossy(&output.stderr);
    assert_ne!(
        output.status.code(),
        Some(0),
        "a listing that failed to load is not a success:\nstdout:\n{stdout}\nstderr:\n{stderr}"
    );
    // The server's rejection is a sentence and a code, not a struct dump.
    assert!(
        stderr.contains("tool index unavailable (code -32603)"),
        "a server's error reads as a sentence:\n{stderr}"
    );
    assert!(
        !stderr.contains("JsonRpcError {"),
        "and not as Rust debug output:\n{stderr}"
    );
    assert!(
        stdout.trim().is_empty(),
        "stdout is the data stream, and there is no data:\n{stdout}"
    );
    assert!(
        stderr.contains("unavailable"),
        "the operator is told the listing failed, not shown an empty one:\n{stderr}"
    );
}

/// An unreachable server is the first failure most people meet, so what it
/// prints is worth pinning.
///
/// It used to arrive twice: once as a framework log record and once as the
/// REPL's own error, with `Transport error:` repeated for each wrapping layer
/// and ANSI escapes that `--color never` was supposed to have turned off.
async fn exercise_connection_failure_output() {
    let mut command = repl_command();
    // Port 9 is discard: reserved, and nothing listens on it.
    command.args([
        "--http",
        "http://127.0.0.1:9/",
        "--no-history",
        "--color",
        "never",
        "--timeout",
        "5",
        "--exec",
        "tools",
    ]);
    let output = run(command, "connection failure", CASE_TIMEOUT).await;
    assert_status(&output, 4, "connection failure");

    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(
        !stderr.contains('\u{1b}'),
        "--color never must reach the log subscriber too:\n{stderr:?}"
    );
    assert_eq!(
        stderr
            .lines()
            .filter(|line| !line.trim().is_empty())
            .count(),
        1,
        "one failure is reported once:\n{stderr}"
    );
    assert_eq!(
        stderr.matches("Transport error:").count(),
        1,
        "the kind of failure is named once, not once per layer:\n{stderr}"
    );
    assert!(
        stderr.contains("HTTP request failed"),
        "and the informative part survives:\n{stderr}"
    );
}

/// Run the demo server, answering elicitation prompts from `stdin`.
async fn run_demo_answering(answers: &str, case: &str, repl_args: &[&str]) -> Output {
    let mut command = repl_command();
    command
        .args(["--demo", "--no-history", "--color", "never"])
        .args(repl_args)
        .stdin(std::process::Stdio::piped())
        .stdout(std::process::Stdio::piped())
        .stderr(std::process::Stdio::piped())
        .kill_on_drop(true);
    let mut child = command
        .spawn()
        .unwrap_or_else(|error| panic!("spawn {case}: {error}"));
    let mut stdin = child.stdin.take().expect("elicitation stdin");
    stdin
        .write_all(answers.as_bytes())
        .await
        .unwrap_or_else(|error| panic!("write {case} answers: {error}"));
    drop(stdin);
    tokio::time::timeout(CASE_TIMEOUT, child.wait_with_output())
        .await
        .unwrap_or_else(|_| panic!("{case} timed out"))
        .unwrap_or_else(|error| panic!("wait for {case}: {error}"))
}

/// A form's fields must be asked in the order the server declared them.
///
/// The schema is an ordered map and the order is protocol-significant, so
/// sorting the field names alphabetically silently pairs each answer with the
/// wrong field. Answering positionally is what catches it: the fields here are
/// declared username, environment, remember_me, which is not alphabetical, so
/// a re-sorted form signs in as `staging`.
async fn exercise_elicitation_field_order() {
    let output = run_demo_answering(
        "ada\nstaging\ny\n",
        "elicitation order",
        &["--elicitation", "prompt", "--exec", "sign_in"],
    )
    .await;
    assert_success(&output, "elicitation order");
    let stdout = String::from_utf8_lossy(&output.stdout);
    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(
        stdout.contains("signed in as ada"),
        "answers must land in declared order\nstdout:\n{stdout}\nstderr:\n{stderr}"
    );
    let username = stderr.find("username").expect("username prompt");
    let environment = stderr.find("environment").expect("environment prompt");
    assert!(
        username < environment,
        "username is declared first, so it is asked first:\n{stderr}"
    );
}

/// `respond` only works where a task can report what it is waiting for, and
/// the refusal has to explain the protocol rather than leak the framework's
/// "task_get_detailed requires ..." transport error.
async fn exercise_respond_needs_the_final_lifecycle() {
    let output = run_demo_answering(
        "",
        "respond on stable",
        &[
            "--protocol",
            "stable",
            // A real task, so the refusal is about the lifecycle rather than
            // an unresolvable id.
            "--exec",
            "slow_add a=1 b=2 &",
            "--exec",
            "task 1 respond",
        ],
    )
    .await;
    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(
        stderr.contains("2026-07-28"),
        "the refusal names the lifecycle that supports it:\n{stderr}"
    );
    assert!(
        !stderr.contains("task_get_detailed"),
        "an internal API name is not an explanation:\n{stderr}"
    );
}

/// Interrupting a call has to reach the server, not just free the prompt.
///
/// The framework cancels a request when the caller's future drops, which is
/// what `run_cancellable` does to the losing `select!` branch, so nothing in
/// this crate sends the notification. What is worth pinning is that the
/// notification goes out at all, that it names this call rather than every
/// pending request, and that a numeric id stays numeric on the way out.
#[cfg(unix)]
async fn exercise_cancellation() {
    let mut command = repl_command();
    command
        .args([
            "--demo",
            "--trace",
            "--no-history",
            "--color",
            "never",
            "--exec",
            "slow_add a=1 b=2",
        ])
        .stdin(std::process::Stdio::null())
        .stdout(std::process::Stdio::null())
        .stderr(std::process::Stdio::piped())
        .kill_on_drop(true);
    let mut child = command.spawn().expect("spawn cancellation case");
    let mut stderr = child.stderr.take().expect("cancellation stderr");
    let pid = child.id().expect("cancellation pid");

    // `slow_add` sleeps three seconds server-side, but interrupt on the trace
    // rather than on a timer: a loaded runner can spend longer than that
    // getting the process up and connected, and a signal that arrives before
    // the call is in flight would test nothing.
    let mut trace = String::new();
    tokio::time::timeout(CASE_TIMEOUT, async {
        let mut chunk = [0u8; 4096];
        loop {
            let read = stderr.read(&mut chunk).await.expect("read wire trace");
            if read == 0 {
                break;
            }
            trace.push_str(&String::from_utf8_lossy(&chunk[..read]));
            if trace.contains("\"slow_add\"") {
                break;
            }
        }
    })
    .await
    .expect("timed out waiting for the call to reach the wire");

    let signalled = Command::new("kill")
        .args(["-INT", &pid.to_string()])
        .status()
        .await
        .expect("send SIGINT");
    assert!(signalled.success(), "kill -INT {pid} failed");

    // The cancellation lands in whatever trace follows the signal.
    stderr
        .read_to_string(&mut trace)
        .await
        .expect("drain wire trace");
    let status = tokio::time::timeout(CASE_TIMEOUT, child.wait())
        .await
        .expect("cancellation case timed out")
        .expect("wait for cancellation case");

    assert_eq!(
        status.code(),
        Some(6),
        "an interrupted command exits cancelled:\n{trace}"
    );
    assert!(
        trace.contains("notifications/cancelled"),
        "the server is never told the call was abandoned:\n{trace}"
    );
    let id = traced_request_id(&trace, "tools/call");
    // Unquoted in the pretty-printed frame, so this also pins the JSON type:
    // a numeric id must not be reported as a string.
    assert!(
        trace.contains(&format!("\"requestId\": {id}")),
        "the cancellation names request {id}:\n{trace}"
    );
}

/// The id of the last traced request for `method`, read back out of the
/// pretty-printed frame that `--trace` writes.
#[cfg(unix)]
fn traced_request_id(trace: &str, method: &str) -> u64 {
    let frame = trace
        .rsplit_once(&format!("\"method\": \"{method}\""))
        .unwrap_or_else(|| panic!("no traced {method} request in:\n{trace}"))
        .0;
    let (_, id) = frame
        .rsplit_once("\"id\": ")
        .unwrap_or_else(|| panic!("traced {method} request carries no id in:\n{trace}"));
    id.trim_start()
        .trim_end_matches([',', '\n', ' '])
        .split(['\n', ','])
        .next()
        .and_then(|value| value.trim().parse().ok())
        .unwrap_or_else(|| panic!("unparsable {method} request id in:\n{trace}"))
}

async fn exercise_interactive_final_task(http: &HttpFixture) {
    let mut command = repl_command();
    command
        .args([
            "--protocol",
            "2026-07-28",
            "--no-history",
            "--color",
            "never",
            "--http",
            &http.url,
        ])
        .stdin(std::process::Stdio::piped())
        .stdout(std::process::Stdio::piped())
        .stderr(std::process::Stdio::piped())
        .kill_on_drop(true);
    let mut child = command.spawn().expect("spawn interactive final mcp-repl");
    let mut stdin = child.stdin.take().expect("interactive stdin");
    stdin
        .write_all(b"slow_add a=2 b=3 &\n")
        .await
        .expect("write task command");
    wait_for_file(&http.subscription_file, "final subscription").await;
    // The subscription is immediate, while the bounded task poller remains a
    // fallback. The fixture advertises a two-second poll interval, so leave a
    // full extra second for the fallback to observe completion before asking
    // the editor thread to exit.
    tokio::time::sleep(Duration::from_millis(3_000)).await;
    stdin
        .write_all(b"jobs\nquit\n")
        .await
        .expect("write task status and quit commands");
    drop(stdin);
    let output = tokio::time::timeout(CASE_TIMEOUT, child.wait_with_output())
        .await
        .expect("interactive final case timed out")
        .expect("wait for interactive final case");
    assert_success(&output, "interactive final task");
    let stdout = String::from_utf8_lossy(&output.stdout);
    assert!(stdout.contains("started"), "{stdout}");
    assert!(stdout.contains("completed"), "{stdout}");
}

async fn exercise_http(fixture: &Path, temp: &TempDir) {
    let http = HttpFixture::start(fixture, temp).await;

    exercise_imported_http_config(&http, temp).await;

    let stable = run_http(
        &http.url,
        "stable HTTP",
        &[
            "--protocol",
            "stable",
            "--verbose",
            "--exec",
            "prompt greet name=Grace",
            "--exec",
            "announce",
        ],
    )
    .await;
    assert_success(&stable, "stable HTTP");
    let stdout = String::from_utf8_lossy(&stable.stdout);
    let stderr = String::from_utf8_lossy(&stable.stderr);
    assert!(stdout.contains("protocol 2025-11-25"), "{stdout}");
    assert!(stdout.contains("Please greet Grace warmly."), "{stdout}");
    assert!(stderr.contains("fixture announcement"), "{stderr}");

    let final_ = run_http(
        &http.url,
        "final HTTP",
        &[
            "--protocol",
            "2026-07-28",
            "--json",
            "--exec",
            "add a=40 b=2",
            "--exec",
            "read fixture://guide",
        ],
    )
    .await;
    assert_success(&final_, "final HTTP");
    let stdout = String::from_utf8_lossy(&final_.stdout);
    assert!(stdout.contains("42"), "{stdout}");
    assert!(stdout.contains("fixture resource body"), "{stdout}");

    exercise_interactive_final_task(&http).await;
    http.shutdown().await;
}

/// The generators run before anything connects, so they need no server, no
/// config file, and no terminal. That is the property a packaging script
/// depends on, and it only holds at the process boundary.
async fn exercise_generators() {
    // Each shell spells a long option its own way: bash and zsh emit
    // `--protocol`, fish emits `-l protocol`.
    for (shell, marker, protocol_flag, demo_flag) in [
        ("bash", "complete -F _mcp-repl", "--protocol", "--demo"),
        ("zsh", "#compdef mcp-repl", "--protocol", "--demo"),
        ("fish", "complete -c mcp-repl", "-l protocol", "-l demo"),
    ] {
        let mut command = repl_command();
        command.args(["--completions", shell]);
        let output = run(command, &format!("completions {shell}"), CASE_TIMEOUT).await;
        assert_success(&output, &format!("completions {shell}"));
        let script = String::from_utf8_lossy(&output.stdout);
        assert!(
            script.contains(marker),
            "{shell} completion does not look like a {shell} script:\n{script}"
        );
        // The flags a user actually reaches for, from the live command
        // definition rather than a snapshot that could drift.
        assert!(
            script.contains(protocol_flag),
            "{shell} completion lost {protocol_flag}"
        );
        assert!(
            script.contains(demo_flag),
            "{shell} completion lost {demo_flag}"
        );
        assert!(
            String::from_utf8_lossy(&output.stderr).is_empty(),
            "a generator must leave stdout clean and say nothing on stderr"
        );
    }

    let mut command = repl_command();
    command.arg("--man");
    let output = run(command, "man page", CASE_TIMEOUT).await;
    assert_success(&output, "man page");
    let roff = String::from_utf8_lossy(&output.stdout);
    for section in [".SH NAME", ".SH SYNOPSIS", ".SH DESCRIPTION", ".SH OPTIONS"] {
        assert!(roff.contains(section), "man page has no {section}");
    }
    assert!(roff.contains("mcp-repl"));
}

#[tokio::test(flavor = "multi_thread")]
async fn published_cli_covers_transports_and_protocol_lifecycles() {
    tokio::time::timeout(SUITE_TIMEOUT, async {
        let temp = TempDir::new().expect("temporary fixture directory");
        let fixture = build_fixture().await;
        exercise_generators().await;
        exercise_connection_failure_output().await;
        exercise_elicitation_field_order().await;
        exercise_respond_needs_the_final_lifecycle().await;
        #[cfg(unix)]
        exercise_cancellation().await;
        exercise_json_contract(&fixture, &temp).await;
        exercise_exec_waits_for_its_own_tasks(&fixture, &temp).await;
        exercise_tools_only_server(&fixture, &temp).await;
        exercise_loglevel(&fixture, &temp).await;
        exercise_sampling().await;
        exercise_repl_config(&temp).await;
        exercise_login_json(&temp).await;
        exercise_unreadable_listing(&fixture, &temp).await;
        exercise_absent_cursor(&fixture, &temp).await;
        exercise_downgraded_protocol(&fixture, &temp).await;
        exercise_schema_contracts(&fixture, &temp).await;
        exercise_imported_stdio_config(&fixture, &temp).await;
        exercise_stdio(&fixture, &temp).await;
        exercise_http(&fixture, &temp).await;
    })
    .await
    .expect("mcp-repl E2E suite exceeded its job-level timeout");
}