Skip to main content
Glama
p-united
by p-united

read_file

Read file contents from secure directories to access stored data for processing or analysis.

Instructions

指定されたファイルの内容を読み込みます(許可されたディレクトリのみ)

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
filepathYes読み込むファイルのパス

Implementation Reference

  • Core handler function implementing the read_file tool logic: validates path and extension, reads file content with fs.readFile, and returns formatted result.
    private async readFile(filepath: string): Promise<CallToolResult> {
      try {
        const pathValidation = this.pathValidator.validatePath(filepath);
        if (!pathValidation.isValid) {
          throw new Error(pathValidation.error);
        }
    
        const extValidation = this.pathValidator.validateFileExtension(pathValidation.normalizedPath);
        if (!extValidation.isValid) {
          throw new Error(extValidation.error);
        }
    
        console.error(`Reading file: ${pathValidation.normalizedPath}`);
        const content = await fs.readFile(pathValidation.normalizedPath, "utf-8");
        return {
          content: [
            {
              type: "text",
              text: `ファイル "${pathValidation.normalizedPath}" の内容:\n\n${content}`,
            },
          ],
          isError: false,
        };
      } catch (error) {
        throw new Error(`ファイルの読み込みに失敗: ${error}`);
      }
    }
  • Input schema defining the required 'filepath' string parameter for the read_file tool.
    inputSchema: {
      type: "object",
      properties: {
        filepath: {
          type: "string",
          description: "読み込むファイルのパス",
        },
      },
      required: ["filepath"],
    },
  • src/index.ts:115-128 (registration)
    Tool definition and registration in the TOOLS array, which is served via the listTools request handler.
    {
      name: "read_file",
      description: "指定されたファイルの内容を読み込みます(許可されたディレクトリのみ)",
      inputSchema: {
        type: "object",
        properties: {
          filepath: {
            type: "string",
            description: "読み込むファイルのパス",
          },
        },
        required: ["filepath"],
      },
    },
  • src/index.ts:275-276 (registration)
    Dispatch case in the callTool request handler that routes 'read_file' calls to the readFile method.
    case "read_file":
      return await this.readFile(args.filepath as string);
  • PathValidator class used by read_file handler for securing file access by restricting to allowed paths and extensions.
    class PathValidator {
      private allowedPaths: string[];
      private blockedPaths: string[];
      private allowedExtensions: string[];
    
      constructor() {
        // 許可されるディレクトリ(絶対パスに正規化)
        this.allowedPaths = [
          //path.resolve(process.cwd()), // 現在のワーキングディレクトリ
          //path.resolve(os.homedir(), 'Documents'), // ドキュメントフォルダ
          path.resolve(os.homedir(), 'Documents/00_AI_Area'), // 専用フォルダ
          //path.resolve(os.homedir(), 'Desktop'), // デスクトップ
          //path.resolve(os.tmpdir()), // 一時ディレクトリ
        ];
    
        // 明示的にブロックするパス
        this.blockedPaths = [
          '/etc',
          '/bin',
          '/sbin',
          '/usr/bin',
          '/usr/sbin',
          '/System',
          '/Windows',
          '/Program Files',
          '/Program Files (x86)',
          path.resolve(os.homedir(), '.ssh'),
          path.resolve(os.homedir(), '.aws'),
          path.resolve(os.homedir(), '.config'),
        ];
    
        // 許可されるファイル拡張子
        this.allowedExtensions = [
          '.txt', '.md', '.json', '.js', '.ts', '.html', '.css',
          '.py', '.java', '.cpp', '.c', '.h', '.xml', '.yaml', '.yml',
          '.log', '.csv', '.tsv', '.sql', '.sh', '.bat', '.ps1'
        ];
      }
    
      validatePath(inputPath: string): { isValid: boolean; normalizedPath: string; error?: string } {
        try {
          // パスを正規化
          const normalizedPath = path.resolve(inputPath);
          
          // ブロックされたパスのチェック
          for (const blockedPath of this.blockedPaths) {
            if (normalizedPath.startsWith(path.resolve(blockedPath))) {
              return {
                isValid: false,
                normalizedPath,
                error: `アクセスが禁止されているディレクトリです: ${blockedPath}`
              };
            }
          }
    
          // 許可されたパスのチェック
          const isAllowed = this.allowedPaths.some(allowedPath => 
            normalizedPath.startsWith(allowedPath)
          );
    
          if (!isAllowed) {
            return {
              isValid: false,
              normalizedPath,
              error: `許可されていないパスです。アクセス可能なパス: ${this.allowedPaths.join(', ')}`
            };
          }
    
          return { isValid: true, normalizedPath };
        } catch (error) {
          return {
            isValid: false,
            normalizedPath: inputPath,
            error: `無効なパスです: ${error}`
          };
        }
      }
    
      validateFileExtension(filepath: string): { isValid: boolean; error?: string } {
        const ext = path.extname(filepath).toLowerCase();
        
        if (ext && !this.allowedExtensions.includes(ext)) {
          return {
            isValid: false,
            error: `許可されていないファイル拡張子です: ${ext}。許可されている拡張子: ${this.allowedExtensions.join(', ')}`
          };
        }
    
        return { isValid: true };
      }
    
      getAllowedPaths(): string[] {
        return [...this.allowedPaths];
      }
    }
Behavior2/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 mentions the restriction to allowed directories, which is useful, but lacks details on permissions, error handling, or output format. For a read operation with zero annotation coverage, this leaves significant gaps in understanding how the tool behaves.

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 a single, efficient sentence that front-loads the core action and includes a crucial restriction in parentheses. There is no wasted language, and it communicates the essential information without unnecessary elaboration.

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

Completeness2/5

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

Given the tool's complexity (a file read operation), lack of annotations, and no output schema, the description is incomplete. It doesn't explain what the tool returns (e.g., file content as text, binary data, or an error structure), leaving the agent uncertain about the result format and potential edge cases.

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 input schema already documents the 'filepath' parameter fully. The description doesn't add any additional meaning or context about the parameter beyond what the schema provides, such as path format examples or allowed directory specifics, resulting in a baseline score.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose4/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the verb ('読み込みます' - reads) and resource ('ファイルの内容' - file content), making the purpose understandable. However, it doesn't explicitly differentiate from sibling tools like 'list_directory' or 'get_allowed_paths', which also involve file system operations but serve different purposes.

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

Usage Guidelines3/5

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

The description implies usage context with the parenthetical note '(許可されたディレクトリのみ)' - only allowed directories, suggesting a restriction. However, it doesn't provide explicit guidance on when to use this tool versus alternatives like 'list_directory' for browsing or 'write_file' for modifications, leaving the agent to infer appropriate contexts.

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/p-united/mcpSample'

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