fast-mcp-ssh 0.4.1

Fast MCP SSH server with persistent PTY sessions, SFTP, and AI-first tool surface
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
//! Filesystem tools: `ls`, `stat`, `dn`, `up`, `wr`, `mkdir`, `rm`, `tail`.

use std::time::Duration;

use base64::Engine;
use rmcp::{
    ErrorData as McpError, RoleServer, handler::server::wrapper::Parameters, model::*, schemars,
    service::RequestContext, tool, tool_router,
};
use serde::Deserialize;

use crate::errors::SshError;
use crate::guards;
use crate::output::{Toon, truncate_with_hint};
use crate::server::{SshServer, elicit_confirmation};
use crate::sftp;
use crate::tail;
use crate::tools::{
    INLINE_MAX_BYTES, MAX_FOLLOW_SECS, MAX_LS_ENTRIES, MAX_WRITE_INLINE_BYTES, text,
};

#[derive(Debug, Deserialize, schemars::JsonSchema)]
pub struct UploadArgs {
    /// Host alias. Omit if a default_host is configured.
    #[serde(default)]
    pub host: Option<String>,
    /// Local source path. `~` expanded.
    pub local: String,
    /// Remote destination path. Parent dir must exist.
    pub remote: String,
}

#[derive(Debug, Deserialize, schemars::JsonSchema)]
pub struct DownloadArgs {
    /// Host alias. Omit if a default_host is configured.
    #[serde(default)]
    pub host: Option<String>,
    /// Remote source path.
    pub remote: String,
    /// Local destination path. Omit to receive content inline (text < 256 KB; binary base64).
    #[serde(default)]
    pub local: Option<String>,
}

#[derive(Debug, Deserialize, schemars::JsonSchema)]
pub struct LsArgs {
    /// Host alias. Omit if a default_host is configured.
    #[serde(default)]
    pub host: Option<String>,
    /// Remote directory path. `~` not expanded server-side; use absolute paths.
    pub path: String,
    /// Max entries returned. Default 1000 (also the hard cap).
    #[serde(default)]
    pub limit: Option<u32>,
    /// Skip the first N entries (alphabetical). Use with `limit` to paginate.
    #[serde(default)]
    pub offset: Option<u32>,
}

#[derive(Debug, Deserialize, schemars::JsonSchema)]
pub struct WriteArgs {
    /// Host alias. Omit if a default_host is configured.
    #[serde(default)]
    pub host: Option<String>,
    /// Remote destination path. Replaces existing file.
    pub remote: String,
    /// File content (UTF-8 text).
    pub content: String,
    /// Octal mode at create time (e.g. 420 = 0o644). Default 0o644.
    #[serde(default)]
    pub mode: Option<u32>,
}

#[derive(Debug, Deserialize, schemars::JsonSchema)]
pub struct MkdirArgs {
    /// Host alias. Omit if a default_host is configured.
    #[serde(default)]
    pub host: Option<String>,
    /// Remote directory path.
    pub path: String,
    /// If true, create intermediate parents (`mkdir -p`). Default false.
    #[serde(default)]
    pub parents: Option<bool>,
}

#[derive(Debug, Deserialize, schemars::JsonSchema)]
pub struct RmArgs {
    /// Host alias. Omit if a default_host is configured.
    #[serde(default)]
    pub host: Option<String>,
    /// Remote path (file or directory).
    pub path: String,
    /// If true, recursively delete a directory and its contents. Default false.
    #[serde(default)]
    pub recursive: Option<bool>,
}

#[derive(Debug, Deserialize, schemars::JsonSchema)]
pub struct StatArgs {
    /// Host alias. Omit if a default_host is configured.
    #[serde(default)]
    pub host: Option<String>,
    /// Remote path.
    pub path: String,
}

#[derive(Debug, Deserialize, schemars::JsonSchema)]
pub struct TailArgs {
    /// Host alias. Omit if a default_host is configured.
    #[serde(default)]
    pub host: Option<String>,
    /// Remote file path.
    pub path: String,
    /// Number of trailing lines to read. Default 100. Ignored when follow=true.
    #[serde(default)]
    pub lines: Option<u32>,
    /// If true, stream new lines for `seconds`. Default false.
    #[serde(default)]
    pub follow: Option<bool>,
    /// Stream duration in seconds when follow=true. Default 5.
    #[serde(default)]
    pub seconds: Option<u64>,
}

#[tool_router(router = files_router, vis = "pub")]
impl SshServer {
    #[tool(
        description = "SFTP upload local→remote, streamed in 256 KB chunks. Use for transferring local files to remote. Not for inline content — use wr.",
        annotations(
            title = "Up",
            read_only_hint = false,
            destructive_hint = true,
            idempotent_hint = true,
            open_world_hint = true
        )
    )]
    async fn up(
        &self,
        Parameters(args): Parameters<UploadArgs>,
    ) -> Result<CallToolResult, McpError> {
        let host_name = self.resolve_host(args.host)?;
        if let Err(e) = self
            .guards()
            .for_host(&host_name)
            .check_sftp_write(&args.remote)
        {
            self.audit.write(
                &host_name,
                "up",
                Some(&args.remote),
                None,
                None,
                None,
                None,
                Some(&e.to_string()),
                Some(e.to_string()),
            );
            return Err(e.into_mcp());
        }
        let session = self
            .pool
            .get_or_connect(&host_name, None)
            .await
            .map_err(|e| e.into_mcp())?;
        self.guard_resolved(&host_name, "up", &session, &args.remote, true)
            .await?;
        // The local side is the operator's own box: without this, `up` is an
        // exfiltration primitive pointed at ~/.ssh or a browser cookie store.
        let local = guards::resolve_local_path(&args.local);
        if let Err(e) = guards::check_local_read(&local) {
            self.audit.write(
                &host_name,
                "up",
                Some(&args.local),
                None,
                None,
                None,
                None,
                Some(&e.to_string()),
                Some(e.to_string()),
            );
            return Err(e.into_mcp());
        }
        let r = sftp::upload(&session, &local, &args.remote)
            .await
            .map_err(|e| e.into_mcp())?;
        self.audit.write(
            &host_name,
            "up",
            Some(&format!("{} -> {}", args.local, args.remote)),
            None,
            Some(r.duration_ms),
            Some(r.bytes),
            None,
            None,
            None,
        );
        let mut t = Toon::new();
        t.field("host", &host_name)
            .field("local", &args.local)
            .field("remote", &args.remote)
            .field("bytes", r.bytes)
            .field("ms", r.duration_ms as u64);
        Ok(text(t.into_string()))
    }

    #[tool(
        description = "SFTP download remote file. With local=<path> writes to disk; without returns inline (text<256KB or base64). Use for fetching files. Not for tailing logs — use tail.",
        annotations(
            title = "Dn",
            read_only_hint = true,
            destructive_hint = false,
            idempotent_hint = true,
            open_world_hint = true
        )
    )]
    async fn dn(
        &self,
        Parameters(args): Parameters<DownloadArgs>,
    ) -> Result<CallToolResult, McpError> {
        let host_name = self.resolve_host(args.host)?;
        if let Err(e) = self
            .guards()
            .for_host(&host_name)
            .check_sftp_read(&args.remote)
        {
            self.audit.write(
                &host_name,
                "dn",
                Some(&args.remote),
                None,
                None,
                None,
                None,
                Some(&e.to_string()),
                Some(e.to_string()),
            );
            return Err(e.into_mcp());
        }
        let session = self
            .pool
            .get_or_connect(&host_name, None)
            .await
            .map_err(|e| e.into_mcp())?;
        self.guard_resolved(&host_name, "dn", &session, &args.remote, false)
            .await?;
        // Remote-controlled bytes landing on the operator's own filesystem:
        // a `dn` into ~/.bashrc or an autostart folder is code execution here.
        let local_path = args.local.as_deref().map(guards::resolve_local_path);
        if let Some(p) = local_path.as_deref()
            && let Err(e) = guards::check_local_write(p)
        {
            self.audit.write(
                &host_name,
                "dn",
                args.local.as_deref(),
                None,
                None,
                None,
                None,
                Some(&e.to_string()),
                Some(e.to_string()),
            );
            return Err(e.into_mcp());
        }
        let (r, content) = sftp::download(
            &session,
            &args.remote,
            local_path.as_deref(),
            INLINE_MAX_BYTES,
        )
        .await
        .map_err(|e| e.into_mcp())?;
        self.audit.write(
            &host_name,
            "dn",
            Some(&args.remote),
            None,
            Some(r.duration_ms),
            None,
            Some(r.bytes),
            None,
            None,
        );

        let mut t = Toon::new();
        t.field("host", &host_name)
            .field("remote", &args.remote)
            .field("bytes", r.bytes)
            .field("ms", r.duration_ms as u64);
        if let Some(buf) = content {
            if sftp::looks_binary(&buf) {
                let encoded = base64::engine::general_purpose::STANDARD.encode(&buf);
                t.field("encoding", "base64");
                t.block("content", &encoded);
            } else {
                let s = String::from_utf8_lossy(&buf);
                let (display, _) = truncate_with_hint(&s, self.cfg().defaults.truncate_bytes);
                t.block("content", &display);
            }
        } else if let Some(p) = args.local.as_deref() {
            t.field("local", p);
        } else {
            // Inline requested but the remote file exceeds the cap; nothing
            // was transferred (`bytes` reports the remote size).
            t.field("content", "(too large for inline; rerun with local=<path>)");
        }
        Ok(text(t.into_string()))
    }

    #[tool(
        description = "SFTP list directory. Use for browsing remote filesystem. Returns name/kind/size/mode/mtime. Not for shell glob — use exec with `ls`.",
        annotations(
            title = "Ls",
            read_only_hint = true,
            destructive_hint = false,
            idempotent_hint = true,
            open_world_hint = true
        )
    )]
    async fn ls(&self, Parameters(args): Parameters<LsArgs>) -> Result<CallToolResult, McpError> {
        let host_name = self.resolve_host(args.host)?;
        if let Err(e) = self
            .guards()
            .for_host(&host_name)
            .check_sftp_read(&args.path)
        {
            self.audit.write(
                &host_name,
                "ls",
                Some(&args.path),
                None,
                None,
                None,
                None,
                Some(&e.to_string()),
                Some(e.to_string()),
            );
            return Err(e.into_mcp());
        }
        let session = self
            .pool
            .get_or_connect(&host_name, None)
            .await
            .map_err(|e| e.into_mcp())?;
        self.guard_resolved(&host_name, "ls", &session, &args.path, false)
            .await?;
        let mut entries = sftp::list_dir(&session, &args.path)
            .await
            .map_err(|e| e.into_mcp())?;
        let total = entries.len();
        let offset = args.offset.unwrap_or(0) as usize;
        let limit = args
            .limit
            .map(|n| n as usize)
            .unwrap_or(MAX_LS_ENTRIES)
            .min(MAX_LS_ENTRIES);
        let page: Vec<sftp::ListEntry> = if offset >= entries.len() {
            Vec::new()
        } else {
            entries.drain(offset..).take(limit).collect()
        };
        self.audit.write(
            &host_name,
            "ls",
            Some(&args.path),
            None,
            None,
            None,
            None,
            None,
            None,
        );
        let rows: Vec<Vec<String>> = page
            .iter()
            .map(|e| {
                vec![
                    e.name.clone(),
                    e.kind.into(),
                    e.size.to_string(),
                    format!("{:o}", e.mode & 0o7777),
                    e.mtime.to_string(),
                ]
            })
            .collect();
        let mut t = Toon::new();
        t.field("host", &host_name).field("path", &args.path);
        t.field("total", total)
            .field("offset", offset)
            .field("returned", page.len());
        if offset + page.len() < total {
            t.hint(&format!(
                "more entries; re-run with offset={}",
                offset + page.len()
            ));
        }
        t.table_strs("entries", &["name", "kind", "size", "mode", "mtime"], &rows);
        Ok(text(t.into_string()))
    }

    #[tool(
        description = "SFTP write inline content to remote file (replaces). Use instead of `echo > file` via exec. Atomic mode set at create time.",
        annotations(
            title = "Wr",
            read_only_hint = false,
            destructive_hint = true,
            idempotent_hint = true,
            open_world_hint = true
        )
    )]
    async fn wr(
        &self,
        Parameters(args): Parameters<WriteArgs>,
    ) -> Result<CallToolResult, McpError> {
        let host_name = self.resolve_host(args.host)?;
        if args.content.len() > MAX_WRITE_INLINE_BYTES {
            return Err(SshError::Config(format!(
                "content too large: {} bytes (max {} — use `up` for larger files)",
                args.content.len(),
                MAX_WRITE_INLINE_BYTES
            ))
            .into_mcp());
        }
        if let Err(e) = self
            .guards()
            .for_host(&host_name)
            .check_sftp_write(&args.remote)
        {
            self.audit.write(
                &host_name,
                "wr",
                Some(&args.remote),
                None,
                None,
                None,
                None,
                Some(&e.to_string()),
                Some(e.to_string()),
            );
            return Err(e.into_mcp());
        }
        let session = self
            .pool
            .get_or_connect(&host_name, None)
            .await
            .map_err(|e| e.into_mcp())?;
        self.guard_resolved(&host_name, "wr", &session, &args.remote, true)
            .await?;
        let r = sftp::write_inline(&session, &args.remote, args.content.as_bytes(), args.mode)
            .await
            .map_err(|e| e.into_mcp())?;
        self.audit.write(
            &host_name,
            "wr",
            Some(&args.remote),
            None,
            Some(r.duration_ms),
            Some(r.bytes),
            None,
            None,
            None,
        );
        let mut t = Toon::new();
        t.field("host", &host_name)
            .field("remote", &args.remote)
            .field("bytes", r.bytes)
            .field("ms", r.duration_ms as u64);
        if let Some(m) = args.mode {
            t.field("mode", format!("{m:o}"));
        }
        Ok(text(t.into_string()))
    }

    #[tool(
        description = "SFTP create directory. parents=true acts like `mkdir -p`. Use instead of `exec mkdir` to save a shell round-trip.",
        annotations(
            title = "Mkdir",
            read_only_hint = false,
            destructive_hint = false,
            idempotent_hint = true,
            open_world_hint = true
        )
    )]
    async fn mkdir(
        &self,
        Parameters(args): Parameters<MkdirArgs>,
    ) -> Result<CallToolResult, McpError> {
        let host_name = self.resolve_host(args.host)?;
        if let Err(e) = self
            .guards()
            .for_host(&host_name)
            .check_sftp_write(&args.path)
        {
            self.audit.write(
                &host_name,
                "mkdir",
                Some(&args.path),
                None,
                None,
                None,
                None,
                Some(&e.to_string()),
                Some(e.to_string()),
            );
            return Err(e.into_mcp());
        }
        let session = self
            .pool
            .get_or_connect(&host_name, None)
            .await
            .map_err(|e| e.into_mcp())?;
        self.guard_resolved(&host_name, "mkdir", &session, &args.path, true)
            .await?;
        sftp::mkdir(&session, &args.path, args.parents.unwrap_or(false))
            .await
            .map_err(|e| e.into_mcp())?;
        self.audit.write(
            &host_name,
            "mkdir",
            Some(&args.path),
            None,
            None,
            None,
            None,
            None,
            None,
        );
        let mut t = Toon::new();
        t.field("host", &host_name)
            .field("path", &args.path)
            .field("status", "created");
        Ok(text(t.into_string()))
    }

    #[tool(
        description = "SFTP remove file. recursive=true for directories. Refuses sensitive system paths. Not for symlink targets — use exec.",
        annotations(
            title = "Rm",
            read_only_hint = false,
            destructive_hint = true,
            idempotent_hint = false,
            open_world_hint = true
        )
    )]
    async fn rm(
        &self,
        Parameters(args): Parameters<RmArgs>,
        ctx: RequestContext<RoleServer>,
    ) -> Result<CallToolResult, McpError> {
        let host_name = self.resolve_host(args.host)?;
        if let Err(e) = self
            .guards()
            .for_host(&host_name)
            .check_sftp_write(&args.path)
        {
            self.audit.write(
                &host_name,
                "rm",
                Some(&args.path),
                None,
                None,
                None,
                None,
                Some(&e.to_string()),
                Some(e.to_string()),
            );
            return Err(e.into_mcp());
        }
        let recursive = args.recursive.unwrap_or(false);
        if recursive {
            // Recursive delete is one of the highest-blast-radius operations
            // this server exposes; always elicit before proceeding.
            let prompt = format!(
                "fast-mcp-ssh wants to recursively delete '{}' on host '{host_name}'. Reply 'yes' to proceed.",
                args.path
            );
            match elicit_confirmation(&ctx, &prompt).await {
                Ok(true) => {}
                Ok(false) => return Err(SshError::ConfirmationDenied.into_mcp()),
                Err(e) => {
                    tracing::warn!(?e, "rm recursive elicit failed; deny");
                    return Err(SshError::ConfirmationDenied.into_mcp());
                }
            }
        }
        let session = self
            .pool
            .get_or_connect(&host_name, None)
            .await
            .map_err(|e| e.into_mcp())?;
        self.guard_resolved(&host_name, "rm", &session, &args.path, true)
            .await?;
        let removed = sftp::remove(&session, &args.path, recursive)
            .await
            .map_err(|e| e.into_mcp())?;
        self.audit.write(
            &host_name,
            "rm",
            Some(&args.path),
            None,
            None,
            None,
            None,
            None,
            None,
        );
        let mut t = Toon::new();
        t.field("host", &host_name)
            .field("path", &args.path)
            .field("removed", removed);
        Ok(text(t.into_string()))
    }

    #[tool(
        description = "SFTP stat path. Returns kind/size/mode/mtime/uid/gid. Use to check existence + metadata. Not for content — use dn.",
        annotations(
            title = "Stat",
            read_only_hint = true,
            destructive_hint = false,
            idempotent_hint = true,
            open_world_hint = true
        )
    )]
    async fn stat(
        &self,
        Parameters(args): Parameters<StatArgs>,
    ) -> Result<CallToolResult, McpError> {
        let host_name = self.resolve_host(args.host)?;
        if let Err(e) = self
            .guards()
            .for_host(&host_name)
            .check_sftp_read(&args.path)
        {
            self.audit.write(
                &host_name,
                "stat",
                Some(&args.path),
                None,
                None,
                None,
                None,
                Some(&e.to_string()),
                Some(e.to_string()),
            );
            return Err(e.into_mcp());
        }
        let session = self
            .pool
            .get_or_connect(&host_name, None)
            .await
            .map_err(|e| e.into_mcp())?;
        self.guard_resolved(&host_name, "stat", &session, &args.path, false)
            .await?;
        let s = sftp::stat(&session, &args.path)
            .await
            .map_err(|e| e.into_mcp())?;
        self.audit.write(
            &host_name,
            "stat",
            Some(&args.path),
            None,
            None,
            None,
            None,
            None,
            None,
        );
        let mut t = Toon::new();
        t.field("host", &host_name)
            .field("path", &args.path)
            .field("kind", s.kind)
            .field("size", s.size)
            .field("mode", format!("{:o}", s.mode & 0o7777))
            .field("mtime", s.mtime)
            .field("uid", s.uid as u64)
            .field("gid", s.gid as u64);
        if let Some(link_target) = &s.target {
            t.field("target", link_target);
        }
        Ok(text(t.into_string()))
    }

    #[tool(
        description = "Read end of file (last N lines) or run `timeout N tail -F` and return the buffered output at the end. Note: MCP returns one response per call, so follow output is delivered after `seconds` elapses, not streamed.",
        annotations(
            title = "Tail",
            read_only_hint = true,
            destructive_hint = false,
            idempotent_hint = true,
            open_world_hint = true
        )
    )]
    async fn tail(
        &self,
        Parameters(args): Parameters<TailArgs>,
    ) -> Result<CallToolResult, McpError> {
        let host_name = self.resolve_host(args.host)?;
        let session = self
            .pool
            .get_or_connect(&host_name, None)
            .await
            .map_err(|e| e.into_mcp())?;
        let lines = args.lines.unwrap_or(100);
        let follow = args.follow.unwrap_or(false);
        let secs = Duration::from_secs(args.seconds.unwrap_or(5).clamp(1, MAX_FOLLOW_SECS));
        let max_capture = self.cfg().defaults.max_capture_bytes;
        let chunk = tail::tail(&session, &args.path, lines, follow, secs, max_capture)
            .await
            .map_err(|e| e.into_mcp())?;
        self.audit.write(
            &host_name,
            "tail",
            Some(&args.path),
            Some(chunk.exit_code),
            None,
            None,
            Some(chunk.bytes),
            None,
            None,
        );
        let mut t = Toon::new();
        t.field("host", &host_name)
            .field("path", &args.path)
            .field("bytes", chunk.bytes)
            .field("follow", follow);
        let (display, total) =
            truncate_with_hint(&chunk.content, self.cfg().defaults.truncate_bytes);
        if let Some(n) = total {
            t.field("truncated_bytes", n);
        }
        t.block("content", &display);
        Ok(text(t.into_string()))
    }
}