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 : '未知錯誤'}`;
        }
    }

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