Skip to main content
Glama

fileRead

Read file contents from text and JSON formats to access data stored in files for processing or analysis.

Instructions

讀取檔案內容,支援純文本和JSON格式

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
filePathYes
modeNotext
encodingNo

Implementation Reference

  • main.ts:176-217 (registration)
    Registration of the 'fileRead' tool including description, input schema, and inline handler function that supports text and JSON modes by delegating to FileWriterTool.
    server.tool("fileRead",
        "讀取檔案內容,支援純文本和JSON格式",
        {
            filePath: z.string(),
            mode: z.enum(['text', 'json']).default('text'),
            encoding: z.string().optional()
        },
        async ({ filePath, mode = 'text', encoding = 'utf8' }) => {
            try {
                if (mode === 'text') {
                    const content = await FileWriterTool.readTextFile(filePath, encoding as BufferEncoding);
    
                    // 檢查是否有錯誤
                    if (content.startsWith('錯誤') || content.startsWith('讀取檔案時發生錯誤')) {
                        return {
                            content: [{ type: "text", text: content }]
                        };
                    }
    
                    return {
                        content: [{ type: "text", text: content }]
                    };
                } else {
                    const result = await FileWriterTool.readJsonFile(filePath);
    
                    if (!result.success) {
                        return {
                            content: [{ type: "text", text: result.error || '讀取JSON檔案失敗' }]
                        };
                    }
    
                    return {
                        content: [{ type: "text", text: JSON.stringify(result.data, null, 2) }]
                    };
                }
            } catch (error) {
                return {
                    content: [{ type: "text", text: `檔案讀取失敗: ${error instanceof Error ? error.message : "未知錯誤"}` }]
                };
            }
        }
    );
  • Core implementation for reading text files, used by fileRead tool in text mode.
    static async readTextFile(filePath: string, encoding: BufferEncoding = 'utf8'): Promise<string> {
        try {
            // 檢查檔案是否存在
            if (!existsSync(filePath)) {
                return `錯誤: 檔案 ${filePath} 不存在`;
            }
    
            // 讀取檔案內容
            const content = await fs.readFile(filePath, { encoding });
            return content;
        } catch (error) {
            console.error(`讀取檔案時發生錯誤: ${error}`);
            return `讀取檔案時發生錯誤: ${error instanceof Error ? error.message : '未知錯誤'}`;
        }
    }
  • Core implementation for reading and parsing JSON files, used by fileRead tool in json mode.
    static async readJsonFile(filePath: string): Promise<{ success: boolean; data?: any; error?: string }> {
        try {
            // 讀取檔案
            const content = await this.readTextFile(filePath);
            
            // 如果讀取出錯,返回錯誤
            if (content.startsWith('錯誤') || content.startsWith('讀取檔案時發生錯誤')) {
                return { success: false, error: content };
            }
    
            // 解析JSON
            try {
                const jsonData = JSON.parse(content);
                return { success: true, data: jsonData };
            } catch (parseError) {
                return { 
                    success: false, 
                    error: `JSON解析錯誤: ${parseError instanceof Error ? parseError.message : '未知錯誤'}` 
                };
            }
        } catch (error) {
            return { 
                success: false, 
                error: `讀取JSON檔案時發生錯誤: ${error instanceof Error ? error.message : '未知錯誤'}` 
            };
        }
    }
  • Zod input schema defining parameters for fileRead tool: filePath (required), mode (text/json), encoding (optional).
        filePath: z.string(),
        mode: z.enum(['text', 'json']).default('text'),
        encoding: z.string().optional()
    },
  • main.ts:183-216 (handler)
    Inline handler function for fileRead tool that handles input parameters, calls appropriate FileWriterTool methods based on mode, processes results, and formats MCP response.
    async ({ filePath, mode = 'text', encoding = 'utf8' }) => {
        try {
            if (mode === 'text') {
                const content = await FileWriterTool.readTextFile(filePath, encoding as BufferEncoding);
    
                // 檢查是否有錯誤
                if (content.startsWith('錯誤') || content.startsWith('讀取檔案時發生錯誤')) {
                    return {
                        content: [{ type: "text", text: content }]
                    };
                }
    
                return {
                    content: [{ type: "text", text: content }]
                };
            } else {
                const result = await FileWriterTool.readJsonFile(filePath);
    
                if (!result.success) {
                    return {
                        content: [{ type: "text", text: result.error || '讀取JSON檔案失敗' }]
                    };
                }
    
                return {
                    content: [{ type: "text", text: JSON.stringify(result.data, null, 2) }]
                };
            }
        } catch (error) {
            return {
                content: [{ type: "text", text: `檔案讀取失敗: ${error instanceof Error ? error.message : "未知錯誤"}` }]
            };
        }
    }
Behavior2/5

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

No annotations are provided, so the description carries the full burden of behavioral disclosure. It states the tool reads files and supports text/JSON formats, but doesn't mention error handling (e.g., what happens if the file doesn't exist or isn't in the expected format), performance characteristics, or security implications. 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 extremely concise—a single sentence that efficiently conveys the core functionality. It's front-loaded with the main purpose ('讀取檔案內容') and adds essential detail about supported formats. There's no wasted verbiage, making it easy to parse quickly.

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 moderate complexity (3 parameters, no output schema, no annotations), the description is incomplete. It doesn't address key aspects like return values (e.g., what structure the JSON mode returns), error conditions, or how it differs from similar sibling tools. For a file-reading tool with multiple parameters and no structured documentation elsewhere, more context is needed.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters2/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

The schema description coverage is 0%, meaning none of the parameters are documented in the schema. The description mentions support for text and JSON formats, which loosely relates to the 'mode' parameter with its enum values, but doesn't explain the 'filePath' parameter (e.g., format, relative vs. absolute paths) or 'encoding' parameter (e.g., default, supported encodings). It adds minimal value beyond what the schema's enum implies.

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 tool's purpose as '讀取檔案內容' (read file content) with support for text and JSON formats. It specifies the verb ('讀取') and resource ('檔案內容'), making the purpose unambiguous. However, it doesn't explicitly differentiate from sibling tools like 'codeFileRead' or 'search_code', which might have overlapping functionality.

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

Usage Guidelines2/5

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

The description provides no guidance on when to use this tool versus alternatives. With sibling tools like 'codeFileRead' (which might be specialized for code files) and 'search_code' (which might search within files), there's no indication of when this general file reader is appropriate. It mentions supported formats but doesn't specify use cases or 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

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/GonTwVn/GonMCPtool'

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