insert_to_file
Insert content at specific positions in files using the GonMCPtool MCP server. Preview changes before applying them to modify code or text files precisely.
Instructions
在檔案的特定位置插入新內容
Input Schema
| Name | Required | Description | Default |
|---|---|---|---|
| path | Yes | ||
| position | Yes | ||
| content | Yes | 要插入的內容 | |
| dryRun | No | 預覽變更而不實際修改檔案 |
Implementation Reference
- tools/fileEditorTool.ts:70-121 (handler)Core handler function that reads the file, inserts content at the specified position (line number or marker), handles dry-run preview, and writes changes back to the file.
static async insertIntoFile( filePath: string, position: number | string, content: string, dryRun: boolean = false ): Promise<string> { try { // 檢查檔案是否存在 if (!existsSync(filePath)) { return `錯誤: 檔案 ${filePath} 不存在`; } // 讀取檔案內容 let fileContent = await fs.readFile(filePath, 'utf8'); let originalContent = fileContent; let lines = fileContent.split(/\r?\n/); // 處理不同的插入位置類型 if (typeof position === 'number') { // 按行號插入(行號從1開始) if (position < 1 || position > lines.length + 1) { return `錯誤: 行號 ${position} 超出範圍 (1 - ${lines.length + 1})`; } // 在指定行前插入 const insertIndex = position - 1; lines.splice(insertIndex, 0, content); fileContent = lines.join('\n'); } else if (typeof position === 'string') { // 按標記字符串插入 if (!fileContent.includes(position)) { return `錯誤: 在檔案中找不到標記「${position}」`; } // 在標記後插入 fileContent = fileContent.replace(position, position + content); } // 如果是預覽模式,生成差異報告 if (dryRun) { return this.generateDiff(originalContent, fileContent, filePath); } // 寫入檔案 await fs.writeFile(filePath, fileContent, 'utf8'); return `內容已成功插入檔案: ${filePath}`; } catch (error) { console.error(`插入內容時發生錯誤: ${error}`); return `插入內容時發生錯誤: ${error instanceof Error ? error.message : '未知錯誤'}`; } } - main.ts:245-268 (registration)Registers the 'insert_to_file' MCP tool with input schema and a thin async wrapper that calls the FileEditorTool.insertIntoFile method and formats the response.
server.tool("insert_to_file", "在檔案的特定位置插入新內容", { path: z.string(), position: z.union([ z.number().describe("行號 (從1開始)"), z.string().describe("作為標記的文字,內容將插入在此標記之後") ]), content: z.string().describe("要插入的內容"), dryRun: z.boolean().default(false).describe("預覽變更而不實際修改檔案") }, async ({ path, position, content, dryRun = false }) => { try { const result = await FileEditorTool.insertIntoFile(path, position, content, dryRun); return { content: [{ type: "text", text: result }] }; } catch (error) { return { content: [{ type: "text", text: `插入內容失敗: ${error instanceof Error ? error.message : "未知錯誤"}` }] }; } } ); - main.ts:248-255 (schema)Zod schema defining the input parameters for the insert_to_file tool: path, position (line or marker), content, and optional dryRun.
path: z.string(), position: z.union([ z.number().describe("行號 (從1開始)"), z.string().describe("作為標記的文字,內容將插入在此標記之後") ]), content: z.string().describe("要插入的內容"), dryRun: z.boolean().default(false).describe("預覽變更而不實際修改檔案") }, - tools/fileEditorTool.ts:203-228 (helper)Helper method used by insertIntoFile for generating a diff preview in dry-run mode, comparing old and new file contents line-by-line.
private static generateDiff(oldContent: string, newContent: string, filePath: string): string { const oldLines = oldContent.split(/\r?\n/); const newLines = newContent.split(/\r?\n/); let diff = `差異預覽 - ${filePath}\n`; diff += `===================================================================\n`; // 簡單的差異檢測 if (oldContent === newContent) { return '沒有變更'; } // 尋找不同的行 for (let i = 0; i < Math.max(oldLines.length, newLines.length); i++) { const oldLine = i < oldLines.length ? oldLines[i] : ''; const newLine = i < newLines.length ? newLines[i] : ''; if (oldLine !== newLine) { diff += `行 ${i+1}:\n`; diff += `- ${oldLine}\n`; diff += `+ ${newLine}\n\n`; } } return diff; }