Skip to main content
Glama

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

TableJSON Schema
NameRequiredDescriptionDefault
pathYes
positionYes
contentYes要插入的內容
dryRunNo預覽變更而不實際修改檔案

Implementation Reference

  • 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 : "未知錯誤"}` }]
                };
            }
        }
    );
  • 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("預覽變更而不實際修改檔案")
    },
  • 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;
    }
Behavior2/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

With no annotations provided, the description carries full burden for behavioral disclosure. It states the tool inserts content but doesn't mention whether this modifies files permanently, requires specific permissions, handles errors, or what happens if the position is invalid. The 'dryRun' parameter suggests preview capability, but this isn't explained in the description itself.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is a single, clear sentence in Chinese that directly states the tool's function. It's front-loaded with the core action and contains no unnecessary words or redundant information. Every part of the sentence contributes to understanding the tool's purpose.

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?

For a file modification tool with 4 parameters, no annotations, and no output schema, the description is insufficient. It doesn't explain the mutation behavior, error conditions, position format (line number vs. character offset), or what the tool returns. The presence of a 'dryRun' parameter suggests important behavioral nuances that aren't addressed in the description.

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 50% (only 'content' and 'dryRun' have descriptions). The description mentions '特定位置' (specific position) which aligns with the 'position' parameter, and '新內容' (new content) which aligns with 'content'. However, it doesn't explain what 'path' represents or provide additional context about parameter formats, constraints, or interactions beyond what's minimally implied.

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 action ('插入新內容' - insert new content) and target resource ('在檔案的特定位置' - at a specific position in a file). It distinguishes from obvious siblings like 'delete_from_file' and 'edit_file' by specifying insertion rather than deletion or general editing. However, it doesn't explicitly differentiate from 'codeLineInsert' which might be a more specific sibling.

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 like 'edit_file', 'codeLineInsert', or 'fileWrite'. There's no mention of prerequisites, constraints, or typical use cases. The agent must infer usage from the tool name and description alone.

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