Skip to main content
Glama
GongRzhe

Terminal Controller for MCP

insert_file_content

Insert content at specific rows in a file to modify text or data precisely within the Terminal Controller for MCP server.

Instructions

Insert content at specific row(s) in a file

Args:
    path: Path to the file
    content: Content to insert (string or JSON object)
    row: Row number to insert at (0-based, optional)
    rows: List of row numbers to insert at (0-based, optional)

Returns:
    Operation result information

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
pathYes
contentYes
rowNo
rowsNo

Implementation Reference

  • The main handler function for the 'insert_file_content' MCP tool. It handles inserting string or JSON content into a file at specified row(s) (0-based indexing), or appending if no row specified. Supports creating directories/files if needed, handles line endings, and provides detailed error messages.
    @mcp.tool()
    async def insert_file_content(path: str, content: str, row: int = None, rows: list = None) -> str:
        """
        Insert content at specific row(s) in a file
        
        Args:
            path: Path to the file
            content: Content to insert (string or JSON object)
            row: Row number to insert at (0-based, optional)
            rows: List of row numbers to insert at (0-based, optional)
        
        Returns:
            Operation result information
        """
        try:
            # Handle different content types
            if not isinstance(content, str):
                try:
                    import json
                    content = json.dumps(content, indent=4, sort_keys=False, ensure_ascii=False, default=str)
                except Exception as e:
                    return f"Error: Unable to convert content to JSON string: {str(e)}"
                
            # Ensure content ends with a newline if it doesn't already
            if content and not content.endswith('\n'):
                content += '\n'
                
            # Create file if it doesn't exist
            directory = os.path.dirname(os.path.abspath(path))
            if not os.path.exists(directory):
                os.makedirs(directory, exist_ok=True)
                
            if not os.path.exists(path):
                with open(path, 'w', encoding='utf-8') as file:
                    pass
                
            with open(path, 'r', encoding='utf-8', errors='replace') as file:
                lines = file.readlines()
            
            # Ensure all existing lines end with newlines
            for i in range(len(lines)):
                if lines[i] and not lines[i].endswith('\n'):
                    lines[i] += '\n'
            
            # Prepare lines for insertion
            content_lines = content.splitlines(True)  # Keep line endings
            
            # Handle inserting at specific rows
            if 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 insertion
                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 > len(lines):
                        # If row is beyond the file, append necessary empty lines
                        lines.extend(['\n'] * (r - len(lines)))
                        lines.extend(content_lines)
                    else:
                        # Insert content at each specified row
                        for line in reversed(content_lines):
                            lines.insert(r, line)
                
                # Write back to the file
                with open(path, 'w', encoding='utf-8') as file:
                    file.writelines(lines)
                    
                return f"Successfully inserted content at rows {rows} in '{path}'."
                
            # Handle inserting at 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 > len(lines):
                    # If row is beyond the file, append necessary empty lines
                    lines.extend(['\n'] * (row - len(lines)))
                    lines.extend(content_lines)
                else:
                    # Insert content at the specified row
                    for line in reversed(content_lines):
                        lines.insert(row, line)
                
                # Write back to the file
                with open(path, 'w', encoding='utf-8') as file:
                    file.writelines(lines)
                    
                return f"Successfully inserted content at row {row} in '{path}'."
            
            # If neither row nor rows specified, append to the end
            else:
                with open(path, 'a', encoding='utf-8') as file:
                    file.write(content)
                return f"Successfully appended content to '{path}'."
                
        except PermissionError:
            return f"Error: No permission to modify file '{path}'."
        except Exception as e:
            return f"Error inserting content: {str(e)}"

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/GongRzhe/terminal-controller-mcp'

If you have feedback or need assistance with the MCP directory API, please join our Discord server