Skip to main content
Glama

read

Read file contents with safety checks and optional line range selection to access specific portions of documents efficiently.

Instructions

Read file contents with safety checks and optional line range

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
pathYesFile path to read
startLineNoStart line number (1-based, default: 1)
endLineNoEnd line number (1-based, optional)
maxLinesNoMaximum number of lines to read (default: 20)

Implementation Reference

  • Core handler function implementing the 'read' tool: input validation, safe file reading with line ranges, content formatting, truncation handling, and error management.
    async execute(args: any): Promise<any> {
      try {
        // Validate and parse input using Zod schema
        const validatedArgs = ReadToolInputSchema.parse(args);
        const { path: filePath, startLine, endLine, maxLines } = validatedArgs;
    
        // Use FileUtils for safe file reading with line range support
        const options: any = {
          startLine,
          maxLines,
        };
        if (endLine !== undefined) {
          options.endLine = endLine;
        }
        const { content: selectedContent, totalLines } = await FileUtils.readFileLines(
          filePath,
          options
        );
    
        // Calculate actual range (for display purposes)
        const actualStartLine = Math.max(1, startLine);
        const actualEndLine = endLine
          ? Math.min(endLine, totalLines)
          : Math.min(actualStartLine + maxLines - 1, totalLines);
    
        // Check character limit for selected content only
        const isRangeSpecified =
          args.startLine !== undefined || args.endLine !== undefined || args.maxLines !== undefined;
        const hasRangeLimit = isRangeSpecified || actualEndLine < totalLines;
    
        if (hasRangeLimit && selectedContent.length > 20000) {
          throw ToolError.createValidationError(
            "contentSize",
            selectedContent.length,
            "Selected range is too large. Maximum allowed: 20,000 characters. Please reduce range"
          );
        }
    
        // Format output (plain text, no line numbers by default)
        let formattedLines = selectedContent;
        const messages = [];
    
        if (actualStartLine > 1) {
          messages.push(`... above (${actualStartLine - 1} lines)`);
        }
    
        if (actualEndLine < totalLines) {
          const remainingLines = totalLines - actualEndLine;
          const nextStart = actualEndLine + 1;
    
          messages.push(`below (${remainingLines} lines) ...`);
    
          // Add helpful suggestions
          const suggestions = [];
          suggestions.push(`startLine=${nextStart}`);
          suggestions.push(`maxLines=<more>`);
    
          messages.push(`To read more: ${suggestions.join(" or ")}`);
        }
    
        if (messages.length > 0) {
          formattedLines = `${formattedLines}\n\n[${messages.join(" | ")}]`;
        }
    
        // Mark file as read for Edit Tool and Write Tool safety
        fileReadTracker.markFileAsRead(filePath);
    
        return ResultFormatter.createResponse(formattedLines);
      } catch (error) {
        // Handle Zod validation errors
        if (error instanceof Error && error.name === "ZodError") {
          throw ToolError.createValidationError("input", args, `Invalid input: ${error.message}`);
        }
        throw ToolError.wrapError("Read operation", error);
      }
    }
  • Zod input schema for the 'read' tool, validating path, line ranges, and maxLines with constraints.
    export const ReadToolInputSchema = z
      .object({
        path: FilePathSchema,
        startLine: LineNumberSchema.default(1),
        endLine: OptionalLineNumberSchema,
        maxLines: z.number().int().min(1).default(20),
      })
      .refine((data) => !data.endLine || data.startLine <= data.endLine, {
        message: "Start line cannot be greater than end line",
        path: ["startLine"],
      });
  • Registration of the 'read' tool by including its definition in the server's tool list.
    protected getTools(): Tool[] {
      return [
        this.readTool.getDefinition(),
        this.findTool.getDefinition(),
        this.grepTool.getDefinition(),
        this.writeTool.getDefinition(),
        this.editTool.getDefinition(),
        this.moveTool.getDefinition(),
        this.copyTool.getDefinition(),
      ];
  • Dispatch to the 'read' tool handler in the main tool call switch statement.
    case "read":
      return await this.readTool.execute(args);
    case "find":
  • JSON schema definition for the 'read' tool input, provided for MCP protocol compliance.
    getDefinition(): Tool {
      return {
        name: "read",
        description: "Read file contents with safety checks and optional line range",
        inputSchema: {
          type: "object",
          properties: {
            path: {
              type: "string",
              description: "File path to read",
            },
            startLine: {
              type: "number",
              default: 1,
              description: "Start line number (1-based, default: 1)",
            },
            endLine: {
              type: "number",
              description: "End line number (1-based, optional)",
            },
            maxLines: {
              type: "number",
              default: 20,
              description: "Maximum number of lines to read (default: 20)",
            },
          },
          required: ["path"],
        },
      };
Behavior4/5

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

With no annotations provided, the description carries full burden and adds valuable behavioral context: 'safety checks' implies validation or restrictions (e.g., file size, permissions), and 'optional line range' clarifies it supports partial reads. However, it doesn't detail error handling, encoding, or what 'safety checks' entail, leaving some gaps.

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 that front-loads the core action ('Read file contents') and adds two key qualifiers ('with safety checks and optional line range'). Every word earns its place with no redundancy or fluff.

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

Completeness3/5

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

For a read operation with 4 parameters, 100% schema coverage, and no output schema, the description is adequate but has gaps: it doesn't explain return values (e.g., format, error cases) or fully detail 'safety checks'. It's minimally viable given the context but could be more complete.

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 the schema fully documents all 4 parameters. The description adds no specific parameter details beyond implying line-range usage, which is already covered in the schema. Baseline 3 is appropriate as the schema does the heavy lifting.

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

Purpose5/5

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

The description clearly states the specific action ('Read file contents') and resource ('file'), distinguishing it from siblings like 'write' (which creates/modifies) and 'edit' (which modifies). It adds valuable context about 'safety checks' and 'optional line range' that further clarifies its purpose beyond basic file reading.

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

Usage Guidelines3/5

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

The description implies usage through 'optional line range' and 'safety checks', suggesting it's for reading files with potential constraints, but doesn't explicitly state when to use this vs. alternatives like 'grep' (searching) or 'find' (locating files). No explicit exclusions or named alternatives are provided.

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/d-issy/mcp'

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