purple-ssh 2.45.0

Open-source terminal SSH manager and SSH config editor. Search hundreds of hosts, sync from 16 clouds, transfer files, manage Docker and Podman over SSH, sign short-lived Vault SSH certs and expose an MCP server for AI agents. Rust TUI, MIT licensed.
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
use super::*;

/// Build a default `McpContext` and dispatch. Lets existing tests stay focused
/// on input/output without re-stating the no-op default options every time.
fn mcp_dispatch(method: &str, params: Option<Value>, path: &std::path::Path) -> JsonRpcResponse {
    let ctx = McpContext::new(path.to_path_buf(), McpOptions::default());
    dispatch(method, params, &ctx)
}

/// Build a context with a custom `McpOptions` (read-only and/or audit log).
fn mcp_dispatch_with(
    method: &str,
    params: Option<Value>,
    path: &std::path::Path,
    options: McpOptions,
) -> (JsonRpcResponse, McpContext) {
    let ctx = McpContext::new(path.to_path_buf(), options);
    let resp = dispatch(method, params, &ctx);
    (resp, ctx)
}

// --- Task 1: JSON-RPC types and parsing ---

#[test]
fn parse_valid_request() {
    let json = r#"{"jsonrpc":"2.0","id":1,"method":"initialize","params":{}}"#;
    let req: JsonRpcRequest = serde_json::from_str(json).unwrap();
    assert_eq!(req.method, "initialize");
    assert_eq!(req.id, Some(Value::Number(1.into())));
}

#[test]
fn parse_notification_no_id() {
    let json = r#"{"jsonrpc":"2.0","method":"notifications/initialized"}"#;
    let req: JsonRpcRequest = serde_json::from_str(json).unwrap();
    assert!(req.id.is_none());
    assert!(req.params.is_none());
}

#[test]
fn parse_invalid_json() {
    let result: Result<JsonRpcRequest, _> = serde_json::from_str("not json");
    assert!(result.is_err());
}

#[test]
fn response_success_serialization() {
    let resp = JsonRpcResponse::success(Some(Value::Number(1.into())), Value::Bool(true));
    let json = serde_json::to_string(&resp).unwrap();
    assert!(json.contains(r#""result":true"#));
    assert!(!json.contains("error"));
}

#[test]
fn response_error_serialization() {
    let resp = JsonRpcResponse::error(
        Some(Value::Number(1.into())),
        -32601,
        "Method not found".to_string(),
    );
    let json = serde_json::to_string(&resp).unwrap();
    assert!(json.contains("-32601"));
    assert!(!json.contains("result"));
}

// --- Task 2: MCP initialize and tools/list handlers ---

#[test]
fn test_handle_initialize() {
    let params = serde_json::json!({
        "protocolVersion": "2024-11-05",
        "capabilities": {},
        "clientInfo": {"name": "test", "version": "1.0"}
    });
    let resp = mcp_dispatch(
        "initialize",
        Some(params),
        &std::path::PathBuf::from("/dev/null"),
    );
    let result = resp.result.unwrap();
    assert_eq!(result["protocolVersion"], "2024-11-05");
    assert!(result["capabilities"]["tools"].is_object());
    assert_eq!(result["serverInfo"]["name"], "purple");
}

#[test]
fn test_handle_tools_list() {
    let resp = mcp_dispatch("tools/list", None, &std::path::PathBuf::from("/dev/null"));
    let result = resp.result.unwrap();
    let tools = result["tools"].as_array().unwrap();
    assert_eq!(tools.len(), 5);
    let names: Vec<&str> = tools.iter().map(|t| t["name"].as_str().unwrap()).collect();
    assert!(names.contains(&"list_hosts"));
    assert!(names.contains(&"get_host"));
    assert!(names.contains(&"run_command"));
    assert!(names.contains(&"list_containers"));
    assert!(names.contains(&"container_action"));
}

#[test]
fn test_handle_unknown_method() {
    let resp = mcp_dispatch("bogus/method", None, &std::path::PathBuf::from("/dev/null"));
    assert!(resp.error.is_some());
    assert_eq!(resp.error.unwrap().code, -32601);
}

// --- Task 3: list_hosts and get_host tool handlers ---

#[test]
fn tool_list_hosts_returns_all_concrete_hosts() {
    let config_path = std::path::PathBuf::from("tests/fixtures/mcp_test_config");
    let args = serde_json::json!({});
    let resp = mcp_dispatch(
        "tools/call",
        Some(serde_json::json!({"name": "list_hosts", "arguments": args})),
        &config_path,
    );
    let result = resp.result.unwrap();
    let text = result["content"][0]["text"].as_str().unwrap();
    let hosts: Vec<Value> = serde_json::from_str(text).unwrap();
    assert_eq!(hosts.len(), 2);
    assert_eq!(hosts[0]["alias"], "web-1");
    assert_eq!(hosts[1]["alias"], "db-1");
}

#[test]
fn tool_list_hosts_filter_by_tag() {
    let config_path = std::path::PathBuf::from("tests/fixtures/mcp_test_config");
    let args = serde_json::json!({"tag": "database"});
    let resp = mcp_dispatch(
        "tools/call",
        Some(serde_json::json!({"name": "list_hosts", "arguments": args})),
        &config_path,
    );
    let result = resp.result.unwrap();
    let text = result["content"][0]["text"].as_str().unwrap();
    let hosts: Vec<Value> = serde_json::from_str(text).unwrap();
    assert_eq!(hosts.len(), 1);
    assert_eq!(hosts[0]["alias"], "db-1");
}

#[test]
fn tool_get_host_found() {
    let config_path = std::path::PathBuf::from("tests/fixtures/mcp_test_config");
    let args = serde_json::json!({"alias": "web-1"});
    let resp = mcp_dispatch(
        "tools/call",
        Some(serde_json::json!({"name": "get_host", "arguments": args})),
        &config_path,
    );
    let result = resp.result.unwrap();
    let text = result["content"][0]["text"].as_str().unwrap();
    let host: Value = serde_json::from_str(text).unwrap();
    assert_eq!(host["alias"], "web-1");
    assert_eq!(host["hostname"], "10.0.1.5");
    assert_eq!(host["user"], "deploy");
    assert_eq!(host["identity_file"], "~/.ssh/id_ed25519");
    assert_eq!(host["provider"], "aws");
}

#[test]
fn tool_get_host_not_found() {
    let config_path = std::path::PathBuf::from("tests/fixtures/mcp_test_config");
    let args = serde_json::json!({"alias": "nonexistent"});
    let resp = mcp_dispatch(
        "tools/call",
        Some(serde_json::json!({"name": "get_host", "arguments": args})),
        &config_path,
    );
    let result = resp.result.unwrap();
    assert!(result["isError"].as_bool().unwrap());
}

#[test]
fn tool_get_host_missing_alias() {
    let config_path = std::path::PathBuf::from("tests/fixtures/mcp_test_config");
    let args = serde_json::json!({});
    let resp = mcp_dispatch(
        "tools/call",
        Some(serde_json::json!({"name": "get_host", "arguments": args})),
        &config_path,
    );
    let result = resp.result.unwrap();
    assert!(result["isError"].as_bool().unwrap());
}

// --- Task 4: run_command tool handler ---

#[test]
fn tool_run_command_missing_alias() {
    let config_path = std::path::PathBuf::from("tests/fixtures/mcp_test_config");
    let args = serde_json::json!({"command": "uptime"});
    let resp = mcp_dispatch(
        "tools/call",
        Some(serde_json::json!({"name": "run_command", "arguments": args})),
        &config_path,
    );
    let result = resp.result.unwrap();
    assert!(result["isError"].as_bool().unwrap());
}

#[test]
fn tool_run_command_missing_command() {
    let config_path = std::path::PathBuf::from("tests/fixtures/mcp_test_config");
    let args = serde_json::json!({"alias": "web-1"});
    let resp = mcp_dispatch(
        "tools/call",
        Some(serde_json::json!({"name": "run_command", "arguments": args})),
        &config_path,
    );
    let result = resp.result.unwrap();
    assert!(result["isError"].as_bool().unwrap());
}

#[test]
fn tool_run_command_empty_alias() {
    let config_path = std::path::PathBuf::from("tests/fixtures/mcp_test_config");
    let args = serde_json::json!({"alias": "", "command": "uptime"});
    let resp = mcp_dispatch(
        "tools/call",
        Some(serde_json::json!({"name": "run_command", "arguments": args})),
        &config_path,
    );
    let result = resp.result.unwrap();
    assert!(result["isError"].as_bool().unwrap());
}

#[test]
fn tool_run_command_empty_command() {
    let config_path = std::path::PathBuf::from("tests/fixtures/mcp_test_config");
    let args = serde_json::json!({"alias": "web-1", "command": ""});
    let resp = mcp_dispatch(
        "tools/call",
        Some(serde_json::json!({"name": "run_command", "arguments": args})),
        &config_path,
    );
    let result = resp.result.unwrap();
    assert!(result["isError"].as_bool().unwrap());
}

// --- Task 5: list_containers and container_action tool handlers ---

#[test]
fn tool_list_containers_missing_alias() {
    let config_path = std::path::PathBuf::from("tests/fixtures/mcp_test_config");
    let args = serde_json::json!({});
    let resp = mcp_dispatch(
        "tools/call",
        Some(serde_json::json!({"name": "list_containers", "arguments": args})),
        &config_path,
    );
    let result = resp.result.unwrap();
    assert!(result["isError"].as_bool().unwrap());
}

#[test]
fn tool_container_action_missing_fields() {
    let config_path = std::path::PathBuf::from("tests/fixtures/mcp_test_config");
    let args = serde_json::json!({"alias": "web-1", "action": "start"});
    let resp = mcp_dispatch(
        "tools/call",
        Some(serde_json::json!({"name": "container_action", "arguments": args})),
        &config_path,
    );
    let result = resp.result.unwrap();
    assert!(result["isError"].as_bool().unwrap());
}

#[test]
fn tool_container_action_invalid_action() {
    let config_path = std::path::PathBuf::from("tests/fixtures/mcp_test_config");
    let args = serde_json::json!({"alias": "web-1", "container_id": "abc", "action": "destroy"});
    let resp = mcp_dispatch(
        "tools/call",
        Some(serde_json::json!({"name": "container_action", "arguments": args})),
        &config_path,
    );
    let result = resp.result.unwrap();
    assert!(result["isError"].as_bool().unwrap());
}

#[test]
fn tool_container_action_invalid_container_id() {
    let config_path = std::path::PathBuf::from("tests/fixtures/mcp_test_config");
    let args =
        serde_json::json!({"alias": "web-1", "container_id": "abc;rm -rf /", "action": "start"});
    let resp = mcp_dispatch(
        "tools/call",
        Some(serde_json::json!({"name": "container_action", "arguments": args})),
        &config_path,
    );
    let result = resp.result.unwrap();
    assert!(result["isError"].as_bool().unwrap());
}

// --- Protocol-level tests ---

#[test]
fn tools_call_missing_params() {
    let config_path = std::path::PathBuf::from("tests/fixtures/mcp_test_config");
    let resp = mcp_dispatch("tools/call", None, &config_path);
    assert!(resp.result.is_none());
    let err = resp.error.unwrap();
    assert_eq!(err.code, -32602);
    assert!(err.message.contains("missing params"));
}

#[test]
fn tools_call_missing_tool_name() {
    let config_path = std::path::PathBuf::from("tests/fixtures/mcp_test_config");
    let resp = mcp_dispatch(
        "tools/call",
        Some(serde_json::json!({"arguments": {}})),
        &config_path,
    );
    assert!(resp.result.is_none());
    let err = resp.error.unwrap();
    assert_eq!(err.code, -32602);
    assert!(err.message.contains("missing tool name"));
}

#[test]
fn tools_call_unknown_tool() {
    let config_path = std::path::PathBuf::from("tests/fixtures/mcp_test_config");
    let resp = mcp_dispatch(
        "tools/call",
        Some(serde_json::json!({"name": "nonexistent_tool", "arguments": {}})),
        &config_path,
    );
    let result = resp.result.unwrap();
    assert!(result["isError"].as_bool().unwrap());
    assert!(
        result["content"][0]["text"]
            .as_str()
            .unwrap()
            .contains("Unknown tool")
    );
}

#[test]
fn tools_call_name_is_number_not_string() {
    let config_path = std::path::PathBuf::from("tests/fixtures/mcp_test_config");
    let resp = mcp_dispatch(
        "tools/call",
        Some(serde_json::json!({"name": 42, "arguments": {}})),
        &config_path,
    );
    assert!(resp.result.is_none());
    let err = resp.error.unwrap();
    assert_eq!(err.code, -32602);
}

#[test]
fn tools_call_no_arguments_field() {
    // arguments defaults to {} when missing
    let config_path = std::path::PathBuf::from("tests/fixtures/mcp_test_config");
    let resp = mcp_dispatch(
        "tools/call",
        Some(serde_json::json!({"name": "list_hosts"})),
        &config_path,
    );
    let result = resp.result.unwrap();
    // Should succeed - list_hosts with no args returns all hosts
    assert!(result.get("isError").is_none());
    let text = result["content"][0]["text"].as_str().unwrap();
    let hosts: Vec<Value> = serde_json::from_str(text).unwrap();
    assert_eq!(hosts.len(), 2);
}

// --- list_hosts additional tests ---

#[test]
fn tool_list_hosts_empty_config() {
    let config_path = std::path::PathBuf::from("tests/fixtures/mcp_empty_config");
    let resp = mcp_dispatch(
        "tools/call",
        Some(serde_json::json!({"name": "list_hosts", "arguments": {}})),
        &config_path,
    );
    let result = resp.result.unwrap();
    let text = result["content"][0]["text"].as_str().unwrap();
    let hosts: Vec<Value> = serde_json::from_str(text).unwrap();
    assert!(hosts.is_empty());
}

#[test]
fn tool_list_hosts_filter_by_provider_name() {
    let config_path = std::path::PathBuf::from("tests/fixtures/mcp_test_config");
    let args = serde_json::json!({"tag": "aws"});
    let resp = mcp_dispatch(
        "tools/call",
        Some(serde_json::json!({"name": "list_hosts", "arguments": args})),
        &config_path,
    );
    let result = resp.result.unwrap();
    let text = result["content"][0]["text"].as_str().unwrap();
    let hosts: Vec<Value> = serde_json::from_str(text).unwrap();
    assert_eq!(hosts.len(), 1);
    assert_eq!(hosts[0]["alias"], "web-1");
}

#[test]
fn tool_list_hosts_filter_case_insensitive() {
    let config_path = std::path::PathBuf::from("tests/fixtures/mcp_test_config");
    let args = serde_json::json!({"tag": "PROD"});
    let resp = mcp_dispatch(
        "tools/call",
        Some(serde_json::json!({"name": "list_hosts", "arguments": args})),
        &config_path,
    );
    let result = resp.result.unwrap();
    let text = result["content"][0]["text"].as_str().unwrap();
    let hosts: Vec<Value> = serde_json::from_str(text).unwrap();
    assert_eq!(hosts.len(), 2); // both web-1 and db-1 have "prod" tag
}

#[test]
fn tool_list_hosts_filter_no_match() {
    let config_path = std::path::PathBuf::from("tests/fixtures/mcp_test_config");
    let args = serde_json::json!({"tag": "nonexistent-tag"});
    let resp = mcp_dispatch(
        "tools/call",
        Some(serde_json::json!({"name": "list_hosts", "arguments": args})),
        &config_path,
    );
    let result = resp.result.unwrap();
    let text = result["content"][0]["text"].as_str().unwrap();
    let hosts: Vec<Value> = serde_json::from_str(text).unwrap();
    assert!(hosts.is_empty());
}

// Regression for the .mcpb-with-unexpanded-${HOME} bug. Before this guard
// existed the parser silently produced an empty config for missing files,
// and list_hosts returned `[]` with `isError: false`. The MCP client then
// presented "no hosts configured" to the user instead of surfacing the real
// problem.
#[test]
fn tool_list_hosts_missing_config_returns_explicit_error() {
    let config_path = std::path::PathBuf::from("/nonexistent/purple/mcp/test/path/ssh_config");
    let resp = mcp_dispatch(
        "tools/call",
        Some(serde_json::json!({"name": "list_hosts", "arguments": {}})),
        &config_path,
    );
    let result = resp.result.unwrap();
    assert_eq!(
        result["isError"].as_bool(),
        Some(true),
        "missing config must surface as MCP-level error, not empty result"
    );
    let text = result["content"][0]["text"].as_str().unwrap();
    assert!(
        text.contains("not found"),
        "error message must indicate the file is missing, got: {text}"
    );
}

#[test]
fn tool_get_host_missing_config_returns_explicit_error() {
    let config_path = std::path::PathBuf::from("/nonexistent/purple/mcp/test/path/ssh_config");
    let resp = mcp_dispatch(
        "tools/call",
        Some(serde_json::json!({
            "name": "get_host",
            "arguments": {"alias": "anything"}
        })),
        &config_path,
    );
    let result = resp.result.unwrap();
    assert_eq!(result["isError"].as_bool(), Some(true));
}

#[test]
fn tool_list_hosts_filter_by_provider_tags() {
    let config_path = std::path::PathBuf::from("tests/fixtures/mcp_provider_tags_config");
    let args = serde_json::json!({"tag": "backend"});
    let resp = mcp_dispatch(
        "tools/call",
        Some(serde_json::json!({"name": "list_hosts", "arguments": args})),
        &config_path,
    );
    let result = resp.result.unwrap();
    let text = result["content"][0]["text"].as_str().unwrap();
    let hosts: Vec<Value> = serde_json::from_str(text).unwrap();
    assert_eq!(hosts.len(), 1);
    assert_eq!(hosts[0]["alias"], "tagged-1");
}

#[test]
fn tool_list_hosts_stale_field_is_boolean() {
    let config_path = std::path::PathBuf::from("tests/fixtures/mcp_stale_config");
    let resp = mcp_dispatch(
        "tools/call",
        Some(serde_json::json!({"name": "list_hosts", "arguments": {}})),
        &config_path,
    );
    let result = resp.result.unwrap();
    let text = result["content"][0]["text"].as_str().unwrap();
    let hosts: Vec<Value> = serde_json::from_str(text).unwrap();
    let stale_host = hosts.iter().find(|h| h["alias"] == "stale-1").unwrap();
    let active_host = hosts.iter().find(|h| h["alias"] == "active-1").unwrap();
    assert_eq!(stale_host["stale"], true);
    assert_eq!(active_host["stale"], false);
}

#[test]
fn tool_list_hosts_output_fields() {
    let config_path = std::path::PathBuf::from("tests/fixtures/mcp_test_config");
    let resp = mcp_dispatch(
        "tools/call",
        Some(serde_json::json!({"name": "list_hosts", "arguments": {}})),
        &config_path,
    );
    let result = resp.result.unwrap();
    let text = result["content"][0]["text"].as_str().unwrap();
    let hosts: Vec<Value> = serde_json::from_str(text).unwrap();
    let host = &hosts[0];
    // Verify all expected fields are present
    assert!(host.get("alias").is_some());
    assert!(host.get("hostname").is_some());
    assert!(host.get("user").is_some());
    assert!(host.get("port").is_some());
    assert!(host.get("tags").is_some());
    assert!(host.get("provider").is_some());
    assert!(host.get("stale").is_some());
    // Verify types
    assert!(host["port"].is_number());
    assert!(host["tags"].is_array());
    assert!(host["stale"].is_boolean());
}

// --- get_host additional tests ---

#[test]
fn tool_get_host_rejects_empty_alias() {
    let config_path = std::path::PathBuf::from("tests/fixtures/mcp_test_config");
    let args = serde_json::json!({"alias": ""});
    let resp = mcp_dispatch(
        "tools/call",
        Some(serde_json::json!({"name": "get_host", "arguments": args})),
        &config_path,
    );
    let result = resp.result.unwrap();
    assert_eq!(result["isError"], true);
    let text = result["content"][0]["text"].as_str().unwrap();
    assert_eq!(text, "Missing required parameter: alias");
}

#[test]
fn tool_get_host_alias_is_number() {
    let config_path = std::path::PathBuf::from("tests/fixtures/mcp_test_config");
    let args = serde_json::json!({"alias": 42});
    let resp = mcp_dispatch(
        "tools/call",
        Some(serde_json::json!({"name": "get_host", "arguments": args})),
        &config_path,
    );
    let result = resp.result.unwrap();
    assert!(result["isError"].as_bool().unwrap());
}

#[test]
fn tool_get_host_output_fields() {
    let config_path = std::path::PathBuf::from("tests/fixtures/mcp_test_config");
    let args = serde_json::json!({"alias": "web-1"});
    let resp = mcp_dispatch(
        "tools/call",
        Some(serde_json::json!({"name": "get_host", "arguments": args})),
        &config_path,
    );
    let result = resp.result.unwrap();
    let text = result["content"][0]["text"].as_str().unwrap();
    let host: Value = serde_json::from_str(text).unwrap();
    // Verify all expected fields
    assert_eq!(host["port"], 22);
    assert!(host["tags"].is_array());
    assert!(host["provider_tags"].is_array());
    assert!(host["provider_meta"].is_object());
    assert!(host["stale"].is_boolean());
    assert_eq!(host["stale"], false);
    assert_eq!(host["tunnel_count"], 0);
    // Verify provider_meta content
    assert_eq!(host["provider_meta"]["region"], "us-east-1");
    assert_eq!(host["provider_meta"]["instance"], "t3.micro");
}

#[test]
fn tool_get_host_no_provider() {
    let config_path = std::path::PathBuf::from("tests/fixtures/mcp_test_config");
    let args = serde_json::json!({"alias": "db-1"});
    let resp = mcp_dispatch(
        "tools/call",
        Some(serde_json::json!({"name": "get_host", "arguments": args})),
        &config_path,
    );
    let result = resp.result.unwrap();
    let text = result["content"][0]["text"].as_str().unwrap();
    let host: Value = serde_json::from_str(text).unwrap();
    assert!(host["provider"].is_null());
    assert!(host["provider_meta"].as_object().unwrap().is_empty());
    assert_eq!(host["port"], 5432);
}

#[test]
fn tool_get_host_stale_is_boolean() {
    let config_path = std::path::PathBuf::from("tests/fixtures/mcp_stale_config");
    let args = serde_json::json!({"alias": "stale-1"});
    let resp = mcp_dispatch(
        "tools/call",
        Some(serde_json::json!({"name": "get_host", "arguments": args})),
        &config_path,
    );
    let result = resp.result.unwrap();
    let text = result["content"][0]["text"].as_str().unwrap();
    let host: Value = serde_json::from_str(text).unwrap();
    assert_eq!(host["stale"], true);
}

#[test]
fn tool_get_host_case_sensitive() {
    let config_path = std::path::PathBuf::from("tests/fixtures/mcp_test_config");
    let args = serde_json::json!({"alias": "WEB-1"});
    let resp = mcp_dispatch(
        "tools/call",
        Some(serde_json::json!({"name": "get_host", "arguments": args})),
        &config_path,
    );
    let result = resp.result.unwrap();
    assert!(result["isError"].as_bool().unwrap());
}

// --- run_command additional tests ---

#[test]
fn tool_run_command_nonexistent_alias() {
    let config_path = std::path::PathBuf::from("tests/fixtures/mcp_test_config");
    let args = serde_json::json!({"alias": "nonexistent-host", "command": "uptime"});
    let resp = mcp_dispatch(
        "tools/call",
        Some(serde_json::json!({"name": "run_command", "arguments": args})),
        &config_path,
    );
    let result = resp.result.unwrap();
    assert!(result["isError"].as_bool().unwrap());
    assert!(
        result["content"][0]["text"]
            .as_str()
            .unwrap()
            .contains("not found")
    );
}

#[test]
fn tool_run_command_alias_is_number() {
    let config_path = std::path::PathBuf::from("tests/fixtures/mcp_test_config");
    let args = serde_json::json!({"alias": 42, "command": "uptime"});
    let resp = mcp_dispatch(
        "tools/call",
        Some(serde_json::json!({"name": "run_command", "arguments": args})),
        &config_path,
    );
    let result = resp.result.unwrap();
    assert!(result["isError"].as_bool().unwrap());
}

#[test]
fn tool_run_command_rejects_non_string_command() {
    let config_path = std::path::PathBuf::from("tests/fixtures/mcp_test_config");
    let args = serde_json::json!({"alias": "web-1", "command": 123});
    let resp = mcp_dispatch(
        "tools/call",
        Some(serde_json::json!({"name": "run_command", "arguments": args})),
        &config_path,
    );
    let result = resp.result.unwrap();
    assert!(result["isError"].as_bool().unwrap());
}

#[test]
fn tool_run_command_timeout_string_falls_back_to_default() {
    // Use a deliberately non-existent alias so the test never invokes ssh
    // even if the local fixture name resolves on the host machine.
    let config_path = std::path::PathBuf::from("tests/fixtures/mcp_test_config");
    let args = serde_json::json!({
        "alias": "nonexistent-host",
        "command": "uptime",
        "timeout": "not-a-number"
    });
    let resp = mcp_dispatch(
        "tools/call",
        Some(serde_json::json!({"name": "run_command", "arguments": args})),
        &config_path,
    );
    let result = resp.result.unwrap();
    assert_eq!(result["isError"], true);
    // The error should be the alias-not-found path, not an input validation
    // error - which proves the bad timeout was tolerated.
    let text = result["content"][0]["text"].as_str().unwrap();
    assert!(text.contains("not found"), "got: {text}");
}

// --- container_action additional tests ---

#[test]
fn tool_container_action_empty_alias() {
    let config_path = std::path::PathBuf::from("tests/fixtures/mcp_test_config");
    let args = serde_json::json!({"alias": "", "container_id": "abc", "action": "start"});
    let resp = mcp_dispatch(
        "tools/call",
        Some(serde_json::json!({"name": "container_action", "arguments": args})),
        &config_path,
    );
    let result = resp.result.unwrap();
    assert!(result["isError"].as_bool().unwrap());
}

#[test]
fn tool_container_action_empty_container_id() {
    let config_path = std::path::PathBuf::from("tests/fixtures/mcp_test_config");
    let args = serde_json::json!({"alias": "web-1", "container_id": "", "action": "start"});
    let resp = mcp_dispatch(
        "tools/call",
        Some(serde_json::json!({"name": "container_action", "arguments": args})),
        &config_path,
    );
    let result = resp.result.unwrap();
    assert!(result["isError"].as_bool().unwrap());
}

#[test]
fn tool_container_action_nonexistent_alias() {
    let config_path = std::path::PathBuf::from("tests/fixtures/mcp_test_config");
    let args =
        serde_json::json!({"alias": "nonexistent", "container_id": "abc", "action": "start"});
    let resp = mcp_dispatch(
        "tools/call",
        Some(serde_json::json!({"name": "container_action", "arguments": args})),
        &config_path,
    );
    let result = resp.result.unwrap();
    assert!(result["isError"].as_bool().unwrap());
    assert!(
        result["content"][0]["text"]
            .as_str()
            .unwrap()
            .contains("not found")
    );
}

#[test]
fn tool_container_action_uppercase_action() {
    let config_path = std::path::PathBuf::from("tests/fixtures/mcp_test_config");
    let args = serde_json::json!({"alias": "web-1", "container_id": "abc", "action": "START"});
    let resp = mcp_dispatch(
        "tools/call",
        Some(serde_json::json!({"name": "container_action", "arguments": args})),
        &config_path,
    );
    let result = resp.result.unwrap();
    assert!(result["isError"].as_bool().unwrap());
    assert!(
        result["content"][0]["text"]
            .as_str()
            .unwrap()
            .contains("Invalid action")
    );
}

#[test]
fn tool_container_action_container_id_with_dots_and_hyphens() {
    // Valid container IDs can have dots, hyphens, underscores
    let config_path = std::path::PathBuf::from("tests/fixtures/mcp_test_config");
    let args = serde_json::json!({"alias": "web-1", "container_id": "my-container_v1.2", "action": "start"});
    let resp = mcp_dispatch(
        "tools/call",
        Some(serde_json::json!({"name": "container_action", "arguments": args})),
        &config_path,
    );
    let result = resp.result.unwrap();
    // Should NOT error on validation - container_id is valid
    // Will proceed to alias check and SSH (which may fail), but no validation error
    let text = result["content"][0]["text"].as_str().unwrap();
    assert!(!text.contains("invalid character"));
}

#[test]
fn tool_container_action_container_id_with_spaces() {
    let config_path = std::path::PathBuf::from("tests/fixtures/mcp_test_config");
    let args =
        serde_json::json!({"alias": "web-1", "container_id": "my container", "action": "start"});
    let resp = mcp_dispatch(
        "tools/call",
        Some(serde_json::json!({"name": "container_action", "arguments": args})),
        &config_path,
    );
    let result = resp.result.unwrap();
    assert!(result["isError"].as_bool().unwrap());
    assert!(
        result["content"][0]["text"]
            .as_str()
            .unwrap()
            .contains("invalid character")
    );
}

#[test]
fn tool_list_containers_rejects_empty_alias() {
    let config_path = std::path::PathBuf::from("tests/fixtures/mcp_test_config");
    let args = serde_json::json!({"alias": ""});
    let resp = mcp_dispatch(
        "tools/call",
        Some(serde_json::json!({"name": "list_containers", "arguments": args})),
        &config_path,
    );
    let result = resp.result.unwrap();
    assert!(result["isError"].as_bool().unwrap());
}

#[test]
fn tool_list_containers_nonexistent_alias() {
    let config_path = std::path::PathBuf::from("tests/fixtures/mcp_test_config");
    let args = serde_json::json!({"alias": "nonexistent"});
    let resp = mcp_dispatch(
        "tools/call",
        Some(serde_json::json!({"name": "list_containers", "arguments": args})),
        &config_path,
    );
    let result = resp.result.unwrap();
    assert!(result["isError"].as_bool().unwrap());
    assert!(
        result["content"][0]["text"]
            .as_str()
            .unwrap()
            .contains("not found")
    );
}

// --- initialize and tools/list output tests ---

#[test]
fn initialize_contains_version() {
    let resp = mcp_dispatch("initialize", None, &std::path::PathBuf::from("/dev/null"));
    let result = resp.result.unwrap();
    assert!(!result["serverInfo"]["version"].as_str().unwrap().is_empty());
}

#[test]
fn tools_list_schema_has_required_fields() {
    let resp = mcp_dispatch("tools/list", None, &std::path::PathBuf::from("/dev/null"));
    let result = resp.result.unwrap();
    let tools = result["tools"].as_array().unwrap();
    for tool in tools {
        assert!(tool["name"].is_string(), "Tool missing name");
        assert!(tool["description"].is_string(), "Tool missing description");
        assert!(tool["inputSchema"].is_object(), "Tool missing inputSchema");
        assert_eq!(tool["inputSchema"]["type"], "object");
    }
}

#[test]
fn every_tool_has_annotations_required_by_directory_submission() {
    // Anthropic's Desktop Extension submission requires every tool to expose
    // a `title` and the appropriate `readOnlyHint` or `destructiveHint`. The
    // hints must agree with the READ_ONLY_TOOLS allowlist: a tool is in the
    // allowlist iff `readOnlyHint == true` and `destructiveHint == false`.
    let resp = mcp_dispatch("tools/list", None, &std::path::PathBuf::from("/dev/null"));
    let result = resp.result.unwrap();
    let tools = result["tools"].as_array().unwrap();
    for tool in tools {
        let name = tool["name"].as_str().unwrap();
        let ann = &tool["annotations"];
        assert!(
            ann.is_object(),
            "{name} is missing the annotations object required for directory submission"
        );
        let title = ann["title"].as_str();
        assert!(
            title.is_some_and(|s| s.len() >= 5 && !s.contains('_')),
            "{name} annotations.title must be a human readable string (>=5 chars, no underscores), got {title:?}"
        );
        let read_only = ann["readOnlyHint"]
            .as_bool()
            .expect("readOnlyHint must be a bool");
        let destructive = ann["destructiveHint"]
            .as_bool()
            .expect("destructiveHint must be a bool");
        let in_allowlist = READ_ONLY_TOOLS.contains(&name);
        assert_eq!(
            in_allowlist,
            read_only && !destructive,
            "{name} hints disagree with READ_ONLY_TOOLS allowlist (read_only={read_only}, destructive={destructive}, in_allowlist={in_allowlist})"
        );
    }
}

#[test]
fn tool_annotations_have_exact_per_tool_values() {
    // Double-entry ledger: a bug that flips both READ_ONLY_TOOLS and the
    // annotations together would slip past the consistency check. This test
    // pins each tool's hints to the exact values we publish to the directory.
    // (tool_name, read_only, destructive, idempotent)
    let expected = [
        ("list_hosts", true, false, true),
        ("get_host", true, false, true),
        ("list_containers", true, false, true),
        ("run_command", false, true, false),
        ("container_action", false, true, false),
    ];
    let resp = mcp_dispatch("tools/list", None, &std::path::PathBuf::from("/dev/null"));
    let tools = resp.result.unwrap()["tools"].as_array().cloned().unwrap();
    assert_eq!(tools.len(), expected.len());
    for (name, ro, destr, idem) in expected {
        let tool = tools
            .iter()
            .find(|t| t["name"] == name)
            .unwrap_or_else(|| panic!("missing tool {name}"));
        let ann = &tool["annotations"];
        assert_eq!(ann["readOnlyHint"], ro, "{name}.readOnlyHint");
        assert_eq!(ann["destructiveHint"], destr, "{name}.destructiveHint");
        assert_eq!(ann["idempotentHint"], idem, "{name}.idempotentHint");
    }
}

// --- Read-only mode tests ---

#[test]
fn read_only_filters_state_changing_tools_from_list() {
    let opts = McpOptions {
        read_only: true,
        audit_log_path: None,
    };
    let (resp, _ctx) = mcp_dispatch_with(
        "tools/list",
        None,
        &std::path::PathBuf::from("/dev/null"),
        opts,
    );
    let result = resp.result.unwrap();
    let tools = result["tools"].as_array().unwrap();
    let mut names: Vec<&str> = tools.iter().map(|t| t["name"].as_str().unwrap()).collect();
    names.sort();
    let mut expected: Vec<&str> = READ_ONLY_TOOLS.to_vec();
    expected.sort();
    assert_eq!(
        names, expected,
        "read-only tools/list must match the READ_ONLY_TOOLS allowlist"
    );
}

#[test]
fn read_only_denies_run_command() {
    let opts = McpOptions {
        read_only: true,
        audit_log_path: None,
    };
    let (resp, _ctx) = mcp_dispatch_with(
        "tools/call",
        Some(serde_json::json!({
            "name": "run_command",
            "arguments": {"alias": "web-1", "command": "uptime"}
        })),
        &std::path::PathBuf::from("tests/fixtures/mcp_test_config"),
        opts,
    );
    let result = resp.result.unwrap();
    assert_eq!(result["isError"], true);
    let text = result["content"][0]["text"].as_str().unwrap();
    assert_eq!(text, crate::messages::MCP_TOOL_DENIED_READ_ONLY);
}

#[test]
fn read_only_denies_container_action() {
    let opts = McpOptions {
        read_only: true,
        audit_log_path: None,
    };
    let (resp, _ctx) = mcp_dispatch_with(
        "tools/call",
        Some(serde_json::json!({
            "name": "container_action",
            "arguments": {"alias": "web-1", "container_id": "abc", "action": "start"}
        })),
        &std::path::PathBuf::from("tests/fixtures/mcp_test_config"),
        opts,
    );
    let result = resp.result.unwrap();
    assert_eq!(result["isError"], true);
    let text = result["content"][0]["text"].as_str().unwrap();
    assert_eq!(text, crate::messages::MCP_TOOL_DENIED_READ_ONLY);
}

#[test]
fn read_only_gates_before_argument_validation() {
    // The read-only guard must fire BEFORE the per-tool argument validation,
    // otherwise an attacker probing in read-only mode could distinguish
    // "tool denied" from "tool would have been called but args were bad",
    // leaking information about which tools the server supports.
    let opts = McpOptions {
        read_only: true,
        audit_log_path: None,
    };
    let (resp, _ctx) = mcp_dispatch_with(
        "tools/call",
        Some(serde_json::json!({
            "name": "container_action",
            "arguments": {"alias": "web-1", "container_id": "abc", "action": "nuke"}
        })),
        &std::path::PathBuf::from("tests/fixtures/mcp_test_config"),
        opts,
    );
    let result = resp.result.unwrap();
    let text = result["content"][0]["text"].as_str().unwrap();
    assert_eq!(
        text,
        crate::messages::MCP_TOOL_DENIED_READ_ONLY,
        "read-only must trump argument validation"
    );
    assert!(!text.contains("Invalid action"));
}

#[test]
fn read_only_allows_list_hosts() {
    let opts = McpOptions {
        read_only: true,
        audit_log_path: None,
    };
    let (resp, _ctx) = mcp_dispatch_with(
        "tools/call",
        Some(serde_json::json!({"name": "list_hosts", "arguments": {}})),
        &std::path::PathBuf::from("tests/fixtures/mcp_test_config"),
        opts,
    );
    let result = resp.result.unwrap();
    assert!(
        result.get("isError").is_none(),
        "list_hosts should succeed in read-only mode, got: {result}"
    );
}

#[test]
fn read_only_allows_get_host() {
    let opts = McpOptions {
        read_only: true,
        audit_log_path: None,
    };
    let (resp, _ctx) = mcp_dispatch_with(
        "tools/call",
        Some(serde_json::json!({"name": "get_host", "arguments": {"alias": "web-1"}})),
        &std::path::PathBuf::from("tests/fixtures/mcp_test_config"),
        opts,
    );
    let result = resp.result.unwrap();
    assert!(result.get("isError").is_none());
}

// --- Audit log tests ---

/// Parse all JSON Lines in an audit log into structured `Value`s.
/// Failing to parse any line is an assertion failure: the audit log MUST
/// remain valid JSON Lines under all inputs.
fn read_audit_entries(path: &std::path::Path) -> Vec<Value> {
    let contents = std::fs::read_to_string(path).unwrap();
    contents
        .lines()
        .map(|line| {
            serde_json::from_str::<Value>(line)
                .unwrap_or_else(|e| panic!("malformed audit line {line:?}: {e}"))
        })
        .collect()
}

#[test]
fn audit_log_records_allowed_call() {
    let dir = tempfile::tempdir().unwrap();
    let log_path = dir.path().join("audit.log");
    let opts = McpOptions {
        read_only: false,
        audit_log_path: Some(log_path.clone()),
    };
    let (_resp, _ctx) = mcp_dispatch_with(
        "tools/call",
        Some(serde_json::json!({"name": "list_hosts", "arguments": {}})),
        &std::path::PathBuf::from("tests/fixtures/mcp_test_config"),
        opts,
    );
    let entries = read_audit_entries(&log_path);
    assert_eq!(entries.len(), 1);
    let e = &entries[0];
    assert_eq!(e["tool"], "list_hosts");
    assert_eq!(e["outcome"], "allowed");
    // The reason field MUST be present and null on allowed entries so SIEM
    // ingest can rely on a stable schema.
    assert!(e.get("reason").is_some(), "reason field must be present");
    assert!(e["reason"].is_null(), "reason must be null on allowed");
    assert!(e["ts"].is_string());
}

#[test]
fn audit_log_records_denied_call_in_read_only_mode() {
    let dir = tempfile::tempdir().unwrap();
    let log_path = dir.path().join("audit.log");
    let opts = McpOptions {
        read_only: true,
        audit_log_path: Some(log_path.clone()),
    };
    let (_resp, _ctx) = mcp_dispatch_with(
        "tools/call",
        Some(serde_json::json!({
            "name": "run_command",
            "arguments": {"alias": "web-1", "command": "uptime"}
        })),
        &std::path::PathBuf::from("tests/fixtures/mcp_test_config"),
        opts,
    );
    let entries = read_audit_entries(&log_path);
    assert_eq!(entries.len(), 1);
    let e = &entries[0];
    assert_eq!(e["tool"], "run_command");
    assert_eq!(e["outcome"], "denied");
    assert_eq!(e["reason"], "read-only mode");
}

#[test]
fn audit_log_records_error_outcome() {
    let dir = tempfile::tempdir().unwrap();
    let log_path = dir.path().join("audit.log");
    let opts = McpOptions {
        read_only: false,
        audit_log_path: Some(log_path.clone()),
    };
    let (_resp, _ctx) = mcp_dispatch_with(
        "tools/call",
        Some(serde_json::json!({
            "name": "get_host",
            "arguments": {"alias": "does-not-exist"}
        })),
        &std::path::PathBuf::from("tests/fixtures/mcp_test_config"),
        opts,
    );
    let entries = read_audit_entries(&log_path);
    assert_eq!(entries.len(), 1);
    let e = &entries[0];
    assert_eq!(e["outcome"], "error");
    assert!(e["reason"].is_null(), "error outcomes carry no reason");
}

#[test]
fn audit_log_appends_multiple_entries() {
    let dir = tempfile::tempdir().unwrap();
    let log_path = dir.path().join("audit.log");
    let opts = McpOptions {
        read_only: false,
        audit_log_path: Some(log_path.clone()),
    };
    let ctx = McpContext::new(
        std::path::PathBuf::from("tests/fixtures/mcp_test_config"),
        opts,
    );
    for _ in 0..3 {
        dispatch(
            "tools/call",
            Some(serde_json::json!({"name": "list_hosts", "arguments": {}})),
            &ctx,
        );
    }
    let entries = read_audit_entries(&log_path);
    assert_eq!(entries.len(), 3);
    for e in &entries {
        assert_eq!(e["tool"], "list_hosts");
        assert_eq!(e["outcome"], "allowed");
    }
}

#[test]
fn audit_log_handles_concurrent_writes() {
    // The AuditLog's `Mutex<File>` claim in the doc comment is only meaningful
    // if it actually holds under concurrent writers. Spawn N threads each
    // writing one entry, then verify N well-formed lines with no truncation
    // or interleaving.
    use std::sync::Arc;
    let dir = tempfile::tempdir().unwrap();
    let log_path = dir.path().join("audit.log");
    let ctx = Arc::new(McpContext::new(
        std::path::PathBuf::from("tests/fixtures/mcp_test_config"),
        McpOptions {
            read_only: false,
            audit_log_path: Some(log_path.clone()),
        },
    ));
    let handles: Vec<_> = (0..16)
        .map(|i| {
            let ctx = Arc::clone(&ctx);
            std::thread::spawn(move || {
                dispatch(
                    "tools/call",
                    Some(serde_json::json!({
                        "name": "list_hosts",
                        "arguments": {"tag": format!("tag-{i}")}
                    })),
                    &ctx,
                );
            })
        })
        .collect();
    for h in handles {
        h.join().unwrap();
    }
    let entries = read_audit_entries(&log_path);
    assert_eq!(entries.len(), 16);
    for e in &entries {
        assert_eq!(e["tool"], "list_hosts");
        assert_eq!(e["outcome"], "allowed");
    }
}

#[test]
fn audit_log_disabled_when_no_path() {
    let opts = McpOptions {
        read_only: false,
        audit_log_path: None,
    };
    let (_resp, ctx) = mcp_dispatch_with(
        "tools/call",
        Some(serde_json::json!({"name": "list_hosts", "arguments": {}})),
        &std::path::PathBuf::from("tests/fixtures/mcp_test_config"),
        opts,
    );
    assert!(ctx.audit.is_none());
}

#[test]
fn audit_log_creates_parent_directory() {
    let dir = tempfile::tempdir().unwrap();
    let log_path = dir.path().join("nested").join("subdir").join("audit.log");
    let opts = McpOptions {
        read_only: false,
        audit_log_path: Some(log_path.clone()),
    };
    let (_resp, _ctx) = mcp_dispatch_with(
        "tools/call",
        Some(serde_json::json!({"name": "list_hosts", "arguments": {}})),
        &std::path::PathBuf::from("tests/fixtures/mcp_test_config"),
        opts,
    );
    assert!(log_path.exists());
}

#[cfg(unix)]
#[test]
fn audit_log_init_failure_does_not_break_dispatch() {
    use std::os::unix::fs::PermissionsExt;
    // Build an unwriteable parent in a tempdir so the test is portable
    // across Linux and macOS (no /proc dependency).
    let dir = tempfile::tempdir().unwrap();
    let ro_parent = dir.path().join("ro");
    std::fs::create_dir(&ro_parent).unwrap();
    std::fs::set_permissions(&ro_parent, std::fs::Permissions::from_mode(0o555)).unwrap();
    let opts = McpOptions {
        read_only: false,
        audit_log_path: Some(ro_parent.join("audit.log")),
    };
    let (resp, ctx) = mcp_dispatch_with(
        "tools/call",
        Some(serde_json::json!({"name": "list_hosts", "arguments": {}})),
        &std::path::PathBuf::from("tests/fixtures/mcp_test_config"),
        opts,
    );
    // The dispatch should still succeed even though audit log failed to open.
    assert!(resp.result.is_some());
    assert!(
        ctx.audit.is_none(),
        "audit should be None after init failure"
    );
    // Restore permissions so tempdir cleanup works.
    let _ = std::fs::set_permissions(&ro_parent, std::fs::Permissions::from_mode(0o755));
}

#[test]
fn audit_log_records_allowed_call_in_read_only_mode() {
    // Closes the gap where read-only + audit + an allowed tool was not
    // exercised together. Earlier tests covered each pair but not the trio.
    let dir = tempfile::tempdir().unwrap();
    let log_path = dir.path().join("audit.log");
    let opts = McpOptions {
        read_only: true,
        audit_log_path: Some(log_path.clone()),
    };
    let (_resp, _ctx) = mcp_dispatch_with(
        "tools/call",
        Some(serde_json::json!({"name": "list_hosts", "arguments": {}})),
        &std::path::PathBuf::from("tests/fixtures/mcp_test_config"),
        opts,
    );
    let entries = read_audit_entries(&log_path);
    assert_eq!(entries.len(), 1);
    let e = &entries[0];
    assert_eq!(e["tool"], "list_hosts");
    assert_eq!(e["outcome"], "allowed");
    assert!(e["reason"].is_null());
}

#[test]
fn audit_log_appends_to_existing_file() {
    // Pre-existing entries must survive: AuditLog::open uses append(true).
    let dir = tempfile::tempdir().unwrap();
    let log_path = dir.path().join("audit.log");
    std::fs::write(&log_path, "{\"pre\":\"existing\"}\n").unwrap();
    let opts = McpOptions {
        read_only: false,
        audit_log_path: Some(log_path.clone()),
    };
    let (_resp, _ctx) = mcp_dispatch_with(
        "tools/call",
        Some(serde_json::json!({"name": "list_hosts", "arguments": {}})),
        &std::path::PathBuf::from("tests/fixtures/mcp_test_config"),
        opts,
    );
    let entries = read_audit_entries(&log_path);
    assert_eq!(entries.len(), 2, "pre-existing line + new entry");
    assert_eq!(entries[0]["pre"], "existing");
    assert_eq!(entries[1]["tool"], "list_hosts");
}

#[test]
fn audit_log_redacts_run_command_command() {
    // The `command` field for run_command may carry secrets. The audit log
    // records that the tool was called and on which host, not the literal
    // command body.
    let dir = tempfile::tempdir().unwrap();
    let log_path = dir.path().join("audit.log");
    let opts = McpOptions {
        read_only: false,
        audit_log_path: Some(log_path.clone()),
    };
    let (_resp, _ctx) = mcp_dispatch_with(
        "tools/call",
        Some(serde_json::json!({
            "name": "run_command",
            "arguments": {"alias": "nonexistent", "command": "mysql -pSUPERSECRET"}
        })),
        &std::path::PathBuf::from("tests/fixtures/mcp_test_config"),
        opts,
    );
    let entries = read_audit_entries(&log_path);
    assert_eq!(entries.len(), 1);
    let e = &entries[0];
    assert_eq!(e["args"]["command"], "<redacted>");
    assert_eq!(e["args"]["alias"], "nonexistent");
    let raw = std::fs::read_to_string(&log_path).unwrap();
    assert!(!raw.contains("SUPERSECRET"), "secret leaked: {raw}");
}

#[test]
fn audit_log_redacts_run_command_when_args_is_not_an_object() {
    // Defensive: if a malformed client sends `arguments` as an array or
    // string for run_command, the secret could land anywhere inside that
    // value. Redact the whole payload.
    let dir = tempfile::tempdir().unwrap();
    let log_path = dir.path().join("audit.log");
    let opts = McpOptions {
        read_only: false,
        audit_log_path: Some(log_path.clone()),
    };
    let (_resp, _ctx) = mcp_dispatch_with(
        "tools/call",
        Some(serde_json::json!({
            "name": "run_command",
            "arguments": ["mysql -pSUPERSECRET", "--force"]
        })),
        &std::path::PathBuf::from("tests/fixtures/mcp_test_config"),
        opts,
    );
    let raw = std::fs::read_to_string(&log_path).unwrap();
    assert!(
        !raw.contains("SUPERSECRET"),
        "secret leaked via non-object args: {raw}"
    );
}

#[test]
fn audit_log_does_not_redact_other_tools() {
    // Only run_command's command field is sensitive. list_hosts args (which
    // include a tag filter) and others should remain visible.
    let dir = tempfile::tempdir().unwrap();
    let log_path = dir.path().join("audit.log");
    let opts = McpOptions {
        read_only: false,
        audit_log_path: Some(log_path.clone()),
    };
    let (_resp, _ctx) = mcp_dispatch_with(
        "tools/call",
        Some(serde_json::json!({"name": "list_hosts", "arguments": {"tag": "prod"}})),
        &std::path::PathBuf::from("tests/fixtures/mcp_test_config"),
        opts,
    );
    let entries = read_audit_entries(&log_path);
    assert_eq!(entries.len(), 1);
    assert_eq!(entries[0]["args"]["tag"], "prod");
}

#[cfg(unix)]
#[test]
fn audit_log_file_is_owner_only() {
    use std::os::unix::fs::PermissionsExt;
    let dir = tempfile::tempdir().unwrap();
    let log_path = dir.path().join("audit.log");
    let opts = McpOptions {
        read_only: false,
        audit_log_path: Some(log_path.clone()),
    };
    let _ = mcp_dispatch_with(
        "tools/call",
        Some(serde_json::json!({"name": "list_hosts", "arguments": {}})),
        &std::path::PathBuf::from("tests/fixtures/mcp_test_config"),
        opts,
    );
    let mode = std::fs::metadata(&log_path).unwrap().permissions().mode() & 0o777;
    assert_eq!(
        mode, 0o600,
        "audit log must be owner read/write only, got {mode:o}"
    );
}

// --- iso8601 helpers ---

#[test]
fn iso8601_format_known_timestamp() {
    // 2026-04-19T00:00:00Z = 1776556800 seconds since epoch
    assert_eq!(format_iso8601_utc(1_776_556_800), "2026-04-19T00:00:00Z");
}

#[test]
fn iso8601_format_epoch() {
    assert_eq!(format_iso8601_utc(0), "1970-01-01T00:00:00Z");
}

#[test]
fn iso8601_format_includes_seconds() {
    // 2026-04-19T12:34:56Z = 1776602096
    assert_eq!(format_iso8601_utc(1_776_602_096), "2026-04-19T12:34:56Z");
}

#[test]
fn iso8601_format_leap_day() {
    // 2024-02-29T00:00:00Z = 1709164800
    assert_eq!(format_iso8601_utc(1_709_164_800), "2024-02-29T00:00:00Z");
}

#[test]
fn iso8601_format_year_2000() {
    // 2000-01-01T00:00:00Z = 946684800
    assert_eq!(format_iso8601_utc(946_684_800), "2000-01-01T00:00:00Z");
}

#[test]
fn iso8601_format_non_leap_century() {
    // 2100 is divisible by 100 but not by 400, so NOT a leap year per Gregorian.
    // 2100-03-01T00:00:00Z = 4107542400.
    // If the algorithm wrongly treated 2100 as leap (Feb 29 inserted), this
    // would render "2100-02-29..." instead.
    assert_eq!(format_iso8601_utc(4_107_542_400), "2100-03-01T00:00:00Z");
}

// --- Additional safety tests ---

#[test]
fn audit_log_redacts_run_command_when_args_is_a_string() {
    let dir = tempfile::tempdir().unwrap();
    let log_path = dir.path().join("audit.log");
    let opts = McpOptions {
        read_only: false,
        audit_log_path: Some(log_path.clone()),
    };
    let (_resp, _ctx) = mcp_dispatch_with(
        "tools/call",
        Some(serde_json::json!({
            "name": "run_command",
            "arguments": "mysql -pSUPERSECRET"
        })),
        &std::path::PathBuf::from("tests/fixtures/mcp_test_config"),
        opts,
    );
    let raw = std::fs::read_to_string(&log_path).unwrap();
    assert!(
        !raw.contains("SUPERSECRET"),
        "secret leaked via string args: {raw}"
    );
}

#[cfg(unix)]
#[test]
fn audit_log_refuses_symlink_target() {
    use std::os::unix::fs::symlink;
    let dir = tempfile::tempdir().unwrap();
    let real = dir.path().join("real.log");
    std::fs::write(&real, b"existing\n").unwrap();
    let link = dir.path().join("link.log");
    symlink(&real, &link).unwrap();

    let opts = McpOptions {
        read_only: false,
        audit_log_path: Some(link.clone()),
    };
    let (resp, ctx) = mcp_dispatch_with(
        "tools/call",
        Some(serde_json::json!({"name": "list_hosts", "arguments": {}})),
        &std::path::PathBuf::from("tests/fixtures/mcp_test_config"),
        opts,
    );
    assert!(
        resp.result.is_some(),
        "dispatch should not break on symlink refusal"
    );
    assert!(
        ctx.audit.is_none(),
        "symlink target must produce a None audit handle"
    );
    // The original file content must be untouched (we never opened it).
    let real_after = std::fs::read_to_string(&real).unwrap();
    assert_eq!(real_after, "existing\n");
}

#[test]
fn run_command_timeout_clamps_to_max_300() {
    // We cannot easily observe the internal clamped value via dispatch, so we
    // exercise the path with an unreachable host. The clamp guarantees that a
    // huge `timeout` does not actually affect this code path either way -
    // assertion is that the call returns an error WITHOUT hanging the test.
    let config_path = std::path::PathBuf::from("tests/fixtures/mcp_test_config");
    let args = serde_json::json!({
        "alias": "nonexistent-host",
        "command": "uptime",
        "timeout": 99_999_999u64
    });
    let resp = mcp_dispatch(
        "tools/call",
        Some(serde_json::json!({"name": "run_command", "arguments": args})),
        &config_path,
    );
    let result = resp.result.unwrap();
    assert_eq!(result["isError"], true);
}

#[test]
fn run_command_timeout_clamps_zero_to_one() {
    // A timeout of 0 would cause the wait to fire immediately. The clamp
    // floors to 1 second, giving the not-found path room to return.
    let config_path = std::path::PathBuf::from("tests/fixtures/mcp_test_config");
    let args = serde_json::json!({
        "alias": "nonexistent-host",
        "command": "uptime",
        "timeout": 0u64
    });
    let resp = mcp_dispatch(
        "tools/call",
        Some(serde_json::json!({"name": "run_command", "arguments": args})),
        &config_path,
    );
    let result = resp.result.unwrap();
    assert_eq!(result["isError"], true);
    let text = result["content"][0]["text"].as_str().unwrap();
    assert!(text.contains("not found"), "got: {text}");
}

// ── default_audit_log_path branches ──────────────────────────────────
//
// `dirs::home_dir()` is hard to force into None in production, but the
// Some/None branch logic lives in a private helper that takes the value
// directly. Test it.

#[test]
fn audit_log_path_from_home_some_returns_default_under_dot_purple() {
    let home = std::path::PathBuf::from("/var/test/home/eric");
    let result = super::audit_log_path_from_home(Some(home));
    assert_eq!(
        result,
        Some(std::path::PathBuf::from(
            "/var/test/home/eric/.purple/mcp-audit.log"
        ))
    );
}

#[test]
fn audit_log_path_from_home_none_returns_none_silently() {
    // The warn! is fire-and-forget; we just verify the return value.
    // In production this disables auditing without crashing the server.
    assert_eq!(super::audit_log_path_from_home(None), None);
}