Skip to main content
Glama
A-Niranjan

MCP Filesystem Server

by A-Niranjan

read_file

Read file contents from the filesystem with support for text encodings and detailed error handling. Use this tool to examine the contents of a single file within allowed directories.

Instructions

Read the complete contents of a file from the file system. Handles various text encodings and provides detailed error messages if the file cannot be read. Use this tool when you need to examine the contents of a single file. Only works within allowed directories.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
pathYesPath to the file to read
encodingNoFile encodingutf-8

Implementation Reference

  • The core handler function for the 'read_file' tool. Validates the path, checks file size limits, reads the file content using Node.js fs.readFile, logs success, records metrics, and handles specific errors like file not found.
    export async function readFile(
      args: z.infer<typeof ReadFileArgsSchema>,
      config: Config
    ): Promise<string> {
      const endMetric = metrics.startOperation('read_file')
      try {
        const validPath = await validatePath(args.path, config)
    
        // Validate file size before reading
        if (config.security.maxFileSize > 0) {
          await validateFileSize(validPath, config.security.maxFileSize)
        }
    
        const content = await fs.readFile(validPath, args.encoding)
        await logger.debug(`Successfully read file: ${validPath}`)
    
        endMetric()
        return content
      } catch (error) {
        metrics.recordError('read_file')
    
        if ((error as NodeJS.ErrnoException).code === 'ENOENT') {
          throw new PathNotFoundError(args.path)
        }
    
        throw error
      }
    }
  • Zod schema defining the input parameters for the read_file tool: required 'path' string and optional 'encoding' enum with default 'utf-8'.
    export const ReadFileArgsSchema = z.object({
      path: z.string().describe('Path to the file to read'),
      encoding: z
        .enum(['utf-8', 'utf8', 'base64'])
        .optional()
        .default('utf-8')
        .describe('File encoding'),
    })
  • src/index.ts:236-243 (registration)
    Tool registration in the list_tools handler, specifying the name, detailed description, and input schema derived from ReadFileArgsSchema.
      name: 'read_file',
      description:
        'Read the complete contents of a file from the file system. ' +
        'Handles various text encodings and provides detailed error messages ' +
        'if the file cannot be read. Use this tool when you need to examine ' +
        'the contents of a single file. Only works within allowed directories.',
      inputSchema: zodToJsonSchema(ReadFileArgsSchema) as ToolInput,
    },
  • MCP call_tool dispatch case for 'read_file' that validates input arguments using ReadFileArgsSchema and delegates to the readFile handler function.
    case 'read_file': {
      const parsed = ReadFileArgsSchema.safeParse(a)
      if (!parsed.success) {
        throw new FileSystemError(`Invalid arguments for ${name}`, 'INVALID_ARGS', undefined, {
          errors: parsed.error.format(),
        })
      }
    
      const content = await readFile(parsed.data, config)
    
      endMetric()
      return {
        content: [{ type: 'text', text: content }],
      }
    }

Schema Changelog

Changes observed during successful MCP inspections.

  1. First observed

TDQS

A4.2/5.0
Behavior4/5

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

With no annotations provided, the description carries the full burden of behavioral disclosure. It adds valuable context beyond basic functionality: it mentions handling 'various text encodings', providing 'detailed error messages', and the constraint 'Only works within allowed directories'. However, it lacks details on performance aspects like file size limits or memory usage, which could be relevant for large files.

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 front-loaded with the core purpose in the first sentence, followed by additional context in subsequent sentences. Each sentence adds value: the first states the action, the second adds behavioral traits, and the third provides usage guidelines and constraints. There is no redundant or wasted information, making it efficiently structured.

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 the tool's moderate complexity (read operation with encoding support), no annotations, and no output schema, the description is mostly complete. It covers purpose, behavioral traits, and usage constraints. However, it lacks details on the return format (e.g., content as string or structured data) and error handling specifics, which would be helpful since there's no output schema.

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?

The input schema has 100% description coverage, with clear documentation for both parameters ('path' and 'encoding'), including enum values and defaults. The description does not add any parameter-specific details beyond what the schema provides, such as examples or format requirements for 'path'. Thus, it meets the baseline for high schema coverage without compensating with extra insights.

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 the complete contents of a file') and resource ('from the file system'), distinguishing it from siblings like 'read_multiple_files' (single vs. multiple files), 'get_file_info' (metadata vs. content), and 'edit_file' (read vs. modify). It explicitly mentions the scope ('Only works within allowed directories'), which further differentiates it.

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 on when to use it ('when you need to examine the contents of a single file') and includes a constraint ('Only works within allowed directories'), but it does not explicitly name alternatives or specify when not to use it. For example, it doesn't mention 'read_multiple_files' for batch operations or 'get_file_info' for metadata only.

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