read_file
Retrieve and display the entire content of a file from the filesystem. Supports multiple text encodings and provides precise error feedback. Ensures access is restricted to predefined directories for security.
Instructions
Read the complete contents of a file from the file system. 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. Only works within allowed directories.
Input Schema
TableJSON Schema
| Name | Required | Description | Default |
|---|---|---|---|
| encoding | No | File encoding | utf-8 |
| path | Yes | Path to the file to read |
Implementation Reference
- src/utils/tools.ts:38-65 (handler)The main handler function that validates the path, checks file size, reads the file content using fs.readFile, handles errors, and returns the content as string.export async function readFile( args: z.infer<typeof ReadFileArgsSchema>, config: Config ): Promise<string> { const endMetric = metrics.startOperation('read_file') try { const validPath = await validatePath(args.path, config) // Validate file size before reading if (config.security.maxFileSize > 0) { await validateFileSize(validPath, config.security.maxFileSize) } const content = await fs.readFile(validPath, args.encoding) await logger.debug(`Successfully read file: ${validPath}`) endMetric() return content } catch (error) { metrics.recordError('read_file') if ((error as NodeJS.ErrnoException).code === 'ENOENT') { throw new PathNotFoundError(args.path) } throw error } }
- src/utils/tools.ts:22-29 (schema)Zod schema defining the input arguments: path (required string) and optional encoding (utf-8, utf8, base64, defaults to utf-8).export const ReadFileArgsSchema = z.object({ path: z.string().describe('Path to the file to read'), encoding: z .enum(['utf-8', 'utf8', 'base64']) .optional() .default('utf-8') .describe('File encoding'), })
- src/index.ts:236-243 (registration)Tool registration in the list_tools response: defines name, description, and converts schema to JSON schema for MCP protocol.name: 'read_file', description: 'Read the complete contents of a file from the file system. ' + '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. Only works within allowed directories.', inputSchema: zodToJsonSchema(ReadFileArgsSchema) as ToolInput, },
- src/index.ts:400-414 (registration)Dispatch handler in the CallToolRequest switch: parses input with schema, calls the readFile handler, returns content as MCP response.case 'read_file': { const parsed = ReadFileArgsSchema.safeParse(a) if (!parsed.success) { throw new FileSystemError(`Invalid arguments for ${name}`, 'INVALID_ARGS', undefined, { errors: parsed.error.format(), }) } const content = await readFile(parsed.data, config) endMetric() return { content: [{ type: 'text', text: content }], } }