mcp-execution-files 0.7.0

Virtual filesystem for MCP code generation and organization
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
//! Core types for the virtual filesystem.
//!
//! This module defines strong types for VFS paths, files, and errors,
//! following Microsoft Rust Guidelines for type safety and error handling.
//!
//! # Examples
//!
//! ```
//! use mcp_execution_files::{FilePath, FileEntry};
//!
//! let path = FilePath::new("/mcp-tools/servers/github/manifest.json").unwrap();
//! let file = FileEntry::new("{}");
//!
//! assert_eq!(path.as_str(), "/mcp-tools/servers/github/manifest.json");
//! assert_eq!(file.content(), "{}");
//! ```

use std::fmt;
use std::path::Path;
use thiserror::Error;

/// Errors that can occur during VFS operations.
///
/// All error variants include contextual information and implement
/// `is_xxx()` methods for easy error classification.
///
/// # Examples
///
/// ```
/// use mcp_execution_files::FilesError;
///
/// let error = FilesError::FileNotFound {
///     path: "/missing.txt".to_string(),
/// };
///
/// assert!(error.is_not_found());
/// ```
#[derive(Error, Debug)]
pub enum FilesError {
    /// File or directory not found at the specified path
    #[error("File not found: {path}")]
    FileNotFound {
        /// The path that was not found
        path: String,
    },

    /// Path exists but is not a directory
    #[error("Not a directory: {path}")]
    NotADirectory {
        /// The path that is not a directory
        path: String,
    },

    /// Path is invalid or malformed
    #[error("Invalid path: {path}")]
    InvalidPath {
        /// The invalid path
        path: String,
    },

    /// Path is not absolute (must start with '/')
    #[error("Path must be absolute: {path}")]
    PathNotAbsolute {
        /// The relative path
        path: String,
    },

    /// Path contains invalid components (e.g., '..')
    #[error("Path contains invalid components: {path}")]
    InvalidPathComponent {
        /// The path with invalid components
        path: String,
    },

    /// I/O operation failed during filesystem export
    #[error("I/O error at {path}: {source}")]
    IoError {
        /// The path where the I/O error occurred
        path: String,
        /// The underlying I/O error
        source: std::io::Error,
    },
}

impl FilesError {
    /// Returns `true` if this is a file not found error.
    ///
    /// # Examples
    ///
    /// ```
    /// use mcp_execution_files::FilesError;
    ///
    /// let error = FilesError::FileNotFound {
    ///     path: "/test.txt".to_string(),
    /// };
    ///
    /// assert!(error.is_not_found());
    /// ```
    #[must_use]
    pub const fn is_not_found(&self) -> bool {
        matches!(self, Self::FileNotFound { .. })
    }

    /// Returns `true` if this is a not-a-directory error.
    ///
    /// # Examples
    ///
    /// ```
    /// use mcp_execution_files::FilesError;
    ///
    /// let error = FilesError::NotADirectory {
    ///     path: "/file.txt".to_string(),
    /// };
    ///
    /// assert!(error.is_not_directory());
    /// ```
    #[must_use]
    pub const fn is_not_directory(&self) -> bool {
        matches!(self, Self::NotADirectory { .. })
    }

    /// Returns `true` if this is an invalid path error.
    ///
    /// # Examples
    ///
    /// ```
    /// use mcp_execution_files::FilesError;
    ///
    /// let error = FilesError::InvalidPath {
    ///     path: "".to_string(),
    /// };
    ///
    /// assert!(error.is_invalid_path());
    /// ```
    #[must_use]
    pub const fn is_invalid_path(&self) -> bool {
        matches!(
            self,
            Self::InvalidPath { .. }
                | Self::PathNotAbsolute { .. }
                | Self::InvalidPathComponent { .. }
        )
    }

    /// Returns `true` if this is an I/O error.
    ///
    /// # Examples
    ///
    /// ```
    /// use mcp_execution_files::FilesError;
    /// use std::io;
    ///
    /// let error = FilesError::IoError {
    ///     path: "/test.ts".to_string(),
    ///     source: io::Error::from(io::ErrorKind::PermissionDenied),
    /// };
    ///
    /// assert!(error.is_io_error());
    /// ```
    #[must_use]
    pub const fn is_io_error(&self) -> bool {
        matches!(self, Self::IoError { .. })
    }
}

/// A validated virtual filesystem path.
///
/// `FilePath` ensures paths use Unix-style conventions on all platforms:
/// - Must start with '/' (absolute paths only)
/// - Free of parent directory references ('..')
/// - Use forward slashes as separators
///
/// This is intentional: VFS paths are platform-independent and always use
/// Unix conventions, even on Windows. This enables consistent path handling
/// across development machines and CI environments.
///
/// # Examples
///
/// ```
/// use mcp_execution_files::FilePath;
///
/// let path = FilePath::new("/mcp-tools/servers/test/file.ts").unwrap();
/// assert_eq!(path.as_str(), "/mcp-tools/servers/test/file.ts");
/// ```
///
/// ```
/// use mcp_execution_files::FilePath;
///
/// // Invalid paths are rejected
/// assert!(FilePath::new("relative/path").is_err());
/// assert!(FilePath::new("/parent/../escape").is_err());
/// ```
///
/// On Windows, Unix-style paths like "/mcp-tools/servers/test" are accepted
/// (not Windows paths like "C:\mcp-tools\servers\test").
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct FilePath(String);

impl FilePath {
    /// Creates a new `FilePath` from a path-like type.
    ///
    /// The path must be absolute (start with '/') and must not contain parent
    /// directory references ('..').
    ///
    /// `FilePath` uses Unix-style path conventions on all platforms, ensuring
    /// consistent behavior on Linux, macOS, and Windows. Paths are validated
    /// using string-based checks rather than platform-specific `Path::is_absolute()`,
    /// which enables cross-platform compatibility.
    ///
    /// # Errors
    ///
    /// Returns `FilesError::PathNotAbsolute` if the path does not start with '/'.
    /// Returns `FilesError::InvalidPathComponent` if the path contains '..'.
    /// Returns `FilesError::InvalidPath` if the path is empty or not UTF-8 valid.
    ///
    /// # Examples
    ///
    /// ```
    /// use mcp_execution_files::FilePath;
    ///
    /// let path = FilePath::new("/mcp-tools/test.ts")?;
    /// assert_eq!(path.as_str(), "/mcp-tools/test.ts");
    ///
    /// // Works on all platforms (Unix-style paths)
    /// let path = FilePath::new("/mcp-tools/servers/test/manifest.json")?;
    /// # Ok::<(), mcp_execution_files::FilesError>(())
    /// ```
    pub fn new(path: impl AsRef<Path>) -> Result<Self> {
        let path = path.as_ref();

        // Convert to string for platform-independent validation
        let path_str = path.to_str().ok_or_else(|| FilesError::InvalidPath {
            path: path.display().to_string(),
        })?;

        // Normalize path separators to Unix-style (forward slashes) on all platforms
        // This ensures VFS paths are consistent regardless of the host OS
        let normalized_str = if cfg!(target_os = "windows") {
            // Replace Windows backslashes with forward slashes
            path_str.replace(std::path::MAIN_SEPARATOR, "/")
        } else {
            path_str.to_string()
        };

        // Check if empty
        if normalized_str.is_empty() {
            return Err(FilesError::InvalidPath {
                path: String::new(),
            });
        }

        // Check if absolute using Unix-style path rules (starts with '/')
        // VFS uses Unix-style paths on all platforms
        if !normalized_str.starts_with('/') {
            return Err(FilesError::PathNotAbsolute {
                path: normalized_str,
            });
        }

        // Check for '..' components in the path string
        if normalized_str.contains("..") {
            return Err(FilesError::InvalidPathComponent {
                path: normalized_str,
            });
        }

        // Store as String with normalized Unix-style separators
        Ok(Self(normalized_str))
    }

    /// Returns the path as a `Path` reference.
    ///
    /// # Examples
    ///
    /// ```
    /// use mcp_execution_files::FilePath;
    ///
    /// let vfs_path = FilePath::new("/test.ts")?;
    /// let path = vfs_path.as_path();
    /// assert_eq!(path.to_str(), Some("/test.ts"));
    /// # Ok::<(), mcp_execution_files::FilesError>(())
    /// ```
    #[must_use]
    pub fn as_path(&self) -> &Path {
        Path::new(&self.0)
    }

    /// Returns the path as a string slice.
    ///
    /// # Examples
    ///
    /// ```
    /// use mcp_execution_files::FilePath;
    ///
    /// let path = FilePath::new("/mcp-tools/file.ts")?;
    /// assert_eq!(path.as_str(), "/mcp-tools/file.ts");
    /// # Ok::<(), mcp_execution_files::FilesError>(())
    /// ```
    #[must_use]
    pub fn as_str(&self) -> &str {
        &self.0
    }

    /// Returns the parent directory of this path.
    ///
    /// Returns `None` if this is the root path.
    ///
    /// # Examples
    ///
    /// ```
    /// use mcp_execution_files::FilePath;
    ///
    /// let path = FilePath::new("/mcp-tools/servers/test.ts")?;
    /// let parent = path.parent().unwrap();
    /// assert_eq!(parent.as_str(), "/mcp-tools/servers");
    /// # Ok::<(), mcp_execution_files::FilesError>(())
    /// ```
    #[must_use]
    pub fn parent(&self) -> Option<Self> {
        // Find the last '/' separator
        self.0.rfind('/').map(|pos| {
            if pos == 0 {
                // Parent of "/foo" is "/" (root)
                Self("/".to_string())
            } else {
                // Parent of "/foo/bar" is "/foo"
                Self(self.0[..pos].to_string())
            }
        })
    }

    /// Checks if this path is a directory path.
    ///
    /// A path is considered a directory if it does not have a file extension.
    ///
    /// # Examples
    ///
    /// ```
    /// use mcp_execution_files::FilePath;
    ///
    /// let dir = FilePath::new("/mcp-tools/servers")?;
    /// assert!(dir.is_dir_path());
    ///
    /// let file = FilePath::new("/mcp-tools/manifest.json")?;
    /// assert!(!file.is_dir_path());
    /// # Ok::<(), mcp_execution_files::FilesError>(())
    /// ```
    #[must_use]
    pub fn is_dir_path(&self) -> bool {
        // A path is a directory if it doesn't contain a '.' after the last '/'
        self.0
            .rfind('/')
            .is_some_and(|last_slash| !self.0[last_slash..].contains('.'))
    }
}

impl fmt::Display for FilePath {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.as_str())
    }
}

impl AsRef<Path> for FilePath {
    fn as_ref(&self) -> &Path {
        Path::new(&self.0)
    }
}

/// A file in the virtual filesystem.
///
/// Contains file content as a string and metadata.
///
/// # Examples
///
/// ```
/// use mcp_execution_files::FileEntry;
///
/// let file = FileEntry::new("console.log('hello');");
/// assert_eq!(file.content(), "console.log('hello');");
/// assert_eq!(file.size(), 21);
/// ```
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FileEntry {
    content: String,
}

impl FileEntry {
    /// Creates a new VFS file with the given content.
    ///
    /// # Examples
    ///
    /// ```
    /// use mcp_execution_files::FileEntry;
    ///
    /// let file = FileEntry::new("export const VERSION = '1.0';");
    /// assert_eq!(file.size(), 29);
    /// ```
    #[must_use]
    pub fn new(content: impl Into<String>) -> Self {
        Self {
            content: content.into(),
        }
    }

    /// Returns the file content as a string slice.
    ///
    /// # Examples
    ///
    /// ```
    /// use mcp_execution_files::FileEntry;
    ///
    /// let file = FileEntry::new("test content");
    /// assert_eq!(file.content(), "test content");
    /// ```
    #[must_use]
    pub fn content(&self) -> &str {
        &self.content
    }

    /// Returns the size of the file content in bytes.
    ///
    /// # Examples
    ///
    /// ```
    /// use mcp_execution_files::FileEntry;
    ///
    /// let file = FileEntry::new("hello");
    /// assert_eq!(file.size(), 5);
    /// ```
    #[must_use]
    pub const fn size(&self) -> usize {
        self.content.len()
    }
}

/// Type alias for VFS operation results.
///
/// # Examples
///
/// ```
/// use mcp_execution_files::{Result, FilePath};
///
/// fn validate_path(path: &str) -> Result<FilePath> {
///     FilePath::new(path)
/// }
/// ```
pub type Result<T> = std::result::Result<T, FilesError>;

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

    #[test]
    fn test_vfs_path_new_valid() {
        let path = FilePath::new("/mcp-tools/test.ts").unwrap();
        assert_eq!(path.as_str(), "/mcp-tools/test.ts");
    }

    #[test]
    fn test_vfs_path_new_relative_fails() {
        let result = FilePath::new("relative/path");
        assert!(result.is_err());
        assert!(result.unwrap_err().is_invalid_path());
    }

    #[test]
    fn test_vfs_path_new_parent_dir_fails() {
        let result = FilePath::new("/parent/../escape");
        assert!(result.is_err());
        assert!(result.unwrap_err().is_invalid_path());
    }

    #[test]
    fn test_vfs_path_new_empty_fails() {
        let result = FilePath::new("");
        assert!(result.is_err());
    }

    #[test]
    fn test_vfs_path_parent() {
        let path = FilePath::new("/mcp-tools/servers/test.ts").unwrap();
        let parent = path.parent().unwrap();
        assert_eq!(parent.as_str(), "/mcp-tools/servers");
    }

    #[test]
    fn test_vfs_path_parent_root() {
        let path = FilePath::new("/test").unwrap();
        let parent = path.parent();
        assert!(parent.is_some());
    }

    #[test]
    fn test_vfs_path_is_dir_path() {
        let dir = FilePath::new("/mcp-tools/servers").unwrap();
        assert!(dir.is_dir_path());

        let file = FilePath::new("/mcp-tools/test.ts").unwrap();
        assert!(!file.is_dir_path());
    }

    #[test]
    fn test_vfs_path_display() {
        let path = FilePath::new("/test.ts").unwrap();
        assert_eq!(format!("{path}"), "/test.ts");
    }

    #[test]
    fn test_vfs_file_new() {
        let file = FileEntry::new("test content");
        assert_eq!(file.content(), "test content");
        assert_eq!(file.size(), 12);
    }

    #[test]
    fn test_vfs_file_empty() {
        let file = FileEntry::new("");
        assert_eq!(file.content(), "");
        assert_eq!(file.size(), 0);
    }

    #[test]
    fn test_vfs_error_is_not_found() {
        let error = FilesError::FileNotFound {
            path: "/test".to_string(),
        };
        assert!(error.is_not_found());
        assert!(!error.is_not_directory());
        assert!(!error.is_invalid_path());
    }

    #[test]
    fn test_vfs_error_is_not_directory() {
        let error = FilesError::NotADirectory {
            path: "/file.txt".to_string(),
        };
        assert!(!error.is_not_found());
        assert!(error.is_not_directory());
        assert!(!error.is_invalid_path());
    }

    #[test]
    fn test_vfs_error_is_invalid_path() {
        let error = FilesError::InvalidPath {
            path: String::new(),
        };
        assert!(error.is_invalid_path());

        let error = FilesError::PathNotAbsolute {
            path: "relative".to_string(),
        };
        assert!(error.is_invalid_path());

        let error = FilesError::InvalidPathComponent {
            path: "../escape".to_string(),
        };
        assert!(error.is_invalid_path());
    }

    #[test]
    fn test_vfs_path_as_ref() {
        let vfs_path = FilePath::new("/test.ts").unwrap();
        let path: &Path = vfs_path.as_ref();
        assert_eq!(path.to_str(), Some("/test.ts"));
    }
}