Skip to main content
Glama

delete_from_file

Remove specific content from files by exact text, line numbers, or markers. Preview changes before applying them to ensure accurate file modifications.

Instructions

從檔案中刪除特定內容

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
pathYes
selectorYes
dryRunNo預覽變更而不實際修改檔案

Implementation Reference

  • The primary handler function implementing the deletion logic for various selector types: exact text string, line range {startLine, endLine}, or between start/end markers.
    static async deleteFromFile(
        filePath: string, 
        selector: string | {startLine: number, endLine?: number} | {start: string, end: string}, 
        dryRun: boolean = false
    ): Promise<string> {
        try {
            // 檢查檔案是否存在
            if (!existsSync(filePath)) {
                return `錯誤: 檔案 ${filePath} 不存在`;
            }
    
            // 讀取檔案內容
            let fileContent = await fs.readFile(filePath, 'utf8');
            let originalContent = fileContent;
            
            // 根據不同的選擇器類型處理刪除操作
            if (typeof selector === 'string') {
                // 刪除特定文字
                if (!fileContent.includes(selector)) {
                    return `錯誤: 在檔案中找不到文字「${selector}」`;
                }
                
                fileContent = fileContent.replace(selector, '');
            } else if ('startLine' in selector) {
                // 刪除行範圍
                const lines = fileContent.split(/\r?\n/);
                const startLine = selector.startLine;
                const endLine = selector.endLine || startLine;
                
                if (startLine < 1 || startLine > lines.length || endLine < startLine || endLine > lines.length) {
                    return `錯誤: 行範圍 ${startLine}-${endLine} 超出檔案範圍 (1-${lines.length})`;
                }
                
                // 刪除指定行範圍
                lines.splice(startLine - 1, endLine - startLine + 1);
                fileContent = lines.join('\n');
            } else if ('start' in selector && 'end' in selector) {
                // 刪除兩個標記之間的內容
                const startPos = fileContent.indexOf(selector.start);
                const endPos = fileContent.indexOf(selector.end, startPos + selector.start.length);
                
                if (startPos === -1 || endPos === -1) {
                    return `錯誤: 在檔案中找不到指定的標記範圍`;
                }
                
                // 刪除開始標記到結束標記之間的內容(包括標記)
                const beforeStart = fileContent.substring(0, startPos);
                const afterEnd = fileContent.substring(endPos + selector.end.length);
                fileContent = beforeStart + afterEnd;
            }
            
            // 如果是預覽模式,生成差異報告
            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 : '未知錯誤'}`;
        }
    }
  • Zod schema defining the input parameters for the delete_from_file tool: path, selector (union of string, line range object, or marker range object), and dryRun flag.
    {
        path: z.string(),
        selector: z.union([
            z.string().describe("要刪除的確切文字"),
            z.object({
                startLine: z.number().describe("開始行號 (從1開始)"),
                endLine: z.number().optional().describe("結束行號,如果省略則只刪除單行")
            }),
            z.object({
                start: z.string().describe("開始標記文字"),
                end: z.string().describe("結束標記文字")
            })
        ]),
        dryRun: z.boolean().default(false).describe("預覽變更而不實際修改檔案")
    },
  • main.ts:271-300 (registration)
    MCP server tool registration for 'delete_from_file', including description, input schema, and thin async handler that delegates to FileEditorTool.deleteFromFile and formats the response.
    server.tool("delete_from_file",
        "從檔案中刪除特定內容",
        {
            path: z.string(),
            selector: z.union([
                z.string().describe("要刪除的確切文字"),
                z.object({
                    startLine: z.number().describe("開始行號 (從1開始)"),
                    endLine: z.number().optional().describe("結束行號,如果省略則只刪除單行")
                }),
                z.object({
                    start: z.string().describe("開始標記文字"),
                    end: z.string().describe("結束標記文字")
                })
            ]),
            dryRun: z.boolean().default(false).describe("預覽變更而不實際修改檔案")
        },
        async ({ path, selector, dryRun = false }) => {
            try {
                const result = await FileEditorTool.deleteFromFile(path, selector, dryRun);
                return {
                    content: [{ type: "text", text: result }]
                };
            } catch (error) {
                return {
                    content: [{ type: "text", text: `刪除內容失敗: ${error instanceof Error ? error.message : "未知錯誤"}` }]
                };
            }
        }
    );
Behavior2/5

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

With no annotations provided, the description carries the full burden of behavioral disclosure. While '刪除' implies a destructive operation, it doesn't specify permissions required, whether changes are reversible, error handling, or side effects. The dryRun parameter hints at 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, efficient sentence with no wasted words. It's appropriately brief and front-loaded with the core action, though this conciseness comes at the expense of completeness.

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 destructive file operation with 3 parameters (2 required), no annotations, and no output schema, the description is insufficient. It lacks details on behavior, error cases, permissions, and doesn't explain the relationship with sibling tools, leaving significant gaps for the agent to navigate.

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?

The description mentions '特定內容' (specific content), which loosely relates to the 'selector' parameter, but adds minimal value beyond what's in the schema. With 33% schema description coverage (only 'dryRun' has a description), the description doesn't adequately compensate for the undocumented 'path' and 'selector' parameters, though it hints at their purpose.

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 (delete) and target (specific content from a file), making the purpose understandable. However, it doesn't explicitly differentiate from sibling tools like 'codeLineDelete' or 'edit_file', which appear to have overlapping functionality.

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 'codeLineDelete' or 'edit_file'. There's no mention of prerequisites, context, or comparison with sibling tools, leaving the agent with insufficient information to choose appropriately.

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