Skip to main content
Glama

codeLineInsert

Insert content at a specific line in code files, shifting existing content downward. Use with codeFileRead for proper file handling.

Instructions

每次使用前、使用後必須先使用(codeFileRead)。在程式碼檔案指定行插入內容,原內容將向下移動。(如果不影響編譯器的話,不需要針對縮排等小問題修改。提醒User就好了)

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
filePathYes
lineNumberYes
contentYes
indentToMatchNo

Implementation Reference

  • main.ts:87-107 (registration)
    Registration of the codeLineInsert tool with MCP server, including description, Zod input schema, and inline async handler that calls the core implementation.
    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 : "未知錯誤"}` }]
                };
            }
        }
    );
  • main.ts:90-94 (schema)
    Input schema using Zod for validating tool parameters: filePath (string), lineNumber (number), content (string), indentToMatch (optional boolean).
        filePath: z.string(),
        lineNumber: z.number(),
        content: z.string(),
        indentToMatch: z.boolean().optional()
    },
  • Core implementation of the line insertion logic: reads the file, validates line number, optionally matches indentation from target line, inserts the new content, and writes back to 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 : '未知錯誤'}`;
        }
    }
  • The myFileInsert class providing the static insertAtLine method used by the tool handler.
    export class myFileInsert {
        /**
         * 在指定行插入內容
         * @param filePath 檔案路徑
         * @param lineNumber 行號(在此行插入內容,原內容將向下移動)
         * @param content 要插入的內容
         * @param indentToMatch 是否匹配目標行的縮排
         * @returns 操作結果訊息
         */
        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 : '未知錯誤'}`;
            }
        }
    }

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