Skip to main content
Glama
idapixl

MCP Starter Kit

read_file

Read files from the filesystem with configurable encoding and size limits. Supports text and binary files while blocking path traversal for secure file access.

Instructions

Read a file from the filesystem. Paths are relative to the configured root directory (/app/workspace). Path traversal (../) is blocked. Use encoding=base64 for binary files.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
pathYesPath to the file, relative to the configured root directory
encodingNoFile encoding — use base64 for binary filesutf8
max_bytesNoMaximum bytes to read (default: 1MB, max: 10MB)

Implementation Reference

  • The readFile function handles reading files from the filesystem while enforcing safety checks (path traversal) and file limits.
    export async function readFile(
      input: ReadFileInput
    ): Promise<ToolResult<ReadFileResult>> {
      const result = safePath(input.path);
      if ("error" in result) {
        return { ok: false, error: result.error, code: "PATH_TRAVERSAL" };
      }
    
      const { resolved } = result;
      const maxBytes = input.max_bytes ?? DEFAULT_MAX_BYTES;
      const encoding = input.encoding ?? "utf8";
    
      logger.debug("Reading file", { path: resolved, maxBytes, encoding });
    
      let stat: Awaited<ReturnType<typeof fs.stat>>;
      try {
        stat = await fs.stat(resolved);
      } catch (err) {
        const code = (err as NodeJS.ErrnoException).code;
        if (code === "ENOENT") {
          return { ok: false, error: `File not found: ${input.path}`, code: "NOT_FOUND" };
        }
        return {
          ok: false,
          error: `Cannot stat file: ${(err as Error).message}`,
          code: "STAT_ERROR",
        };
      }
    
      if (!stat.isFile()) {
        return {
          ok: false,
          error: `Path is not a file: ${input.path}`,
          code: "NOT_A_FILE",
        };
      }
    
      const truncated = stat.size > maxBytes;
      const bytesToRead = Math.min(stat.size, maxBytes);
    
      let content: string;
      try {
        const handle = await fs.open(resolved, "r");
        try {
          const buffer = Buffer.alloc(bytesToRead);
          await handle.read(buffer, 0, bytesToRead, 0);
          content =
            encoding === "base64"
              ? buffer.toString("base64")
              : buffer.toString("utf8");
        } finally {
          await handle.close();
        }
      } catch (err) {
        return {
          ok: false,
          error: `Failed to read file: ${(err as Error).message}`,
          code: "READ_ERROR",
        };
      }
    
      logger.info("File read", { path: input.path, bytes: bytesToRead, truncated });
    
      return {
        ok: true,
        data: {
          path: input.path,
          size_bytes: stat.size,
          encoding,
          content,
          truncated,
          read_at: new Date().toISOString(),
        },
      };
    }
  • Schema definition for the inputs to the read_file tool.
    export const ReadFileSchema = z.object({
      path: z
        .string()
        .min(1)
        .describe("Path to the file, relative to the configured root directory"),
      encoding: z
        .enum(["utf8", "base64"])
        .optional()
        .default("utf8")
        .describe("File encoding — use base64 for binary files"),
      max_bytes: z
        .number()
        .int()
        .min(1)
        .max(10_485_760)
        .optional()
        .describe("Maximum bytes to read (default: 1MB, max: 10MB)"),
    });
    
    export type ReadFileInput = z.infer<typeof ReadFileSchema>;
  • src/index.ts:63-71 (registration)
    Registration and tool handler invocation in the main server logic. Note: The snippet is reconstructed from the flow in index.ts based on the provided search context.
    "read_file",
    `Read a file from the filesystem. Paths are relative to the configured root directory (${config.fileReaderRoot}). ` +
      "Path traversal (../) is blocked. " +
      "Use encoding=base64 for binary files.",
    ReadFileSchema.shape,
    async (args) => {
      const result = await readFile(args);
    
      if (!result.ok) {
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 does well by disclosing important behavioral traits: path traversal blocking, root directory context, and encoding recommendations for binary files. It doesn't mention error conditions, permissions, or rate limits, but provides solid operational context for a read operation.

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?

Three concise sentences with zero waste - each sentence provides essential information: core purpose, path constraints, and encoding guidance. Perfectly front-loaded with the main action first, followed by important operational details.

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?

For a read operation with no annotations and no output schema, the description provides good context about path handling and encoding. It could mention what happens with non-existent files or permission errors, but covers the essential operational constraints well given the tool's complexity.

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 already documents all parameters thoroughly. The description adds minimal value beyond the schema - it mentions encoding=base64 for binary files (which is also in the schema) and implies path handling context. Baseline 3 is appropriate when 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 a file') and resource ('from the filesystem'), distinguishing it from sibling tools like list_directory (which lists files) or fetch_url (which retrieves from URLs). It provides specific context about path handling that makes the purpose unambiguous.

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 clear context about when to use certain options ('use encoding=base64 for binary files') and mentions path traversal restrictions, but doesn't explicitly contrast when to use this tool versus alternatives like fetch_url or transform_data. It gives operational guidance but not sibling differentiation.

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/idapixl/mcp-starter-kit'

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