read_file
Read text file contents to access and analyze stored information for file system exploration and data retrieval tasks.
Instructions
Read the contents of a text file
Input Schema
TableJSON Schema
| Name | Required | Description | Default |
|---|---|---|---|
| path | Yes | The file path to read |
Implementation Reference
- src/index.ts:270-295 (handler)Main execution logic for the read_file tool: validates input with schema, sanitizes path, checks if file (not dir), enforces 1MB size limit, reads content with fs.readFile, and formats response with metadata.case "read_file": { const { path: filePath } = ReadFileArgsSchema.parse(args); const safePath = validatePath(filePath); const stats = await fs.stat(safePath); if (stats.isDirectory()) { throw new Error("Cannot read a directory as a file"); } // Check file size to prevent reading huge files const maxSize = 1024 * 1024; // 1MB limit if (stats.size > maxSize) { throw new Error(`File too large (${formatFileSize(stats.size)}). Maximum size is ${formatFileSize(maxSize)}`); } const content = await fs.readFile(safePath, 'utf-8'); return { content: [ { type: "text", text: `File: ${safePath}\nSize: ${formatFileSize(stats.size)}\nModified: ${stats.mtime.toLocaleString()}\n\n--- Content ---\n${content}` } ] }; }
- src/index.ts:36-38 (schema)Zod schema for validating read_file tool arguments: requires a 'path' string.const ReadFileArgsSchema = z.object({ path: z.string().describe("The file path to read") });
- src/index.ts:158-171 (registration)Tool registration in ListToolsRequestHandler response, defining name, description, and input schema matching the Zod schema.{ name: "read_file", description: "Read the contents of a text file", inputSchema: { type: "object", properties: { path: { type: "string", description: "The file path to read" } }, required: ["path"] } },
- src/index.ts:52-60 (helper)Helper function to safely resolve file paths using path.resolve to prevent directory traversal attacks.function validatePath(inputPath: string): string { // Resolve the path to prevent directory traversal const resolved = path.resolve(inputPath); // For security, you might want to restrict to certain directories // This is a basic example - in production, implement proper access controls return resolved; }
- src/index.ts:65-70 (helper)Helper utility to format file sizes in human-readable units (B, KB, MB, etc.), used in error messages and response metadata.function formatFileSize(bytes: number): string { const sizes = ['B', 'KB', 'MB', 'GB', 'TB']; if (bytes === 0) return '0 B'; const i = Math.floor(Math.log(bytes) / Math.log(1024)); return Math.round(bytes / Math.pow(1024, i) * 100) / 100 + ' ' + sizes[i]; }