Skip to main content
Glama
GongRzhe

Terminal Controller for MCP

by GongRzhe

delete_file_content

Delete specific rows or substrings from a file using row numbers or substring matching.

Instructions

Delete content at specific row(s) from a file

Args:
    path: Path to the file
    row: Row number to delete (0-based, optional)
    rows: List of row numbers to delete (0-based, optional)
    substring: If provided, only delete this substring within the specified row(s), not the entire row (optional)

Returns:
    Operation result information

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
pathYes
rowNo
rowsNo
substringNo

Implementation Reference

  • Tool registration via @mcp.tool() decorator on the delete_file_content function
    @mcp.tool()
    async def delete_file_content(path: str, row: int = None, rows: list = None, substring: str = None) -> str:
  • Main handler function that deletes content from a file. Supports: deleting a single row, multiple rows, substring removal within rows, or clearing entire file when no params specified.
    async def delete_file_content(path: str, row: int = None, rows: list = None, substring: str = None) -> str:
        """
        Delete content at specific row(s) from a file
        
        Args:
            path: Path to the file
            row: Row number to delete (0-based, optional)
            rows: List of row numbers to delete (0-based, optional)
            substring: If provided, only delete this substring within the specified row(s), not the entire row (optional)
        
        Returns:
            Operation result information
        """
        try:
            if not os.path.exists(path):
                return f"Error: File '{path}' does not exist."
                
            if not os.path.isfile(path):
                return f"Error: '{path}' is not a file."
                
            with open(path, 'r', encoding='utf-8', errors='replace') as file:
                lines = file.readlines()
            
            total_lines = len(lines)
            deleted_rows = []
            modified_rows = []
            
            # Handle substring deletion (doesn't delete entire rows)
            if substring is not None:
                # For multiple rows
                if rows is not None:
                    if not isinstance(rows, list):
                        return "Error: 'rows' parameter must be a list of integers."
                    
                    for r in rows:
                        if not isinstance(r, int) or r < 0:
                            return "Error: Row numbers must be non-negative integers."
                            
                        if r < total_lines and substring in lines[r]:
                            original_line = lines[r]
                            lines[r] = lines[r].replace(substring, '')
                            # Ensure line ends with newline if original did
                            if original_line.endswith('\n') and not lines[r].endswith('\n'):
                                lines[r] += '\n'
                            modified_rows.append(r)
                
                # For single row
                elif row is not None:
                    if not isinstance(row, int) or row < 0:
                        return "Error: Row number must be a non-negative integer."
                        
                    if row >= total_lines:
                        return f"Error: Row {row} is out of range (file has {total_lines} lines)."
                        
                    if substring in lines[row]:
                        original_line = lines[row]
                        lines[row] = lines[row].replace(substring, '')
                        # Ensure line ends with newline if original did
                        if original_line.endswith('\n') and not lines[row].endswith('\n'):
                            lines[row] += '\n'
                        modified_rows.append(row)
                
                # For entire file
                else:
                    for i in range(len(lines)):
                        if substring in lines[i]:
                            original_line = lines[i]
                            lines[i] = lines[i].replace(substring, '')
                            # Ensure line ends with newline if original did
                            if original_line.endswith('\n') and not lines[i].endswith('\n'):
                                lines[i] += '\n'
                            modified_rows.append(i)
                
                # Write back to the file
                with open(path, 'w', encoding='utf-8') as file:
                    file.writelines(lines)
                    
                if not modified_rows:
                    return f"No occurrences of '{substring}' found in the specified rows."
                return f"Successfully removed '{substring}' from {len(modified_rows)} rows ({modified_rows}) in '{path}'."
            
            # Handle deleting multiple rows
            elif rows is not None:
                if not isinstance(rows, list):
                    return "Error: 'rows' parameter must be a list of integers."
                    
                # Sort rows in descending order to avoid changing indices during deletion
                rows = sorted(rows, reverse=True)
                
                for r in rows:
                    if not isinstance(r, int) or r < 0:
                        return "Error: Row numbers must be non-negative integers."
                        
                    if r < total_lines:
                        lines.pop(r)
                        deleted_rows.append(r)
                
                # Write back to the file
                with open(path, 'w', encoding='utf-8') as file:
                    file.writelines(lines)
                    
                if not deleted_rows:
                    return f"No rows were within range to delete (file has {total_lines} lines)."
                return f"Successfully deleted {len(deleted_rows)} rows ({deleted_rows}) from '{path}'."
                
            # Handle deleting a single row
            elif row is not None:
                if not isinstance(row, int) or row < 0:
                    return "Error: Row number must be a non-negative integer."
                    
                if row >= total_lines:
                    return f"Error: Row {row} is out of range (file has {total_lines} lines)."
                    
                # Delete the specified row
                lines.pop(row)
                
                # Write back to the file
                with open(path, 'w', encoding='utf-8') as file:
                    file.writelines(lines)
                    
                return f"Successfully deleted row {row} from '{path}'."
            
            # If neither row nor rows specified, clear the file
            else:
                with open(path, 'w', encoding='utf-8') as file:
                    pass
                return f"Successfully cleared all content from '{path}'."
                
        except PermissionError:
            return f"Error: No permission to modify file '{path}'."
        except Exception as e:
            return f"Error deleting content: {str(e)}"

Schema Changelog

Changes observed during successful MCP inspections.

  1. First observed

TDQS

A3.6/5.0
Behavior3/5

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

The description discloses that substring deletion only removes the substring within the row, not the entire row. However, with no annotations, it fails to mention destructive nature, error handling, or index behavior (e.g., shifting after deletion).

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

Conciseness4/5

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

The description is structured with Args and Returns, and each parameter is explained in a single line. It is not overly verbose, though it could omit 'Args:' and 'Returns:' for brevity.

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 tool with no annotations and no output schema, the description omits important details: error cases (e.g., invalid row), behavior when both row and rows are provided, and return value. This leaves significant gaps for an agent.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters5/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema coverage is 0%, but the description adds full meaning: row is 0-based integer, rows is list, substring optional for partial deletion. This compensates entirely for the missing schema explanations.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the tool deletes content at specific rows from a file, using a specific verb and resource. It distinguishes from siblings like update_file_content and insert_file_content by focusing on deletion.

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?

No explicit guidance on when to use this tool versus alternatives such as update_file_content or write_file. The description lacks context for choosing between row deletion and substring deletion.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.