Repository navigation
Expand file tree
/
Copy pathfilesystem-handlers.ts
More file actions
507 lines (465 loc) · 19.5 KB
/
Copy pathfilesystem-handlers.ts
File metadata and controls
507 lines (465 loc) · 19.5 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
import {
readFile,
readMultipleFiles,
writeFile,
createDirectory,
listDirectory,
moveFile,
getFileInfo,
writePdf,
getDefaultEditorMetadata,
type FileResult,
type MultiFileResult
} from '../tools/filesystem.js';
import type { ReadOptions } from '../utils/files/base.js';
import { TextFileHandler } from '../utils/files/text.js';
import { ServerResult } from '../types.js';
import { withTimeout } from '../utils/withTimeout.js';
import { createErrorResponse } from '../error-handlers.js';
import { configManager } from '../config-manager.js';
import {
ReadFileArgsSchema,
ReadMultipleFilesArgsSchema,
WriteFileArgsSchema,
CreateDirectoryArgsSchema,
ListDirectoryArgsSchema,
MoveFileArgsSchema,
GetFileInfoArgsSchema,
WritePdfArgsSchema
} from '../tools/schemas.js';
import path from 'path';
import os from 'os';
import { resolvePreviewFileType } from '../ui/file-preview/shared/preview-file-types.js';
/**
* Expand home directory (~) in a file path
*/
function expandHome(filePath: string): string {
if (filePath === '~' || filePath.startsWith('~/') || filePath.startsWith(`~${path.sep}`)) {
return path.join(os.homedir(), filePath.slice(1));
}
return filePath;
}
/**
* Resolve a file path to an absolute path for use in structured content.
* This ensures "Open in folder" always has a valid absolute path.
*/
export function resolveAbsolutePath(filePath: string): string {
const expanded = expandHome(filePath);
return path.isAbsolute(expanded)
? path.resolve(expanded)
: path.resolve(process.cwd(), expanded);
}
/**
* Helper function to check if path contains an error
*/
function isErrorPath(filePath: string): boolean {
return filePath.startsWith('__ERROR__:');
}
/**
* Extract error message from error path
*/
function getErrorFromPath(path: string): string {
return path.substring('__ERROR__:'.length).trim();
}
/**
* Handle read_file command
*/
export async function handleReadFile(args: unknown): Promise<ServerResult> {
// Backstop for the whole handler operation. The real control is the
// 3-minute cancellable read timeout inside readFileFromDisk; this sits just
// above it (so that one fires first, with cleanup + a useful error) but
// still below the MCP client's ~4-minute hard cap, so we never leave the
// client hanging on an opaque timeout.
const HANDLER_TIMEOUT = 3.5 * 60 * 1000; // 3m30s
// Add input validation
if (args === null || args === undefined) {
return createErrorResponse('No arguments provided for read_file command');
}
const readFileOperation = async () => {
const parsed = ReadFileArgsSchema.parse(args);
// Get the configuration for file read limits
const config = await configManager.getConfig();
if (!config) {
return createErrorResponse('Configuration not available');
}
// The schema fills in `length: 1000` (the default tools/list shows), so
// whether the caller sent a length is read from the raw arguments: an
// omitted length follows the fileReadLineLimit setting, as documented.
const defaultLimit = config.fileReadLineLimit ?? 1000;
const lengthGiven = (args as { length?: unknown }).length !== undefined;
// The sheet goes as given: the Excel handler knows the sheet names, so it
// decides whether "2024" is an index or a sheet named 2024
const options: ReadOptions = {
isUrl: parsed.isUrl,
offset: parsed.offset ?? 0,
length: lengthGiven ? parsed.length : defaultLimit,
sheet: parsed.sheet,
range: parsed.range,
// The preview widget draws an SVG as an image (ui/file-preview/src/image-preview.ts);
// everyone else reads it as the text it is
svgAsImage: parsed.origin === 'ui'
};
// Resolve to absolute path for local files (not URLs) so "Open in folder" works
const resolvedFilePath = parsed.isUrl
? parsed.path
: resolveAbsolutePath(parsed.path);
const fileResult = await readFile(parsed.path, options);
// Handle PDF files
if (fileResult.metadata?.isPdf) {
const meta = fileResult.metadata;
const author = meta?.author ? `, Author: ${meta?.author}` : "";
const title = meta?.title ? `, Title: ${meta?.title}` : "";
const pdfContent = fileResult.metadata?.pages?.flatMap((p: any) => [
...(p.images?.map((image: any) => ({
type: "image",
data: image.data,
mimeType: image.mimeType
})) ?? []),
{
type: "text",
text: `<!-- Page: ${p.pageNumber} -->\n${p.text}`,
},
]) ?? [];
return {
content: [
{
type: "text",
text: `PDF file: ${parsed.path}${author}${title} (${meta?.totalPages} pages) \n`
},
...pdfContent
],
...(parsed.origin === 'ui' ? {
structuredContent: {
fileName: path.basename(resolvedFilePath),
filePath: resolvedFilePath,
fileType: 'unsupported' as const,
...await getDefaultEditorMetadata(resolvedFilePath),
},
} : {}),
};
}
// Handle image files
if (fileResult.metadata?.isImage) {
// Return the image bytes in the MCP content array so the host model can
// actually see the image. The preview widget gets its copy from its own
// origin:'ui' read — structuredContent stays metadata-only.
const imageData = typeof fileResult.content === 'string'
? fileResult.content
: fileResult.content.toString('base64');
const imageSummary = `Image file: ${parsed.path} (${fileResult.mimeType})\n`;
const imageStructuredContent = {
fileName: path.basename(resolvedFilePath),
filePath: resolvedFilePath,
fileType: 'image' as const,
...await getDefaultEditorMetadata(resolvedFilePath),
mimeType: fileResult.mimeType,
};
// Widget pull (origin: 'ui'): return the base64 in a TEXT block, never
// an image block. An image content block makes the host inline-vision-
// render the result, which preempts delivery of this RPC response to
// the widget — leaving the preview stuck on "Preparing preview…" for
// exactly the host-rendered types (png/jpeg/gif/webp). Text-only lets
// the RPC response through so the widget can draw the <img>.
if (parsed.origin === 'ui') {
return {
content: [{ type: "text", text: imageData }],
structuredContent: imageStructuredContent,
};
}
// Model-facing read: keep the image block so the host/model sees it.
// No structuredContent — the widget renders from its own origin:'ui'
// read, and nothing else consumes it.
return {
content: [
{
type: "text",
text: imageSummary
},
{
type: "image",
data: imageData,
mimeType: fileResult.mimeType
}
],
};
} else {
// For all other files, return as text.
// structuredContent carries only file metadata (no content duplication);
// the widget reads text from the MCP content array (over the RPC read).
let textContent = typeof fileResult.content === 'string'
? fileResult.content
: fileResult.content.toString('utf8');
const fileType = fileResult.metadata?.isDirectory ? 'directory' as const : resolvePreviewFileType(resolvedFilePath);
// The directory fallback prefixes a "use list_directory instead" hint
// for the LLM. The widget's own read (a list_directory preview pulls
// read_file on the dir path) would render that hint as a notice — strip it.
if (parsed.origin === 'ui' && fileType === 'directory') {
textContent = textContent.replace(/^This is a directory, not a file\.[^\n]*\n+/, '');
}
return {
content: [{ type: "text", text: textContent }],
...(parsed.origin === 'ui' ? {
structuredContent: {
fileName: path.basename(resolvedFilePath),
filePath: resolvedFilePath,
fileType,
...await getDefaultEditorMetadata(resolvedFilePath),
},
} : {}),
};
}
};
// Execute with timeout at the handler level
const result = await withTimeout(
readFileOperation(),
HANDLER_TIMEOUT,
'Read file handler operation',
null
);
if (result == null) {
// Handles the impossible case where withTimeout resolves to null instead of throwing
throw new Error('Failed to read the file');
}
return result;
}
/**
* Handle read_multiple_files command
*/
export async function handleReadMultipleFiles(args: unknown): Promise<ServerResult> {
const parsed = ReadMultipleFilesArgsSchema.parse(args);
const fileResults = await readMultipleFiles(parsed.paths);
// Create a text summary of all files
const textSummary = fileResults.map(result => {
if (result.error) {
return `${result.path}: Error - ${result.error}`;
} else if (result.isPdf) {
return `${result.path}: PDF file with ${result.payload?.pages?.length} pages`;
} else if (result.mimeType) {
return `${result.path}: ${result.mimeType} ${result.isImage ? '(image)' : '(text)'}`;
} else {
return `${result.path}: Unknown type`;
}
}).join("\n");
// Create content items for each file
const contentItems: Array<{ type: string, text?: string, data?: string, mimeType?: string }> = [];
// Add the text summary
contentItems.push({ type: "text", text: textSummary });
// Add each file content after its path: several images, or a PDF's pages,
// can't be told apart by their order alone
for (const result of fileResults) {
if (!result.error && result.content !== undefined) {
const header = `\n--- ${result.path} contents: ---\n`;
if (result.isPdf) {
contentItems.push({ type: "text", text: header });
result.payload?.pages.forEach((page, i) => {
page.images.forEach((image, i) => {
contentItems.push({
type: "image",
data: image.data,
mimeType: image.mimeType
});
});
contentItems.push({
type: "text",
text: page.text,
});
});
} else if (result.isImage && result.mimeType) {
// For image files, add an image content item
contentItems.push({ type: "text", text: header });
contentItems.push({
type: "image",
data: result.content,
mimeType: result.mimeType
});
} else {
// For text files, add a text summary
contentItems.push({
type: "text",
text: `${header}${result.content}`
});
}
}
}
return { content: contentItems };
}
/**
* Handle write_file command
*/
export async function handleWriteFile(args: unknown): Promise<ServerResult> {
try {
const modeProvided = !!(args && typeof args === 'object' && 'mode' in args);
const parsed = WriteFileArgsSchema.parse(args);
// An omitted `mode` falls back to 'rewrite', which silently destroys
// the target's existing content. The common failure is an LLM caller
// intending to append but dropping the optional param (issue #541), so
// require explicit intent when the target already has content;
// new/empty files keep the zero-friction default.
if (!modeProvided) {
let existing: Record<string, any> | null = null;
try {
existing = await getFileInfo(parsed.path);
} catch {
// Missing file or invalid path — nothing to protect; the write
// itself will surface any real path error.
}
if (existing?.isFile && existing.size > 0) {
return createErrorResponse(
`Write rejected to prevent accidental data loss: ${parsed.path} already exists ` +
`with content (${existing.size} bytes), and no 'mode' was specified — the default ` +
`mode 'rewrite' would REPLACE the entire file. Retry with an explicit mode: ` +
`'append' to add your content to the end of the existing file, or 'rewrite' ` +
`to replace all existing content.`
);
}
}
// Get the line limit from configuration
const config = await configManager.getConfig();
const MAX_LINES = config.fileWriteLineLimit ?? 50; // Default to 50 if not set
// Lines as read_file counts them: a final line break doesn't start another line
const lineCount = TextFileHandler.countLines(parsed.content);
let errorMessage = "";
if (lineCount > MAX_LINES) {
errorMessage = `✅ File written successfully! (${lineCount} lines)
💡 Performance tip: For optimal speed, consider chunking files into ≤30 line pieces in future operations.`;
}
// Pass the mode parameter to writeFile
await writeFile(parsed.path, parsed.content, parsed.mode);
// Provide more informative message based on mode
const modeMessage = parsed.mode === 'append' ? 'appended to' : 'wrote to';
// No structuredContent: nothing in the UI calls write_file (the widget
// previews the write via its own read_file pull at tool-result time).
return {
content: [{
type: "text",
text: `Successfully ${modeMessage} ${parsed.path} (${lineCount} lines) ${errorMessage}`
}],
};
} catch (error) {
const errorMessage = error instanceof Error ? error.message : String(error);
return createErrorResponse(errorMessage);
}
}
/**
* Handle create_directory command
*/
export async function handleCreateDirectory(args: unknown): Promise<ServerResult> {
try {
const parsed = CreateDirectoryArgsSchema.parse(args);
await createDirectory(parsed.path);
return {
content: [{ type: "text", text: `Successfully created directory ${parsed.path}` }],
};
} catch (error) {
const errorMessage = error instanceof Error ? error.message : String(error);
return createErrorResponse(errorMessage);
}
}
/**
* Handle list_directory command
*/
export async function handleListDirectory(args: unknown): Promise<ServerResult> {
try {
const startTime = Date.now();
const parsed = ListDirectoryArgsSchema.parse(args);
const entries = await listDirectory(parsed.path, parsed.depth);
const duration = Date.now() - startTime;
const resultText = entries.join('\n');
const resolvedPath = resolveAbsolutePath(parsed.path);
return {
content: [{ type: "text", text: resultText }],
...(parsed.origin === 'ui' ? {
structuredContent: {
fileName: path.basename(resolvedPath),
filePath: resolvedPath,
fileType: 'directory' as const,
},
} : {}),
};
} catch (error) {
const errorMessage = error instanceof Error ? error.message : String(error);
return createErrorResponse(errorMessage);
}
}
/**
* Handle move_file command
*/
export async function handleMoveFile(args: unknown): Promise<ServerResult> {
try {
const parsed = MoveFileArgsSchema.parse(args);
await moveFile(parsed.source, parsed.destination);
return {
content: [{ type: "text", text: `Successfully moved ${parsed.source} to ${parsed.destination}` }],
};
} catch (error) {
const errorMessage = error instanceof Error ? error.message : String(error);
return createErrorResponse(errorMessage);
}
}
/**
* Format a value for display, handling objects and arrays
*/
function formatValue(value: unknown, indent: string = ''): string {
if (value === null || value === undefined) {
return String(value);
}
if (Array.isArray(value)) {
if (value.length === 0) return '[]';
// For arrays of objects (like sheets), format each item
const items = value.map((item, i) => {
if (typeof item === 'object' && item !== null) {
const props = Object.entries(item)
.map(([k, v]) => `${k}: ${v}`)
.join(', ');
return `${indent} [${i}] { ${props} }`;
}
return `${indent} [${i}] ${item}`;
});
return `\n${items.join('\n')}`;
}
if (typeof value === 'object') {
return JSON.stringify(value);
}
return String(value);
}
/**
* Handle get_file_info command
*/
export async function handleGetFileInfo(args: unknown): Promise<ServerResult> {
try {
const parsed = GetFileInfoArgsSchema.parse(args);
const info = await getFileInfo(parsed.path);
// Generic formatting for any file type
const formattedText = Object.entries(info)
.map(([key, value]) => `${key}: ${formatValue(value)}`)
.join('\n');
return {
content: [{
type: "text",
text: formattedText
}],
};
} catch (error) {
const errorMessage = error instanceof Error ? error.message : String(error);
return createErrorResponse(errorMessage);
}
}
// Use get_config to retrieve the allowedDirectories configuration
/**
* Handle write_pdf command
*/
export async function handleWritePdf(args: unknown): Promise<ServerResult> {
try {
const parsed = WritePdfArgsSchema.parse(args);
const ignoredOptions = await writePdf(parsed.path, parsed.content, parsed.outputPath, parsed.options);
const targetPath = parsed.outputPath || parsed.path;
return {
content: [{ type: "text", text: `Successfully wrote PDF to ${targetPath}${parsed.outputPath ? `\nOriginal file: ${parsed.path}` : ''}` }],
// Which options were ignored, and why: internal (tests), not sent to the client (see utils/internal-facts.ts)
...(ignoredOptions.length > 0 ? { structuredContent: { ignoredOptions } } : {}),
};
} catch (error) {
const errorMessage = error instanceof Error ? error.message : String(error);
return createErrorResponse(errorMessage);
}
}