insert_file_content
Insert content at specific row(s) in a file using a Terminal Controller for MCP. Specify file path, content, and row(s) for precise modifications.
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
| Name | Required | Description | Default |
|---|---|---|---|
| content | Yes | ||
| path | Yes | ||
| row | No | ||
| rows | No |
Implementation Reference
- terminal_controller.py:400-504 (handler)The core handler function for the 'insert_file_content' tool. It inserts content (string or JSON) into a file at specified row(s) or appends if no row specified. Registered via @mcp.tool() decorator. The docstring defines the tool schema including parameters and return type.@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)}"