Skip to main content
Glama
gabrielmaialva33

MCP Filesystem Server

read_file

Retrieve and display the entire content of a file from the filesystem. Supports multiple text encodings and provides precise error feedback. Ensures access is restricted to predefined directories for security.

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
encodingNoFile encodingutf-8
pathYesPath to the file to read

Implementation Reference

  • The main handler function that validates the path, checks file size, reads the file content using fs.readFile, handles errors, and returns the content as string.
    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 arguments: path (required string) and optional encoding (utf-8, utf8, base64, defaults to 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 response: defines name, description, and converts schema to JSON schema for MCP protocol.
      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,
    },
  • src/index.ts:400-414 (registration)
    Dispatch handler in the CallToolRequest switch: parses input with schema, calls the readFile handler, returns content as MCP response.
    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 }],
      }
    }
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.

Install Server

Other Tools

Related 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/gabrielmaialva33/mcp-filesystem'

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