Skip to main content
Glama

read_file

Retrieve file contents from a specified path with options for encoding, line ranges, and size limits to access and process text data.

Instructions

Read the contents of a file

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
pathYesPath to the file
encodingNoFile encoding (default: utf-8)
start_lineNoStart line (1-indexed)
end_lineNoEnd line (inclusive)
max_size_kbNoMax file size in KB (default: 10240)

Implementation Reference

  • The core logic for reading files, including validation, file size checks, and optional line range parsing.
    async function readFileImpl(input: ReadFileInput): Promise<ToolResult> {
      try {
        const absolutePath = path.resolve(input.path);
    
        // Check if file exists
        const stats = await fs.stat(absolutePath);
    
        if (!stats.isFile()) {
          return {
            isError: true,
            content: [
              {
                type: 'text',
                text: JSON.stringify({
                  code: 'INVALID_PATH',
                  message: `Path is not a file: ${input.path}`,
                }),
              },
            ],
          };
        }
    
        // Check file size
        const maxBytes = input.max_size_kb * 1024;
        if (stats.size > maxBytes) {
          return {
            isError: true,
            content: [
              {
                type: 'text',
                text: JSON.stringify({
                  code: 'FILE_TOO_LARGE',
                  message: `File size ${stats.size} bytes exceeds limit of ${maxBytes} bytes`,
                  details: {
                    file_size: stats.size,
                    limit: maxBytes,
                  },
                }),
              },
            ],
          };
        }
    
        // Read file content
        const content = await fs.readFile(absolutePath, {
          encoding: input.encoding as BufferEncoding,
        });
    
        // Handle line ranges if specified
        let result = content;
        if (input.start_line !== undefined || input.end_line !== undefined) {
          const lines = content.split('\n');
          const startIdx = (input.start_line ?? 1) - 1;
          const endIdx = input.end_line ?? lines.length;
          result = lines.slice(startIdx, endIdx).join('\n');
        }
    
        return {
          content: [
            {
              type: 'text',
              text: result,
            },
          ],
        };
      } catch (error) {
        const err = error as NodeJS.ErrnoException;
    
        if (err.code === 'ENOENT') {
          return {
            isError: true,
            content: [
              {
                type: 'text',
                text: JSON.stringify({
                  code: 'FILE_NOT_FOUND',
                  message: `File not found: ${input.path}`,
                }),
              },
            ],
          };
        }
    
        if (err.code === 'EACCES') {
          return {
            isError: true,
            content: [
              {
                type: 'text',
                text: JSON.stringify({
                  code: 'PERMISSION_DENIED',
                  message: `Permission denied: ${input.path}`,
                }),
              },
            ],
          };
        }
    
        return {
          isError: true,
          content: [
            {
              type: 'text',
              text: JSON.stringify({
                code: 'UNKNOWN_ERROR',
                message: `Error reading file: ${err.message}`,
              }),
            },
          ],
        };
      }
    }
  • Registration of the 'read_file' tool with the MCP server using zod schema validation.
    // read_file tool
    server.tool(
      'read_file',
      'Read the contents of a file',
      {
        path: z.string().describe('Path to the file'),
        encoding: z.string().optional().describe('File encoding (default: utf-8)'),
        start_line: z.number().optional().describe('Start line (1-indexed)'),
        end_line: z.number().optional().describe('End line (inclusive)'),
        max_size_kb: z.number().optional().describe('Max file size in KB (default: 10240)'),
      },
      async (args) => {
        const input = ReadFileInputSchema.parse(args);
        return await readFileImpl(input);
      }
    );
Behavior2/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

No annotations are provided, so the description carries full burden for behavioral disclosure. While 'Read' implies a read-only operation, it doesn't specify permissions needed, error handling for missing files, or output format. It mentions 'contents' but not whether it returns text, binary data, or structured content. For a tool with 5 parameters and no annotations, this is insufficient behavioral context.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is a single, efficient sentence with zero wasted words. It's front-loaded with the core purpose ('Read the contents of a file') and contains no unnecessary elaboration. Every word earns its place in conveying the essential function.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness2/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given 5 parameters, no annotations, and no output schema, the description is incomplete. It doesn't address what the tool returns (text? binary? error formats?), how it handles large files (streaming? memory limits?), or permissions required. For a file I/O tool with multiple configuration options, this minimal description leaves too many operational questions unanswered.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters3/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema description coverage is 100%, so all parameters are documented in the schema. The description adds no parameter-specific information beyond the basic purpose. It doesn't explain how parameters interact (e.g., that start_line/end_line enable partial reads) or provide examples. With complete schema coverage, baseline 3 is appropriate as the description doesn't add value beyond what's already structured.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose4/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the verb ('Read') and resource ('contents of a file'), making the purpose immediately understandable. However, it doesn't differentiate from sibling tools like 'read_multiple' or 'read_directory', which also involve reading operations. The purpose is clear but lacks sibling distinction.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines2/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description provides no guidance on when to use this tool versus alternatives. With siblings like 'read_multiple' (for multiple files), 'read_directory' (for directory contents), and 'file_stat' (for metadata), there's no indication of when this single-file read operation is appropriate versus other reading tools. No exclusions or alternatives are mentioned.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

Install Server

Other Tools

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/mcp-tool-shop-org/mcp-file-forge'

If you have feedback or need assistance with the MCP directory API, please join our Discord server