pty-mcp 0.3.0

An MCP server for PTY management with SSH connections, remote sessions, file access, and mounts
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
use chrono::Utc;
use pty_mcp::{
    AppState, Config, PtyMcpServer,
    app::SshDisconnectRequest,
    mcp::tools::{
        PtyListResponse, PtyReadResponse, PtyWaitResponse, SshConnectResponse,
        SshDisconnectResponse, SshExecResponse, SshListDirResponse, SshListResponse,
        SshMkdirResponse, SshMountResponse, SshReadFileResponse, SshRunResponse,
        SshSessionSpawnResponse, SshWriteFileResponse,
    },
    ssh::{
        SshConnectionStatus, SshMountBackend, SshMountId, SshMountStatus, SshMountSummary,
        SshTarget,
    },
};
use rmcp::{
    ClientHandler, ServiceExt,
    model::{CallToolRequestParams, ReadResourceRequestParams, TaskSupport},
};
use serde_json::Value;
use std::{
    fs,
    path::{Path, PathBuf},
    sync::Arc,
    time::{SystemTime, UNIX_EPOCH},
};

fn test_app() -> AppState {
    AppState::new(Config::default())
}

fn mount_feature_unavailable_config() -> Config {
    let mut config = Config::default();
    config.ssh.sshfs_bin_path = Some(PathBuf::from("/definitely/missing/sshfs"));
    config.ssh.umount_bin_path = Some(PathBuf::from("/definitely/missing/umount"));
    config
}

fn default_target() -> SshTarget {
    SshTarget {
        host_alias: Some("devbox".to_string()),
        host: "devbox.example.com".to_string(),
        user: Some("alice".to_string()),
        port: Some(22),
    }
}

fn mounted_summary(connection_id: pty_mcp::ssh::SshConnectionId, suffix: &str) -> SshMountSummary {
    SshMountSummary {
        mount_id: SshMountId::new(),
        title: Some(format!("mount-{suffix}")),
        description: None,
        connection_id,
        target_summary: "alice@devbox:22".to_string(),
        status: SshMountStatus::Mounted,
        backend: SshMountBackend::Sshfs,
        local_path: format!("/tmp/ssh-mount-{suffix}"),
        remote_path: format!("/srv/project-{suffix}"),
        read_only: false,
        mounted_at: Utc::now(),
        last_error: None,
    }
}

#[test]
fn app_state_exposes_ssh_registry_connection_summary() {
    let app = test_app();
    let target = default_target();
    let created = app.ssh().create_placeholder_connection(target.clone());

    let fetched = app
        .ssh()
        .get_connection(&created.connection_id)
        .expect("connection should exist");
    assert_eq!(fetched.connection_id, created.connection_id);
    assert_eq!(fetched.target, target);
    assert_eq!(fetched.target_summary, "alice@devbox:22");
    assert_eq!(fetched.status, SshConnectionStatus::Connecting);
    assert_eq!(fetched.active_session_count, 0);
    assert_eq!(fetched.active_mount_count, 0);
    assert_eq!(fetched.active_tunnel_count, 0);
}

#[test]
fn app_state_tracks_multiple_mounts_for_same_connection() {
    let app = test_app();
    let connection = app.ssh().create_placeholder_connection(default_target());
    let mount_one = mounted_summary(connection.connection_id.clone(), "one");
    let mount_two = mounted_summary(connection.connection_id.clone(), "two");

    app.ssh().upsert_mount(mount_one.clone());
    app.ssh().upsert_mount(mount_two.clone());

    let listed = app.ssh().list_mounts();
    assert_eq!(listed.len(), 2);
    assert!(
        listed
            .iter()
            .any(|mount| mount.mount_id == mount_one.mount_id)
    );
    assert!(
        listed
            .iter()
            .any(|mount| mount.mount_id == mount_two.mount_id)
    );
    assert!(app.ssh().get_mount(&mount_one.mount_id).is_some());
    assert!(app.ssh().get_mount(&mount_two.mount_id).is_some());

    let removed = app
        .ssh()
        .remove_mounts_for_connection(&connection.connection_id);
    assert_eq!(removed, 2);
    assert!(app.ssh().list_mounts().is_empty());
}

#[test]
fn disconnect_precheck_rejects_connection_with_active_sessions() {
    let app = test_app();
    let connection = app.ssh().create_placeholder_connection(default_target());
    let first = pty_mcp::session::SessionId::new();
    let second = pty_mcp::session::SessionId::new();
    app.ssh()
        .track_session(&connection.connection_id, first)
        .expect("first session tracked");
    app.ssh()
        .track_session(&connection.connection_id, second)
        .expect("second session tracked");

    let counts = app
        .ssh()
        .active_resource_counts(&connection.connection_id)
        .expect("resource counts should exist");
    assert_eq!(counts.active_session_count, 2);
    assert_eq!(counts.active_mount_count, 0);

    let error = app
        .ssh()
        .disconnect_precheck(&connection.connection_id)
        .expect_err("disconnect should be rejected");
    let text = format!("{error:#}");
    assert!(text.contains("active sessions"));
    assert!(text.contains(connection.connection_id.as_str()));
}

#[test]
fn disconnect_precheck_rejects_connection_with_active_mounts() {
    let app = test_app();
    let mut connection = app.ssh().create_placeholder_connection(default_target());
    connection.status = SshConnectionStatus::Ready;
    app.ssh().upsert_connection(connection.clone());

    let mount = mounted_summary(connection.connection_id.clone(), "active");
    app.ssh().upsert_mount(mount);

    let relations = app
        .ssh()
        .connection_relations(&connection.connection_id)
        .expect("relations should exist");
    assert!(relations.session_ids.is_empty());
    assert_eq!(relations.mount_ids.len(), 1);

    let error = app
        .ssh()
        .disconnect_precheck(&connection.connection_id)
        .expect_err("disconnect should be rejected");
    let text = format!("{error:#}");
    assert!(text.contains("active mounts"));
    assert!(text.contains(connection.connection_id.as_str()));
}

#[test]
fn disconnect_precheck_allows_idle_connection() {
    let app = test_app();
    let mut connection = app.ssh().create_placeholder_connection(default_target());
    connection.status = SshConnectionStatus::Ready;
    connection.active_session_count = 0;
    connection.active_mount_count = 0;
    connection.active_tunnel_count = 0;
    app.ssh().upsert_connection(connection.clone());

    app.ssh()
        .disconnect_precheck(&connection.connection_id)
        .expect("idle connection should pass precheck");
}

#[tokio::test]
async fn force_disconnect_requires_cleanup_mounts_to_remove_active_mounts() {
    let app = test_app();
    let mut connection = app.ssh().create_placeholder_connection(default_target());
    connection.status = SshConnectionStatus::Ready;
    app.ssh().upsert_connection(connection.clone());
    app.ssh().upsert_mount(mounted_summary(
        connection.connection_id.clone(),
        "force-required",
    ));

    let error = app
        .ssh()
        .disconnect(SshDisconnectRequest {
            connection_id: connection.connection_id,
            force: true,
            cleanup_mounts: false,
            cleanup_tunnels: false,
        })
        .await
        .expect_err("disconnect should require cleanup_mounts=true");
    let text = format!("{error:#}");
    assert!(text.contains("active mounts"));
    assert!(text.contains("cleanup_mounts=true"));
}

#[test]
fn disconnect_precheck_reports_missing_connection() {
    let app = test_app();
    let unknown_id = pty_mcp::ssh::SshConnectionId::new();

    let error = app
        .ssh()
        .disconnect_precheck(&unknown_id)
        .expect_err("unknown connection should fail");
    let text = format!("{error:#}");
    assert!(text.contains("ssh connection not found"));
    assert!(text.contains(unknown_id.as_str()));
}

#[derive(Debug, Clone, Default)]
struct DummyClient;

impl ClientHandler for DummyClient {}

#[derive(Debug)]
struct TempDirGuard {
    path: PathBuf,
}

impl TempDirGuard {
    fn new(prefix: &str) -> anyhow::Result<Self> {
        let nanos = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .expect("clock before unix epoch")
            .as_nanos();
        let path = std::env::temp_dir().join(format!(
            "pty_mcp_ssh_{prefix}_{}_{}",
            std::process::id(),
            nanos
        ));
        fs::create_dir_all(&path)?;
        Ok(Self { path })
    }
}

impl Drop for TempDirGuard {
    fn drop(&mut self) {
        let _ = fs::remove_dir_all(&self.path);
    }
}

#[cfg(unix)]
fn mount_feature_available_config(sandbox: &TempDirGuard) -> anyhow::Result<Config> {
    let ssh_path = sandbox.path.join("ssh");
    let sshfs_path = sandbox.path.join("sshfs");
    let umount_path = sandbox.path.join("umount");

    write_fake_executable(&ssh_path, "#!/bin/sh\necho 'OpenSSH_9.9p1' >&2\n")?;
    let sshfs_version = if cfg!(target_os = "macos") {
        "SSHFS 3.7.3 (macFUSE 4.6.0)"
    } else {
        "SSHFS 3.7.3"
    };
    write_fake_executable(&sshfs_path, &format!("#!/bin/sh\necho '{sshfs_version}'\n"))?;
    write_fake_executable(&umount_path, "#!/bin/sh\necho 'umount util-linux 2.39'\n")?;

    let mut config = Config::default();
    config.ssh.ssh_bin_path = Some(ssh_path);
    config.ssh.sshfs_bin_path = Some(sshfs_path);
    config.ssh.umount_bin_path = Some(umount_path);
    Ok(config)
}

#[cfg(unix)]
fn write_fake_executable(path: &Path, body: &str) -> anyhow::Result<()> {
    use std::os::unix::fs::PermissionsExt;

    let nanos = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .expect("clock before unix epoch")
        .as_nanos();
    let tmp_path = path.with_extension(format!("tmp-{}-{nanos}", std::process::id()));
    fs::write(&tmp_path, body)?;
    let mut permissions = fs::metadata(&tmp_path)?.permissions();
    permissions.set_mode(0o755);
    fs::set_permissions(&tmp_path, permissions)?;
    fs::rename(&tmp_path, path)?;
    Ok(())
}

#[cfg(unix)]
#[test]
fn ssh_mount_tools_are_registered_when_mount_feature_is_available() -> anyhow::Result<()> {
    let sandbox = TempDirGuard::new("mount_tool_registration")?;
    let server = PtyMcpServer::new(Arc::new(AppState::new(mount_feature_available_config(
        &sandbox,
    )?)));
    let tool_defs = server.tool_definitions();
    let connect = tool_defs
        .iter()
        .find(|tool| tool.name == "ssh_connect")
        .expect("ssh_connect should be registered");
    let list = tool_defs
        .iter()
        .find(|tool| tool.name == "ssh_list")
        .expect("ssh_list should be registered");
    let session_spawn = tool_defs
        .iter()
        .find(|tool| tool.name == "ssh_session_spawn")
        .expect("ssh_session_spawn should be registered");
    let exec = tool_defs
        .iter()
        .find(|tool| tool.name == "ssh_exec")
        .expect("ssh_exec should be registered");
    let run = tool_defs
        .iter()
        .find(|tool| tool.name == "ssh_run")
        .expect("ssh_run should be registered");
    let mount = tool_defs
        .iter()
        .find(|tool| tool.name == "ssh_mount")
        .expect("ssh_mount should be registered");
    let tunnel_open = tool_defs
        .iter()
        .find(|tool| tool.name == "ssh_tunnel_open")
        .expect("ssh_tunnel_open should be registered");
    let tunnel_close = tool_defs
        .iter()
        .find(|tool| tool.name == "ssh_tunnel_close")
        .expect("ssh_tunnel_close should be registered");
    let read_file = tool_defs
        .iter()
        .find(|tool| tool.name == "ssh_read_file")
        .expect("ssh_read_file should be registered");
    let write_file = tool_defs
        .iter()
        .find(|tool| tool.name == "ssh_write_file")
        .expect("ssh_write_file should be registered");
    let list_dir = tool_defs
        .iter()
        .find(|tool| tool.name == "ssh_list_dir")
        .expect("ssh_list_dir should be registered");
    let mkdir = tool_defs
        .iter()
        .find(|tool| tool.name == "ssh_mkdir")
        .expect("ssh_mkdir should be registered");
    let unmount = tool_defs
        .iter()
        .find(|tool| tool.name == "ssh_unmount")
        .expect("ssh_unmount should be registered");
    let disconnect = tool_defs
        .iter()
        .find(|tool| tool.name == "ssh_disconnect")
        .expect("ssh_disconnect should be registered");

    assert_eq!(connect.task_support(), TaskSupport::Optional);
    assert_eq!(list.task_support(), TaskSupport::Optional);
    assert_eq!(session_spawn.task_support(), TaskSupport::Optional);
    assert_eq!(exec.task_support(), TaskSupport::Optional);
    assert_eq!(run.task_support(), TaskSupport::Optional);
    assert_eq!(mount.task_support(), TaskSupport::Optional);
    assert_eq!(tunnel_open.task_support(), TaskSupport::Optional);
    assert_eq!(tunnel_close.task_support(), TaskSupport::Optional);
    assert_eq!(read_file.task_support(), TaskSupport::Optional);
    assert_eq!(write_file.task_support(), TaskSupport::Optional);
    assert_eq!(list_dir.task_support(), TaskSupport::Optional);
    assert_eq!(mkdir.task_support(), TaskSupport::Optional);
    assert_eq!(unmount.task_support(), TaskSupport::Optional);
    assert_eq!(disconnect.task_support(), TaskSupport::Optional);

    let exec_required = exec
        .input_schema
        .get("required")
        .and_then(Value::as_array)
        .expect("ssh_exec should expose required fields");
    assert!(exec_required.contains(&serde_json::json!("connection_id")));
    assert!(exec_required.contains(&serde_json::json!("script")));
    let run_required = run
        .input_schema
        .get("required")
        .and_then(Value::as_array)
        .expect("ssh_run should expose required fields");
    assert!(run_required.contains(&serde_json::json!("connection_id")));
    assert!(run_required.contains(&serde_json::json!("script")));
    assert!(
        !exec
            .input_schema
            .get("properties")
            .and_then(Value::as_object)
            .expect("ssh_exec properties")
            .contains_key("interactive")
    );
    let exec_properties = exec
        .input_schema
        .get("properties")
        .and_then(Value::as_object)
        .expect("ssh_exec properties");
    assert!(exec_properties.contains_key("wait_timeout_ms"));
    assert!(exec_properties.contains_key("capture_limit"));
    assert!(exec_properties.contains_key("output_view"));
    assert!(exec_properties.contains_key("line_number_mode"));
    assert!(
        !session_spawn
            .input_schema
            .get("properties")
            .and_then(Value::as_object)
            .expect("ssh_session_spawn properties")
            .contains_key("script")
    );
    let session_spawn_properties = session_spawn
        .input_schema
        .get("properties")
        .and_then(Value::as_object)
        .expect("ssh_session_spawn properties");
    assert!(session_spawn_properties.contains_key("capture_wait_ms"));
    assert!(session_spawn_properties.contains_key("capture_limit"));
    assert!(session_spawn_properties.contains_key("output_view"));
    assert!(session_spawn_properties.contains_key("line_number_mode"));

    let mount_required = mount
        .input_schema
        .get("required")
        .and_then(Value::as_array)
        .expect("ssh_mount should expose required fields");
    assert!(mount_required.contains(&serde_json::json!("target_path")));
    let mount_properties = mount
        .input_schema
        .get("properties")
        .and_then(Value::as_object)
        .expect("ssh_mount properties");
    let remote_path_description = mount_properties["remote_path"]["description"]
        .as_str()
        .expect("ssh_mount remote_path description");
    assert!(remote_path_description.contains("absolute path"));
    assert!(remote_path_description.contains("~, or ~/"));

    let tunnel_open_required = tunnel_open
        .input_schema
        .get("required")
        .and_then(Value::as_array)
        .expect("ssh_tunnel_open should expose required fields");
    assert!(tunnel_open_required.contains(&serde_json::json!("connection_id")));
    assert!(tunnel_open_required.contains(&serde_json::json!("local_port")));
    assert!(tunnel_open_required.contains(&serde_json::json!("remote_port")));
    let tunnel_open_properties = tunnel_open
        .input_schema
        .get("properties")
        .and_then(Value::as_object)
        .expect("ssh_tunnel_open properties");
    assert!(
        tunnel_open_properties["local_port"]["description"]
            .as_str()
            .unwrap_or_default()
            .contains("0")
    );
    let tunnel_close_required = tunnel_close
        .input_schema
        .get("required")
        .and_then(Value::as_array)
        .expect("ssh_tunnel_close should expose required fields");
    assert!(tunnel_close_required.contains(&serde_json::json!("tunnel_id")));

    let read_required = read_file
        .input_schema
        .get("required")
        .and_then(Value::as_array)
        .expect("ssh_read_file should expose required fields");
    assert!(read_required.contains(&serde_json::json!("connection_id")));
    assert!(read_required.contains(&serde_json::json!("path")));

    Ok(())
}

#[test]
fn ssh_mount_tools_are_hidden_when_mount_feature_is_unavailable() {
    let server = PtyMcpServer::new(Arc::new(AppState::new(mount_feature_unavailable_config())));
    let tool_names = server
        .tool_definitions()
        .into_iter()
        .map(|tool| tool.name.to_string())
        .collect::<Vec<_>>();

    assert!(tool_names.iter().any(|name| name == "ssh_connect"));
    assert!(tool_names.iter().any(|name| name == "ssh_tunnel_open"));
    assert!(tool_names.iter().any(|name| name == "ssh_tunnel_close"));
    assert!(tool_names.iter().all(|name| name != "ssh_mount"));
    assert!(tool_names.iter().all(|name| name != "ssh_unmount"));
}

#[cfg(unix)]
#[tokio::test]
async fn ssh_connect_and_ssh_list_support_reuse_flow() -> anyhow::Result<()> {
    let sandbox = TempDirGuard::new("connect_reuse")?;
    let ssh_path = sandbox.path.join("ssh");
    let sshfs_path = sandbox.path.join("sshfs");
    write_fake_executable(&ssh_path, "#!/bin/sh\necho 'OpenSSH_9.9p1' >&2\n")?;
    write_fake_executable(&sshfs_path, "#!/bin/sh\necho 'SSHFS 3.7.3'\n")?;

    let mut config = Config::default();
    config.ssh.ssh_bin_path = Some(ssh_path);
    config.ssh.sshfs_bin_path = Some(sshfs_path);
    let app = Arc::new(AppState::new(config));
    let server = PtyMcpServer::new(app);
    let (server_transport, client_transport) = tokio::io::duplex(16 * 1024);
    let server_handle = tokio::spawn(async move {
        server.serve(server_transport).await?.waiting().await?;
        anyhow::Ok(())
    });

    let client = DummyClient.serve(client_transport).await?;
    let connect_args = serde_json::json!({
        "host_alias": "devbox",
        "auth_kind": "config_alias",
        "user": "alice",
        "title": "Devbox",
        "description": "ssh connect contract"
    })
    .as_object()
    .expect("connect args object")
    .clone();

    let first = client
        .call_tool(CallToolRequestParams::new("ssh_connect").with_arguments(connect_args.clone()))
        .await?
        .into_typed::<SshConnectResponse>()?;
    assert!(!first.reused);
    assert_eq!(first.target.host_alias.as_deref(), Some("devbox"));
    assert_eq!(first.target.user.as_deref(), Some("alice"));
    assert!(matches!(
        first.status,
        SshConnectionStatus::Ready | SshConnectionStatus::Degraded
    ));

    let second = client
        .call_tool(CallToolRequestParams::new("ssh_connect").with_arguments(connect_args))
        .await?
        .into_typed::<SshConnectResponse>()?;
    assert!(second.reused);
    assert_eq!(second.connection_id, first.connection_id);

    let listed = client
        .call_tool(CallToolRequestParams::new("ssh_list"))
        .await?
        .into_typed::<SshListResponse>()?;
    assert_eq!(listed.connections.len(), 1);
    assert!(listed.mounts.is_empty());
    assert!(listed.tunnels.is_empty());
    assert_eq!(listed.connections[0].connection_id, first.connection_id);

    client.cancel().await?;
    server_handle.await??;
    Ok(())
}

#[tokio::test]
async fn ssh_resources_expose_connection_and_mount_snapshots() -> anyhow::Result<()> {
    let sandbox = TempDirGuard::new("mount_resources_visible")?;
    let app = Arc::new(AppState::new(mount_feature_available_config(&sandbox)?));
    let mut connection = app.ssh().create_placeholder_connection(default_target());
    connection.status = SshConnectionStatus::Ready;
    app.ssh().upsert_connection(connection.clone());
    let mount = mounted_summary(connection.connection_id.clone(), "resource");
    app.ssh().upsert_mount(mount.clone());

    let (server_transport, client_transport) = tokio::io::duplex(16 * 1024);
    let server = PtyMcpServer::new(app);
    let server_handle = tokio::spawn(async move {
        server.serve(server_transport).await?.waiting().await?;
        anyhow::Ok(())
    });

    let client = DummyClient.serve(client_transport).await?;
    let listed = client
        .call_tool(CallToolRequestParams::new("ssh_list"))
        .await?
        .into_typed::<SshListResponse>()?;
    let resources = client.list_resources(None).await?;
    let uris = resources
        .resources
        .iter()
        .map(|resource| resource.raw.uri.as_ref())
        .collect::<Vec<_>>();
    assert!(uris.contains(&"ssh://connections"));
    assert!(uris.contains(&"ssh://tunnels"));
    assert!(uris.contains(&"ssh://mounts"));
    assert!(
        uris.contains(&format!("ssh://connections/{}", connection.connection_id.as_str()).as_str())
    );
    assert!(uris.contains(&format!("ssh://mounts/{}", mount.mount_id.as_str()).as_str()));

    let connections_resource = read_json_resource(&client, "ssh://connections").await?;
    assert_eq!(
        connections_resource["connections"],
        serde_json::to_value(&listed.connections)?
    );

    let connection_resource = read_json_resource(
        &client,
        &format!("ssh://connections/{}", connection.connection_id.as_str()),
    )
    .await?;
    assert_eq!(
        connection_resource["connection"]["connection_id"],
        connection.connection_id.as_str()
    );
    assert_eq!(connection_resource["connection"]["status"], "ready");
    assert_eq!(
        connection_resource["connection"]["target_summary"],
        listed.connections[0].target_summary
    );
    assert_eq!(
        connection_resource["relations"]["mount_ids"][0],
        mount.mount_id.as_str()
    );

    let mounts_resource = read_json_resource(&client, "ssh://mounts").await?;
    assert_eq!(
        mounts_resource["mounts"],
        serde_json::to_value(&listed.mounts)?
    );
    assert_eq!(listed.mounts[0].target_summary, connection.target_summary);

    let tunnels_resource = read_json_resource(&client, "ssh://tunnels").await?;
    assert_eq!(tunnels_resource["tunnels"], serde_json::json!([]));

    let mount_resource = read_json_resource(
        &client,
        &format!("ssh://mounts/{}", mount.mount_id.as_str()),
    )
    .await?;
    assert_eq!(mount_resource["mount_id"], mount.mount_id.as_str());
    assert_eq!(
        mount_resource["connection_id"],
        connection.connection_id.as_str()
    );
    assert_eq!(mount_resource["target_summary"], connection.target_summary);
    assert_eq!(mount_resource["target_path"], mount.local_path);
    assert_eq!(mount_resource["remote_path"], mount.remote_path);

    client.cancel().await?;
    server_handle.await??;
    Ok(())
}

#[tokio::test]
async fn ssh_mount_resources_are_hidden_when_mount_feature_is_unavailable() -> anyhow::Result<()> {
    let app = Arc::new(AppState::new(mount_feature_unavailable_config()));
    let connection = app.ssh().create_placeholder_connection(default_target());
    app.ssh()
        .upsert_mount(mounted_summary(connection.connection_id.clone(), "hidden"));

    let (server_transport, client_transport) = tokio::io::duplex(16 * 1024);
    let server = PtyMcpServer::new(app);
    let server_handle = tokio::spawn(async move {
        server.serve(server_transport).await?.waiting().await?;
        anyhow::Ok(())
    });

    let client = DummyClient.serve(client_transport).await?;
    let resources = client.list_resources(None).await?;
    let resource_uris = resources
        .resources
        .iter()
        .map(|resource| resource.raw.uri.as_ref())
        .collect::<Vec<_>>();
    assert!(resource_uris.contains(&"ssh://tunnels"));
    assert!(!resource_uris.contains(&"ssh://mounts"));
    assert!(
        !resource_uris
            .iter()
            .any(|uri| uri.starts_with("ssh://mounts/"))
    );

    let templates = client.list_resource_templates(None).await?;
    let template_uris = templates
        .resource_templates
        .iter()
        .map(|template| template.raw.uri_template.as_ref())
        .collect::<Vec<_>>();
    assert!(template_uris.contains(&"ssh://tunnels/{id}"));
    assert!(!template_uris.contains(&"ssh://mounts/{id}"));

    let read_error = client
        .read_resource(ReadResourceRequestParams::new("ssh://mounts"))
        .await
        .expect_err("ssh://mounts should not be readable when mount feature is hidden");
    assert!(read_error.to_string().contains("resource not found"));

    client.cancel().await?;
    server_handle.await??;
    Ok(())
}

#[tokio::test]
async fn ssh_connect_reports_capability_unavailable_when_ssh_missing() -> anyhow::Result<()> {
    let mut config = Config::default();
    config.ssh.ssh_bin_path = Some(PathBuf::from("/definitely/missing/ssh"));
    let app = Arc::new(AppState::new(config));
    let server = PtyMcpServer::new(app);
    let (server_transport, client_transport) = tokio::io::duplex(16 * 1024);
    let server_handle = tokio::spawn(async move {
        server.serve(server_transport).await?.waiting().await?;
        anyhow::Ok(())
    });

    let client = DummyClient.serve(client_transport).await?;
    let result = client
        .call_tool(
            CallToolRequestParams::new("ssh_connect").with_arguments(
                serde_json::json!({
                    "host": "devbox.example.com",
                    "auth_kind": "ssh_agent",
                    "user": "alice",
                    "description": "missing ssh capability"
                })
                .as_object()
                .expect("connect args object")
                .clone(),
            ),
        )
        .await?;
    assert_eq!(result.is_error, Some(true));
    let body = result.structured_content.expect("structured error");
    assert!(
        body["message"]
            .as_str()
            .expect("error message")
            .contains("ssh capability is unavailable")
    );

    client.cancel().await?;
    server_handle.await??;
    Ok(())
}

#[cfg(unix)]
#[tokio::test]
async fn ssh_mount_requires_target_path_in_tool_contract() -> anyhow::Result<()> {
    let sandbox = TempDirGuard::new("mount_requires_target_path")?;
    let app = Arc::new(AppState::new(mount_feature_available_config(&sandbox)?));
    let mut connection = app.ssh().create_placeholder_connection(default_target());
    connection.status = SshConnectionStatus::Ready;
    app.ssh().upsert_connection(connection.clone());

    let (server_transport, client_transport) = tokio::io::duplex(16 * 1024);
    let server = PtyMcpServer::new(app);
    let server_handle = tokio::spawn(async move {
        server.serve(server_transport).await?.waiting().await?;
        anyhow::Ok(())
    });

    let client = DummyClient.serve(client_transport).await?;
    let error = client
        .call_tool(
            CallToolRequestParams::new("ssh_mount").with_arguments(
                serde_json::json!({
                    "connection_id": connection.connection_id,
                    "remote_path": "/srv/project",
                    "description": "missing target path"
                })
                .as_object()
                .expect("mount args object")
                .clone(),
            ),
        )
        .await
        .expect_err("missing target_path should fail during parameter validation");
    assert!(error.to_string().contains("missing field `target_path`"));

    client.cancel().await?;
    server_handle.await??;
    Ok(())
}

async fn read_json_resource(
    client: &rmcp::service::RunningService<rmcp::RoleClient, DummyClient>,
    uri: &str,
) -> anyhow::Result<Value> {
    let response = client
        .read_resource(ReadResourceRequestParams::new(uri))
        .await?;
    let text = match &response.contents[0] {
        rmcp::model::ResourceContents::TextResourceContents { text, .. } => text,
        other => anyhow::bail!("unexpected resource contents for {uri}: {other:?}"),
    };

    Ok(serde_json::from_str(text)?)
}

#[cfg(unix)]
#[tokio::test]
async fn ssh_session_spawn_reuses_pty_path_and_enriches_pty_list() -> anyhow::Result<()> {
    let sandbox = TempDirGuard::new("session_spawn")?;
    let ssh_path = sandbox.path.join("ssh");
    write_fake_executable(
        &ssh_path,
        "#!/bin/sh\nif [ \"$1\" = \"-V\" ]; then echo 'OpenSSH_9.9p1' 1>&2; exit 0; fi\nprintf 'remote-ready\\n'\nsleep 0.2\n",
    )?;

    let mut config = Config::default();
    config.ssh.ssh_bin_path = Some(ssh_path);
    let app = Arc::new(AppState::new(config));
    let server = PtyMcpServer::new(app);
    let (server_transport, client_transport) = tokio::io::duplex(16 * 1024);
    let server_handle = tokio::spawn(async move {
        server.serve(server_transport).await?.waiting().await?;
        anyhow::Ok(())
    });

    let client = DummyClient.serve(client_transport).await?;
    let connected = client
        .call_tool(
            CallToolRequestParams::new("ssh_connect").with_arguments(
                serde_json::json!({
                    "host_alias": "devbox",
                    "auth_kind": "config_alias",
                    "user": "alice",
                    "description": "ssh session spawn contract"
                })
                .as_object()
                .expect("connect args object")
                .clone(),
            ),
        )
        .await?
        .into_typed::<SshConnectResponse>()?;

    let spawned = client
        .call_tool(
            CallToolRequestParams::new("ssh_session_spawn").with_arguments(
                serde_json::json!({
                    "connection_id": connected.connection_id,
                    "command": "printf",
                    "args": ["remote-command\\n"],
                    "cwd": "/srv/project",
                    "env": {"TERM":"xterm-256color"},
                    "interactive": true,
                    "description": "remote shell",
                    "capture_wait_ms": 500,
                    "capture_limit": 20
                })
                .as_object()
                .expect("session spawn args object")
                .clone(),
            ),
        )
        .await?
        .into_typed::<SshSessionSpawnResponse>()?;

    assert_eq!(spawned.connection_id, connected.connection_id);
    assert_eq!(spawned.transport, pty_mcp::session::SessionTransport::Ssh);
    assert_eq!(spawned.remote_cwd.as_deref(), Some("/srv/project"));
    assert_eq!(spawned.target_summary.as_deref(), Some("alice@devbox"));
    assert!(
        spawned
            .initial_output
            .as_ref()
            .is_some_and(|snapshot| { snapshot.text.contains("remote-ready") })
    );

    tokio::time::sleep(std::time::Duration::from_millis(50)).await;

    let listed = client
        .call_tool(CallToolRequestParams::new("pty_list"))
        .await?
        .into_typed::<PtyListResponse>()?;
    let session = listed
        .sessions
        .into_iter()
        .find(|session| session.session_id == spawned.session_id)
        .expect("spawned session should appear in pty_list");
    assert_eq!(session.transport, pty_mcp::session::SessionTransport::Ssh);
    assert_eq!(session.connection_id, Some(connected.connection_id));
    assert_eq!(session.target_summary.as_deref(), Some("alice@devbox"));
    assert_eq!(session.remote_cwd.as_deref(), Some("/srv/project"));
    assert!(session.remote_command.is_some());
    assert_eq!(
        session.remote_env_preview.get("TERM").map(String::as_str),
        Some("xterm-256color")
    );

    client.cancel().await?;
    server_handle.await??;
    Ok(())
}

#[cfg(unix)]
#[tokio::test]
async fn ssh_exec_runs_shell_snippets_and_session_spawn_keeps_argv_literal() -> anyhow::Result<()> {
    let sandbox = TempDirGuard::new("exec_vs_spawn")?;
    let ssh_path = sandbox.path.join("ssh");
    write_fake_executable(
        &ssh_path,
        "#!/bin/sh\nset -eu\nif [ \"${1:-}\" = \"-V\" ]; then echo 'OpenSSH_9.9p1' 1>&2; exit 0; fi\nlast=''\nfor arg in \"$@\"; do last=\"$arg\"; done\nif [ \"$last\" = \"0\" ]; then exit 0; fi\nsh -lc \"$last\"\n",
    )?;

    let mut config = Config::default();
    config.ssh.ssh_bin_path = Some(ssh_path);
    let app = Arc::new(AppState::new(config));
    let server = PtyMcpServer::new(app);
    let (server_transport, client_transport) = tokio::io::duplex(16 * 1024);
    let server_handle = tokio::spawn(async move {
        server.serve(server_transport).await?.waiting().await?;
        anyhow::Ok(())
    });

    let client = DummyClient.serve(client_transport).await?;
    let connected = client
        .call_tool(
            CallToolRequestParams::new("ssh_connect").with_arguments(
                serde_json::json!({
                    "host_alias": "devbox",
                    "auth_kind": "config_alias",
                    "user": "alice",
                    "description": "ssh exec contract"
                })
                .as_object()
                .expect("connect args object")
                .clone(),
            ),
        )
        .await?
        .into_typed::<SshConnectResponse>()?;

    let exec_spawned = client
        .call_tool(
            CallToolRequestParams::new("ssh_exec").with_arguments(
                serde_json::json!({
                    "connection_id": connected.connection_id,
                    "script": "printf '%s\\n' \"$HOME\"",
                    "description": "shell script over ssh"
                })
                .as_object()
                .expect("ssh_exec args object")
                .clone(),
            ),
        )
        .await?
        .into_typed::<SshExecResponse>()?;
    assert_eq!(
        exec_spawned.transport,
        pty_mcp::session::SessionTransport::Ssh
    );

    wait_for_session_exit(&client, &exec_spawned.session_id).await?;
    let exec_output = read_session_output(&client, &exec_spawned.session_id).await?;
    let home = std::env::var("HOME").expect("HOME should be set for shell execution test");
    assert!(
        exec_output
            .page
            .text
            .lines()
            .any(|line| line.trim() == home)
    );

    let argv_spawned = client
        .call_tool(
            CallToolRequestParams::new("ssh_session_spawn").with_arguments(
                serde_json::json!({
                    "connection_id": connected.connection_id,
                    "command": "printf",
                    "args": ["%s\\n", "$HOME"],
                    "interactive": false,
                    "description": "argv contract over ssh"
                })
                .as_object()
                .expect("ssh_session_spawn args object")
                .clone(),
            ),
        )
        .await?
        .into_typed::<SshSessionSpawnResponse>()?;

    wait_for_session_exit(&client, &argv_spawned.session_id).await?;
    let argv_output = read_session_output(&client, &argv_spawned.session_id).await?;
    assert!(
        argv_output
            .page
            .text
            .lines()
            .any(|line| line.trim() == "$HOME")
    );

    client.cancel().await?;
    server_handle.await??;
    Ok(())
}

#[cfg(unix)]
#[tokio::test]
async fn ssh_run_returns_direct_output_without_creating_session() -> anyhow::Result<()> {
    let sandbox = TempDirGuard::new("ssh_run_direct_output")?;
    let ssh_path = sandbox.path.join("ssh");
    write_fake_executable(
        &ssh_path,
        "#!/bin/sh\nset -eu\nif [ \"${1:-}\" = \"-V\" ]; then echo 'OpenSSH_9.9p1' 1>&2; exit 0; fi\nlast=''\nfor arg in \"$@\"; do last=\"$arg\"; done\nif [ \"$last\" = \"0\" ]; then exit 0; fi\nsh -lc \"$last\"\n",
    )?;

    let mut config = Config::default();
    config.ssh.ssh_bin_path = Some(ssh_path);
    let app = Arc::new(AppState::new(config));
    let server = PtyMcpServer::new(app);
    let (server_transport, client_transport) = tokio::io::duplex(16 * 1024);
    let server_handle = tokio::spawn(async move {
        server.serve(server_transport).await?.waiting().await?;
        anyhow::Ok(())
    });

    let client = DummyClient.serve(client_transport).await?;
    let connected = client
        .call_tool(
            CallToolRequestParams::new("ssh_connect").with_arguments(
                serde_json::json!({
                    "host_alias": "devbox",
                    "auth_kind": "config_alias",
                    "user": "alice",
                    "description": "ssh run contract"
                })
                .as_object()
                .expect("connect args object")
                .clone(),
            ),
        )
        .await?
        .into_typed::<SshConnectResponse>()?;

    let run = client
        .call_tool(
            CallToolRequestParams::new("ssh_run").with_arguments(
                serde_json::json!({
                    "connection_id": connected.connection_id,
                    "script": "printf 'out\\n'; printf 'err\\n' >&2",
                })
                .as_object()
                .expect("ssh_run args object")
                .clone(),
            ),
        )
        .await?
        .into_typed::<SshRunResponse>()?;

    assert!(run.success);
    assert_eq!(run.exit_code, Some(0));
    assert_eq!(run.exit_signal, None);
    assert_eq!(run.stdout, "out\n");
    assert_eq!(run.stderr, "err\n");

    let listed = client
        .call_tool(
            CallToolRequestParams::new("pty_list").with_arguments(
                serde_json::json!({})
                    .as_object()
                    .expect("pty_list args object")
                    .clone(),
            ),
        )
        .await?
        .into_typed::<PtyListResponse>()?;
    assert!(listed.sessions.is_empty());

    client.cancel().await?;
    server_handle.await??;
    Ok(())
}

#[cfg(unix)]
#[tokio::test]
async fn ssh_run_enforces_max_output_bytes() -> anyhow::Result<()> {
    let sandbox = TempDirGuard::new("ssh_run_output_limit")?;
    let ssh_path = sandbox.path.join("ssh");
    write_fake_executable(
        &ssh_path,
        "#!/bin/sh\nset -eu\nif [ \"${1:-}\" = \"-V\" ]; then echo 'OpenSSH_9.9p1' 1>&2; exit 0; fi\nlast=''\nfor arg in \"$@\"; do last=\"$arg\"; done\nif [ \"$last\" = \"0\" ]; then exit 0; fi\nsh -lc \"$last\"\n",
    )?;

    let mut config = Config::default();
    config.ssh.ssh_bin_path = Some(ssh_path);
    let app = Arc::new(AppState::new(config));
    let server = PtyMcpServer::new(app);
    let (server_transport, client_transport) = tokio::io::duplex(16 * 1024);
    let server_handle = tokio::spawn(async move {
        server.serve(server_transport).await?.waiting().await?;
        anyhow::Ok(())
    });

    let client = DummyClient.serve(client_transport).await?;
    let connected = client
        .call_tool(
            CallToolRequestParams::new("ssh_connect").with_arguments(
                serde_json::json!({
                    "host_alias": "devbox",
                    "auth_kind": "config_alias",
                    "user": "alice",
                    "description": "ssh run output limit contract"
                })
                .as_object()
                .expect("connect args object")
                .clone(),
            ),
        )
        .await?
        .into_typed::<SshConnectResponse>()?;

    let result = client
        .call_tool(
            CallToolRequestParams::new("ssh_run").with_arguments(
                serde_json::json!({
                    "connection_id": connected.connection_id,
                    "script": "printf '1234567890'",
                    "max_output_bytes": 4
                })
                .as_object()
                .expect("ssh_run args object")
                .clone(),
            ),
        )
        .await?;
    assert_eq!(result.is_error, Some(true));
    let structured = result.structured_content.expect("structured error");
    let message = structured["message"].as_str().expect("error message");
    assert!(message.contains("ssh command output exceeded max_output_bytes"));
    assert!(message.contains("limit=4"));

    client.cancel().await?;
    server_handle.await??;
    Ok(())
}

#[cfg(unix)]
#[tokio::test]
async fn ssh_exec_can_wait_briefly_and_return_completed_result() -> anyhow::Result<()> {
    let sandbox = TempDirGuard::new("ssh_exec_wait_complete")?;
    let ssh_path = sandbox.path.join("ssh");
    write_fake_executable(
        &ssh_path,
        "#!/bin/sh\nset -eu\nif [ \"${1:-}\" = \"-V\" ]; then echo 'OpenSSH_9.9p1' 1>&2; exit 0; fi\nlast=''\nfor arg in \"$@\"; do last=\"$arg\"; done\nif [ \"$last\" = \"0\" ]; then exit 0; fi\nsh -lc \"$last\"\n",
    )?;

    let mut config = Config::default();
    config.ssh.ssh_bin_path = Some(ssh_path);
    let app = Arc::new(AppState::new(config));
    let server = PtyMcpServer::new(app);
    let (server_transport, client_transport) = tokio::io::duplex(16 * 1024);
    let server_handle = tokio::spawn(async move {
        server.serve(server_transport).await?.waiting().await?;
        anyhow::Ok(())
    });

    let client = DummyClient.serve(client_transport).await?;
    let connected = client
        .call_tool(
            CallToolRequestParams::new("ssh_connect").with_arguments(
                serde_json::json!({
                    "host_alias": "devbox",
                    "auth_kind": "config_alias",
                    "user": "alice",
                    "description": "ssh exec wait contract"
                })
                .as_object()
                .expect("connect args object")
                .clone(),
            ),
        )
        .await?
        .into_typed::<SshConnectResponse>()?;

    let exec = client
        .call_tool(
            CallToolRequestParams::new("ssh_exec").with_arguments(
                serde_json::json!({
                    "connection_id": connected.connection_id,
                    "script": "printf 'done\\n'",
                    "description": "shell script over ssh",
                    "wait_timeout_ms": 500,
                    "capture_limit": 20
                })
                .as_object()
                .expect("ssh_exec args object")
                .clone(),
            ),
        )
        .await?
        .into_typed::<SshExecResponse>()?;

    assert_eq!(exec.completed, Some(true));
    assert_eq!(exec.exit_code, Some(0));
    assert_eq!(exec.exit_signal, None);
    assert!(
        exec.initial_output
            .as_ref()
            .is_some_and(|snapshot| snapshot.text.contains("done"))
    );

    client.cancel().await?;
    server_handle.await??;
    Ok(())
}

#[cfg(unix)]
#[tokio::test]
async fn ssh_exec_wait_timeout_returns_session_without_completion() -> anyhow::Result<()> {
    let sandbox = TempDirGuard::new("ssh_exec_wait_timeout")?;
    let ssh_path = sandbox.path.join("ssh");
    write_fake_executable(
        &ssh_path,
        "#!/bin/sh\nset -eu\nif [ \"${1:-}\" = \"-V\" ]; then echo 'OpenSSH_9.9p1' 1>&2; exit 0; fi\nlast=''\nfor arg in \"$@\"; do last=\"$arg\"; done\nif [ \"$last\" = \"0\" ]; then exit 0; fi\nsh -lc \"$last\"\n",
    )?;

    let mut config = Config::default();
    config.ssh.ssh_bin_path = Some(ssh_path);
    let app = Arc::new(AppState::new(config));
    let server = PtyMcpServer::new(app);
    let (server_transport, client_transport) = tokio::io::duplex(16 * 1024);
    let server_handle = tokio::spawn(async move {
        server.serve(server_transport).await?.waiting().await?;
        anyhow::Ok(())
    });

    let client = DummyClient.serve(client_transport).await?;
    let connected = client
        .call_tool(
            CallToolRequestParams::new("ssh_connect").with_arguments(
                serde_json::json!({
                    "host_alias": "devbox",
                    "auth_kind": "config_alias",
                    "user": "alice",
                    "description": "ssh exec timeout contract"
                })
                .as_object()
                .expect("connect args object")
                .clone(),
            ),
        )
        .await?
        .into_typed::<SshConnectResponse>()?;

    let exec = client
        .call_tool(
            CallToolRequestParams::new("ssh_exec").with_arguments(
                serde_json::json!({
                    "connection_id": connected.connection_id,
                    "script": "printf 'start\\n'; sleep 1; printf 'finish\\n'",
                    "description": "shell script over ssh",
                    "wait_timeout_ms": 50,
                    "capture_limit": 20
                })
                .as_object()
                .expect("ssh_exec args object")
                .clone(),
            ),
        )
        .await?
        .into_typed::<SshExecResponse>()?;

    assert_eq!(exec.completed, Some(false));
    assert_eq!(exec.exit_code, None);
    assert_eq!(exec.exit_signal, None);

    let waited = wait_for_session_exit(&client, &exec.session_id).await?;
    assert!(waited.completed);

    let output = read_session_output(&client, &exec.session_id).await?;
    assert!(output.page.text.contains("start"));
    assert!(output.page.text.contains("finish"));

    client.cancel().await?;
    server_handle.await??;
    Ok(())
}

#[cfg(unix)]
#[tokio::test]
async fn ssh_disconnect_force_cleans_up_session_and_mounts() -> anyhow::Result<()> {
    let sandbox = TempDirGuard::new("disconnect_force")?;
    let ssh_path = sandbox.path.join("ssh");
    let sshfs_path = sandbox.path.join("sshfs");
    let umount_path = sandbox.path.join("umount");
    let managed_root = sandbox.path.join("managed");
    fs::create_dir_all(&managed_root)?;

    write_fake_executable(
        &ssh_path,
        "#!/bin/sh\nif [ \"$1\" = \"-V\" ]; then echo 'OpenSSH_9.9p1' 1>&2; exit 0; fi\nif [ \"$1\" = \"-T\" ]; then exit 0; fi\nprintf 'remote-running\\n'\nsleep 5\n",
    )?;
    write_fake_executable(
        &sshfs_path,
        "#!/bin/sh\nset -eu\nif [ \"${1:-}\" = \"--version\" ] || [ \"${1:-}\" = \"-V\" ]; then echo 'SSHFS 3.7.3 (macFUSE 4.6.0)'; exit 0; fi\nlast=''\nfor arg in \"$@\"; do last=\"$arg\"; done\nmkdir -p \"$last\"\ntouch \"$last/.sshfs-mounted\"\n",
    )?;
    write_fake_executable(
        &umount_path,
        "#!/bin/sh\nset -eu\ntarget=''\nfor arg in \"$@\"; do target=\"$arg\"; done\nrm -f \"$target/.sshfs-mounted\"\n",
    )?;

    let mut config = Config::default();
    config.ssh.ssh_bin_path = Some(ssh_path);
    config.ssh.sshfs_bin_path = Some(sshfs_path);
    config.ssh.umount_bin_path = Some(umount_path);
    config.ssh.managed_mount_root = Some(managed_root.clone());
    let app = Arc::new(AppState::new(config));
    let server = PtyMcpServer::new(app);
    let (server_transport, client_transport) = tokio::io::duplex(16 * 1024);
    let server_handle = tokio::spawn(async move {
        server.serve(server_transport).await?.waiting().await?;
        anyhow::Ok(())
    });

    let client = DummyClient.serve(client_transport).await?;
    let connected = client
        .call_tool(
            CallToolRequestParams::new("ssh_connect").with_arguments(
                serde_json::json!({
                    "host_alias": "devbox",
                    "auth_kind": "config_alias",
                    "user": "alice",
                    "description": "disconnect contract"
                })
                .as_object()
                .expect("connect args object")
                .clone(),
            ),
        )
        .await?
        .into_typed::<SshConnectResponse>()?;

    let spawned = client
        .call_tool(
            CallToolRequestParams::new("ssh_session_spawn").with_arguments(
                serde_json::json!({
                    "connection_id": connected.connection_id,
                    "command": "printf",
                    "args": ["hold-open"],
                    "interactive": true,
                    "description": "remote session for disconnect"
                })
                .as_object()
                .expect("session spawn args object")
                .clone(),
            ),
        )
        .await?
        .into_typed::<SshSessionSpawnResponse>()?;

    let mounted = client
        .call_tool(
            CallToolRequestParams::new("ssh_mount").with_arguments(
                serde_json::json!({
                    "connection_id": connected.connection_id,
                    "remote_path": "/srv/project",
                    "target_path": managed_root.join("disconnect-mount"),
                    "description": "remote mount for disconnect"
                })
                .as_object()
                .expect("mount args object")
                .clone(),
            ),
        )
        .await?
        .into_typed::<SshMountResponse>()?;
    assert!(Path::new(&mounted.target_path).exists());

    let disconnected = client
        .call_tool(
            CallToolRequestParams::new("ssh_disconnect").with_arguments(
                serde_json::json!({
                    "connection_id": connected.connection_id,
                    "force": true,
                    "cleanup_mounts": true
                })
                .as_object()
                .expect("disconnect args object")
                .clone(),
            ),
        )
        .await?
        .into_typed::<SshDisconnectResponse>()?;

    assert_eq!(disconnected.connection_id, connected.connection_id);
    assert_eq!(disconnected.previous_status, connected.status);
    assert_eq!(
        disconnected.current_status,
        pty_mcp::ssh::SshConnectionStatus::Disconnected
    );
    assert_eq!(disconnected.closed_sessions, 1);
    assert_eq!(disconnected.closed_mounts, 1);
    assert!(!Path::new(&mounted.target_path).exists());

    let listed = client
        .call_tool(CallToolRequestParams::new("pty_list"))
        .await?
        .into_typed::<PtyListResponse>()?;
    assert!(
        listed
            .sessions
            .into_iter()
            .all(|session| session.session_id != spawned.session_id)
    );

    client.cancel().await?;
    server_handle.await??;
    Ok(())
}

#[cfg(unix)]
#[tokio::test]
async fn ssh_file_and_directory_tools_operate_over_existing_connection() -> anyhow::Result<()> {
    let sandbox = TempDirGuard::new("file_tools")?;
    let ssh_path = sandbox.path.join("ssh");
    write_fake_executable(
        &ssh_path,
        "#!/bin/sh\nset -eu\nif [ \"${1:-}\" = \"-V\" ]; then echo 'OpenSSH_9.9p1' 1>&2; exit 0; fi\nlast=''\nfor arg in \"$@\"; do last=\"$arg\"; done\nif [ \"$last\" = \"0\" ]; then exit 0; fi\nsh -lc \"$last\"\n",
    )?;

    let mut config = Config::default();
    config.ssh.ssh_bin_path = Some(ssh_path);
    let app = Arc::new(AppState::new(config));
    let server = PtyMcpServer::new(app);
    let (server_transport, client_transport) = tokio::io::duplex(16 * 1024);
    let server_handle = tokio::spawn(async move {
        server.serve(server_transport).await?.waiting().await?;
        anyhow::Ok(())
    });

    let client = DummyClient.serve(client_transport).await?;
    let connected = client
        .call_tool(
            CallToolRequestParams::new("ssh_connect").with_arguments(
                serde_json::json!({
                    "host_alias": "devbox",
                    "auth_kind": "config_alias",
                    "user": "alice",
                    "description": "ssh file tools contract"
                })
                .as_object()
                .expect("connect args object")
                .clone(),
            ),
        )
        .await?
        .into_typed::<SshConnectResponse>()?;

    let created_dir = client
        .call_tool(
            CallToolRequestParams::new("ssh_mkdir").with_arguments(
                serde_json::json!({
                    "connection_id": connected.connection_id,
                    "path": sandbox.path.join("remote/nested"),
                    "create_parents": true
                })
                .as_object()
                .expect("ssh_mkdir args object")
                .clone(),
            ),
        )
        .await?
        .into_typed::<SshMkdirResponse>()?;
    assert!(created_dir.create_parents);
    assert!(Path::new(&created_dir.path).is_dir());

    let written = client
        .call_tool(
            CallToolRequestParams::new("ssh_write_file").with_arguments(
                serde_json::json!({
                    "connection_id": connected.connection_id,
                    "path": sandbox.path.join("remote/nested/note.txt"),
                    "content": "alpha\nbeta\n",
                    "create_parents": true
                })
                .as_object()
                .expect("ssh_write_file args object")
                .clone(),
            ),
        )
        .await?
        .into_typed::<SshWriteFileResponse>()?;
    assert_eq!(written.bytes_written, "alpha\nbeta\n".len());
    assert_eq!(fs::read_to_string(&written.path)?, "alpha\nbeta\n");

    let appended = client
        .call_tool(
            CallToolRequestParams::new("ssh_write_file").with_arguments(
                serde_json::json!({
                    "connection_id": connected.connection_id,
                    "path": written.path,
                    "content": "gamma\n",
                    "append": true
                })
                .as_object()
                .expect("ssh_write_file append args object")
                .clone(),
            ),
        )
        .await?
        .into_typed::<SshWriteFileResponse>()?;
    assert!(appended.append);

    let read = client
        .call_tool(
            CallToolRequestParams::new("ssh_read_file").with_arguments(
                serde_json::json!({
                    "connection_id": connected.connection_id,
                    "path": appended.path
                })
                .as_object()
                .expect("ssh_read_file args object")
                .clone(),
            ),
        )
        .await?
        .into_typed::<SshReadFileResponse>()?;
    assert_eq!(read.content, "alpha\nbeta\ngamma\n");

    fs::write(sandbox.path.join("remote/.secret"), "hidden")?;
    let listed = client
        .call_tool(
            CallToolRequestParams::new("ssh_list_dir").with_arguments(
                serde_json::json!({
                    "connection_id": connected.connection_id,
                    "path": sandbox.path.join("remote"),
                    "include_hidden": true
                })
                .as_object()
                .expect("ssh_list_dir args object")
                .clone(),
            ),
        )
        .await?
        .into_typed::<SshListDirResponse>()?;
    assert!(listed.entries.iter().any(|entry| entry.name == "nested"));
    assert!(listed.entries.iter().any(|entry| entry.name == ".secret"));

    client.cancel().await?;
    server_handle.await??;
    Ok(())
}

#[cfg(unix)]
#[tokio::test]
async fn ssh_read_file_enforces_max_bytes() -> anyhow::Result<()> {
    let sandbox = TempDirGuard::new("read_limit")?;
    let ssh_path = sandbox.path.join("ssh");
    write_fake_executable(
        &ssh_path,
        "#!/bin/sh\nset -eu\nif [ \"${1:-}\" = \"-V\" ]; then echo 'OpenSSH_9.9p1' 1>&2; exit 0; fi\nlast=''\nfor arg in \"$@\"; do last=\"$arg\"; done\nif [ \"$last\" = \"0\" ]; then exit 0; fi\nsh -lc \"$last\"\n",
    )?;
    fs::write(sandbox.path.join("big.txt"), "0123456789")?;

    let mut config = Config::default();
    config.ssh.ssh_bin_path = Some(ssh_path);
    let app = Arc::new(AppState::new(config));
    let server = PtyMcpServer::new(app);
    let (server_transport, client_transport) = tokio::io::duplex(16 * 1024);
    let server_handle = tokio::spawn(async move {
        server.serve(server_transport).await?.waiting().await?;
        anyhow::Ok(())
    });

    let client = DummyClient.serve(client_transport).await?;
    let connected = client
        .call_tool(
            CallToolRequestParams::new("ssh_connect").with_arguments(
                serde_json::json!({
                    "host_alias": "devbox",
                    "auth_kind": "config_alias",
                    "user": "alice",
                    "description": "ssh read limit contract"
                })
                .as_object()
                .expect("connect args object")
                .clone(),
            ),
        )
        .await?
        .into_typed::<SshConnectResponse>()?;

    let result = client
        .call_tool(
            CallToolRequestParams::new("ssh_read_file").with_arguments(
                serde_json::json!({
                    "connection_id": connected.connection_id,
                    "path": sandbox.path.join("big.txt"),
                    "max_bytes": 4
                })
                .as_object()
                .expect("ssh_read_file args object")
                .clone(),
            ),
        )
        .await?;
    assert_eq!(result.is_error, Some(true));
    let structured = result.structured_content.expect("structured error");
    let message = structured["message"].as_str().expect("error message");
    assert!(message.contains("remote file exceeds max_bytes"));
    assert!(message.contains("max_bytes=4"));

    client.cancel().await?;
    server_handle.await??;
    Ok(())
}

async fn wait_for_session_exit(
    client: &rmcp::service::RunningService<rmcp::RoleClient, DummyClient>,
    session_id: &pty_mcp::session::SessionId,
) -> anyhow::Result<PtyWaitResponse> {
    Ok(client
        .call_tool(
            CallToolRequestParams::new("pty_wait").with_arguments(
                serde_json::json!({
                    "session_id": session_id,
                    "timeout_ms": 5_000
                })
                .as_object()
                .expect("pty_wait args object")
                .clone(),
            ),
        )
        .await?
        .into_typed::<PtyWaitResponse>()?)
}

async fn read_session_output(
    client: &rmcp::service::RunningService<rmcp::RoleClient, DummyClient>,
    session_id: &pty_mcp::session::SessionId,
) -> anyhow::Result<PtyReadResponse> {
    Ok(client
        .call_tool(
            CallToolRequestParams::new("pty_read").with_arguments(
                serde_json::json!({
                    "session_id": session_id,
                    "offset": 0,
                    "limit": 200
                })
                .as_object()
                .expect("pty_read args object")
                .clone(),
            ),
        )
        .await?
        .into_typed::<PtyReadResponse>()?)
}