Skip to main content
Glama
sichang824

MCP Terminal

by sichang824

file_modify

Modify file content by writing, appending, or inserting text at specific positions within files on the MCP Terminal server.

Instructions

Writes content to a file

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
filepathYes
contentYes
modeNooverwrite
positionNo
create_dirsNo

Implementation Reference

  • The core handler function for the 'file_modify' tool. It writes content to a specified file path using one of three modes: overwrite, append, or insert at a position. Handles directory creation, error logging, and returns a structured response.
    @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,
            )
  • Pydantic model defining the response structure for file operations, including success status, error message, filepath, and details. Used as return type for file_modify.
    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"
        )
  • Enum defining the write modes supported by the file_modify tool: 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
  • In the register_tools method of MCPTerminalServer, the FileTool instance is created and its register_mcp method is called on the FastMCP server instance, which in turn registers the file_modify tool via its decorator.
    terminal_tool = TerminalTool(
        self.controller_type,
        whitelist_file=self.whitelist_file,
        blacklist_file=self.blacklist_file,
        whitelist_mode=self.whitelist_mode,
    )
    file_tool = FileTool()
    terminal_tool.register_mcp(self.mcp)
    file_tool.register_mcp(self.mcp)
    self.tools["terminal"] = terminal_tool
    self.tools["file"] = file_tool
Behavior2/5

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

With no annotations provided, the description carries the full burden of behavioral disclosure. 'Writes content to a file' indicates a mutation operation but fails to detail critical aspects such as permissions required, error handling (e.g., if the file doesn't exist), side effects, or response format. It doesn't contradict annotations (none exist), but offers minimal behavioral insight beyond the basic action.

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

Conciseness5/5

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

The description is extremely concise with 'Writes content to a file', a single sentence that front-loads the core action without unnecessary words. It's appropriately sized for the basic purpose, though this brevity contributes to gaps in other dimensions.

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 the complexity (5 parameters, mutation tool, no annotations, no output schema), the description is incomplete. It doesn't explain parameter roles, behavioral traits, or return values, leaving the agent with insufficient information to use the tool effectively. The conciseness comes at the cost of essential details needed for proper invocation.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters1/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema description coverage is 0%, meaning parameters like 'filepath', 'content', 'mode', 'position', and 'create_dirs' are undocumented in the schema. The description adds no meaning beyond the basic action, failing to explain what these parameters do, their formats, or how they affect the write operation. For a tool with 5 parameters, this is a significant gap.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose3/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description 'Writes content to a file' clearly states the verb ('writes') and resource ('a file'), making the basic purpose understandable. However, it lacks specificity about what kind of writing (e.g., overwriting, appending) and doesn't differentiate from potential sibling tools like 'execute_command' or 'get_terminal_info', which are unrelated to file operations. It's not tautological but remains somewhat vague.

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?

The description provides no guidance on when to use this tool versus alternatives. There are no explicit instructions on scenarios for application, prerequisites, or comparisons with sibling tools (e.g., 'execute_command' for command execution vs. file writing). Usage is implied by the action but lacks contextual direction.

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

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