Skip to main content
Glama

read_file

Retrieve the entire content of a specified file as UTF-8 text using relative or absolute paths. Relative paths resolve against a session default for efficient file access.

Instructions

Reads the entire content of a specified file as UTF-8 text. Accepts relative or absolute paths. Relative paths are resolved against the session default set by set_filesystem_default.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
pathYesThe path to the file to read. Can be relative or absolute. If relative, it resolves against the path set by `set_filesystem_default`. If absolute, it is used directly. If relative and no default is set, an error occurs.

Implementation Reference

  • Core handler function that resolves the file path using serverState.resolvePath and reads the file content with comprehensive error handling for not found, directories, and I/O errors.
    export const readFileLogic = async (input: ReadFileInput, context: RequestContext): Promise<ReadFileOutput> => {
      const { path: requestedPath } = input;
    
      // Resolve the path using serverState (handles relative/absolute logic and sanitization)
      // This will throw McpError if a relative path is given without a default set.
      const absolutePath = serverState.resolvePath(requestedPath, context);
    
      try {
        // Read the file content using the resolved absolute path
        const content = await fs.readFile(absolutePath, 'utf8');
        return { content };
      } catch (error: any) {
        // Handle specific file system errors
        // Handle specific file system errors using the resolved absolutePath in messages
        if (error.code === 'ENOENT') {
          // Use NOT_FOUND error code
          throw new McpError(BaseErrorCode.NOT_FOUND, `File not found at resolved path: ${absolutePath}`, { ...context, requestedPath, resolvedPath: absolutePath, originalError: error });
        }
        if (error.code === 'EISDIR') {
           // Use VALIDATION_ERROR
           throw new McpError(BaseErrorCode.VALIDATION_ERROR, `Resolved path is a directory, not a file: ${absolutePath}`, { ...context, requestedPath, resolvedPath: absolutePath, originalError: error });
        }
        // Handle other potential I/O errors using INTERNAL_ERROR
        throw new McpError(BaseErrorCode.INTERNAL_ERROR, `Failed to read file: ${error.message || 'Unknown I/O error'}`, { ...context, originalError: error });
      }
    };
  • Zod input schema for read_file tool parameters, TypeScript input/output types.
    export const ReadFileInputSchema = z.object({
      path: z.string().min(1, 'Path cannot be empty')
        .describe('The path to the file to read. Can be relative or absolute. If relative, it resolves against the path set by `set_filesystem_default`. If absolute, it is used directly. If relative and no default is set, an error occurs.'),
    });
    
    // Define the TypeScript type for the input
    export type ReadFileInput = z.infer<typeof ReadFileInputSchema>;
    
    // Define the TypeScript type for the output
    export interface ReadFileOutput {
      content: string;
    }
  • Registers the 'read_file' MCP tool with description, input schema shape, and async handler function that invokes readFileLogic and formats the MCP response.
    server.tool(
      'read_file', // Tool name
      'Reads the entire content of a specified file as UTF-8 text. Accepts relative or absolute paths. Relative paths are resolved against the session default set by `set_filesystem_default`.', // Updated Description
      ReadFileInputSchema.shape, // Pass the schema shape, not the object instance
      async (params, extra) => { // Correct handler signature: params and extra
        // Cast params to the correct type within the handler for type safety
        const typedParams = params as ReadFileInput;
        // Create a new context for this specific tool execution
        // We might potentially use `extra.requestId` if available and needed for tracing, but let's keep it simple for now.
        const callContext = requestContextService.createRequestContext({ operation: 'ReadFileToolExecution', parentId: registrationContext.requestId });
        logger.info(`Executing 'read_file' tool for path: ${typedParams.path}`, callContext);
    
        // ErrorHandler will catch McpErrors thrown by readFileLogic and format them
        const result = await ErrorHandler.tryCatch(
          () => readFileLogic(typedParams, callContext), // Use typedParams
          {
            operation: 'readFileLogic',
            context: callContext,
            input: typedParams, // Input is automatically sanitized by ErrorHandler for logging
            errorCode: BaseErrorCode.INTERNAL_ERROR // Default error if unexpected failure
          }
        );
    
        logger.info(`Successfully read file: ${typedParams.path}`, callContext); // Use typedParams
    
        // Format the successful response
        return {
          content: [{ type: 'text', text: result.content }],
        };
      }
    );
  • Calls registerReadFileTool(server) as part of the Promise.all for registering all filesystem tools during server initialization.
    const registrationPromises = [
      registerReadFileTool(server),
      registerSetFilesystemDefaultTool(server),
      registerWriteFileTool(server),
      registerUpdateFileTool(server),
      registerListFilesTool(server),
      registerDeleteFileTool(server),
      registerDeleteDirectoryTool(server),
      registerCreateDirectoryTool(server),
      registerMovePathTool(server),
      registerCopyPathTool(server)
    ];
Behavior3/5

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

With no annotations provided, the description carries the full burden. It discloses that the tool reads files as UTF-8 and handles path resolution, but it does not mention error conditions beyond the relative path case, performance implications for large files, or return format details. It adds some behavioral context but leaves 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 front-loaded with the core purpose in the first sentence, followed by essential usage details in the second. Both sentences earn their place by providing critical information without waste, making it highly efficient and well-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 low complexity (one parameter, no output schema, no annotations), the description is mostly complete. It covers the purpose, usage, and path semantics adequately, but it lacks details on return values (e.g., text content format) and error handling, which would be beneficial for full completeness.

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 fully documents the single parameter. The description adds no additional meaning beyond what the schema provides about the path parameter, such as examples or edge cases. 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 ('Reads the entire content') and resource ('of a specified file'), with additional details about encoding ('as UTF-8 text') that distinguish it from siblings like write_file or update_file. It precisely defines what the tool does without being tautological.

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 this tool by explaining path resolution rules and referencing set_filesystem_default, but it does not explicitly state when not to use it or name alternatives (e.g., list_files for metadata). The guidance is helpful but lacks explicit exclusions.

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/cyanheads/filesystem-mcp-server'

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