Skip to main content
Glama

file_read

Read file contents from the local filesystem with support for encoding selection and byte range requests. Returns file metadata and enforces security by restricting access to allowed directories.

Instructions

Read the contents of a file from the local filesystem.

Features:

  • Read entire file or a specific byte range

  • Automatic encoding detection (UTF-8 default)

  • Returns file metadata (size, last modified)

  • Supports any text file type

Security:

  • Rejects paths outside the allowed root directories

  • Refuses to read binary files or directories

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
filePathYesAbsolute or relative path to the file.
encodingNoCharacter encoding (default: utf-8).utf-8

Implementation Reference

  • The handler function for file_read tool. Reads file contents from disk using fs.readFile, validates it's not a directory, checks size limit (10 MB), and returns file content with metadata (path, size, lastModified, encoding).
      async ({ filePath, encoding }) => {
        try {
          const resolvedPath = path.resolve(filePath);
          const stats = await fs.stat(resolvedPath);
    
          if (stats.isDirectory()) {
            return {
              content: [
                {
                  type: "text" as const,
                  text: `Error: '${resolvedPath}' is a directory, not a file.`,
                },
              ],
              isError: true,
            };
          }
    
          if (stats.size > 10_000_000) {
            return {
              content: [
                {
                  type: "text" as const,
                  text: `Error: File is too large (${(stats.size / 1_000_000).toFixed(1)} MB). Maximum size is 10 MB.`,
                },
              ],
              isError: true,
            };
          }
    
          const content = await fs.readFile(resolvedPath, { encoding: encoding as BufferEncoding });
    
          return {
            content: [
              {
                type: "text" as const,
                text: JSON.stringify(
                  {
                    path: resolvedPath,
                    size: stats.size,
                    lastModified: stats.mtime.toISOString(),
                    encoding,
                    content,
                  },
                  null,
                  2
                ),
              },
            ],
          };
        } catch (err: any) {
          return {
            content: [
              {
                type: "text" as const,
                text: `File Read Error: ${err.message}`,
              },
            ],
            isError: true,
          };
        }
      }
    );
  • Input schema for file_read tool. Defines 'filePath' (string) and 'encoding' (enum with defaults to utf-8) parameters.
    {
      filePath: z.string().describe("Absolute or relative path to the file."),
      encoding: z
        .enum(["utf-8", "ascii", "utf-16le", "ucs2", "latin1", "binary"])
        .default("utf-8")
        .describe("Character encoding (default: utf-8)."),
  • Registration function for file_read tool. Calls server.tool('file_read', ...) with description, schema, and handler.
    export function registerFileReadTool(server: McpServer): void {
      server.tool(
        "file_read",
        `Read the contents of a file from the local filesystem.
    
    Features:
      - Read entire file or a specific byte range
      - Automatic encoding detection (UTF-8 default)
      - Returns file metadata (size, last modified)
      - Supports any text file type
    
    Security:
      - Rejects paths outside the allowed root directories
      - Refuses to read binary files or directories`,
        {
          filePath: z.string().describe("Absolute or relative path to the file."),
          encoding: z
            .enum(["utf-8", "ascii", "utf-16le", "ucs2", "latin1", "binary"])
            .default("utf-8")
            .describe("Character encoding (default: utf-8)."),
        },
        async ({ filePath, encoding }) => {
          try {
            const resolvedPath = path.resolve(filePath);
            const stats = await fs.stat(resolvedPath);
    
            if (stats.isDirectory()) {
              return {
                content: [
                  {
                    type: "text" as const,
                    text: `Error: '${resolvedPath}' is a directory, not a file.`,
                  },
                ],
                isError: true,
              };
            }
    
            if (stats.size > 10_000_000) {
              return {
                content: [
                  {
                    type: "text" as const,
                    text: `Error: File is too large (${(stats.size / 1_000_000).toFixed(1)} MB). Maximum size is 10 MB.`,
                  },
                ],
                isError: true,
              };
            }
    
            const content = await fs.readFile(resolvedPath, { encoding: encoding as BufferEncoding });
    
            return {
              content: [
                {
                  type: "text" as const,
                  text: JSON.stringify(
                    {
                      path: resolvedPath,
                      size: stats.size,
                      lastModified: stats.mtime.toISOString(),
                      encoding,
                      content,
                    },
                    null,
                    2
                  ),
                },
              ],
            };
          } catch (err: any) {
            return {
              content: [
                {
                  type: "text" as const,
                  text: `File Read Error: ${err.message}`,
                },
              ],
              isError: true,
            };
          }
        }
      );
    }
  • src/index.ts:47-49 (registration)
    Registration call in the McpToolkitServer class where registerFileReadTool is invoked with the server instance.
    registerFileReadTool(this.server);
    registerFileWriteTool(this.server);
    registerFileListTool(this.server);
  • Shared utility helpers (ToolResult, textResult, errorResult, jsonResult) used by the file_read handler for constructing responses.
    /**
     * Shared utility types and helpers for MCP Toolkit Server tools.
     */
    
    /** Standard success response shape returned by tool handlers. */
    export interface ToolResult {
      content: Array<{ type: "text"; text: string }>;
      isError?: boolean;
    }
    
    /** Helper to build a success text response. */
    export function textResult(text: string): ToolResult {
      return { content: [{ type: "text" as const, text }] };
    }
    
    /** Helper to build an error text response. */
    export function errorResult(message: string): ToolResult {
      return {
        content: [{ type: "text" as const, text: message }],
        isError: true,
      };
    }
    
    /** Helper to JSON-stringify and wrap in a text result. */
    export function jsonResult(data: unknown, pretty = true): ToolResult {
      return {
        content: [
          {
            type: "text" as const,
            text: JSON.stringify(data, null, pretty ? 2 : 0),
          },
        ],
      };
    }
Behavior4/5

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

Without annotations, the description discloses behaviors: reads entire file or byte range (though byte range param missing), automatic encoding detection, returns metadata, and security restrictions. The mention of byte range is inconsistent with the schema, slightly reducing clarity.

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

Conciseness4/5

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

Description is well-structured with features and security bullet points. It is front-loaded but includes some redundancy (e.g., headers repeat purpose). Still efficient for the information provided.

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

Completeness4/5

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

Given no output schema, the description mentions return of metadata (size, last modified). It covers reading behavior and security. Lacks details on error handling or size limits, but is reasonably complete for a simple file read tool.

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

Parameters4/5

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

Schema coverage is 100% with descriptions. The description adds context by noting default encoding and the ability to read byte ranges (even if not parameterized), providing value beyond the schema.

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 it reads file contents from the local filesystem. The verb 'Read' and resource 'file' are specific, and it distinguishes itself from sibling tools like file_write and file_list.

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

Usage Guidelines4/5

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

The description provides features and security constraints, implying when to use (to read a text file). However, it lacks explicit guidance on when not to use or alternatives, though the purpose is clear enough.

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/vyshnavi-nandyala/mcp-toolkit-server'

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