ssh-mcp-rs 4.0.0

MCP server exposing SSH control for Linux systems via Model Context Protocol
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
use crate::validate::validate_basic_path_str;

const BEGIN_PATCH: &str = "*** Begin Patch";
const END_PATCH: &str = "*** End Patch";
const ADD_FILE: &str = "*** Add File: ";
const UPDATE_FILE: &str = "*** Update File: ";
const DELETE_FILE: &str = "*** Delete File: ";

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum PatchOperationKind {
    Add,
    Update,
    Delete,
}

impl PatchOperationKind {
    pub(crate) const fn as_str(self) -> &'static str {
        match self {
            Self::Add => "add",
            Self::Update => "update",
            Self::Delete => "delete",
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct FilePatch {
    path: String,
    operation: PatchOperation,
}

#[derive(Debug, Clone, PartialEq, Eq)]
enum PatchOperation {
    Add { content: String },
    Update { hunks: Vec<PatchHunk> },
    Delete,
}

#[derive(Debug, Clone, PartialEq, Eq)]
struct PatchHunk {
    anchor: Option<String>,
    old_lines: Vec<String>,
    new_lines: Vec<String>,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct PlannedPatch {
    pub(crate) path: String,
    pub(crate) operation: PatchOperationKind,
    pub(crate) new_content: Option<String>,
    pub(crate) changed: bool,
}

#[derive(Debug, thiserror::Error, PartialEq, Eq)]
pub(crate) enum PatchError {
    #[error("invalid patch envelope: {0}")]
    InvalidEnvelope(String),
    #[error("invalid patch section: {0}")]
    InvalidSection(String),
    #[error("patch must contain exactly one file section")]
    MultipleFiles,
    #[error("unsupported patch operation: {0}")]
    UnsupportedOperation(String),
    #[error("invalid patch path: {0}")]
    InvalidPath(String),
    #[error("invalid update hunk: {0}")]
    InvalidHunk(String),
    #[error("file already exists: {0}")]
    AlreadyExists(String),
    #[error("file does not exist: {0}")]
    NotFound(String),
    #[error("update hunk {hunk} context was not found")]
    ContextNotFound { hunk: usize },
    #[error("update hunk {hunk} context is ambiguous")]
    AmbiguousContext { hunk: usize },
}

impl PatchError {
    pub(crate) const fn kind(&self) -> &'static str {
        match self {
            Self::InvalidEnvelope(_) | Self::InvalidSection(_) | Self::InvalidHunk(_) => {
                "invalid_patch"
            }
            Self::MultipleFiles => "multiple_files",
            Self::UnsupportedOperation(_) => "unsupported_operation",
            Self::InvalidPath(_) => "invalid_path",
            Self::AlreadyExists(_) => "already_exists",
            Self::NotFound(_) => "not_found",
            Self::ContextNotFound { .. } => "context_not_found",
            Self::AmbiguousContext { .. } => "ambiguous_context",
        }
    }
}

impl FilePatch {
    pub(crate) fn parse(input: &str) -> Result<Self, PatchError> {
        let input = input.strip_suffix('\n').unwrap_or(input);
        let lines: Vec<&str> = input.split('\n').collect();

        if lines.first() != Some(&BEGIN_PATCH) {
            return Err(PatchError::InvalidEnvelope(format!(
                "first line must be {BEGIN_PATCH:?}"
            )));
        }
        if lines.last() != Some(&END_PATCH) {
            return Err(PatchError::InvalidEnvelope(format!(
                "last line must be {END_PATCH:?}"
            )));
        }
        if lines.len() < 3 {
            return Err(PatchError::InvalidEnvelope(
                "a file section is required".to_owned(),
            ));
        }

        let section = &lines[1..lines.len() - 1];
        let header = section[0];
        let body = &section[1..];

        let (path, operation) = if let Some(path) = header.strip_prefix(ADD_FILE) {
            let content = parse_add(body)?;
            (path, PatchOperation::Add { content })
        } else if let Some(path) = header.strip_prefix(UPDATE_FILE) {
            let hunks = parse_update(body)?;
            (path, PatchOperation::Update { hunks })
        } else if let Some(path) = header.strip_prefix(DELETE_FILE) {
            if let Some(extra) = body.first() {
                return Err(section_tail_error(extra));
            }
            (path, PatchOperation::Delete)
        } else if header.starts_with("*** Move to:") {
            return Err(PatchError::UnsupportedOperation("Move File".to_owned()));
        } else {
            return Err(PatchError::InvalidSection(header.to_owned()));
        };

        validate_path(path)?;

        Ok(Self {
            path: path.to_owned(),
            operation,
        })
    }

    pub(crate) fn path(&self) -> &str {
        &self.path
    }

    pub(crate) fn operation(&self) -> PatchOperationKind {
        match self.operation {
            PatchOperation::Add { .. } => PatchOperationKind::Add,
            PatchOperation::Update { .. } => PatchOperationKind::Update,
            PatchOperation::Delete => PatchOperationKind::Delete,
        }
    }

    pub(crate) fn plan(&self, current: Option<&str>) -> Result<PlannedPatch, PatchError> {
        let (new_content, changed) = match (&self.operation, current) {
            (PatchOperation::Add { .. }, Some(_)) => {
                return Err(PatchError::AlreadyExists(self.path.clone()));
            }
            (PatchOperation::Add { content }, None) => (Some(content.clone()), true),
            (PatchOperation::Update { .. }, None) | (PatchOperation::Delete, None) => {
                return Err(PatchError::NotFound(self.path.clone()));
            }
            (PatchOperation::Update { hunks }, Some(content)) => {
                let updated = apply_hunks(content, hunks)?;
                let changed = updated != content;
                (Some(updated), changed)
            }
            (PatchOperation::Delete, Some(_)) => (None, true),
        };

        Ok(PlannedPatch {
            path: self.path.clone(),
            operation: self.operation(),
            new_content,
            changed,
        })
    }
}

fn parse_add(lines: &[&str]) -> Result<String, PatchError> {
    let mut content_lines = Vec::with_capacity(lines.len());
    for line in lines {
        let Some(content) = line.strip_prefix('+') else {
            return Err(section_tail_error(line));
        };
        content_lines.push(content);
    }

    if content_lines.is_empty() {
        return Ok(String::new());
    }

    let mut content = content_lines.join("\n");
    content.push('\n');
    Ok(content)
}

fn parse_update(lines: &[&str]) -> Result<Vec<PatchHunk>, PatchError> {
    if lines.is_empty() {
        return Err(PatchError::InvalidHunk(
            "at least one hunk is required".to_owned(),
        ));
    }

    let mut hunks = Vec::new();
    let mut index = 0;
    while index < lines.len() {
        let marker = lines[index];
        if marker.starts_with("*** ") {
            return Err(section_tail_error(marker));
        }
        let anchor = if marker == "@@" {
            None
        } else if let Some(anchor) = marker.strip_prefix("@@ ") {
            if anchor.is_empty() {
                return Err(PatchError::InvalidHunk(
                    "hunk anchor cannot be empty".to_owned(),
                ));
            }
            Some(anchor.to_owned())
        } else {
            return Err(PatchError::InvalidHunk(format!(
                "expected @@ marker, got {marker:?}"
            )));
        };
        index += 1;

        let mut old_lines = Vec::new();
        let mut new_lines = Vec::new();
        let mut has_change = false;
        while index < lines.len() && !lines[index].starts_with("@@") {
            let line = lines[index];
            if line.starts_with("*** ") {
                return Err(section_tail_error(line));
            }
            let Some(prefix) = line.chars().next() else {
                return Err(PatchError::InvalidHunk(
                    "every hunk line needs a space, +, or - prefix".to_owned(),
                ));
            };
            let text = &line[prefix.len_utf8()..];
            match prefix {
                ' ' => {
                    old_lines.push(text.to_owned());
                    new_lines.push(text.to_owned());
                }
                '-' => {
                    old_lines.push(text.to_owned());
                    has_change = true;
                }
                '+' => {
                    new_lines.push(text.to_owned());
                    has_change = true;
                }
                _ => {
                    return Err(PatchError::InvalidHunk(format!(
                        "invalid hunk line prefix {prefix:?}"
                    )));
                }
            }
            index += 1;
        }

        if old_lines.is_empty() {
            return Err(PatchError::InvalidHunk(
                "a hunk must include context or a removed line".to_owned(),
            ));
        }
        if !has_change {
            return Err(PatchError::InvalidHunk(
                "a hunk must contain a + or - line".to_owned(),
            ));
        }
        hunks.push(PatchHunk {
            anchor,
            old_lines,
            new_lines,
        });
    }

    Ok(hunks)
}

fn apply_hunks(content: &str, hunks: &[PatchHunk]) -> Result<String, PatchError> {
    let had_final_newline = content.ends_with('\n');
    let body = content.strip_suffix('\n').unwrap_or(content);
    let mut lines: Vec<String> = if content.is_empty() {
        Vec::new()
    } else {
        body.split('\n').map(str::to_owned).collect()
    };

    for (index, hunk) in hunks.iter().enumerate() {
        let old_len = hunk.old_lines.len();
        let mut candidates = Vec::new();
        if old_len <= lines.len() {
            for start in 0..=lines.len() - old_len {
                if lines[start..start + old_len] != hunk.old_lines {
                    continue;
                }
                if let Some(anchor) = &hunk.anchor
                    && !lines[..start + old_len]
                        .iter()
                        .any(|line| line.contains(anchor))
                {
                    continue;
                }
                candidates.push(start);
            }
        }

        let start = match candidates.as_slice() {
            [] => return Err(PatchError::ContextNotFound { hunk: index + 1 }),
            [start] => *start,
            _ => return Err(PatchError::AmbiguousContext { hunk: index + 1 }),
        };
        lines.splice(start..start + old_len, hunk.new_lines.iter().cloned());
    }

    let mut result = lines.join("\n");
    if had_final_newline && !lines.is_empty() {
        result.push('\n');
    }
    Ok(result)
}

fn validate_path(path: &str) -> Result<(), PatchError> {
    validate_basic_path_str(path, "patch path").map_err(PatchError::InvalidPath)?;
    if !path.starts_with('/') {
        return Err(PatchError::InvalidPath(
            "patch path must be absolute".to_owned(),
        ));
    }
    if path.ends_with('/') {
        return Err(PatchError::InvalidPath(
            "patch path must identify a file".to_owned(),
        ));
    }
    Ok(())
}

fn section_tail_error(line: &str) -> PatchError {
    if line.starts_with(ADD_FILE) || line.starts_with(UPDATE_FILE) || line.starts_with(DELETE_FILE)
    {
        PatchError::MultipleFiles
    } else if line.starts_with("*** Move to:") {
        PatchError::UnsupportedOperation("Move File".to_owned())
    } else {
        PatchError::InvalidSection(line.to_owned())
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn parses_and_plans_add_and_delete() {
        let add = FilePatch::parse(
            "*** Begin Patch\n*** Add File: /tmp/new.txt\n+first\n+second\n*** End Patch",
        )
        .unwrap();
        let add_plan = add.plan(None).unwrap();
        assert_eq!(add_plan.operation, PatchOperationKind::Add);
        assert_eq!(add_plan.new_content.as_deref(), Some("first\nsecond\n"));
        assert_eq!(
            add.plan(Some("occupied")).unwrap_err().kind(),
            "already_exists"
        );

        let delete =
            FilePatch::parse("*** Begin Patch\n*** Delete File: /tmp/old.txt\n*** End Patch")
                .unwrap();
        let delete_plan = delete.plan(Some("old\n")).unwrap();
        assert_eq!(delete_plan.operation, PatchOperationKind::Delete);
        assert_eq!(delete_plan.new_content, None);
    }

    #[test]
    fn applies_multiple_update_hunks_exactly() {
        let patch = FilePatch::parse(
            "*** Begin Patch\n*** Update File: /tmp/app.conf\n@@ server\n server\n-port=80\n+port=8080\n@@\n-enabled=false\n+enabled=true\n*** End Patch",
        )
        .unwrap();
        let plan = patch
            .plan(Some("server\nport=80\nenabled=false\n"))
            .unwrap();
        assert_eq!(plan.operation, PatchOperationKind::Update);
        assert_eq!(
            plan.new_content.as_deref(),
            Some("server\nport=8080\nenabled=true\n")
        );
    }

    #[test]
    fn rejects_invalid_or_multiple_sections() {
        let relative =
            FilePatch::parse("*** Begin Patch\n*** Add File: relative.txt\n+x\n*** End Patch")
                .unwrap_err();
        assert_eq!(relative.kind(), "invalid_path");

        let multiple = FilePatch::parse(
            "*** Begin Patch\n*** Add File: /tmp/a\n+x\n*** Delete File: /tmp/b\n*** End Patch",
        )
        .unwrap_err();
        assert_eq!(multiple, PatchError::MultipleFiles);

        let move_file =
            FilePatch::parse("*** Begin Patch\n*** Move to: /tmp/b\n*** End Patch").unwrap_err();
        assert_eq!(move_file.kind(), "unsupported_operation");
    }

    #[test]
    fn rejects_missing_and_ambiguous_update_context() {
        let patch = FilePatch::parse(
            "*** Begin Patch\n*** Update File: /tmp/a\n@@\n-value=old\n+value=new\n*** End Patch",
        )
        .unwrap();
        assert_eq!(
            patch.plan(Some("other=value\n")).unwrap_err(),
            PatchError::ContextNotFound { hunk: 1 }
        );
        assert_eq!(
            patch.plan(Some("value=old\nvalue=old\n")).unwrap_err(),
            PatchError::AmbiguousContext { hunk: 1 }
        );
    }
}