Skip to main content
Glama
GongRzhe

Terminal Controller for MCP

insert_file_content

Insert content at specific row(s) in a file using path and content parameters, with optional row or rows arguments for precise placement.

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 for the 'insert_file_content' tool. This async function accepts path, content, and optional row/rows parameters. It handles inserting content at specific row(s) in a file, creating the file if it doesn't exist, and appending content if neither row nor rows is specified. Decorated with @mcp.tool() which registers it as an MCP tool.
    @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)}"
  • The tool is registered via the @mcp.tool() decorator on line 400. The 'mcp' object is a FastMCP instance created on line 11 with name 'terminal-controller'.
    @mcp.tool()
Behavior2/5

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

No annotations are provided, so the description must disclose behavioral traits. It mentions 0-based row numbering and that content can be a string or JSON object, but does not explain what happens if rows exceed file length, whether content is inserted as new lines, or if existing content is shifted. Critical safety information is missing.

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

Conciseness3/5

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

The description is a docstring with Args and Returns sections. It is fairly concise but the Returns line is vague ('Operation result information'). Some content, like the repetition of 0-based row information, could be condensed.

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?

Given 4 parameters, no output schema, and no annotations, the description lacks behavioral details (e.g., error handling, row insertion behavior) and return value structure. It provides basic parameter descriptions but is incomplete for safe and effective agent use.

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 coverage is 0%, so the description must compensate. It adds context: 'Content to insert (string or JSON object)' and specifies 0-based row numbering. However, it does not clarify the relationship between 'row' and 'rows' (e.g., exclusive or cumulative) nor specify the type of items in the 'rows' array beyond the schema's generic 'items': {}.

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 states 'Insert content at specific row(s) in a file', which is a specific verb+resource combination. It clearly distinguishes from sibling tools like write_file, update_file_content, and delete_file_content by focusing on insertion at specific rows.

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 guidance on when to use this tool vs alternatives. The description lists arguments but does not clarify when insert is preferred over write or update. This leaves the agent uncertain about tool selection.

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

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