/**
* Tool: file_reader
* Read file contents from the filesystem
*/
import fs from "fs";
import path from "path";
export const fileReaderTool = async (args) => {
try {
const filePath = args.path;
const encoding = args.encoding || "utf-8";
// Validate path
if (!filePath || typeof filePath !== "string") {
return {
error: "Invalid path",
message: "Path must be a non-empty string",
};
}
// Resolve to absolute path
const absolutePath = path.resolve(filePath);
// Security: Prevent directory traversal
if (!absolutePath.startsWith(path.resolve("/"))) {
return {
error: "Invalid path",
message: "Path must be absolute or relative to root",
};
}
// Check if file exists
if (!fs.existsSync(absolutePath)) {
return {
error: "File not found",
path: absolutePath,
};
}
// Check if it's a file (not a directory)
const stats = fs.statSync(absolutePath);
if (stats.isDirectory()) {
return {
error: "Path is a directory, not a file",
path: absolutePath,
tip: "Use the file path pointing to a specific file",
};
}
// Check file size (limit to 10MB for safety)
const maxSize = 10 * 1024 * 1024; // 10MB
if (stats.size > maxSize) {
return {
error: "File too large",
path: absolutePath,
size: `${Math.round(stats.size / (1024 * 1024))} MB`,
maxAllowed: "10 MB",
};
}
// Read file
const content = fs.readFileSync(absolutePath, encoding);
return {
path: absolutePath,
size: `${stats.size} bytes`,
modified: stats.mtime.toISOString(),
content,
encoding,
};
}
catch (error) {
const errorMsg = error instanceof Error ? error.message : String(error);
return {
error: "Failed to read file",
details: errorMsg,
};
}
};
export const fileReaderToolDefinition = {
name: "file_reader",
description: "Read the contents of a file from the filesystem",
inputSchema: {
type: "object",
properties: {
path: {
type: "string",
description: "Absolute or relative path to the file to read",
},
encoding: {
type: "string",
description: "File encoding (default: utf-8)",
},
},
required: ["path"],
},
};
//# sourceMappingURL=file_reader.js.map