file_modify
Modify file content by writing, appending, or inserting text at specified positions. Create directories if missing. Use with filepath and content inputs to manage files efficiently via MCP Terminal.
Instructions
Writes content to a file
Input Schema
TableJSON Schema
| Name | Required | Description | Default |
|---|---|---|---|
| content | Yes | ||
| create_dirs | No | ||
| filepath | Yes | ||
| mode | No | overwrite | |
| position | No |
Implementation Reference
- src/mcp_terminal/tools/file.py:57-120 (handler)The core handler for the 'file_modify' tool. This decorated async function implements writing content to a file with modes: overwrite (default), append, or insert at position. Handles directory creation, error handling, and returns FileOperationResponse.@mcp.tool(name="file_modify", description="Writes content to a file") async def file_modify( filepath: str, content: str, mode: WriteMode = WriteMode.OVERWRITE, position: Optional[int] = None, create_dirs: bool = True, ) -> FileOperationResponse: try: # Create directories if they don't exist if create_dirs: directory = os.path.dirname(filepath) if directory and not os.path.exists(directory): os.makedirs(directory) # Handle different write modes details = {"mode": mode} if mode == WriteMode.INSERT: if position is None: raise ValueError( "Position must be specified when using INSERT mode" ) # Read existing content if file exists existing_content = "" if os.path.exists(filepath): with open(filepath, "r", encoding="utf-8") as f: existing_content = f.read() # Insert the new content at the specified position position = min(position, len(existing_content)) new_content = ( existing_content[:position] + content + existing_content[position:] ) details["position"] = position # Write the combined content with open(filepath, "w", encoding="utf-8") as f: f.write(new_content) elif mode == WriteMode.APPEND: # Append to file with open(filepath, "a", encoding="utf-8") as f: f.write(content) else: # OVERWRITE # Overwrite file with open(filepath, "w", encoding="utf-8") as f: f.write(content) return FileOperationResponse( success=True, filepath=filepath, details=details ) except Exception as e: logger.error(f"Error writing to file {filepath}: {e}") return FileOperationResponse( success=False, error=f"Error writing to file: {str(e)}", filepath=filepath, )
- src/mcp_terminal/server.py:100-102 (registration)Registers the FileTool by instantiating it and calling register_mcp(self.mcp), which triggers the @mcp.tool decorator for file_modify.file_tool = FileTool() terminal_tool.register_mcp(self.mcp) file_tool.register_mcp(self.mcp)
- src/mcp_terminal/tools/file.py:31-41 (schema)Pydantic BaseModel FileOperationResponse defining the output schema: success, error, filepath, details.class FileOperationResponse(BaseModel): """Response model for file operations.""" success: bool = Field(..., description="Whether the operation was successful") error: Optional[str] = Field( None, description="Error message if the operation failed" ) filepath: str = Field(..., description="Path to the file that was operated on") details: Optional[Dict[str, Any]] = Field( None, description="Additional operation details" )
- src/mcp_terminal/tools/file.py:23-28 (schema)Enum WriteMode defining input parameter 'mode': OVERWRITE, APPEND, INSERT.class WriteMode(str, Enum): """Enum representing different file writing modes.""" OVERWRITE = "overwrite" # Overwrite the entire file APPEND = "append" # Append to the end of the file INSERT = "insert" # Insert at a specific position