Repository navigation
Expand file tree
/
Copy pathserver.ts
More file actions
1309 lines (1239 loc) · 48 KB
/
Copy pathserver.ts
File metadata and controls
1309 lines (1239 loc) · 48 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
// The filesystem server, built per call by createServer(). index.ts is the
// stdio entry point that resolves the allowed directories from argv and hands
// them here. Building the server in a factory, rather than at module load,
// lets the tests drive a real Client against it in-process over an in-memory
// transport (#4854), and holding the allow-list in this closure rather than in
// a module global lets two instances coexist in one process.
import { McpServer } from "@modelcontextprotocol/server";
import type { Root } from "@modelcontextprotocol/server";
import path from "path";
import { pathToFileURL } from "url";
import { z } from "zod";
import { getValidRootDirectories } from "./roots-utils.js";
import {
confineRootsToDirectories,
describeAllowedDirectories,
} from "./allowed-directories.js";
import {
formatSize,
validatePath,
getFileStats,
readFileContent,
writeFileContent,
appendFileContent,
createDirectory,
moveFile,
copyFile,
searchFilesWithValidation,
isExcludedPath,
applyFileEdits,
tailFile,
headFile,
listValidatedDirectory,
createEntryBudget,
} from "./lib.js";
import { registerFileResources } from "./file-resources.js";
import { describeReadOnlyDirectories } from "./read-only-directories.js";
import { SERVER_VERSION } from "./version.js";
// The JSON Schema dialect every advertised tool schema declares (#4841). The
// SDK 1.x tools/list handler rendered zod schemas with zod's draft-07 target and
// stamped "$schema": draft-07 on each one, which validators that accept only
// 2020-12 (the dialect MCP assumes for tool schemas) reject outright. Setting
// $schema in the root object's zod metadata overrode that stamp. SDK v2 stamps
// 2020-12 itself, so the label is now the SDK's default as well. The schemas
// below use nothing whose draft-07 and 2020-12 renderings differ (no tuples),
// so the label is the only change; server-tools.test.ts fails if a draft-07-only
// keyword ever appears under it.
const JSON_SCHEMA_DIALECT = "https://json-schema.org/draft/2020-12/schema";
/** A tool's input or output shape as an object schema declaring 2020-12. */
function jsonSchema2020<Shape extends z.ZodRawShape>(shape: Shape) {
return z.object(shape).meta({ $schema: JSON_SCHEMA_DIALECT });
}
// How every path argument is resolved, appended to its description: a model
// that is told only "the file" guesses at relative paths and at the sandbox.
const PATH_RULE =
"Absolute, or relative to an allowed directory; it must resolve inside the allowed directories.";
/** A path argument, described as `what` followed by how it is resolved. */
function pathArg(what: string) {
return z.string().describe(`${what}. ${PATH_RULE}`);
}
// Schema definitions
const ReadTextFileArgsSchema = z.object({
path: pathArg("The file to read as text"),
tail: z
.number()
.int()
.min(0)
.optional()
.describe("If provided, returns only the last N lines of the file"),
head: z
.number()
.int()
.min(0)
.optional()
.describe("If provided, returns only the first N lines of the file"),
});
const ReadMediaFileArgsSchema = z.object({
path: pathArg("The image, audio or other file to read as base64"),
});
const ReadMultipleFilesArgsSchema = z.object({
paths: z
.array(z.string())
.min(1)
.describe(
"Array of file paths to read. Each path must be a string pointing to a valid file within allowed directories.",
),
});
const WriteFileArgsSchema = z.object({
path: pathArg(
"The file to create, or to overwrite if it exists; its parent directory must exist",
),
content: z
.string()
.describe("The complete text the file will contain, replacing any it had"),
});
const AppendFileArgsSchema = z.object({
path: pathArg("The file to append to; it is created if it does not exist"),
content: z
.string()
.describe(
"Text to append, exactly as given. No newline is added: end it with \\n if the next append should start on a new line.",
),
});
const EditOperation = z.object({
oldText: z.string().describe("Text to search for - must match exactly"),
newText: z.string().describe("Text to replace with"),
});
const EditFileArgsSchema = z.object({
path: pathArg("The text file to edit"),
edits: z
.array(EditOperation)
.describe(
"The replacements to make, applied in order, each to the result of the ones before it. " +
"If any one has no match, none is written.",
),
dryRun: z
.boolean()
.default(false)
.describe("Preview changes using git-style diff format"),
});
const CreateDirectoryArgsSchema = z.object({
path: pathArg(
"The directory to create, with any missing parents; an existing directory is left as is",
),
});
const ListDirectoryArgsSchema = z.object({
path: pathArg("The directory to list"),
});
const ListDirectoryWithSizesArgsSchema = z.object({
path: pathArg("The directory to list"),
sortBy: z
.enum(["name", "size"])
.optional()
.default("name")
.describe("Sort entries by name or size"),
});
const DirectoryTreeArgsSchema = z.object({
path: pathArg("The directory at the root of the tree"),
excludePatterns: z
.array(z.string())
.optional()
.default([])
.describe(
"Patterns for entries to leave out, with their contents, matched against each entry's path relative to path. " +
"A pattern with no '*' matches that name at any depth ('node_modules' leaves out every node_modules directory); " +
"a pattern with '*' is a glob matched as written, and one ending in '/**' also leaves out the directory it names.",
),
depth: z
.number()
.int()
.positive()
.optional()
.describe(
"How many levels to descend: 1 lists only the entries directly in path. " +
"Directories at the last level have no children array. Omit for the whole tree.",
),
});
const MoveFileArgsSchema = z.object({
source: pathArg("The file or directory to move or rename"),
destination: pathArg(
"Its new path, including the name; nothing may exist there yet",
),
});
const CopyFileArgsSchema = z.object({
source: z.string().describe("The file to copy"),
destination: z
.string()
.describe("Where to create the copy; nothing may exist there yet"),
});
const SearchFilesArgsSchema = z.object({
path: pathArg("The directory to search under"),
pattern: z
.string()
.describe(
"Glob matched against each entry's path relative to path, never its content: " +
"'*.ts' matches directly under path, '**/*.ts' at any depth.",
),
excludePatterns: z
.array(z.string())
.optional()
.default([])
.describe(
"Patterns for entries to leave out, with their contents, matched against each entry's path relative to path. " +
"A pattern with no '*' matches that name at any depth ('node_modules' leaves out every node_modules directory); " +
"a pattern with '*' is a glob matched as written, and one ending in '/**' also leaves out the directory it names.",
),
});
const GetFileInfoArgsSchema = z.object({
path: pathArg("The file or directory to describe"),
});
/**
* Why the server cannot operate when it has no allowed directories from either
* the command line or the client's Roots (#4992).
*/
export const NO_ALLOWED_DIRECTORIES_ERROR =
"Server cannot operate: No allowed directories available. Server was started without command-line directories and client does not support MCP roots protocol. Please either: 1) Start server with directory arguments, or 2) Use a client that supports MCP roots protocol and provides valid root directories.";
/**
* Why the server cannot operate on a 2026-07-28 connection when it was started
* with no allowed directories. That revision has no initialize handshake and
* no server-to-client roots/list, so the client's Roots cannot supply them
* (Roots is deprecated as of 2026-07-28); only the command line can (#4852).
*/
export const NO_ALLOWED_DIRECTORIES_MODERN_ERROR =
"Server cannot operate: No allowed directories available. Server was started without command-line directories, and on protocol version 2026-07-28 the client cannot provide them through MCP Roots. Restart the server with the directories it may access as command-line arguments.";
export interface ServerOptions {
/**
* The protocol era the server will serve (default `legacy`). On a
* 2025-era connection the client's Roots, when it supports them, replace
* the command-line directories after initialize. A 2026-07-28 connection
* has no initialize and no roots/list, so it is limited to the
* command-line directories.
*/
era?: "legacy" | "modern";
/**
* Called after the server has closed the connection because it cannot
* operate: no directories were given and the client does not support
* Roots (#4992). The stdio entry point exits the process from here.
*/
onCannotOperate?: (error: Error) => void;
/**
* Serve only the tools that cannot change the filesystem (#632, #1160):
* every tool whose annotations do not declare `readOnlyHint: true` is left
* out of the server, so clients never see it and cannot call it.
*/
readOnly?: boolean;
/**
* Confine the client's Roots to the command-line directories (#3133): on a
* 2025-era connection a root may narrow them but never widen them, and a
* root outside every one of them is ignored. Has no effect when the server
* was started with no command-line directories.
*/
confineRoots?: boolean;
/**
* Directories every write tool refuses (`--read-only-dir`, #5348), already
* resolved by resolveReadOnlyDirectories. A write whose resolved target is
* inside any of them is refused, whatever the allowed directories in force,
* so a client's Roots never lift the marking. The write tools stay listed,
* since the other directories are writable.
*/
readOnlyDirectories?: readonly string[];
}
/**
* Build a filesystem server that may touch only `initialAllowedDirectories`
* (already resolved and normalized by the caller), until the client's Roots
* replace them on a 2025-era connection.
*/
export function createServer(
initialAllowedDirectories: string[],
options: ServerOptions = {},
): McpServer {
let allowedDirectories = [...initialAllowedDirectories];
const readOnlyDirectories = [...(options.readOnlyDirectories ?? [])];
// True once the client's roots have replaced the command-line directories.
// From then on a roots update replaces them even with none, so a client that
// withdraws its roots withdraws the server's access too (#5094). Until then an
// update with no valid roots keeps the command-line directories.
let rootsInForce = false;
// Each roots refresh (the initial load and every roots/list_changed) takes
// the next generation before it asks for roots. The SDK runs notification
// handlers without waiting for earlier ones, so answers can come back out of
// order; one is applied only if no newer refresh has started since, so a
// stale answer cannot undo a newer update, such as a revocation (#5097).
let rootsGeneration = 0;
const server = new McpServer({
name: "secure-filesystem-server",
version: SERVER_VERSION,
});
// The barrier every tool call waits on, so a call that arrives while roots are
// being fetched is checked against the roots that come back rather than the
// ones being replaced: the command-line directories while the initial
// roots/list is outstanding (#3204), or a root the client has just withdrawn
// while a roots/list_changed refresh is pending (#5101). Each refresh (the
// initial load included) installs a new barrier before it sends roots/list,
// and settles it when it finishes, successfully or not. Installing one also
// settles the barrier it replaces, so calls waiting on an older refresh wake
// at once and move on to the newer one instead of waiting for the older
// one's answer (#5097, #5101).
let barrier = { settled: Promise.resolve(), settle: () => {} };
function installBarrier(): () => void {
let settle!: () => void;
const settled = new Promise<void>((resolve) => (settle = resolve));
const replaced = barrier;
barrier = { settled, settle };
replaced.settle();
return settle;
}
const registerTool = server.registerTool.bind(server);
server.registerTool = ((
name: string,
config: Parameters<typeof registerTool>[1],
handler: (...args: unknown[]) => unknown,
) =>
registerTool(name, config, (async (...args: unknown[]) => {
let awaited: typeof barrier;
do {
awaited = barrier;
await awaited.settled;
} while (awaited !== barrier);
// A 2025-era session with no directories closes at initialize (#4992).
// A 2026-07-28 one has no initialize to close at, and its client cannot
// add directories, so every call says why it cannot run.
if (options.era === "modern" && allowedDirectories.length === 0) {
return {
content: [
{ type: "text", text: NO_ALLOWED_DIRECTORIES_MODERN_ERROR },
],
isError: true,
};
}
return handler(...args);
}) as never)) as typeof server.registerTool;
// Read-only mode (#632, #1160) withholds every tool that does not declare
// itself read-only. Keying on the annotation rather than on a list of write
// tools fails closed: a new tool is withheld unless its registration says
// `readOnlyHint: true`, the hint the repository already requires to be set
// truthfully, so a new write tool needs no change here. A withheld tool is
// registered and then removed, before any client connects, so it is absent
// from tools/list and a call to it is answered as an unknown tool.
if (options.readOnly) {
const registerReadWrite = server.registerTool.bind(server);
server.registerTool = ((
name: string,
config: Parameters<typeof registerReadWrite>[1],
handler: Parameters<typeof registerReadWrite>[2],
) => {
const tool = registerReadWrite(name, config, handler);
if (config.annotations?.readOnlyHint !== true) tool.remove();
return tool;
}) as typeof server.registerTool;
}
// Tool registrations
// read_file (deprecated) and read_text_file
const readTextFileHandler = async (
args: z.infer<typeof ReadTextFileArgsSchema>,
) => {
const validPath = await validatePath(args.path, allowedDirectories, "read");
// Compared against undefined, not tested for truthiness: a count of 0
// asks for zero lines, not for the whole file (#5184).
if (args.head !== undefined && args.tail !== undefined) {
throw new Error(
"Cannot specify both head and tail parameters simultaneously",
);
}
let content: string;
if (args.tail !== undefined) {
content = await tailFile(validPath, args.tail);
} else if (args.head !== undefined) {
content = await headFile(validPath, args.head);
} else {
content = await readFileContent(validPath);
}
return {
content: [{ type: "text" as const, text: content }],
structuredContent: { content },
};
};
server.registerTool(
"read_file",
{
title: "Read File (Deprecated)",
description:
"Read the complete contents of a file as text. DEPRECATED: Use read_text_file instead.",
inputSchema: jsonSchema2020(ReadTextFileArgsSchema.shape),
outputSchema: jsonSchema2020({ content: z.string() }),
annotations: {
readOnlyHint: true,
idempotentHint: true,
destructiveHint: false,
openWorldHint: false,
},
},
readTextFileHandler,
);
server.registerTool(
"read_text_file",
{
title: "Read Text File",
description:
"Read the complete contents of a file from the file system as text. " +
"Handles various text encodings and provides detailed error messages " +
"if the file cannot be read. Use this tool when you need to examine " +
"the contents of a single file. Use the 'head' parameter to read only " +
"the first N lines of a file, or the 'tail' parameter to read only " +
"the last N lines of a file. Operates on the file as text regardless of extension. " +
"Only works within allowed directories.",
inputSchema: jsonSchema2020(ReadTextFileArgsSchema.shape),
outputSchema: jsonSchema2020({ content: z.string() }),
annotations: {
readOnlyHint: true,
idempotentHint: true,
destructiveHint: false,
openWorldHint: false,
},
},
readTextFileHandler,
);
server.registerTool(
"read_media_file",
{
title: "Read Media File",
description:
"Read a file and return it as a base64-encoded content block with its MIME type. " +
"Image and audio files are returned as image/audio content; any other file type is " +
"returned as an embedded resource. Only works within allowed directories.",
inputSchema: jsonSchema2020(ReadMediaFileArgsSchema.shape),
outputSchema: jsonSchema2020({
content: z.array(
z.union([
z.object({
type: z.enum(["image", "audio"]),
data: z.string(),
mimeType: z.string(),
}),
z.object({
type: z.literal("resource"),
resource: z.object({
uri: z.string(),
// Optional, matching the SDK's BlobResourceContents shape (the handler always sets it).
mimeType: z.string().optional(),
blob: z.string(),
}),
}),
]),
),
}),
annotations: {
readOnlyHint: true,
idempotentHint: true,
destructiveHint: false,
openWorldHint: false,
},
},
async (args: z.infer<typeof ReadMediaFileArgsSchema>) => {
const validPath = await validatePath(
args.path,
allowedDirectories,
"read",
);
const extension = path.extname(validPath).toLowerCase();
const mimeTypes: Record<string, string> = {
".png": "image/png",
".jpg": "image/jpeg",
".jpeg": "image/jpeg",
".gif": "image/gif",
".webp": "image/webp",
".bmp": "image/bmp",
".svg": "image/svg+xml",
".mp3": "audio/mpeg",
".wav": "audio/wav",
".ogg": "audio/ogg",
".flac": "audio/flac",
};
const mimeType = mimeTypes[extension] || "application/octet-stream";
// Read through the anchored descriptor, as every read is (lib.ts).
const data = await readFileContent(validPath, "base64");
// Map the MIME type to a valid MCP content block. The spec only allows
// text, image, audio, resource_link, and resource — so non-image/audio
// binaries are returned as an embedded resource (NOT type:"blob", which the
// SDK content-block union rejects on schema validation).
const contentItem = mimeType.startsWith("image/")
? { type: "image" as const, data, mimeType }
: mimeType.startsWith("audio/")
? { type: "audio" as const, data, mimeType }
: {
type: "resource" as const,
resource: {
uri: pathToFileURL(validPath).href,
mimeType,
blob: data,
},
};
return {
content: [contentItem],
structuredContent: { content: [contentItem] },
};
},
);
server.registerTool(
"read_multiple_files",
{
title: "Read Multiple Files",
description:
"Read the contents of multiple files simultaneously. This is more " +
"efficient than reading files one by one when you need to analyze " +
"or compare multiple files. Each file's content is returned with its " +
"path as a reference. Failed reads for individual files won't stop " +
"the entire operation. Only works within allowed directories.",
inputSchema: jsonSchema2020(ReadMultipleFilesArgsSchema.shape),
outputSchema: jsonSchema2020({ content: z.string() }),
annotations: {
readOnlyHint: true,
idempotentHint: true,
destructiveHint: false,
openWorldHint: false,
},
},
async (args: z.infer<typeof ReadMultipleFilesArgsSchema>) => {
const results = await Promise.all(
args.paths.map(async (filePath: string) => {
try {
const validPath = await validatePath(
filePath,
allowedDirectories,
"read",
);
const content = await readFileContent(validPath);
return `${filePath}:\n${content}\n`;
} catch (error) {
const errorMessage =
error instanceof Error ? error.message : String(error);
return `${filePath}: Error - ${errorMessage}`;
}
}),
);
const text = results.join("\n---\n");
return {
content: [{ type: "text" as const, text }],
structuredContent: { content: text },
};
},
);
server.registerTool(
"write_file",
{
title: "Write File",
description:
"Create a new file or completely overwrite an existing file with new content. " +
"Use with caution as it will overwrite existing files without warning. " +
"Handles text content with proper encoding. Only works within allowed directories.",
inputSchema: jsonSchema2020(WriteFileArgsSchema.shape),
outputSchema: jsonSchema2020({ content: z.string() }),
annotations: {
readOnlyHint: false,
idempotentHint: true,
destructiveHint: true,
openWorldHint: false,
},
},
async (args: z.infer<typeof WriteFileArgsSchema>) => {
const validPath = await validatePath(
args.path,
allowedDirectories,
"write",
readOnlyDirectories,
);
await writeFileContent(validPath, args.content);
const text = `Successfully wrote to ${args.path}`;
return {
content: [{ type: "text" as const, text }],
structuredContent: { content: text },
};
},
);
server.registerTool(
"append_file",
{
title: "Append File",
description:
"Append text to the end of a file, creating the file if it does not exist. " +
"The existing content is never changed or replaced. The text is appended exactly " +
"as given, with no newline added before or after it, so end it with a newline " +
"if the next append should start on a new line. Only works within allowed directories.",
inputSchema: jsonSchema2020(AppendFileArgsSchema.shape),
outputSchema: jsonSchema2020({ content: z.string() }),
annotations: {
readOnlyHint: false,
idempotentHint: false,
destructiveHint: false,
openWorldHint: false,
},
},
async (args: z.infer<typeof AppendFileArgsSchema>) => {
const validPath = await validatePath(
args.path,
allowedDirectories,
"write",
readOnlyDirectories,
);
await appendFileContent(validPath, args.content);
const text = `Successfully appended to ${args.path}`;
return {
content: [{ type: "text" as const, text }],
structuredContent: { content: text },
};
},
);
server.registerTool(
"edit_file",
{
title: "Edit File",
description:
"Make line-based edits to a text file. Edits apply in order, each to the " +
"result of the ones before it, and each replaces the first match of its " +
"oldText with newText. oldText must match the file's text exactly, except " +
"that line endings (LF or CRLF) never matter and, when there is no exact " +
"match, a run of whole lines matches if each line is equal once leading and " +
"trailing whitespace is ignored (newText then takes the file's indentation). " +
"Whitespace inside a line must match. If any edit has no match, nothing is " +
"written and the error shows the closest lines of the file, numbered, to " +
"copy oldText from. Returns a git-style diff showing the changes made. " +
"Only works within allowed directories.",
inputSchema: jsonSchema2020(EditFileArgsSchema.shape),
outputSchema: jsonSchema2020({ content: z.string() }),
annotations: {
readOnlyHint: false,
idempotentHint: false,
destructiveHint: true,
openWorldHint: false,
},
},
async (args: z.infer<typeof EditFileArgsSchema>) => {
const validPath = await validatePath(
args.path,
allowedDirectories,
"write",
readOnlyDirectories,
);
const result = await applyFileEdits(validPath, args.edits, args.dryRun);
return {
content: [{ type: "text" as const, text: result }],
structuredContent: { content: result },
};
},
);
server.registerTool(
"create_directory",
{
title: "Create Directory",
description:
"Create a new directory or ensure a directory exists. Can create multiple " +
"nested directories in one operation. If the directory already exists, " +
"this operation will succeed silently. Perfect for setting up directory " +
"structures for projects or ensuring required paths exist. Only works within allowed directories.",
inputSchema: jsonSchema2020(CreateDirectoryArgsSchema.shape),
outputSchema: jsonSchema2020({ content: z.string() }),
annotations: {
readOnlyHint: false,
idempotentHint: true,
destructiveHint: false,
openWorldHint: false,
},
},
async (args: z.infer<typeof CreateDirectoryArgsSchema>) => {
const validPath = await validatePath(
args.path,
allowedDirectories,
"write",
readOnlyDirectories,
);
await createDirectory(validPath);
const text = `Successfully created directory ${args.path}`;
return {
content: [{ type: "text" as const, text }],
structuredContent: { content: text },
};
},
);
server.registerTool(
"list_directory",
{
title: "List Directory",
description:
"List the files and directories directly inside a path, each marked [FILE] or [DIR]. " +
"Use it to see what a directory contains; when you also need each entry's size or " +
"want entries sorted by size, use list_directory_with_sizes instead, and for a " +
"recursive view use directory_tree. Returns one line per entry. Only works within " +
"allowed directories.",
inputSchema: jsonSchema2020(ListDirectoryArgsSchema.shape),
outputSchema: jsonSchema2020({ content: z.string() }),
annotations: {
readOnlyHint: true,
idempotentHint: true,
destructiveHint: false,
openWorldHint: false,
},
},
async (args: z.infer<typeof ListDirectoryArgsSchema>) => {
const validPath = await validatePath(
args.path,
allowedDirectories,
"read",
);
const entries = await listValidatedDirectory(validPath, false);
const formatted = entries
.map(
(entry) =>
`${entry.isDirectory() ? "[DIR]" : "[FILE]"} ${entry.name}`,
)
.join("\n");
return {
content: [{ type: "text" as const, text: formatted }],
structuredContent: { content: formatted },
};
},
);
server.registerTool(
"list_directory_with_sizes",
{
title: "List Directory with Sizes",
description:
"List the files and directories directly inside a path with each file's size, " +
"marked [FILE] or [DIR], sorted by name or by size, largest first (sortBy). Use it " +
"when sizes matter, such as finding the largest files; for names only, use " +
"list_directory, which returns less text. Returns one line per entry, followed by " +
"the totals. Only works within allowed directories.",
inputSchema: jsonSchema2020(ListDirectoryWithSizesArgsSchema.shape),
outputSchema: jsonSchema2020({ content: z.string() }),
annotations: {
readOnlyHint: true,
idempotentHint: true,
destructiveHint: false,
openWorldHint: false,
},
},
async (args: z.infer<typeof ListDirectoryWithSizesArgsSchema>) => {
const validPath = await validatePath(
args.path,
allowedDirectories,
"read",
);
const entries = await listValidatedDirectory(validPath, false);
// Get detailed information for each entry; size is undefined when the
// entry could not be stat'd
type SizedEntry = {
name: string;
isDirectory: boolean;
size: number | undefined;
};
const detailedEntries = await Promise.all(
entries.map(async (entry): Promise<SizedEntry> => {
const entryPath = path.join(validPath, entry.name);
try {
// Validate each entry, so a symlink whose target is outside the
// allowed directories is listed with no size rather than the
// target's; the size is then read from the resolved entry,
// anchored to its directory (lib.ts).
const validEntryPath = await validatePath(
entryPath,
allowedDirectories,
"read",
);
const stats = await getFileStats(validEntryPath);
return {
name: entry.name,
isDirectory: entry.isDirectory(),
size: stats.size,
};
} catch {
// The entry could not be stat'd (unreadable, a dangling symlink,
// removed since readdir, or outside the allowed directories).
// Its size is unknown, not 0: inventing one would list it as an
// empty file and count it in the total (#5190).
return {
name: entry.name,
isDirectory: entry.isDirectory(),
size: undefined,
};
}
}),
);
// Sort entries based on sortBy parameter
const sortedEntries = [...detailedEntries].sort((a, b) => {
if (args.sortBy === "size") {
// Descending by size; an entry of unknown size sorts last
return (b.size ?? -1) - (a.size ?? -1);
}
// Default sort by name
return a.name.localeCompare(b.name);
});
// Format the output
const formattedEntries = sortedEntries.map(
(entry) =>
`${entry.isDirectory ? "[DIR]" : "[FILE]"} ${entry.name.padEnd(30)} ${
entry.isDirectory
? ""
: (entry.size === undefined
? "unknown"
: formatSize(entry.size)
).padStart(10)
}`,
);
// Add summary
const totalFiles = detailedEntries.filter((e) => !e.isDirectory).length;
const totalDirs = detailedEntries.filter((e) => e.isDirectory).length;
const totalSize = detailedEntries.reduce(
(sum, entry) => sum + (entry.isDirectory ? 0 : (entry.size ?? 0)),
0,
);
const unknownFiles = detailedEntries.filter(
(e) => !e.isDirectory && e.size === undefined,
).length;
const summary = [
"",
`Total: ${totalFiles} files, ${totalDirs} directories`,
`Combined size: ${formatSize(totalSize)}` +
(unknownFiles > 0
? ` (excludes ${unknownFiles} ${unknownFiles === 1 ? "file" : "files"} of unknown size)`
: ""),
];
const text = [...formattedEntries, ...summary].join("\n");
const contentBlock = { type: "text" as const, text };
return {
content: [contentBlock],
structuredContent: { content: text },
};
},
);
server.registerTool(
"directory_tree",
{
title: "Directory Tree",
description:
"Get a recursive tree view of files and directories as a JSON structure. " +
"Each entry includes 'name', 'type' (file/directory), and 'children' for directories. " +
"Files have no children array, while directories always have a children array (which may be empty), " +
"except at the last level when 'depth' limits the tree: those directories are not read and have no children array. " +
"The output is formatted with 2-space indentation for readability. Only works within allowed directories.",
inputSchema: jsonSchema2020(DirectoryTreeArgsSchema.shape),
outputSchema: jsonSchema2020({ content: z.string() }),
annotations: {
readOnlyHint: true,
idempotentHint: true,
destructiveHint: false,
openWorldHint: false,
},
},
async (args: z.infer<typeof DirectoryTreeArgsSchema>) => {
interface TreeEntry {
name: string;
type: "file" | "directory";
children?: TreeEntry[];
}
const rootPath = args.path;
const visit = createEntryBudget("directory_tree", rootPath);
// `level` is the depth of currentPath's entries: 1 for those directly
// in the requested path. A directory at the depth limit is listed but
// not read, so its subtree costs no readdir and no entry budget (#1077).
async function buildTree(
currentPath: string,
excludePatterns: string[] = [],
level: number = 1,
): Promise<TreeEntry[]> {
const validPath = await validatePath(
currentPath,
allowedDirectories,
"read",
);
const entries = await listValidatedDirectory(validPath, true);
const result: TreeEntry[] = [];
for (const entry of entries) {
const relativePath = path.relative(
rootPath,
path.join(currentPath, entry.name),
);
if (
isExcludedPath(relativePath, excludePatterns, entry.isDirectory())
)
continue;
// Counted after the exclude check, so excluded subtrees cost
// nothing; the cap and the readdir timeout keep one call from
// walking an unbounded or stalled tree (#4162).
visit();
const entryData: TreeEntry = {
name: entry.name,
type: entry.isDirectory() ? "directory" : "file",
};
if (
entry.isDirectory() &&
(args.depth === undefined || level < args.depth)
) {
const subPath = path.join(currentPath, entry.name);
entryData.children = await buildTree(
subPath,
excludePatterns,
level + 1,
);
}
result.push(entryData);
}
return result;
}
const treeData = await buildTree(rootPath, args.excludePatterns);
const text = JSON.stringify(treeData, null, 2);
const contentBlock = { type: "text" as const, text };
return {
content: [contentBlock],
structuredContent: { content: text },
};
},
);
server.registerTool(
"move_file",
{
title: "Move File",
description:
"Move or rename files and directories. Can move files between directories " +
"and rename them in a single operation. If the destination exists, the " +
"operation will fail. Works across different directories and can be used " +
"for simple renaming within the same directory. Both source and destination must be within allowed directories.",
inputSchema: jsonSchema2020(MoveFileArgsSchema.shape),
outputSchema: jsonSchema2020({ content: z.string() }),
annotations: {
readOnlyHint: false,
idempotentHint: false,
destructiveHint: true,
openWorldHint: false,
},
},
async (args: z.infer<typeof MoveFileArgsSchema>) => {
const validSourcePath = await validatePath(
args.source,
allowedDirectories,
"move",
readOnlyDirectories,
);
const validDestPath = await validatePath(
args.destination,
allowedDirectories,
"move",
readOnlyDirectories,
);
await moveFile(validSourcePath, validDestPath);
const text = `Successfully moved ${args.source} to ${args.destination}`;
const contentBlock = { type: "text" as const, text };
return {
content: [contentBlock],
structuredContent: { content: text },
};
},
);
server.registerTool(
"copy_file",
{
title: "Copy File",
description:
"Copy a file to a new location, without reading its content into the conversation. " +
"Copies one regular file, keeping its permissions and modification time; directories " +
"are not copied. If the destination exists, the operation will fail: it never " +
"overwrites. Both source and destination must be within allowed directories.",
inputSchema: jsonSchema2020(CopyFileArgsSchema.shape),
outputSchema: jsonSchema2020({ content: z.string() }),
annotations: {
readOnlyHint: false,
idempotentHint: true,