|
| 1 | +"""Handler for appending content to text files.""" |
| 2 | + |
| 3 | +import json |
| 4 | +import logging |
| 5 | +import os |
| 6 | +import traceback |
| 7 | +from typing import Any, Dict, Sequence |
| 8 | + |
| 9 | +from mcp.types import TextContent, Tool |
| 10 | + |
| 11 | +from .base import BaseHandler |
| 12 | + |
| 13 | +logger = logging.getLogger("mcp-text-editor") |
| 14 | + |
| 15 | + |
| 16 | +class AppendTextFileContentsHandler(BaseHandler): |
| 17 | + """Handler for appending content to an existing text file.""" |
| 18 | + |
| 19 | + name = "append_text_file_contents" |
| 20 | + description = "Append content to an existing text file. The file must exist." |
| 21 | + |
| 22 | + def get_tool_description(self) -> Tool: |
| 23 | + """Get the tool description.""" |
| 24 | + return Tool( |
| 25 | + name=self.name, |
| 26 | + description=self.description, |
| 27 | + inputSchema={ |
| 28 | + "type": "object", |
| 29 | + "properties": { |
| 30 | + "file_path": { |
| 31 | + "type": "string", |
| 32 | + "description": "Path to the text file. File path must be absolute.", |
| 33 | + }, |
| 34 | + "contents": { |
| 35 | + "type": "string", |
| 36 | + "description": "Content to append to the file", |
| 37 | + }, |
| 38 | + "file_hash": { |
| 39 | + "type": "string", |
| 40 | + "description": "Hash of the file contents for concurrency control. it should be matched with the file_hash when get_text_file_contents is called.", |
| 41 | + }, |
| 42 | + "encoding": { |
| 43 | + "type": "string", |
| 44 | + "description": "Text encoding (default: 'utf-8')", |
| 45 | + "default": "utf-8", |
| 46 | + }, |
| 47 | + }, |
| 48 | + "required": ["file_path", "contents", "file_hash"], |
| 49 | + }, |
| 50 | + ) |
| 51 | + |
| 52 | + async def run_tool(self, arguments: Dict[str, Any]) -> Sequence[TextContent]: |
| 53 | + """Execute the tool with given arguments.""" |
| 54 | + try: |
| 55 | + if "file_path" not in arguments: |
| 56 | + raise RuntimeError("Missing required argument: file_path") |
| 57 | + if "contents" not in arguments: |
| 58 | + raise RuntimeError("Missing required argument: contents") |
| 59 | + if "file_hash" not in arguments: |
| 60 | + raise RuntimeError("Missing required argument: file_hash") |
| 61 | + |
| 62 | + file_path = arguments["file_path"] |
| 63 | + if not os.path.isabs(file_path): |
| 64 | + raise RuntimeError(f"File path must be absolute: {file_path}") |
| 65 | + |
| 66 | + # Check if file exists |
| 67 | + if not os.path.exists(file_path): |
| 68 | + raise RuntimeError(f"File does not exist: {file_path}") |
| 69 | + |
| 70 | + encoding = arguments.get("encoding", "utf-8") |
| 71 | + |
| 72 | + # Check file contents and hash before modification |
| 73 | + # Get file information and verify hash |
| 74 | + content, _, _, current_hash, total_lines, _ = ( |
| 75 | + await self.editor.read_file_contents(file_path, encoding=encoding) |
| 76 | + ) |
| 77 | + |
| 78 | + # Verify file hash |
| 79 | + if current_hash != arguments["file_hash"]: |
| 80 | + raise RuntimeError("File hash mismatch - file may have been modified") |
| 81 | + |
| 82 | + # Ensure the append content ends with newline |
| 83 | + append_content = arguments["contents"] |
| 84 | + if not append_content.endswith("\n"): |
| 85 | + append_content += "\n" |
| 86 | + |
| 87 | + # Create patch for append operation |
| 88 | + result = await self.editor.edit_file_contents( |
| 89 | + file_path, |
| 90 | + expected_hash=arguments["file_hash"], |
| 91 | + patches=[ |
| 92 | + { |
| 93 | + "start": total_lines + 1, |
| 94 | + "end": None, |
| 95 | + "contents": append_content, |
| 96 | + "range_hash": "", |
| 97 | + } |
| 98 | + ], |
| 99 | + encoding=encoding, |
| 100 | + ) |
| 101 | + |
| 102 | + return [TextContent(type="text", text=json.dumps(result, indent=2))] |
| 103 | + |
| 104 | + except Exception as e: |
| 105 | + logger.error(f"Error processing request: {str(e)}") |
| 106 | + logger.error(traceback.format_exc()) |
| 107 | + raise RuntimeError(f"Error processing request: {str(e)}") from e |
0 commit comments