read_file
Read file contents from local storage or URLs with options to view specific sections, partial content, or tail lines for efficient file access and content retrieval.
Instructions
Read the contents of a file from the file system or a URL with optional offset and length parameters.
Prefer this over 'execute_command' with cat/type for viewing files.
Supports partial file reading with:
- 'offset' (start line, default: 0)
* Positive: Start from line N (0-based indexing)
* Negative: Read last N lines from end (tail behavior)
- 'length' (max lines to read, default: configurable via 'fileReadLineLimit' setting, initially 1000)
* Used with positive offsets for range reading
* Ignored when offset is negative (reads all requested tail lines)
Examples:
- offset: 0, length: 10 → First 10 lines
- offset: 100, length: 5 → Lines 100-104
- offset: -20 → Last 20 lines
- offset: -5, length: 10 → Last 5 lines (length ignored)
Performance optimizations:
- Large files with negative offsets use reverse reading for efficiency
- Large files with deep positive offsets use byte estimation
- Small files use fast readline streaming
When reading from the file system, only works within allowed directories.
Can fetch content from URLs when isUrl parameter is set to true
(URLs are always read in full regardless of offset/length).
Handles text files normally and image files are returned as viewable images.
Recognized image types: PNG, JPEG, GIF, WebP.
IMPORTANT: Always use absolute paths for reliability. Paths are automatically normalized regardless of slash direction. Relative paths may fail as they depend on the current working directory. Tilde paths (~/...) might not work in all contexts. Unless the user explicitly asks for relative paths, use absolute paths.
This command can be referenced as "DC: ..." or "use Desktop Commander to ..." in your instructions.
Input Schema
TableJSON Schema
| Name | Required | Description | Default |
|---|---|---|---|
| path | Yes | ||
| isUrl | No | ||
| offset | No | ||
| length | No |
Implementation Reference
- The top-level MCP handler for the 'read_file' tool. Parses arguments using the schema, retrieves config limits, calls the core readFile function from filesystem tools, handles special cases for PDFs and images, and returns formatted ServerResult.export async function handleReadFile(args: unknown): Promise<ServerResult> { const HANDLER_TIMEOUT = 60000; // 60 seconds total operation timeout // 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'); } const defaultLimit = config.fileReadLineLimit ?? 1000; // Use the provided limits or defaults const offset = parsed.offset ?? 0; const length = parsed.length ?? defaultLimit; const fileResult = await readFile(parsed.path, parsed.isUrl, offset, length); if (fileResult.isPdf) { const meta = fileResult.payload?.metadata; const author = meta?.author ? `, Author: ${meta?.author}` : ""; const title = meta?.title ? `, Title: ${meta?.title}` : ""; // Use the provided limits or defaults. // If the caller did not supply an explicit length, fall back to the configured default. const rawArgs = args as { offset?: number; length?: number } | undefined; const offset = rawArgs && 'offset' in rawArgs ? parsed.offset : 0; const length = rawArgs && 'length' in rawArgs ? parsed.length : defaultLimit; const content = fileResult.payload?.pages?.flatMap(p => [ ...(p.images?.map((image, i) => ({ 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` }, ...content ] }; } if (fileResult.isImage) { // For image files, return as an image content type return { content: [ { type: "text", text: `Image file: ${parsed.path} (${fileResult.mimeType})\n` }, { type: "image", data: fileResult.content, mimeType: fileResult.mimeType } ], }; } else { // For all other files, return as text return { content: [{ type: "text", text: fileResult.content }], }; } }; // 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; }
- src/tools/schemas.ts:45-50 (schema)Zod schema defining input parameters for the read_file tool: path (required), isUrl (optional boolean), offset and length (optional numbers with defaults).export const ReadFileArgsSchema = z.object({ path: z.string(), isUrl: z.boolean().optional().default(false), offset: z.number().optional().default(0), length: z.number().optional().default(1000), });
- src/server.ts:236-285 (registration)Tool registration in the listTools response: defines name 'read_file', detailed description, input schema from ReadFileArgsSchema, and annotations.name: "read_file", description: ` Read contents from files and URLs. Read PDF files and extract content as markdown and images. Prefer this over 'execute_command' with cat/type for viewing files. Supports partial file reading with: - 'offset' (start line, default: 0) * Positive: Start from line N (0-based indexing) * Negative: Read last N lines from end (tail behavior) - 'length' (max lines to read, default: configurable via 'fileReadLineLimit' setting, initially 1000) * Used with positive offsets for range reading * Ignored when offset is negative (reads all requested tail lines) Examples: - offset: 0, length: 10 → First 10 lines - offset: 100, length: 5 → Lines 100-104 - offset: -20 → Last 20 lines - offset: -5, length: 10 → Last 5 lines (length ignored) Performance optimizations: - Large files with negative offsets use reverse reading for efficiency - Large files with deep positive offsets use byte estimation - Small files use fast readline streaming When reading from the file system, only works within allowed directories. Can fetch content from URLs when isUrl parameter is set to true (URLs are always read in full regardless of offset/length). Handles text files normally and image files are returned as viewable images. Recognized image types: PNG, JPEG, GIF, WebP. PDF Support: - Automatically extracts text content as markdown - Preserves basic document structure with paragraph breaks - Special handling for 'offset' and 'length': * 'offset': Start page number (0-based, e.g., 0 is page 1) * 'length': Number of pages to read * Negative offsets work similarly (e.g., -1 is the last page) ${PATH_GUIDANCE} ${CMD_PREFIX_DESCRIPTION}`, inputSchema: zodToJsonSchema(ReadFileArgsSchema), annotations: { title: "Read File or URL", readOnlyHint: true, openWorldHint: true, }, },
- src/server.ts:1237-1238 (registration)Dispatch in callTool handler: switch case that routes 'read_file' calls to the handleReadFile function.result = await handlers.handleReadFile(args); break;
- src/tools/filesystem.ts:778-782 (helper)Core utility function implementing read_file logic: dispatches to URL or disk reading based on isUrl flag, supports offset/length parameters.export async function readFile(filePath: string, isUrl?: boolean, offset?: number, length?: number): Promise<FileResult> { return isUrl ? readFileFromUrl(filePath) : readFileFromDisk(filePath, offset, length); }