Skip to main content
Glama

fileWrite

Create, edit, and write files with support for write, append, and JSON modes, directory creation, and formatting options.

Instructions

檔案寫入功能,為文件提供建立、編輯與寫入功能

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
filePathYes
contentYes
modeNowrite
createDirsNo
prettifyNo

Implementation Reference

  • main.ts:139-172 (handler)
    Main handler function that executes the fileWrite tool logic. It handles different modes ('write', 'append', 'json') by calling appropriate FileWriterTool static methods and returns MCP formatted response.
    async ({ filePath, content, mode = 'write', createDirs = true, prettify = true }) => {
        try {
            let result = '';
    
            // 根據模式選擇適當的方法
            switch (mode) {
                case 'write':
                    result = await FileWriterTool.writeTextToFile(filePath, content, createDirs);
                    break;
                case 'append':
                    result = await FileWriterTool.appendTextToFile(filePath, content, createDirs);
                    break;
                case 'json':
                    try {
                        // 嘗試解析JSON
                        const jsonData = JSON.parse(content);
                        result = await FileWriterTool.writeJsonToFile(filePath, jsonData, prettify, createDirs);
                    } catch (parseError) {
                        return {
                            content: [{ type: "text", text: `JSON格式錯誤: ${parseError instanceof Error ? parseError.message : "未知錯誤"}` }]
                        };
                    }
                    break;
            }
    
            return {
                content: [{ type: "text", text: result }]
            };
        } catch (error) {
            return {
                content: [{ type: "text", text: `檔案寫入失敗: ${error instanceof Error ? error.message : "未知錯誤"}` }]
            };
        }
    }
  • Input schema using Zod for validating parameters of the fileWrite tool: filePath, content, mode, createDirs, prettify.
    {
        filePath: z.string(),
        content: z.string(),
        mode: z.enum(['write', 'append', 'json']).default('write'),
        createDirs: z.boolean().optional(),
        prettify: z.boolean().optional()
    },
  • main.ts:130-173 (registration)
    Registration of the 'fileWrite' tool on the MCP server, including name, description, schema, and handler.
    server.tool("fileWrite",
        "檔案寫入功能,為文件提供建立、編輯與寫入功能",
        {
            filePath: z.string(),
            content: z.string(),
            mode: z.enum(['write', 'append', 'json']).default('write'),
            createDirs: z.boolean().optional(),
            prettify: z.boolean().optional()
        },
        async ({ filePath, content, mode = 'write', createDirs = true, prettify = true }) => {
            try {
                let result = '';
    
                // 根據模式選擇適當的方法
                switch (mode) {
                    case 'write':
                        result = await FileWriterTool.writeTextToFile(filePath, content, createDirs);
                        break;
                    case 'append':
                        result = await FileWriterTool.appendTextToFile(filePath, content, createDirs);
                        break;
                    case 'json':
                        try {
                            // 嘗試解析JSON
                            const jsonData = JSON.parse(content);
                            result = await FileWriterTool.writeJsonToFile(filePath, jsonData, prettify, createDirs);
                        } catch (parseError) {
                            return {
                                content: [{ type: "text", text: `JSON格式錯誤: ${parseError instanceof Error ? parseError.message : "未知錯誤"}` }]
                            };
                        }
                        break;
                }
    
                return {
                    content: [{ type: "text", text: result }]
                };
            } catch (error) {
                return {
                    content: [{ type: "text", text: `檔案寫入失敗: ${error instanceof Error ? error.message : "未知錯誤"}` }]
                };
            }
        }
    );
  • Core helper method for writing text to file, creates directories if needed, handles errors.
    static async writeTextToFile(filePath: string, content: string, createDirs: boolean = true): Promise<string> {
        try {
            // 獲取目錄路徑
            const directory = path.dirname(filePath);
            
            // 檢查並創建目錄(如果不存在且createDirs為true)
            if (createDirs && !existsSync(directory)) {
                mkdirSync(directory, { recursive: true });
                console.log(`已創建目錄: ${directory}`);
            }
            
            // 寫入檔案
            await fs.writeFile(filePath, content, 'utf8');
            
            return `檔案已成功寫入: ${filePath}`;
        } catch (error) {
            console.error(`寫入檔案時發生錯誤: ${error}`);
            return `寫入檔案時發生錯誤: ${error instanceof Error ? error.message : '未知錯誤'}`;
        }
    }
  • Core helper method for appending text to file, creates file/dir if specified, handles errors.
    static async appendTextToFile(filePath: string, content: string, createIfNotExist: boolean = true): Promise<string> {
        try {
            // 檢查檔案是否存在
            const fileExists = existsSync(filePath);
            
            // 如果檔案不存在且不需要創建,則返回錯誤
            if (!fileExists && !createIfNotExist) {
                return `錯誤: 檔案 ${filePath} 不存在`;
            }
            
            // 獲取目錄路徑(如果需要創建文件)
            if (!fileExists && createIfNotExist) {
                const directory = path.dirname(filePath);
                if (!existsSync(directory)) {
                    mkdirSync(directory, { recursive: true });
                }
            }
            
            // 追加內容到檔案
            await fs.appendFile(filePath, content, 'utf8');
            
            return `內容已成功追加到檔案: ${filePath}`;
        } catch (error) {
            console.error(`追加內容到檔案時發生錯誤: ${error}`);
            return `追加內容到檔案時發生錯誤: ${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 mentions 'create, edit, and write' functions but doesn't clarify permissions needed, whether files are overwritten or appended, error handling, or output format. For a mutation tool with 5 parameters and no annotations, this is a significant gap in transparency.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness4/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is a single, efficient sentence in Chinese that front-loads the core functionality. It avoids unnecessary words, though it could be more specific. Every word contributes to stating the purpose, earning its place without waste.

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 complexity (5 parameters, no annotations, no output schema, and 0% schema coverage), the description is incomplete. It doesn't explain parameters, behavioral traits, or usage context, making it inadequate for an agent to reliably invoke this file-writing tool among many siblings.

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?

Schema description coverage is 0%, so the description must compensate by explaining parameters. It adds no information about the 5 parameters (filePath, content, mode, createDirs, prettify), their meanings, or how they interact. This leaves critical semantics undocumented, failing to address the coverage gap.

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

Purpose3/5

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

The description states the tool provides '建立、編輯與寫入功能' (create, edit, and write functions) for files, which gives a general purpose. However, it doesn't specify what types of files or distinguish it from sibling tools like 'edit_file', 'insert_to_file', or 'delete_from_file' that also modify files. The purpose is clear but lacks sibling differentiation.

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?

No guidance is provided on when to use this tool versus alternatives. With multiple file-modification siblings (e.g., 'edit_file', 'insert_to_file', 'delete_from_file'), the description offers no context on appropriate use cases, prerequisites, or exclusions, leaving the agent to guess based on the tool name alone.

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