-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.test.ts
More file actions
1209 lines (1045 loc) · 53.3 KB
/
Copy pathindex.test.ts
File metadata and controls
1209 lines (1045 loc) · 53.3 KB
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
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { describe, it, expect, beforeAll, afterAll, vi } from "vitest";
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
import { InMemoryTransport } from "@modelcontextprotocol/sdk/inMemory.js";
import fs from "fs/promises";
import path from "path";
import os from "os";
import { pathToFileURL } from "url";
import { createHash } from "crypto";
import { setupServer, parseRootUri, getValidRootDirectories, updateAllowedDirectoriesFromRoots } from "./index.js";
import { setAllowedDirectories, getAllowedDirectories, getAllowedRoots, setAllowedRoots, hasErrorCode } from "./lib.js";
// Helper type for MCP tool call result content items
interface ContentItem { type: string; text?: string; data?: string; mimeType?: string; }
// Helper type for directory tree entries
interface TreeEntry { name: string; type: string; children?: TreeEntry[]; }
function sha256(content: string): string {
return createHash("sha256").update(content).digest("hex");
}
async function createOutsideDirectory(prefix = "fs-mcp-outside-"): Promise<string> {
const rawDir = await fs.mkdtemp(path.join(os.tmpdir(), prefix));
return fs.realpath(rawDir);
}
async function createDirectorySymlink(target: string, linkPath: string): Promise<void> {
await fs.symlink(target, linkPath, process.platform === "win32" ? "junction" : "dir");
}
// In-process integration tests using InMemoryTransport for v8 coverage
describe("index.ts integration", () => {
let client: Client;
let testDir: string;
beforeAll(async () => {
const rawDir = await fs.mkdtemp(path.join(os.tmpdir(), "fs-mcp-integration-"));
testDir = await fs.realpath(rawDir);
// Create test fixtures
await fs.writeFile(path.join(testDir, "hello.txt"), "line1\nline2\nline3\nline4\nline5\n");
await fs.writeFile(path.join(testDir, "data.json"), '{"key": "value"}');
await fs.mkdir(path.join(testDir, "subdir"), { recursive: true });
await fs.writeFile(path.join(testDir, "subdir", "nested.txt"), "nested content");
// Set allowed directories BEFORE creating the server
setAllowedDirectories([testDir, rawDir]);
const server = setupServer();
const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair();
await server.connect(serverTransport);
client = new Client({ name: "test-client", version: "1.0.0" });
await client.connect(clientTransport);
}, 15000);
afterAll(async () => {
try { await client?.close(); } catch { /* ignore cleanup */ }
setAllowedDirectories([]);
await fs.rm(testDir, { recursive: true, force: true });
});
// --- Tool Listing ---
it("should list all registered tools", async () => {
const tools = await client.listTools();
const toolNames = tools.tools.map((t: { name: string }) => t.name);
expect(toolNames).toContain("read_file");
expect(toolNames).toContain("read_text_file");
expect(toolNames).toContain("read_media_file");
expect(toolNames).toContain("read_multiple_files");
expect(toolNames).toContain("write_file");
expect(toolNames).toContain("edit_file");
expect(toolNames).toContain("create_directory");
expect(toolNames).toContain("list_directory");
expect(toolNames).toContain("list_directory_with_sizes");
expect(toolNames).toContain("directory_tree");
expect(toolNames).toContain("rename_file");
expect(toolNames).toContain("search_files");
expect(toolNames).toContain("get_file_info");
expect(toolNames).toContain("list_allowed_directories");
});
// --- read_file ---
describe("read_file", () => {
it("should read full file", async () => {
const result = await client.callTool({ name: "read_file", arguments: { path: path.join(testDir, "hello.txt") } });
const text = (result.content as ContentItem[])[0].text;
expect(text).toContain("line1");
expect(text).toContain("line5");
});
it("should read line range", async () => {
const result = await client.callTool({ name: "read_file", arguments: { path: path.join(testDir, "hello.txt"), start_line: 2, end_line: 3 } });
const text = (result.content as ContentItem[])[0].text;
expect(text).toContain("line2");
expect(text).toContain("line3");
expect(text).not.toContain("line1");
});
it("should support head parameter", async () => {
const result = await client.callTool({ name: "read_file", arguments: { path: path.join(testDir, "hello.txt"), head: 2 } });
const text = (result.content as ContentItem[])[0].text!;
const lines = text.split("\n").filter(Boolean);
expect(lines.length).toBe(2);
expect(lines[0]).toBe("line1");
});
it("should support tail parameter", async () => {
const result = await client.callTool({ name: "read_file", arguments: { path: path.join(testDir, "hello.txt"), tail: 2 } });
const text = (result.content as ContentItem[])[0].text;
expect(text).toContain("line5");
});
it("should reject head + tail together", async () => {
const result = await client.callTool({ name: "read_file", arguments: { path: path.join(testDir, "hello.txt"), head: 2, tail: 2 } });
expect(result.isError).toBe(true);
});
it("should reject head + start_line together", async () => {
const result = await client.callTool({ name: "read_file", arguments: { path: path.join(testDir, "hello.txt"), head: 2, start_line: 1 } });
expect(result.isError).toBe(true);
});
it("should reject start_line > end_line", async () => {
const result = await client.callTool({ name: "read_file", arguments: { path: path.join(testDir, "hello.txt"), start_line: 5, end_line: 2 } });
expect(result.isError).toBe(true);
});
it("should reject non-positive and fractional line controls", async () => {
const filePath = path.join(testDir, "hello.txt");
const invalidCalls = [
{ start_line: 0 },
{ end_line: -1 },
{ head: 0 },
{ tail: -2 },
{ start_line: 1.5 },
{ end_line: 2.25 },
{ head: 1.5 },
{ tail: 2.25 },
];
for (const args of invalidCalls) {
const result = await client.callTool({ name: "read_file", arguments: { path: filePath, ...args } });
expect(result.isError).toBe(true);
}
});
it("should error for path outside allowed directories", async () => {
const result = await client.callTool({ name: "read_file", arguments: { path: "/etc/passwd" } });
expect(result.isError).toBe(true);
});
it("should support encoding parameter", async () => {
const result = await client.callTool({ name: "read_file", arguments: { path: path.join(testDir, "hello.txt"), encoding: "ascii" } });
const text = (result.content as ContentItem[])[0].text;
expect(text).toContain("line1");
});
it("should reject invalid encoding", async () => {
const result = await client.callTool({ name: "read_file", arguments: { path: path.join(testDir, "hello.txt"), encoding: "cp1252" } });
expect(result.isError).toBe(true);
});
it("should return numbered lines and structured line metadata when requested", async () => {
const result = await client.callTool({
name: "read_file",
arguments: {
path: path.join(testDir, "hello.txt"),
start_line: 2,
end_line: 3,
show_line_numbers: true,
output_format: "both",
},
});
expect(result.isError).toBeFalsy();
const text = (result.content as ContentItem[])[0].text!;
expect(text).toContain("2 | line2");
expect(text).toContain("3 | line3");
expect(text).not.toContain("line1");
const structured = result.structuredContent as { lines?: Array<{ lineNumber: number; text: string }>; startLine?: number; endLine?: number };
expect(structured.startLine).toBe(2);
expect(structured.endLine).toBe(3);
expect(structured.lines).toEqual([
{ lineNumber: 2, text: "line2" },
{ lineNumber: 3, text: "line3" },
]);
});
it("should read around a line with before/after context", async () => {
const result = await client.callTool({
name: "read_file",
arguments: {
path: path.join(testDir, "hello.txt"),
mode: "around",
line: 3,
before: 1,
after: 1,
show_line_numbers: true,
},
});
expect(result.isError).toBeFalsy();
const text = (result.content as ContentItem[])[0].text!;
expect(text).toContain("2 | line2");
expect(text).toContain("3 | line3");
expect(text).toContain("4 | line4");
expect(text).not.toContain("1 | line1");
});
it("should read matching lines with context", async () => {
const result = await client.callTool({
name: "read_file",
arguments: {
path: path.join(testDir, "hello.txt"),
mode: "matches",
pattern: "line[24]",
search_mode: "regex",
before: 0,
after: 0,
show_line_numbers: true,
},
});
expect(result.isError).toBeFalsy();
const text = (result.content as ContentItem[])[0].text!;
expect(text).toContain("2 | line2");
expect(text).toContain("4 | line4");
const structured = result.structuredContent as { matches?: Array<{ lineNumber: number; text: string }> };
expect(structured.matches?.map((match) => match.lineNumber)).toEqual([2, 4]);
});
it("should support full reads with line numbers and max_lines truncation", async () => {
const result = await client.callTool({
name: "read_file",
arguments: { path: path.join(testDir, "hello.txt"), show_line_numbers: true, max_lines: 2 },
});
expect(result.isError).toBeFalsy();
const text = (result.content as ContentItem[])[0].text!;
expect(text).toBe("1 | line1\n2 | line2");
expect(result.result).toMatchObject({ warningCode: "CONTENT_TRUNCATED" });
});
it("should truncate full reads by max_bytes", async () => {
const result = await client.callTool({
name: "read_file",
arguments: { path: path.join(testDir, "hello.txt"), max_bytes: 5 },
});
expect(result.isError).toBeFalsy();
expect((result.content as ContentItem[])[0].text).toBe("line1");
expect(result.result).toMatchObject({ warningCode: "CONTENT_TRUNCATED" });
});
it("should validate explicit read modes", async () => {
const headWithoutCount = await client.callTool({
name: "read_file",
arguments: { path: path.join(testDir, "hello.txt"), mode: "head" },
});
expect(headWithoutCount.isError).toBe(true);
const aroundWithoutLine = await client.callTool({
name: "read_file",
arguments: { path: path.join(testDir, "hello.txt"), mode: "around" },
});
expect(aroundWithoutLine.isError).toBe(true);
const matchesWithoutPattern = await client.callTool({
name: "read_file",
arguments: { path: path.join(testDir, "hello.txt"), mode: "matches" },
});
expect(matchesWithoutPattern.isError).toBe(true);
});
it("should truncate read_file matches and include context metadata", async () => {
const result = await client.callTool({
name: "read_file",
arguments: {
path: path.join(testDir, "hello.txt"),
mode: "matches",
pattern: "line",
before: 1,
after: 1,
max_matches: 1,
},
});
expect(result.isError).toBeFalsy();
expect(result.result).toMatchObject({ warningCode: "RESULTS_TRUNCATED" });
const structured = result.structuredContent as { matches?: Array<{ lineNumber: number; before?: unknown[]; after?: unknown[] }> };
expect(structured.matches).toHaveLength(1);
expect(structured.matches?.[0].lineNumber).toBe(1);
expect(structured.matches?.[0].after).toHaveLength(1);
});
});
// --- read_text_file ---
describe("read_text_file", () => {
it("should read full file", async () => {
const result = await client.callTool({ name: "read_text_file", arguments: { path: path.join(testDir, "hello.txt") } });
expect((result.content as ContentItem[])[0].text).toContain("line1");
});
it("should support head", async () => {
const result = await client.callTool({ name: "read_text_file", arguments: { path: path.join(testDir, "hello.txt"), head: 1 } });
expect((result.content as ContentItem[])[0].text).toBe("line1");
});
it("should support tail", async () => {
const result = await client.callTool({ name: "read_text_file", arguments: { path: path.join(testDir, "hello.txt"), tail: 2 } });
const text = (result.content as ContentItem[])[0].text;
expect(text).toContain("line5");
});
it("should reject head + tail together", async () => {
const result = await client.callTool({ name: "read_text_file", arguments: { path: path.join(testDir, "hello.txt"), head: 1, tail: 1 } });
expect(result.isError).toBe(true);
});
it("should reject negative and fractional head/tail values", async () => {
const negative = await client.callTool({ name: "read_text_file", arguments: { path: path.join(testDir, "hello.txt"), head: -1 } });
expect(negative.isError).toBe(true);
const fractional = await client.callTool({ name: "read_text_file", arguments: { path: path.join(testDir, "hello.txt"), tail: 1.5 } });
expect(fractional.isError).toBe(true);
});
});
// --- read_media_file ---
describe("read_media_file", () => {
it("should read file as base64 with MIME type", async () => {
const pngPath = path.join(testDir, "media-test.png");
await fs.writeFile(pngPath, Buffer.from("fake png content for base64 testing"));
const result = await client.callTool({ name: "read_media_file", arguments: { path: pngPath } });
expect(result.isError).toBeFalsy();
const content = (result.content as ContentItem[])[0];
expect(content.mimeType).toBe("image/png");
expect(content.data).toBeTruthy();
});
it("should not emit SVG as MCP image content", async () => {
const svgPath = path.join(testDir, "active-content.svg");
await fs.writeFile(svgPath, '<svg xmlns="http://www.w3.org/2000/svg"><script>alert(1)</script></svg>');
const result = await client.callTool({ name: "read_media_file", arguments: { path: svgPath } });
expect(result.isError).toBeFalsy();
const content = (result.content as ContentItem[])[0];
expect(content.type).toBe("text");
expect(content.text).toContain("base64 data omitted");
expect(content.data).toBeUndefined();
});
it("should read audio files as MCP audio content", async () => {
const audioPath = path.join(testDir, "audio-test.mp3");
await fs.writeFile(audioPath, Buffer.from("fake mp3 content for base64 testing"));
const result = await client.callTool({ name: "read_media_file", arguments: { path: audioPath } });
expect(result.isError).toBeFalsy();
const content = (result.content as ContentItem[])[0];
expect(content.type).toBe("audio");
expect(content.mimeType).toBe("audio/mpeg");
expect(content.data).toBeTruthy();
});
});
// --- read_multiple_files ---
describe("read_multiple_files", () => {
it("should read multiple files", async () => {
const result = await client.callTool({ name: "read_multiple_files", arguments: { paths: [path.join(testDir, "hello.txt"), path.join(testDir, "data.json")] } });
const text = (result.content as ContentItem[])[0].text;
expect(text).toContain("line1");
expect(text).toContain('"key"');
});
it("should include error for non-existent file inline", async () => {
const result = await client.callTool({ name: "read_multiple_files", arguments: { paths: [path.join(testDir, "hello.txt"), path.join(testDir, "nonexistent.txt")] } });
const text = (result.content as ContentItem[])[0].text;
expect(text).toContain("line1");
expect(text).toContain("Error");
});
it("should include structured per-file success and error entries", async () => {
const missingPath = path.join(testDir, "missing-multiple.txt");
const result = await client.callTool({
name: "read_multiple_files",
arguments: { paths: [path.join(testDir, "hello.txt"), missingPath], output_format: "both" },
});
expect(result.isError).toBeFalsy();
const structured = result.structuredContent as { files?: Array<{ path: string; success: boolean; content?: string; errorCode?: string }> };
expect(structured.files).toHaveLength(2);
expect(structured.files?.[0]).toMatchObject({ path: path.join(testDir, "hello.txt"), success: true });
expect(structured.files?.[0].content).toContain("line1");
expect(structured.files?.[1]).toMatchObject({ path: missingPath, success: false, errorCode: "PATH_NOT_FOUND" });
});
});
// --- write_file ---
describe("write_file", () => {
it("should create a new file", async () => {
const filePath = path.join(testDir, "new-write.txt");
const result = await client.callTool({ name: "write_file", arguments: { path: filePath, content: "new content" } });
expect(result.isError).toBeFalsy();
const content = await fs.readFile(filePath, "utf-8");
expect(content).toBe("new content");
});
it("should fail on existing file without overwrite", async () => {
const filePath = path.join(testDir, "new-write.txt");
const result = await client.callTool({ name: "write_file", arguments: { path: filePath, content: "overwrite attempt" } });
expect(result.isError).toBe(true);
expect((result.content as ContentItem[])[0].text).toContain("already exists");
});
it("should overwrite with overwrite: true", async () => {
const filePath = path.join(testDir, "new-write.txt");
const result = await client.callTool({ name: "write_file", arguments: { path: filePath, content: "overwritten", overwrite: true } });
expect(result.isError).toBeFalsy();
expect(await fs.readFile(filePath, "utf-8")).toBe("overwritten");
});
it("should append with append: true", async () => {
const filePath = path.join(testDir, "new-write.txt");
await client.callTool({ name: "write_file", arguments: { path: filePath, content: " more", append: true } });
expect(await fs.readFile(filePath, "utf-8")).toBe("overwritten more");
});
it("should create parent directories with create_parents", async () => {
const filePath = path.join(testDir, "deep", "nested", "dir", "file.txt");
const result = await client.callTool({ name: "write_file", arguments: { path: filePath, content: "deep", create_parents: true } });
expect(result.isError).toBeFalsy();
expect(await fs.readFile(filePath, "utf-8")).toBe("deep");
});
it("should support dry-run writes with diff output", async () => {
const filePath = path.join(testDir, "write-dry-run.txt");
await fs.writeFile(filePath, "before\n");
const result = await client.callTool({
name: "write_file",
arguments: { path: filePath, content: "after\n", overwrite: true, dryRun: true, return_diff: true },
});
expect(result.isError).toBeFalsy();
expect(await fs.readFile(filePath, "utf-8")).toBe("before\n");
const text = (result.content as ContentItem[])[0].text!;
expect(text).toContain("-before");
expect(text).toContain("+after");
});
it("should reject writes when expected_hash does not match current content", async () => {
const filePath = path.join(testDir, "write-hash-guard.txt");
await fs.writeFile(filePath, "current");
const result = await client.callTool({
name: "write_file",
arguments: { path: filePath, content: "changed", overwrite: true, expected_hash: sha256("different") },
});
expect(result.isError).toBe(true);
expect(await fs.readFile(filePath, "utf-8")).toBe("current");
});
it("should support expected_modified guards, backup creation, and diff output", async () => {
const filePath = path.join(testDir, "write-guarded-backup.txt");
await fs.writeFile(filePath, "before");
const modified = (await fs.stat(filePath)).mtime.toISOString();
const result = await client.callTool({
name: "write_file",
arguments: {
path: filePath,
content: "after",
overwrite: true,
expected_hash: sha256("before"),
expected_modified: modified,
create_backup: true,
return_diff: true,
output_format: "both",
},
});
expect(result.isError).toBeFalsy();
expect(await fs.readFile(filePath, "utf-8")).toBe("after");
const structured = result.structuredContent as { backupPath?: string; diff?: string };
expect(structured.backupPath).toBeTruthy();
expect(await fs.readFile(structured.backupPath!, "utf-8")).toBe("before");
expect(structured.diff).toContain("-before");
expect(structured.diff).toContain("+after");
});
it("should reject expected state checks for files that do not exist", async () => {
const filePath = path.join(testDir, "write-missing-expected.txt");
const result = await client.callTool({
name: "write_file",
arguments: { path: filePath, content: "new", expected_hash: sha256("") },
});
expect(result.isError).toBe(true);
expect(result.result).toMatchObject({ errorCode: "PATH_NOT_FOUND" });
});
});
// --- edit_file ---
describe("edit_file", () => {
it("should apply an edit and return diff", async () => {
const filePath = path.join(testDir, "edit-target.txt");
await fs.writeFile(filePath, "original line\n");
const result = await client.callTool({ name: "edit_file", arguments: { path: filePath, edits: [{ oldText: "original line", newText: "modified line" }] } });
expect(result.isError).toBeFalsy();
const text = (result.content as ContentItem[])[0].text;
expect(text).toContain("original line");
expect(text).toContain("modified line");
expect(await fs.readFile(filePath, "utf-8")).toContain("modified line");
});
it("should support dryRun", async () => {
const filePath = path.join(testDir, "edit-target.txt");
await fs.writeFile(filePath, "keep me\n");
const result = await client.callTool({ name: "edit_file", arguments: { path: filePath, edits: [{ oldText: "keep me", newText: "changed" }], dryRun: true } });
expect(result.isError).toBeFalsy();
expect(await fs.readFile(filePath, "utf-8")).toContain("keep me");
});
it("should support line-range replacements", async () => {
const filePath = path.join(testDir, "edit-lines.txt");
await fs.writeFile(filePath, "one\ntwo\nthree\n");
const result = await client.callTool({
name: "edit_file",
arguments: { path: filePath, edits: [{ start_line: 2, end_line: 2, newText: "TWO" }] },
});
expect(result.isError).toBeFalsy();
expect(await fs.readFile(filePath, "utf-8")).toBe("one\nTWO\nthree\n");
});
it("should support line insertion", async () => {
const filePath = path.join(testDir, "edit-insert.txt");
await fs.writeFile(filePath, "one\nthree\n");
const result = await client.callTool({
name: "edit_file",
arguments: { path: filePath, edits: [{ insert_at_line: 2, newText: "two" }] },
});
expect(result.isError).toBeFalsy();
expect(await fs.readFile(filePath, "utf-8")).toBe("one\ntwo\nthree\n");
});
it("should reject edits when expected_hash does not match current content", async () => {
const filePath = path.join(testDir, "edit-hash-guard.txt");
await fs.writeFile(filePath, "current");
const result = await client.callTool({
name: "edit_file",
arguments: {
path: filePath,
edits: [{ oldText: "current", newText: "changed" }],
expected_hash: sha256("different"),
},
});
expect(result.isError).toBe(true);
expect(await fs.readFile(filePath, "utf-8")).toBe("current");
});
});
// --- create_directory ---
describe("create_directory", () => {
it("should create a new directory", async () => {
const dirPath = path.join(testDir, "new-dir");
const result = await client.callTool({ name: "create_directory", arguments: { path: dirPath } });
expect(result.isError).toBeFalsy();
const stat = await fs.stat(dirPath);
expect(stat.isDirectory()).toBe(true);
});
it("should succeed silently if directory already exists", async () => {
const dirPath = path.join(testDir, "new-dir");
const result = await client.callTool({ name: "create_directory", arguments: { path: dirPath } });
expect(result.isError).toBeFalsy();
});
});
// --- list_directory ---
describe("list_directory", () => {
it("should list directory contents", async () => {
const result = await client.callTool({ name: "list_directory", arguments: { path: testDir } });
const text = (result.content as ContentItem[])[0].text;
expect(text).toContain("hello.txt");
expect(text).toContain("[FILE]");
expect(text).toContain("[DIR]");
});
it("should list recursively", async () => {
const result = await client.callTool({ name: "list_directory", arguments: { path: testDir, recursive: true } });
const text = (result.content as ContentItem[])[0].text;
expect(text).toContain("nested.txt");
});
it("should include metadata when requested", async () => {
const result = await client.callTool({ name: "list_directory", arguments: { path: testDir, include_metadata: true } });
const text = (result.content as ContentItem[])[0].text;
expect(text).toContain("Size:");
expect(text).toContain("Total:");
});
it("should support sorting", async () => {
const result = await client.callTool({ name: "list_directory", arguments: { path: testDir, sortBy: "name", order: "desc" } });
expect(result.isError).toBeFalsy();
});
it("should sort by size", async () => {
const result = await client.callTool({ name: "list_directory", arguments: { path: testDir, sortBy: "size" } });
expect(result.isError).toBeFalsy();
});
it("should sort by modified date", async () => {
const result = await client.callTool({ name: "list_directory", arguments: { path: testDir, sortBy: "modified" } });
expect(result.isError).toBeFalsy();
});
it("should include metadata in recursive listing", async () => {
const result = await client.callTool({ name: "list_directory", arguments: { path: testDir, recursive: true, include_metadata: true } });
const text = (result.content as ContentItem[])[0].text;
expect(text).toContain("Size:");
});
it("should provide structured entries and respect hidden/depth options", async () => {
const hiddenFile = path.join(testDir, ".hidden-list-entry");
await fs.writeFile(hiddenFile, "hidden");
const result = await client.callTool({
name: "list_directory",
arguments: { path: testDir, recursive: true, include_metadata: true, include_hidden: false, maxDepth: 1, output_format: "both" },
});
expect(result.isError).toBeFalsy();
const text = (result.content as ContentItem[])[0].text!;
expect(text).not.toContain(".hidden-list-entry");
expect(text).not.toContain("nested.txt");
const structured = result.structuredContent as { entries?: Array<{ name: string; type: string; size?: number; modified?: string; errorCode?: string; depth: number }> };
expect(structured.entries?.some((entry) => entry.name === "hello.txt" && entry.type === "file")).toBe(true);
expect(structured.entries?.some((entry) => entry.name === ".hidden-list-entry")).toBe(false);
expect(structured.entries?.every((entry) => entry.depth <= 1)).toBe(true);
});
it("should support structured-only rendering and field filtering", async () => {
const result = await client.callTool({
name: "list_directory",
arguments: { path: testDir, include_metadata: true, fields: ["size"], output_format: "structured" },
});
expect(result.isError).toBeFalsy();
const text = (result.content as ContentItem[])[0].text!;
expect(() => JSON.parse(text)).not.toThrow();
const structured = result.structuredContent as { entries?: Array<Record<string, unknown>> };
const hello = structured.entries?.find((entry) => entry.name === "hello.txt");
expect(hello?.size).toBeTypeOf("number");
expect(hello?.modified).toBeUndefined();
});
});
// --- list_directory_with_sizes ---
describe("list_directory_with_sizes", () => {
it("should list with sizes and dates", async () => {
const result = await client.callTool({ name: "list_directory_with_sizes", arguments: { path: testDir } });
const text = (result.content as ContentItem[])[0].text;
expect(text).toContain("hello.txt");
expect(text).toContain("Total:");
});
it("should support sort by size", async () => {
const result = await client.callTool({ name: "list_directory_with_sizes", arguments: { path: testDir, sortBy: "size" } });
expect(result.isError).toBeFalsy();
});
it("should not follow symlinks outside allowed roots for metadata", async () => {
const rawDir = await fs.mkdtemp(path.join(os.tmpdir(), "fs-mcp-symlink-metadata-"));
const realDir = await fs.realpath(rawDir);
const outsideDir = await createOutsideDirectory();
const previousRoots = getAllowedDirectories();
try {
await fs.writeFile(path.join(outsideDir, "secret.txt"), "outside");
try {
await createDirectorySymlink(outsideDir, path.join(rawDir, "outside-link"));
} catch (error: unknown) {
if (hasErrorCode(error) && (error.code === "EPERM" || error.code === "EACCES")) return;
throw error;
}
setAllowedDirectories([rawDir, realDir]);
const listing = await client.callTool({ name: "list_directory", arguments: { path: rawDir, include_metadata: true } });
const listingText = (listing.content as ContentItem[])[0].text!;
expect(listingText).toContain("outside-link");
expect(listingText).toContain("ACCESS_DENIED");
expect(listingText).not.toMatch(/outside-link \(Size:/);
const sizes = await client.callTool({ name: "list_directory_with_sizes", arguments: { path: rawDir } });
const sizesText = (sizes.content as ContentItem[])[0].text!;
expect(sizesText).toContain("outside-link");
expect(sizesText).toContain("ACCESS_DENIED");
} finally {
setAllowedDirectories(previousRoots);
await fs.rm(rawDir, { recursive: true, force: true });
await fs.rm(outsideDir, { recursive: true, force: true });
}
});
});
// --- directory_tree ---
describe("directory_tree", () => {
it("should return JSON tree", async () => {
const result = await client.callTool({ name: "directory_tree", arguments: { path: testDir } });
const text = (result.content as ContentItem[])[0].text!;
const tree = JSON.parse(text);
expect(Array.isArray(tree)).toBe(true);
const names = (tree as TreeEntry[]).map((e) => e.name);
expect(names).toContain("hello.txt");
});
it("should respect excludePatterns", async () => {
const result = await client.callTool({ name: "directory_tree", arguments: { path: testDir, excludePatterns: ["subdir/**"] } });
const text = (result.content as ContentItem[])[0].text;
expect(text).not.toContain("nested.txt");
});
it("should respect maxDepth", async () => {
const result = await client.callTool({ name: "directory_tree", arguments: { path: testDir, maxDepth: 1 } });
const tree = JSON.parse((result.content as ContentItem[])[0].text!) as TreeEntry[];
const subdir = tree.find((e) => e.name === "subdir");
if (subdir) {
expect(subdir.children?.length || 0).toBe(0);
}
});
});
// --- rename_file ---
describe("rename_file", () => {
it("should rename a file", async () => {
const src = path.join(testDir, "rename-me.txt");
const dst = path.join(testDir, "renamed.txt");
await fs.writeFile(src, "rename content");
const result = await client.callTool({ name: "rename_file", arguments: { source: src, destination: dst } });
expect(result.isError).toBeFalsy();
expect(await fs.readFile(dst, "utf-8")).toBe("rename content");
await expect(fs.access(src)).rejects.toThrow();
});
it("should fail if destination exists", async () => {
const src = path.join(testDir, "renamed.txt");
const dst = path.join(testDir, "hello.txt");
const result = await client.callTool({ name: "rename_file", arguments: { source: src, destination: dst } });
expect(result.isError).toBe(true);
expect((result.content as ContentItem[])[0].text).toContain("already exists");
});
it("should refuse cross-root renames so rename cannot be used as a delete workaround", async () => {
const src = path.join(testDir, "cross-root-source.txt");
const otherRawDir = await fs.mkdtemp(path.join(os.tmpdir(), "fs-mcp-cross-root-"));
const otherDir = await fs.realpath(otherRawDir);
const previousRoots = getAllowedDirectories();
try {
setAllowedDirectories([testDir, otherDir]);
await fs.writeFile(src, "do not rename across roots");
const dst = path.join(otherDir, "cross-root-dest.txt");
const result = await client.callTool({ name: "rename_file", arguments: { source: src, destination: dst } });
expect(result.isError).toBe(true);
expect((result.content as ContentItem[])[0].text).toContain("Cross-root renames are refused");
expect(await fs.readFile(src, "utf-8")).toBe("do not rename across roots");
await expect(fs.access(dst)).rejects.toThrow();
} finally {
setAllowedDirectories(previousRoots);
await fs.rm(otherDir, { recursive: true, force: true });
}
});
it("should refuse EXDEV instead of falling back to copy plus delete", async () => {
const src = path.join(testDir, "exdev-source.txt");
const dst = path.join(testDir, "exdev-dest.txt");
await fs.writeFile(src, "same-root cross-device refusal");
const originalRename = fs.rename.bind(fs);
const renameSpy = vi.spyOn(fs, "rename").mockImplementation(async (source, destination) => {
if (source === src && destination === dst) {
throw Object.assign(new Error("cross-device link not permitted"), { code: "EXDEV" });
}
return originalRename(source, destination);
});
try {
const result = await client.callTool({ name: "rename_file", arguments: { source: src, destination: dst } });
expect(result.isError).toBe(true);
expect((result.content as ContentItem[])[0].text).toContain("does not emulate rename with copy/delete");
expect(await fs.readFile(src, "utf-8")).toBe("same-root cross-device refusal");
await expect(fs.access(dst)).rejects.toThrow();
} finally {
renameSpy.mockRestore();
}
});
});
// --- search_files ---
describe("search_files", () => {
it("should search by substring", async () => {
const result = await client.callTool({ name: "search_files", arguments: { path: testDir, pattern: "hello" } });
const text = (result.content as ContentItem[])[0].text;
expect(text).toContain("hello.txt");
});
it("should search by regex", async () => {
const result = await client.callTool({ name: "search_files", arguments: { path: testDir, pattern: "\\.txt$", search_mode: "regex" } });
const text = (result.content as ContentItem[])[0].text;
expect(text).toContain(".txt");
});
it("should search by glob", async () => {
const result = await client.callTool({ name: "search_files", arguments: { path: testDir, pattern: "*.json", search_mode: "glob" } });
const text = (result.content as ContentItem[])[0].text;
expect(text).toContain("data.json");
});
it("should support max_results", async () => {
const result = await client.callTool({ name: "search_files", arguments: { path: testDir, pattern: "", max_results: 1 } });
expect(result.isError).toBeFalsy();
});
it("should support match_path", async () => {
const result = await client.callTool({ name: "search_files", arguments: { path: testDir, pattern: "subdir", match_path: true } });
const text = (result.content as ContentItem[])[0].text;
expect(text).toContain("subdir");
});
it("should report error for invalid regex", async () => {
const result = await client.callTool({ name: "search_files", arguments: { path: testDir, pattern: "[invalid", search_mode: "regex" } });
expect(result.isError).toBe(true);
});
it("should search file contents with line context and structured matches", async () => {
const result = await client.callTool({
name: "search_files",
arguments: {
path: testDir,
pattern: "line[24]",
search_mode: "regex",
target: "content",
include_context: true,
before: 0,
after: 0,
show_line_numbers: true,
output_format: "both",
},
});
expect(result.isError).toBeFalsy();
const text = (result.content as ContentItem[])[0].text!;
expect(text).toContain("hello.txt:2 | line2");
expect(text).toContain("hello.txt:4 | line4");
const structured = result.structuredContent as { matches?: Array<{ path: string; lineNumber: number; text: string }> };
expect(structured.matches?.filter((match) => match.path.endsWith("hello.txt")).map((match) => match.lineNumber)).toEqual([2, 4]);
});
it("should reject glob mode for content-only search", async () => {
const result = await client.callTool({
name: "search_files",
arguments: { path: testDir, pattern: "*.txt", search_mode: "glob", target: "content" },
});
expect(result.isError).toBe(true);
});
it("should report skipped files for content search size and binary policies", async () => {
const smallLimit = await client.callTool({
name: "search_files",
arguments: { path: testDir, pattern: "line", target: "content", max_file_bytes: 1 },
});
expect(smallLimit.isError).toBeFalsy();
const smallLimitStructured = smallLimit.structuredContent as { skippedFiles?: unknown[] };
expect(smallLimitStructured.skippedFiles?.length).toBeGreaterThan(0);
const binaryPath = path.join(testDir, "content-binary.bin");
await fs.writeFile(binaryPath, Buffer.from("needle\x00value"));
const includeWarning = await client.callTool({
name: "search_files",
arguments: { path: testDir, pattern: "needle", target: "content", binary_policy: "include_warning" },
});
expect(includeWarning.isError).toBeFalsy();
const warningStructured = includeWarning.structuredContent as { matches?: Array<{ path: string }>; skippedFiles?: Array<{ errorCode?: string }> };
expect(warningStructured.matches?.some((match) => match.path.endsWith("content-binary.bin"))).toBe(true);
expect(warningStructured.skippedFiles?.some((file) => file.errorCode === "BINARY_CONTENT_DETECTED")).toBe(true);
});
it("should combine path and content matches with target all", async () => {
const allTargetPath = path.join(testDir, "needle-name.txt");
await fs.writeFile(allTargetPath, "needle body");
const result = await client.callTool({
name: "search_files",
arguments: { path: testDir, pattern: "needle", target: "all", output_format: "both" },
});
expect(result.isError).toBeFalsy();
const structured = result.structuredContent as { paths?: string[]; contentMatches?: Array<{ path: string }> };
expect(structured.paths?.some((matchedPath) => matchedPath.endsWith("needle-name.txt"))).toBe(true);
expect(structured.contentMatches?.some((match) => match.path.endsWith("needle-name.txt"))).toBe(true);
});
});
// --- get_file_info ---
describe("get_file_info", () => {
it("should return file metadata", async () => {
const result = await client.callTool({ name: "get_file_info", arguments: { path: path.join(testDir, "hello.txt") } });
const text = (result.content as ContentItem[])[0].text;
expect(text).toContain("isFile: true");
expect(text).toContain("size:");
expect(text).toContain("lineCount:");
});
it("should return directory metadata", async () => {
const result = await client.callTool({ name: "get_file_info", arguments: { path: testDir } });
const text = (result.content as ContentItem[])[0].text;
expect(text).toContain("isDirectory: true");
});
it("should include mimeType for known extensions", async () => {
const result = await client.callTool({ name: "get_file_info", arguments: { path: path.join(testDir, "data.json") } });
const text = (result.content as ContentItem[])[0].text;
expect(text).toContain("application/json");
});
it("should return structured metadata for multiple paths", async () => {
const result = await client.callTool({
name: "get_file_info",
arguments: { paths: [path.join(testDir, "hello.txt"), path.join(testDir, "data.json")], output_format: "both" },
});
expect(result.isError).toBeFalsy();
const structured = result.structuredContent as { files?: Array<{ path: string; success: boolean; isFile?: boolean; mimeType?: string; lineCount?: number }> };
expect(structured.files).toHaveLength(2);
expect(structured.files?.[0]).toMatchObject({ path: path.join(testDir, "hello.txt"), success: true, isFile: true });
expect(structured.files?.[0].lineCount).toBeGreaterThan(0);
expect(structured.files?.[1]).toMatchObject({ path: path.join(testDir, "data.json"), success: true, mimeType: "application/json" });
});
it("should include access explanation and resolved path when requested", async () => {
const result = await client.callTool({
name: "get_file_info",
arguments: { path: path.join(testDir, "hello.txt"), resolve: true, explain_access: true, output_format: "both" },
});
expect(result.isError).toBeFalsy();
const structured = result.structuredContent as { resolvedPath?: string; allowed?: boolean; allowedRoots?: string[] };
expect(structured.resolvedPath).toBe(path.join(testDir, "hello.txt"));
expect(structured.allowed).toBe(true);
expect(structured.allowedRoots?.length).toBeGreaterThan(0);
});
it("should report per-path errors in batch metadata calls", async () => {
const missingPath = path.join(testDir, "missing-info-batch.txt");
const result = await client.callTool({
name: "get_file_info",
arguments: { paths: [path.join(testDir, "hello.txt"), missingPath], output_format: "both" },
});
expect(result.isError).toBeFalsy();
const structured = result.structuredContent as { files?: Array<{ path: string; success: boolean; errorCode?: string }> };
expect(structured.files?.[1]).toMatchObject({ path: missingPath, success: false, errorCode: "PATH_NOT_FOUND" });
});
});
// --- list_allowed_directories ---
describe("list_allowed_directories", () => {
it("should list the test directory", async () => {
const result = await client.callTool({ name: "list_allowed_directories", arguments: {} });
const text = (result.content as ContentItem[])[0].text;
expect(text).toContain("Allowed filesystem roots:");
});
});
describe("exact file roots", () => {
it("should allow an exact file root and reject siblings through tool calls", async () => {
const previousRoots = getAllowedRoots();
const allowedFile = path.join(testDir, "file-root-only.txt");
const siblingFile = path.join(testDir, "file-root-sibling.txt");
await fs.writeFile(allowedFile, "allowed file root");
await fs.writeFile(siblingFile, "sibling should be denied");
try {
await updateAllowedDirectoriesFromRoots([{ uri: pathToFileURL(allowedFile).href }]);
const allowed = await client.callTool({ name: "read_file", arguments: { path: allowedFile } });
expect(allowed.isError).toBeFalsy();
expect((allowed.content as ContentItem[])[0].text).toContain("allowed file root");
const overwritten = await client.callTool({ name: "write_file", arguments: { path: allowedFile, content: "overwritten file root", overwrite: true } });
expect(overwritten.isError).toBeFalsy();
expect(await fs.readFile(allowedFile, "utf-8")).toBe("overwritten file root");
const edited = await client.callTool({