-
Notifications
You must be signed in to change notification settings - Fork 27
/
Copy pathmain.go
847 lines (765 loc) · 18.9 KB
/
main.go
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
package main
import (
"context"
"fmt"
"log"
"os"
"path/filepath"
"strings"
"time"
"github.com/mark3labs/mcp-go/mcp"
"github.com/mark3labs/mcp-go/server"
)
type FileInfo struct {
Size int64 `json:"size"`
Created time.Time `json:"created"`
Modified time.Time `json:"modified"`
Accessed time.Time `json:"accessed"`
IsDirectory bool `json:"isDirectory"`
IsFile bool `json:"isFile"`
Permissions string `json:"permissions"`
}
type FilesystemServer struct {
allowedDirs []string
server *server.MCPServer
}
func NewFilesystemServer(allowedDirs []string) (*FilesystemServer, error) {
// Normalize and validate directories
normalized := make([]string, 0, len(allowedDirs))
for _, dir := range allowedDirs {
abs, err := filepath.Abs(dir)
if err != nil {
return nil, fmt.Errorf("failed to resolve path %s: %w", dir, err)
}
info, err := os.Stat(abs)
if err != nil {
return nil, fmt.Errorf(
"failed to access directory %s: %w",
abs,
err,
)
}
if !info.IsDir() {
return nil, fmt.Errorf("path is not a directory: %s", abs)
}
// Ensure the path ends with a separator to prevent prefix matching issues
// For example, /tmp/foo should not match /tmp/foobar
normalized = append(normalized, filepath.Clean(abs)+string(filepath.Separator))
}
s := &FilesystemServer{
allowedDirs: normalized,
server: server.NewMCPServer(
"secure-filesystem-server",
"0.2.0",
),
}
// Register tool handlers
s.server.AddTool(mcp.NewTool(
"read_file",
mcp.WithDescription("Read the complete contents of a file from the file system."),
mcp.WithString("path",
mcp.Description("Path to the file to read"),
mcp.Required(),
),
), s.handleReadFile)
s.server.AddTool(mcp.NewTool(
"write_file",
mcp.WithDescription("Create a new file or overwrite an existing file with new content."),
mcp.WithString("path",
mcp.Description("Path where to write the file"),
mcp.Required(),
),
mcp.WithString("content",
mcp.Description("Content to write to the file"),
mcp.Required(),
),
), s.handleWriteFile)
s.server.AddTool(mcp.NewTool(
"list_directory",
mcp.WithDescription("Get a detailed listing of all files and directories in a specified path."),
mcp.WithString("path",
mcp.Description("Path of the directory to list"),
mcp.Required(),
),
), s.handleListDirectory)
s.server.AddTool(mcp.NewTool(
"create_directory",
mcp.WithDescription("Create a new directory or ensure a directory exists."),
mcp.WithString("path",
mcp.Description("Path of the directory to create"),
mcp.Required(),
),
), s.handleCreateDirectory)
s.server.AddTool(mcp.NewTool(
"move_file",
mcp.WithDescription("Move or rename files and directories."),
mcp.WithString("source",
mcp.Description("Source path of the file or directory"),
mcp.Required(),
),
mcp.WithString("destination",
mcp.Description("Destination path"),
mcp.Required(),
),
), s.handleMoveFile)
s.server.AddTool(mcp.NewTool(
"search_files",
mcp.WithDescription("Recursively search for files and directories matching a pattern."),
mcp.WithString("path",
mcp.Description("Starting path for the search"),
mcp.Required(),
),
mcp.WithString("pattern",
mcp.Description("Search pattern to match against file names"),
mcp.Required(),
),
), s.handleSearchFiles)
s.server.AddTool(mcp.NewTool(
"get_file_info",
mcp.WithDescription("Retrieve detailed metadata about a file or directory."),
mcp.WithString("path",
mcp.Description("Path to the file or directory"),
mcp.Required(),
),
), s.handleGetFileInfo)
s.server.AddTool(mcp.NewTool(
"list_allowed_directories",
mcp.WithDescription("Returns the list of directories that this server is allowed to access."),
), s.handleListAllowedDirectories)
return s, nil
}
// isPathInAllowedDirs checks if a path is within any of the allowed directories
func (s *FilesystemServer) isPathInAllowedDirs(path string) bool {
// Ensure path is absolute and clean
absPath, err := filepath.Abs(path)
if err != nil {
return false
}
// Add trailing separator to ensure we're checking a directory or a file within a directory
// and not a prefix match (e.g., /tmp/foo should not match /tmp/foobar)
if !strings.HasSuffix(absPath, string(filepath.Separator)) {
// If it's a file, we need to check its directory
if info, err := os.Stat(absPath); err == nil && !info.IsDir() {
absPath = filepath.Dir(absPath) + string(filepath.Separator)
} else {
absPath = absPath + string(filepath.Separator)
}
}
for _, dir := range s.allowedDirs {
if strings.HasPrefix(absPath, dir) {
return true
}
}
return false
}
func (s *FilesystemServer) validatePath(requestedPath string) (string, error) {
abs, err := filepath.Abs(requestedPath)
if err != nil {
return "", fmt.Errorf("invalid path: %w", err)
}
// Check if path is within allowed directories
if !s.isPathInAllowedDirs(abs) {
return "", fmt.Errorf(
"access denied - path outside allowed directories: %s",
abs,
)
}
// Handle symlinks
realPath, err := filepath.EvalSymlinks(abs)
if err != nil {
if !os.IsNotExist(err) {
return "", err
}
// For new files, check parent directory
parent := filepath.Dir(abs)
realParent, err := filepath.EvalSymlinks(parent)
if err != nil {
return "", fmt.Errorf("parent directory does not exist: %s", parent)
}
if !s.isPathInAllowedDirs(realParent) {
return "", fmt.Errorf(
"access denied - parent directory outside allowed directories",
)
}
return abs, nil
}
// Check if the real path (after resolving symlinks) is still within allowed directories
if !s.isPathInAllowedDirs(realPath) {
return "", fmt.Errorf(
"access denied - symlink target outside allowed directories",
)
}
return realPath, nil
}
func (s *FilesystemServer) getFileStats(path string) (FileInfo, error) {
info, err := os.Stat(path)
if err != nil {
return FileInfo{}, err
}
return FileInfo{
Size: info.Size(),
Created: info.ModTime(), // Note: ModTime used as birth time isn't always available
Modified: info.ModTime(),
Accessed: info.ModTime(), // Note: Access time isn't always available
IsDirectory: info.IsDir(),
IsFile: !info.IsDir(),
Permissions: fmt.Sprintf("%o", info.Mode().Perm()),
}, nil
}
func (s *FilesystemServer) searchFiles(
rootPath, pattern string,
) ([]string, error) {
var results []string
pattern = strings.ToLower(pattern)
err := filepath.Walk(
rootPath,
func(path string, info os.FileInfo, err error) error {
if err != nil {
return nil // Skip errors and continue
}
// Try to validate path
if _, err := s.validatePath(path); err != nil {
return nil // Skip invalid paths
}
if strings.Contains(strings.ToLower(info.Name()), pattern) {
results = append(results, path)
}
return nil
},
)
if err != nil {
return nil, err
}
return results, nil
}
// Tool handlers
func (s *FilesystemServer) handleReadFile(
ctx context.Context,
request mcp.CallToolRequest,
) (*mcp.CallToolResult, error) {
path, ok := request.Params.Arguments["path"].(string)
if !ok {
return nil, fmt.Errorf("path must be a string")
}
validPath, err := s.validatePath(path)
if err != nil {
return &mcp.CallToolResult{
Content: []mcp.Content{
mcp.TextContent{
Type: "text",
Text: fmt.Sprintf("Error: %v", err),
},
},
IsError: true,
}, nil
}
// Check if it's a directory
info, err := os.Stat(validPath)
if err != nil {
return &mcp.CallToolResult{
Content: []mcp.Content{
mcp.TextContent{
Type: "text",
Text: fmt.Sprintf("Error: %v", err),
},
},
IsError: true,
}, nil
}
if info.IsDir() {
return &mcp.CallToolResult{
Content: []mcp.Content{
mcp.TextContent{
Type: "text",
Text: "Error: Cannot read a directory, use list_directory instead",
},
},
IsError: true,
}, nil
}
content, err := os.ReadFile(validPath)
if err != nil {
return &mcp.CallToolResult{
Content: []mcp.Content{
mcp.TextContent{
Type: "text",
Text: fmt.Sprintf("Error reading file: %v", err),
},
},
IsError: true,
}, nil
}
return &mcp.CallToolResult{
Content: []mcp.Content{
mcp.TextContent{
Type: "text",
Text: string(content),
},
},
}, nil
}
func (s *FilesystemServer) handleWriteFile(
ctx context.Context,
request mcp.CallToolRequest,
) (*mcp.CallToolResult, error) {
path, ok := request.Params.Arguments["path"].(string)
if !ok {
return nil, fmt.Errorf("path must be a string")
}
content, ok := request.Params.Arguments["content"].(string)
if !ok {
return nil, fmt.Errorf("content must be a string")
}
validPath, err := s.validatePath(path)
if err != nil {
return &mcp.CallToolResult{
Content: []mcp.Content{
mcp.TextContent{
Type: "text",
Text: fmt.Sprintf("Error: %v", err),
},
},
IsError: true,
}, nil
}
// Check if it's a directory
if info, err := os.Stat(validPath); err == nil && info.IsDir() {
return &mcp.CallToolResult{
Content: []mcp.Content{
mcp.TextContent{
Type: "text",
Text: "Error: Cannot write to a directory",
},
},
IsError: true,
}, nil
}
// Create parent directories if they don't exist
parentDir := filepath.Dir(validPath)
if err := os.MkdirAll(parentDir, 0755); err != nil {
return &mcp.CallToolResult{
Content: []mcp.Content{
mcp.TextContent{
Type: "text",
Text: fmt.Sprintf("Error creating parent directories: %v", err),
},
},
IsError: true,
}, nil
}
if err := os.WriteFile(validPath, []byte(content), 0644); err != nil {
return &mcp.CallToolResult{
Content: []mcp.Content{
mcp.TextContent{
Type: "text",
Text: fmt.Sprintf("Error writing file: %v", err),
},
},
IsError: true,
}, nil
}
return &mcp.CallToolResult{
Content: []mcp.Content{
mcp.TextContent{
Type: "text",
Text: fmt.Sprintf("Successfully wrote to %s", path),
},
},
}, nil
}
func (s *FilesystemServer) handleListDirectory(
ctx context.Context,
request mcp.CallToolRequest,
) (*mcp.CallToolResult, error) {
path, ok := request.Params.Arguments["path"].(string)
if !ok {
return nil, fmt.Errorf("path must be a string")
}
validPath, err := s.validatePath(path)
if err != nil {
return &mcp.CallToolResult{
Content: []mcp.Content{
mcp.TextContent{
Type: "text",
Text: fmt.Sprintf("Error: %v", err),
},
},
IsError: true,
}, nil
}
// Check if it's a directory
info, err := os.Stat(validPath)
if err != nil {
return &mcp.CallToolResult{
Content: []mcp.Content{
mcp.TextContent{
Type: "text",
Text: fmt.Sprintf("Error: %v", err),
},
},
IsError: true,
}, nil
}
if !info.IsDir() {
return &mcp.CallToolResult{
Content: []mcp.Content{
mcp.TextContent{
Type: "text",
Text: "Error: Path is not a directory",
},
},
IsError: true,
}, nil
}
entries, err := os.ReadDir(validPath)
if err != nil {
return &mcp.CallToolResult{
Content: []mcp.Content{
mcp.TextContent{
Type: "text",
Text: fmt.Sprintf("Error reading directory: %v", err),
},
},
IsError: true,
}, nil
}
var result strings.Builder
result.WriteString(fmt.Sprintf("Directory listing for: %s\n\n", validPath))
for _, entry := range entries {
prefix := "[FILE]"
if entry.IsDir() {
prefix = "[DIR] "
}
fmt.Fprintf(&result, "%s %s\n", prefix, entry.Name())
}
return &mcp.CallToolResult{
Content: []mcp.Content{
mcp.TextContent{
Type: "text",
Text: result.String(),
},
},
}, nil
}
func (s *FilesystemServer) handleCreateDirectory(
ctx context.Context,
request mcp.CallToolRequest,
) (*mcp.CallToolResult, error) {
path, ok := request.Params.Arguments["path"].(string)
if !ok {
return nil, fmt.Errorf("path must be a string")
}
validPath, err := s.validatePath(path)
if err != nil {
return &mcp.CallToolResult{
Content: []mcp.Content{
mcp.TextContent{
Type: "text",
Text: fmt.Sprintf("Error: %v", err),
},
},
IsError: true,
}, nil
}
// Check if path already exists
if info, err := os.Stat(validPath); err == nil {
if info.IsDir() {
return &mcp.CallToolResult{
Content: []mcp.Content{
mcp.TextContent{
Type: "text",
Text: fmt.Sprintf("Directory already exists: %s", path),
},
},
}, nil
}
return &mcp.CallToolResult{
Content: []mcp.Content{
mcp.TextContent{
Type: "text",
Text: fmt.Sprintf("Error: Path exists but is not a directory: %s", path),
},
},
IsError: true,
}, nil
}
if err := os.MkdirAll(validPath, 0755); err != nil {
return &mcp.CallToolResult{
Content: []mcp.Content{
mcp.TextContent{
Type: "text",
Text: fmt.Sprintf("Error creating directory: %v", err),
},
},
IsError: true,
}, nil
}
return &mcp.CallToolResult{
Content: []mcp.Content{
mcp.TextContent{
Type: "text",
Text: fmt.Sprintf("Successfully created directory %s", path),
},
},
}, nil
}
func (s *FilesystemServer) handleMoveFile(
ctx context.Context,
request mcp.CallToolRequest,
) (*mcp.CallToolResult, error) {
source, ok := request.Params.Arguments["source"].(string)
if !ok {
return nil, fmt.Errorf("source must be a string")
}
destination, ok := request.Params.Arguments["destination"].(string)
if !ok {
return nil, fmt.Errorf("destination must be a string")
}
validSource, err := s.validatePath(source)
if err != nil {
return &mcp.CallToolResult{
Content: []mcp.Content{
mcp.TextContent{
Type: "text",
Text: fmt.Sprintf("Error with source path: %v", err),
},
},
IsError: true,
}, nil
}
// Check if source exists
if _, err := os.Stat(validSource); os.IsNotExist(err) {
return &mcp.CallToolResult{
Content: []mcp.Content{
mcp.TextContent{
Type: "text",
Text: fmt.Sprintf("Error: Source does not exist: %s", source),
},
},
IsError: true,
}, nil
}
validDest, err := s.validatePath(destination)
if err != nil {
return &mcp.CallToolResult{
Content: []mcp.Content{
mcp.TextContent{
Type: "text",
Text: fmt.Sprintf("Error with destination path: %v", err),
},
},
IsError: true,
}, nil
}
// Create parent directory for destination if it doesn't exist
destDir := filepath.Dir(validDest)
if err := os.MkdirAll(destDir, 0755); err != nil {
return &mcp.CallToolResult{
Content: []mcp.Content{
mcp.TextContent{
Type: "text",
Text: fmt.Sprintf("Error creating destination directory: %v", err),
},
},
IsError: true,
}, nil
}
if err := os.Rename(validSource, validDest); err != nil {
return &mcp.CallToolResult{
Content: []mcp.Content{
mcp.TextContent{
Type: "text",
Text: fmt.Sprintf("Error moving file: %v", err),
},
},
IsError: true,
}, nil
}
return &mcp.CallToolResult{
Content: []mcp.Content{
mcp.TextContent{
Type: "text",
Text: fmt.Sprintf(
"Successfully moved %s to %s",
source,
destination,
),
},
},
}, nil
}
func (s *FilesystemServer) handleSearchFiles(
ctx context.Context,
request mcp.CallToolRequest,
) (*mcp.CallToolResult, error) {
path, ok := request.Params.Arguments["path"].(string)
if !ok {
return nil, fmt.Errorf("path must be a string")
}
pattern, ok := request.Params.Arguments["pattern"].(string)
if !ok {
return nil, fmt.Errorf("pattern must be a string")
}
validPath, err := s.validatePath(path)
if err != nil {
return &mcp.CallToolResult{
Content: []mcp.Content{
mcp.TextContent{
Type: "text",
Text: fmt.Sprintf("Error: %v", err),
},
},
IsError: true,
}, nil
}
// Check if it's a directory
info, err := os.Stat(validPath)
if err != nil {
return &mcp.CallToolResult{
Content: []mcp.Content{
mcp.TextContent{
Type: "text",
Text: fmt.Sprintf("Error: %v", err),
},
},
IsError: true,
}, nil
}
if !info.IsDir() {
return &mcp.CallToolResult{
Content: []mcp.Content{
mcp.TextContent{
Type: "text",
Text: "Error: Search path must be a directory",
},
},
IsError: true,
}, nil
}
results, err := s.searchFiles(validPath, pattern)
if err != nil {
return &mcp.CallToolResult{
Content: []mcp.Content{
mcp.TextContent{
Type: "text",
Text: fmt.Sprintf("Error searching files: %v",
err),
},
},
IsError: true,
}, nil
}
if len(results) == 0 {
return &mcp.CallToolResult{
Content: []mcp.Content{
mcp.TextContent{
Type: "text",
Text: fmt.Sprintf("No files found matching pattern '%s' in %s", pattern, path),
},
},
}, nil
}
return &mcp.CallToolResult{
Content: []mcp.Content{
mcp.TextContent{
Type: "text",
Text: fmt.Sprintf("Found %d results:\n%s", len(results), strings.Join(results, "\n")),
},
},
}, nil
}
func (s *FilesystemServer) handleGetFileInfo(
ctx context.Context,
request mcp.CallToolRequest,
) (*mcp.CallToolResult, error) {
path, ok := request.Params.Arguments["path"].(string)
if !ok {
return nil, fmt.Errorf("path must be a string")
}
validPath, err := s.validatePath(path)
if err != nil {
return &mcp.CallToolResult{
Content: []mcp.Content{
mcp.TextContent{
Type: "text",
Text: fmt.Sprintf("Error: %v", err),
},
},
IsError: true,
}, nil
}
info, err := s.getFileStats(validPath)
if err != nil {
return &mcp.CallToolResult{
Content: []mcp.Content{
mcp.TextContent{
Type: "text",
Text: fmt.Sprintf("Error getting file info: %v", err),
},
},
IsError: true,
}, nil
}
return &mcp.CallToolResult{
Content: []mcp.Content{
mcp.TextContent{
Type: "text",
Text: fmt.Sprintf(
"File information for: %s\n\nSize: %d bytes\nCreated: %s\nModified: %s\nAccessed: %s\nIsDirectory: %v\nIsFile: %v\nPermissions: %s",
validPath,
info.Size,
info.Created.Format(time.RFC3339),
info.Modified.Format(time.RFC3339),
info.Accessed.Format(time.RFC3339),
info.IsDirectory,
info.IsFile,
info.Permissions,
),
},
},
}, nil
}
func (s *FilesystemServer) handleListAllowedDirectories(
ctx context.Context,
request mcp.CallToolRequest,
) (*mcp.CallToolResult, error) {
// Remove the trailing separator for display purposes
displayDirs := make([]string, len(s.allowedDirs))
for i, dir := range s.allowedDirs {
displayDirs[i] = strings.TrimSuffix(dir, string(filepath.Separator))
}
return &mcp.CallToolResult{
Content: []mcp.Content{
mcp.TextContent{
Type: "text",
Text: fmt.Sprintf(
"Allowed directories:\n%s",
strings.Join(displayDirs, "\n"),
),
},
},
}, nil
}
func (s *FilesystemServer) Serve() error {
return server.ServeStdio(s.server)
}
func main() {
// Parse command line arguments
if len(os.Args) < 2 {
fmt.Fprintf(
os.Stderr,
"Usage: %s <allowed-directory> [additional-directories...]\n",
os.Args[0],
)
os.Exit(1)
}
// Create and start the server
fs, err := NewFilesystemServer(os.Args[1:])
if err != nil {
log.Fatalf("Failed to create server: %v", err)
}
// Serve requests
if err := fs.Serve(); err != nil {
log.Fatalf("Server error: %v", err)
}
}