Skip to main content
Glama

edit_file

Edit files by replacing specific text content with exact matches, allowing preview of changes before applying modifications.

Instructions

對檔案進行精確的編輯,可以替換特定文字內容

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
pathYes
editsYes
dryRunNo預覽變更而不實際修改檔案

Implementation Reference

  • main.ts:220-242 (registration)
    Registers the 'edit_file' MCP tool, including input schema validation with Zod and a thin wrapper handler that delegates to FileEditorTool.editFile
    server.tool("edit_file",
        "對檔案進行精確的編輯,可以替換特定文字內容",
        {
            path: z.string(),
            edits: z.array(z.object({
                oldText: z.string().describe("要搜尋的文字 - 必須完全匹配"),
                newText: z.string().describe("替換成的新文字")
            })),
            dryRun: z.boolean().default(false).describe("預覽變更而不實際修改檔案")
        },
        async ({ path, edits, dryRun = false }) => {
            try {
                const result = await FileEditorTool.editFile(path, edits, dryRun);
                return {
                    content: [{ type: "text", text: result }]
                };
            } catch (error) {
                return {
                    content: [{ type: "text", text: `編輯檔案失敗: ${error instanceof Error ? error.message : "未知錯誤"}` }]
                };
            }
        }
    );
  • Core implementation of file editing: reads file, performs exact text replacements ensuring uniqueness, supports dry-run with diff preview, and writes changes if not dry-run
    static async editFile(
        filePath: string, 
        edits: Array<{oldText: string, newText: string}>, 
        dryRun: boolean = false
    ): Promise<string> {
        try {
            // 檢查檔案是否存在
            if (!existsSync(filePath)) {
                return `錯誤: 檔案 ${filePath} 不存在`;
            }
    
            // 讀取檔案內容
            let content = await fs.readFile(filePath, 'utf8');
            let originalContent = content;
            
            // 套用所有編輯
            for (const edit of edits) {
                const { oldText, newText } = edit;
                
                // 檢查 oldText 是否存在且唯一
                const count = (content.match(new RegExp(this.escapeRegExp(oldText), 'g')) || []).length;
                if (count === 0) {
                    return `錯誤: 在檔案中找不到文字「${oldText}」`;
                }
                if (count > 1) {
                    return `錯誤: 文字「${oldText}」在檔案中出現多次 (${count} 次),無法確定要替換哪一個`;
                }
                
                // 替換文字
                content = content.replace(oldText, newText);
            }
            
            // 如果是預覽模式,生成差異報告
            if (dryRun) {
                return this.generateDiff(originalContent, content, filePath);
            }
            
            // 寫入檔案
            await fs.writeFile(filePath, content, 'utf8');
            
            return `檔案已成功編輯: ${filePath},共應用了 ${edits.length} 個修改`;
        } 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. The description mentions '精確的編輯' (precise editing) and text replacement, but doesn't disclose critical behavioral traits: whether this is a destructive operation, what permissions are required, how errors are handled, or what the output looks like. For a file modification tool with zero annotation coverage, this is a significant gap.

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 concise and front-loaded with the core purpose in a single sentence: '對檔案進行精確的編輯,可以替換特定文字內容'. There's no wasted text or unnecessary elaboration. However, it could be slightly more structured by explicitly mentioning the parameters or usage context.

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 of a file editing tool with 3 parameters, no annotations, and no output schema, the description is incomplete. It doesn't explain the tool's behavior beyond basic functionality, doesn't provide usage guidance among similar tools, and leaves critical aspects like error handling, permissions, and output format undocumented. For a mutation tool in this context, the description should do more to compensate for the lack of structured metadata.

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 only 33% (1 of 3 parameters has a description in the schema). The description adds some value by implying the tool operates on text content ('替換特定文字內容'), which aligns with the 'edits' parameter. However, it doesn't explain the 'path' parameter or the 'dryRun' option beyond what the schema provides. The description partially compensates for the low schema coverage but doesn't fully address the parameter semantics gap.

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: '對檔案進行精確的編輯,可以替換特定文字內容' (perform precise editing on files, can replace specific text content). It specifies the verb ('edit') and resource ('files') with the specific operation of text replacement. However, it doesn't explicitly distinguish this tool from sibling tools like 'delete_from_file' or 'insert_to_file' that also modify files.

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 multiple sibling tools that modify files (e.g., 'delete_from_file', 'insert_to_file', 'fileWrite'), there's no indication of when text replacement is appropriate versus other editing operations. The description only states what the tool does, not when to choose it.

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