codeLineInsert
Insert content into a specified line of a code file, shifting existing content downward. Works with the GonMCPtool MCP server for precise code modifications without altering formatting unnecessarily.
Instructions
每次使用前、使用後必須先使用(codeFileRead)。在程式碼檔案指定行插入內容,原內容將向下移動。(如果不影響編譯器的話,不需要針對縮排等小問題修改。提醒User就好了)
Input Schema
TableJSON Schema
| Name | Required | Description | Default |
|---|---|---|---|
| content | Yes | ||
| filePath | Yes | ||
| indentToMatch | No | ||
| lineNumber | Yes |
Implementation Reference
- tools/csLineInserter.ts:16-60 (handler)Core implementation of the line insertion logic, reading the file, inserting content at the specified line (shifting existing lines down), optionally matching indentation, and writing back to the file.static async insertAtLine( filePath: string, lineNumber: number, content: string, indentToMatch: boolean = true ): Promise<string> { try { // 檢查檔案是否存在 if (!existsSync(filePath)) { return `錯誤: 檔案 ${filePath} 不存在`; } // 讀取檔案內容 const fileContent = await fs.readFile(filePath, 'utf8'); const lines = fileContent.split(/\r?\n/); // 檢查行號是否有效 if (lineNumber < 1 || lineNumber > lines.length) { return `錯誤: 行號 ${lineNumber} 超出範圍,檔案共有 ${lines.length} 行`; } // 處理縮排匹配 let contentToInsert = content; if (indentToMatch) { const targetLine = lines[lineNumber - 1]; const indent = targetLine.match(/^(\s*)/)?.[1] || ''; contentToInsert = content.split(/\r?\n/).map(line => { // 跳過空行的縮排處理 if (line.trim() === '') return line; return indent + line; }).join('\n'); } // 插入內容(在指定行號 -1 的位置插入,使原內容向下移動) lines.splice(lineNumber - 1, 0, contentToInsert); // 寫回檔案 await fs.writeFile(filePath, lines.join('\n'), 'utf8'); return `成功在第 ${lineNumber} 行插入內容`; } catch (error) { console.error(`插入內容時發生錯誤: ${error}`); return `插入內容時發生錯誤: ${error instanceof Error ? error.message : '未知錯誤'}`; } }
- main.ts:89-94 (schema)Zod schema defining the input parameters for the codeLineInsert tool.{ filePath: z.string(), lineNumber: z.number(), content: z.string(), indentToMatch: z.boolean().optional() },
- main.ts:87-107 (registration)Registers the 'codeLineInsert' tool with the MCP server, including description, input schema, and a thin async handler that delegates to myFileInsert.insertAtLine and formats the response.server.tool("codeLineInsert", "每次使用前、使用後必須先使用(codeFileRead)。在程式碼檔案指定行插入內容,原內容將向下移動。(如果不影響編譯器的話,不需要針對縮排等小問題修改。提醒User就好了)", { filePath: z.string(), lineNumber: z.number(), content: z.string(), indentToMatch: z.boolean().optional() }, async ({ filePath, lineNumber, content, indentToMatch = true }) => { try { const result = await myFileInsert.insertAtLine(filePath, lineNumber, content, indentToMatch); return { content: [{ type: "text", text: result }] }; } catch (error) { return { content: [{ type: "text", text: `插入內容失敗: ${error instanceof Error ? error.message : "未知錯誤"}` }] }; } } );