1use std::path::{Path, PathBuf};
25
26use fastmcp_core::{McpContext, McpError, McpOutcome, McpResult, Outcome};
27use fastmcp_protocol::{Resource, ResourceContent, ResourceTemplate};
28
29use crate::handler::{BoxFuture, ResourceHandler, UriParams};
30
31const DEFAULT_MAX_SIZE: usize = 10 * 1024 * 1024;
33
34#[derive(Debug, Clone)]
36pub enum FilesystemProviderError {
37 PathTraversal { requested: String },
39 TooLarge { path: String, size: u64, max: usize },
41 SymlinkDenied { path: String },
43 SymlinkEscapesRoot { path: String },
45 Io { message: String },
47 NotFound { path: String },
49}
50
51impl std::fmt::Display for FilesystemProviderError {
52 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
53 match self {
54 Self::PathTraversal { requested } => {
55 write!(f, "Path traversal attempt blocked: {requested}")
56 }
57 Self::TooLarge { path, size, max } => {
58 write!(f, "File too large: {path} ({size} bytes, max {max} bytes)")
59 }
60 Self::SymlinkDenied { path } => {
61 write!(f, "Symlink access denied: {path}")
62 }
63 Self::SymlinkEscapesRoot { path } => {
64 write!(f, "Symlink target escapes root directory: {path}")
65 }
66 Self::Io { message } => write!(f, "IO error: {message}"),
67 Self::NotFound { path } => write!(f, "File not found: {path}"),
68 }
69 }
70}
71
72impl std::error::Error for FilesystemProviderError {}
73
74impl From<FilesystemProviderError> for McpError {
75 fn from(err: FilesystemProviderError) -> Self {
76 match err {
77 FilesystemProviderError::PathTraversal { .. } => {
78 McpError::invalid_request(err.to_string())
80 }
81 FilesystemProviderError::TooLarge { .. } => McpError::invalid_request(err.to_string()),
82 FilesystemProviderError::SymlinkDenied { .. }
83 | FilesystemProviderError::SymlinkEscapesRoot { .. } => {
84 McpError::invalid_request(err.to_string())
86 }
87 FilesystemProviderError::Io { .. } => McpError::internal_error(err.to_string()),
88 FilesystemProviderError::NotFound { path } => McpError::resource_not_found(&path),
89 }
90 }
91}
92
93#[derive(Debug, Clone)]
116pub struct FilesystemProvider {
117 root: PathBuf,
119 prefix: Option<String>,
121 include_patterns: Vec<String>,
123 exclude_patterns: Vec<String>,
125 recursive: bool,
127 max_file_size: usize,
129 follow_symlinks: bool,
131 description: Option<String>,
133}
134
135impl FilesystemProvider {
136 #[must_use]
148 pub fn new(root: impl AsRef<Path>) -> Self {
149 Self {
150 root: root.as_ref().to_path_buf(),
151 prefix: None,
152 include_patterns: Vec::new(),
153 exclude_patterns: vec![".*".to_string()], recursive: false,
155 max_file_size: DEFAULT_MAX_SIZE,
156 follow_symlinks: false,
157 description: None,
158 }
159 }
160
161 #[must_use]
173 pub fn with_prefix(mut self, prefix: impl Into<String>) -> Self {
174 self.prefix = Some(prefix.into());
175 self
176 }
177
178 #[must_use]
190 pub fn with_patterns(mut self, patterns: &[&str]) -> Self {
191 self.include_patterns = patterns.iter().map(|s| (*s).to_string()).collect();
192 self
193 }
194
195 #[must_use]
207 pub fn with_exclude(mut self, patterns: &[&str]) -> Self {
208 self.exclude_patterns = patterns.iter().map(|s| (*s).to_string()).collect();
209 self
210 }
211
212 #[must_use]
223 pub fn with_recursive(mut self, enabled: bool) -> Self {
224 self.recursive = enabled;
225 self
226 }
227
228 #[must_use]
240 pub fn with_max_size(mut self, bytes: usize) -> Self {
241 self.max_file_size = bytes;
242 self
243 }
244
245 #[must_use]
257 pub fn with_follow_symlinks(mut self, enabled: bool) -> Self {
258 self.follow_symlinks = enabled;
259 self
260 }
261
262 #[must_use]
271 pub fn with_description(mut self, description: impl Into<String>) -> Self {
272 self.description = Some(description.into());
273 self
274 }
275
276 #[must_use]
291 pub fn build(self) -> FilesystemResourceHandler {
292 FilesystemResourceHandler::new(self)
293 }
294
295 fn validate_path(&self, requested: &str) -> Result<PathBuf, FilesystemProviderError> {
302 let requested_path = Path::new(requested);
303
304 if requested_path.is_absolute() {
306 return Err(FilesystemProviderError::PathTraversal {
307 requested: requested.to_string(),
308 });
309 }
310
311 let full_path = self.root.join(requested_path);
313
314 let canonical = full_path.canonicalize().map_err(|e| {
317 if e.kind() == std::io::ErrorKind::NotFound {
318 FilesystemProviderError::NotFound {
319 path: requested.to_string(),
320 }
321 } else {
322 FilesystemProviderError::Io {
323 message: e.to_string(),
324 }
325 }
326 })?;
327
328 let canonical_root = self
330 .root
331 .canonicalize()
332 .map_err(|e| FilesystemProviderError::Io {
333 message: format!("Cannot canonicalize root: {e}"),
334 })?;
335
336 if !canonical.starts_with(&canonical_root) {
338 return Err(FilesystemProviderError::PathTraversal {
339 requested: requested.to_string(),
340 });
341 }
342
343 if full_path.is_symlink() {
345 self.check_symlink(&full_path, &canonical_root)?;
346 }
347
348 Ok(canonical)
349 }
350
351 fn check_symlink(
353 &self,
354 path: &Path,
355 canonical_root: &Path,
356 ) -> Result<(), FilesystemProviderError> {
357 if !self.follow_symlinks {
358 return Err(FilesystemProviderError::SymlinkDenied {
359 path: path.display().to_string(),
360 });
361 }
362
363 let target = std::fs::read_link(path).map_err(|e| FilesystemProviderError::Io {
365 message: e.to_string(),
366 })?;
367
368 let resolved = if target.is_absolute() {
369 target
370 } else {
371 path.parent().unwrap_or(Path::new("")).join(&target)
372 };
373
374 let canonical_target =
375 resolved
376 .canonicalize()
377 .map_err(|e| FilesystemProviderError::Io {
378 message: e.to_string(),
379 })?;
380
381 if !canonical_target.starts_with(canonical_root) {
382 return Err(FilesystemProviderError::SymlinkEscapesRoot {
383 path: path.display().to_string(),
384 });
385 }
386
387 Ok(())
388 }
389
390 fn matches_patterns(&self, relative_path: &str) -> bool {
392 for pattern in &self.exclude_patterns {
394 if glob_match(pattern, relative_path) {
395 return false;
396 }
397 }
398
399 if self.include_patterns.is_empty() {
401 return true;
402 }
403
404 for pattern in &self.include_patterns {
406 if glob_match(pattern, relative_path) {
407 return true;
408 }
409 }
410
411 false
412 }
413
414 fn list_files(&self) -> Result<Vec<FileEntry>, FilesystemProviderError> {
416 let canonical_root = self
417 .root
418 .canonicalize()
419 .map_err(|e| FilesystemProviderError::Io {
420 message: format!("Cannot canonicalize root: {e}"),
421 })?;
422
423 let mut entries = Vec::new();
424 self.walk_directory(&canonical_root, &canonical_root, &mut entries)?;
425 Ok(entries)
426 }
427
428 fn walk_directory(
430 &self,
431 current: &Path,
432 root: &Path,
433 entries: &mut Vec<FileEntry>,
434 ) -> Result<(), FilesystemProviderError> {
435 let read_dir = std::fs::read_dir(current).map_err(|e| FilesystemProviderError::Io {
436 message: e.to_string(),
437 })?;
438
439 for entry_result in read_dir {
440 let entry = entry_result.map_err(|e| FilesystemProviderError::Io {
441 message: e.to_string(),
442 })?;
443
444 let path = entry.path();
445 let file_type = entry.file_type().map_err(|e| FilesystemProviderError::Io {
446 message: e.to_string(),
447 })?;
448
449 if file_type.is_symlink() && !self.follow_symlinks {
451 continue;
452 }
453
454 let relative = path
456 .strip_prefix(root)
457 .map_err(|e| FilesystemProviderError::Io {
458 message: e.to_string(),
459 })?;
460 let relative_str = relative.to_string_lossy().replace('\\', "/");
461
462 if file_type.is_dir() || (file_type.is_symlink() && path.is_dir()) {
463 if self.recursive {
464 self.walk_directory(&path, root, entries)?;
465 }
466 } else if file_type.is_file() || (file_type.is_symlink() && path.is_file()) {
467 if self.matches_patterns(&relative_str) {
469 let metadata = std::fs::metadata(&path).ok();
470 entries.push(FileEntry {
471 path: path.clone(),
472 relative_path: relative_str,
473 size: metadata.as_ref().map(|m| m.len()),
474 mime_type: detect_mime_type(&path),
475 });
476 }
477 }
478 }
479
480 Ok(())
481 }
482
483 fn file_uri(&self, relative_path: &str) -> String {
485 match &self.prefix {
486 Some(prefix) => format!("file://{prefix}/{relative_path}"),
487 None => format!("file://{relative_path}"),
488 }
489 }
490
491 fn uri_template(&self) -> String {
493 match &self.prefix {
494 Some(prefix) => format!("file://{prefix}/{{path}}"),
495 None => "file://{path}".to_string(),
496 }
497 }
498
499 fn path_from_uri(&self, uri: &str) -> Option<String> {
501 let expected_prefix = match &self.prefix {
502 Some(p) => format!("file://{p}/"),
503 None => "file://".to_string(),
504 };
505
506 if uri.starts_with(&expected_prefix) {
507 Some(uri[expected_prefix.len()..].to_string())
508 } else {
509 None
510 }
511 }
512
513 fn read_file(&self, relative_path: &str) -> Result<FileContent, FilesystemProviderError> {
515 let path = self.validate_path(relative_path)?;
517
518 let metadata = std::fs::metadata(&path).map_err(|e| {
520 if e.kind() == std::io::ErrorKind::NotFound {
521 FilesystemProviderError::NotFound {
522 path: relative_path.to_string(),
523 }
524 } else {
525 FilesystemProviderError::Io {
526 message: e.to_string(),
527 }
528 }
529 })?;
530
531 if metadata.len() > self.max_file_size as u64 {
532 return Err(FilesystemProviderError::TooLarge {
533 path: relative_path.to_string(),
534 size: metadata.len(),
535 max: self.max_file_size,
536 });
537 }
538
539 let mime_type = detect_mime_type(&path);
541
542 let content = if is_binary_mime_type(&mime_type) {
544 let bytes = std::fs::read(&path).map_err(|e| FilesystemProviderError::Io {
545 message: e.to_string(),
546 })?;
547 FileContent::Binary(bytes)
548 } else {
549 let text = std::fs::read_to_string(&path).map_err(|e| FilesystemProviderError::Io {
550 message: e.to_string(),
551 })?;
552 FileContent::Text(text)
553 };
554
555 Ok(content)
556 }
557}
558
559#[derive(Debug)]
561struct FileEntry {
562 #[allow(dead_code)]
563 path: PathBuf,
564 relative_path: String,
565 #[allow(dead_code)]
566 size: Option<u64>,
567 mime_type: String,
568}
569
570enum FileContent {
572 Text(String),
573 Binary(Vec<u8>),
574}
575
576pub struct FilesystemResourceHandler {
578 provider: FilesystemProvider,
579 cached_resources: Vec<Resource>,
581}
582
583impl FilesystemResourceHandler {
584 fn new(provider: FilesystemProvider) -> Self {
586 let cached_resources = match provider.list_files() {
588 Ok(entries) => entries
589 .into_iter()
590 .map(|entry| Resource {
591 uri: provider.file_uri(&entry.relative_path),
592 name: entry.relative_path.clone(),
593 description: None,
594 mime_type: Some(entry.mime_type),
595 icon: None,
596 version: None,
597 tags: vec![],
598 })
599 .collect(),
600 Err(_) => Vec::new(),
601 };
602
603 Self {
604 provider,
605 cached_resources,
606 }
607 }
608}
609
610impl ResourceHandler for FilesystemResourceHandler {
611 fn definition(&self) -> Resource {
612 Resource {
614 uri: self.provider.uri_template(),
615 name: self
616 .provider
617 .prefix
618 .clone()
619 .unwrap_or_else(|| "files".to_string()),
620 description: self.provider.description.clone(),
621 mime_type: None,
622 icon: None,
623 version: None,
624 tags: vec![],
625 }
626 }
627
628 fn template(&self) -> Option<ResourceTemplate> {
629 Some(ResourceTemplate {
630 uri_template: self.provider.uri_template(),
631 name: self
632 .provider
633 .prefix
634 .clone()
635 .unwrap_or_else(|| "files".to_string()),
636 description: self.provider.description.clone(),
637 mime_type: None,
638 icon: None,
639 version: None,
640 tags: vec![],
641 })
642 }
643
644 fn read(&self, _ctx: &McpContext) -> McpResult<Vec<ResourceContent>> {
645 let files = self.provider.list_files()?;
647
648 let listing = files
649 .iter()
650 .map(|f| format!("{}: {}", f.relative_path, f.mime_type))
651 .collect::<Vec<_>>()
652 .join("\n");
653
654 Ok(vec![ResourceContent {
655 uri: self.provider.uri_template(),
656 mime_type: Some("text/plain".to_string()),
657 text: Some(listing),
658 blob: None,
659 }])
660 }
661
662 fn read_with_uri(
663 &self,
664 _ctx: &McpContext,
665 uri: &str,
666 params: &UriParams,
667 ) -> McpResult<Vec<ResourceContent>> {
668 let relative_path = if let Some(path) = params.get("path") {
670 path.clone()
671 } else if let Some(path) = self.provider.path_from_uri(uri) {
672 path
673 } else {
674 return Err(McpError::invalid_params("Missing path parameter"));
675 };
676
677 let content = self.provider.read_file(&relative_path)?;
678
679 let resource_content = match content {
680 FileContent::Text(text) => ResourceContent {
681 uri: uri.to_string(),
682 mime_type: Some(detect_mime_type(Path::new(&relative_path))),
683 text: Some(text),
684 blob: None,
685 },
686 FileContent::Binary(bytes) => {
687 let base64_str = base64_encode(&bytes);
688
689 ResourceContent {
690 uri: uri.to_string(),
691 mime_type: Some(detect_mime_type(Path::new(&relative_path))),
692 text: None,
693 blob: Some(base64_str),
694 }
695 }
696 };
697
698 Ok(vec![resource_content])
699 }
700
701 fn read_async_with_uri<'a>(
702 &'a self,
703 ctx: &'a McpContext,
704 uri: &'a str,
705 params: &'a UriParams,
706 ) -> BoxFuture<'a, McpOutcome<Vec<ResourceContent>>> {
707 Box::pin(async move {
708 match self.read_with_uri(ctx, uri, params) {
709 Ok(v) => Outcome::Ok(v),
710 Err(e) => Outcome::Err(e),
711 }
712 })
713 }
714}
715
716impl std::fmt::Debug for FilesystemResourceHandler {
717 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
718 f.debug_struct("FilesystemResourceHandler")
719 .field("provider", &self.provider)
720 .field("cached_resources", &self.cached_resources.len())
721 .finish()
722 }
723}
724
725fn detect_mime_type(path: &Path) -> String {
727 let extension = path
728 .extension()
729 .and_then(|e| e.to_str())
730 .map(str::to_lowercase);
731
732 match extension.as_deref() {
733 Some("txt") => "text/plain",
735 Some("md" | "markdown") => "text/markdown",
736 Some("html" | "htm") => "text/html",
737 Some("css") => "text/css",
738 Some("csv") => "text/csv",
739 Some("xml") => "application/xml",
740
741 Some("rs") => "text/x-rust",
743 Some("py") => "text/x-python",
744 Some("js" | "mjs") => "text/javascript",
745 Some("ts" | "mts") => "text/typescript",
746 Some("json") => "application/json",
747 Some("yaml" | "yml") => "application/yaml",
748 Some("toml") => "application/toml",
749 Some("sh" | "bash") => "text/x-shellscript",
750 Some("c") => "text/x-c",
751 Some("cpp" | "cc" | "cxx") => "text/x-c++",
752 Some("h" | "hpp") => "text/x-c-header",
753 Some("java") => "text/x-java",
754 Some("go") => "text/x-go",
755 Some("rb") => "text/x-ruby",
756 Some("php") => "text/x-php",
757 Some("swift") => "text/x-swift",
758 Some("kt" | "kts") => "text/x-kotlin",
759 Some("sql") => "text/x-sql",
760
761 Some("png") => "image/png",
763 Some("jpg" | "jpeg") => "image/jpeg",
764 Some("gif") => "image/gif",
765 Some("svg") => "image/svg+xml",
766 Some("webp") => "image/webp",
767 Some("ico") => "image/x-icon",
768 Some("bmp") => "image/bmp",
769
770 Some("pdf") => "application/pdf",
772 Some("zip") => "application/zip",
773 Some("gz" | "gzip") => "application/gzip",
774 Some("tar") => "application/x-tar",
775 Some("wasm") => "application/wasm",
776 Some("exe") => "application/octet-stream",
777 Some("dll") => "application/octet-stream",
778 Some("so") => "application/octet-stream",
779 Some("bin") => "application/octet-stream",
780
781 _ => "application/octet-stream",
783 }
784 .to_string()
785}
786
787fn is_binary_mime_type(mime_type: &str) -> bool {
789 mime_type.starts_with("image/")
790 || mime_type.starts_with("audio/")
791 || mime_type.starts_with("video/")
792 || mime_type == "application/octet-stream"
793 || mime_type == "application/pdf"
794 || mime_type == "application/zip"
795 || mime_type == "application/gzip"
796 || mime_type == "application/x-tar"
797 || mime_type == "application/wasm"
798}
799
800const BASE64_CHARS: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
802
803fn base64_encode(data: &[u8]) -> String {
805 let mut result = String::with_capacity((data.len() + 2) / 3 * 4);
806
807 for chunk in data.chunks(3) {
808 let b0 = chunk[0] as usize;
809 let b1 = chunk.get(1).copied().unwrap_or(0) as usize;
810 let b2 = chunk.get(2).copied().unwrap_or(0) as usize;
811
812 let combined = (b0 << 16) | (b1 << 8) | b2;
813
814 result.push(BASE64_CHARS[(combined >> 18) & 0x3F] as char);
815 result.push(BASE64_CHARS[(combined >> 12) & 0x3F] as char);
816
817 if chunk.len() > 1 {
818 result.push(BASE64_CHARS[(combined >> 6) & 0x3F] as char);
819 } else {
820 result.push('=');
821 }
822
823 if chunk.len() > 2 {
824 result.push(BASE64_CHARS[combined & 0x3F] as char);
825 } else {
826 result.push('=');
827 }
828 }
829
830 result
831}
832
833fn glob_match(pattern: &str, path: &str) -> bool {
840 glob_match_recursive(pattern, path)
841}
842
843fn glob_match_recursive(pattern: &str, path: &str) -> bool {
845 let mut pattern_chars = pattern.chars().peekable();
846 let mut path_chars = path.chars().peekable();
847
848 while let Some(p) = pattern_chars.next() {
849 match p {
850 '*' => {
851 if pattern_chars.peek() == Some(&'*') {
853 pattern_chars.next(); if pattern_chars.peek() == Some(&'/') {
857 pattern_chars.next();
858 }
859
860 let remaining_pattern: String = pattern_chars.collect();
861
862 let remaining_path: String = path_chars.collect();
865
866 if glob_match_recursive(&remaining_pattern, &remaining_path) {
868 return true;
869 }
870
871 for i in 0..=remaining_path.len() {
873 if glob_match_recursive(&remaining_pattern, &remaining_path[i..]) {
874 return true;
875 }
876 }
877 return false;
878 }
879
880 let remaining_pattern: String = pattern_chars.collect();
882 let remaining_path: String = path_chars.collect();
883
884 for i in 0..=remaining_path.len() {
886 if remaining_path[..i].contains('/') {
888 break;
889 }
890 if glob_match_recursive(&remaining_pattern, &remaining_path[i..]) {
891 return true;
892 }
893 }
894 return false;
895 }
896 '?' => {
897 if path_chars.next().is_none() {
899 return false;
900 }
901 }
902 c => {
903 if path_chars.next() != Some(c) {
905 return false;
906 }
907 }
908 }
909 }
910
911 path_chars.next().is_none()
913}
914
915#[cfg(test)]
916mod tests {
917 use super::*;
918
919 #[test]
920 fn test_glob_match_star() {
921 assert!(glob_match("*.md", "readme.md"));
922 assert!(glob_match("*.md", "CHANGELOG.md"));
923 assert!(!glob_match("*.md", "readme.txt"));
924 assert!(!glob_match("*.md", "dir/readme.md")); }
926
927 #[test]
928 fn test_glob_match_double_star() {
929 assert!(glob_match("**/*.md", "readme.md"));
930 assert!(glob_match("**/*.md", "docs/readme.md"));
931 assert!(glob_match("**/*.md", "docs/api/readme.md"));
932 assert!(!glob_match("**/*.md", "readme.txt"));
933 }
934
935 #[test]
936 fn test_glob_match_question() {
937 assert!(glob_match("file?.txt", "file1.txt"));
938 assert!(glob_match("file?.txt", "fileA.txt"));
939 assert!(!glob_match("file?.txt", "file12.txt"));
940 }
941
942 #[test]
943 fn test_glob_match_hidden() {
944 assert!(glob_match(".*", ".hidden"));
945 assert!(glob_match(".*", ".gitignore"));
946 assert!(!glob_match(".*", "visible"));
947 }
948
949 #[test]
950 fn test_detect_mime_type() {
951 assert_eq!(detect_mime_type(Path::new("file.md")), "text/markdown");
952 assert_eq!(detect_mime_type(Path::new("file.json")), "application/json");
953 assert_eq!(detect_mime_type(Path::new("file.rs")), "text/x-rust");
954 assert_eq!(detect_mime_type(Path::new("file.png")), "image/png");
955 assert_eq!(
956 detect_mime_type(Path::new("file.unknown")),
957 "application/octet-stream"
958 );
959 }
960
961 #[test]
962 fn test_is_binary_mime_type() {
963 assert!(is_binary_mime_type("image/png"));
964 assert!(is_binary_mime_type("application/pdf"));
965 assert!(!is_binary_mime_type("text/plain"));
966 assert!(!is_binary_mime_type("application/json"));
967 }
968}