Skip to main content
Glama
TwT23333
by TwT23333

write_file

Write content to a file, automatically creating necessary parent directories for storage. Specify file path and content to streamline file management tasks.

Instructions

Write content to a file. Creates parent directories if needed.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
contentYesContent to write to the file
file_pathYesPath to the file to write (relative to workspace root)

Implementation Reference

  • The execute method of WriteFileTool class that implements the core logic for the write_file tool: validates input, delegates writing to workspace file context, computes stats, and returns ToolResult.
    async def execute(self, arguments: Dict[str, Any]) -> ToolResult:
        try:
            self.validate_arguments(arguments)
            
            file_path = arguments["file_path"]
            content = arguments["content"]
            
            # Write file content
            self.workspace.get_file_context().write_file_content(file_path, content)
            
            lines = content.splitlines()
            size_bytes = len(content.encode('utf-8'))
            
            return ToolResult(
                message=f"Successfully wrote {len(lines)} lines ({size_bytes} bytes) to {file_path}",
                properties={
                    "file_path": file_path,
                    "lines_written": len(lines),
                    "size_bytes": size_bytes
                }
            )
            
        except Exception as e:
            logger.error(f"Error writing file {arguments.get('file_path', 'unknown')}: {e}")
            return self.format_error(e)
  • Input schema definition for write_file tool, specifying file_path and content as required string parameters.
    def input_schema(self) -> Dict[str, Any]:
        return {
            "type": "object",
            "properties": {
                "file_path": {
                    "type": "string",
                    "description": "Path to the file to write (relative to workspace root)"
                },
                "content": {
                    "type": "string",
                    "description": "Content to write to the file"
                }
            },
            "required": ["file_path", "content"]
        }
  • Registration of WriteFileTool (line 54) along with other default tools in ToolRegistry._register_default_tools method, which instantiates and registers all tools by name.
    def _register_default_tools(self):
        """Register all default tools"""
        
        # File operation tools
        tools = [
            ReadFileTool(self.workspace),
            WriteFileTool(self.workspace),
            ListFilesTool(self.workspace),
            StringReplaceTool(self.workspace),
            
            # Search tools
            GrepTool(self.workspace),
            FindFilesTool(self.workspace),
            WorkspaceInfoTool(self.workspace),
            
            # Advanced tools
            FindClassTool(self.workspace),
            FindFunctionTool(self.workspace),
            ViewCodeTool(self.workspace),
            SemanticSearchTool(self.workspace),
            RunTestsTool(self.workspace),
            
            # Vector database tools
            BuildVectorIndexTool(self.workspace),
            VectorIndexStatusTool(self.workspace),
            ClearVectorIndexTool(self.workspace),
    
            # Project Understand tools
            ProjectUnderstandTool(self.workspace),
        ]
        
        for tool in tools:
            self.register_tool(tool)
        
        logger.info(f"Registered {len(self.tools)} tools")
  • Low-level file writing implementation in FileContext.write_file_content, called by the tool handler. Handles permissions, directory creation, UTF-8 writing, and cache update.
    def write_file_content(self, file_path: str, content: str) -> None:
        """Write content to file"""
        full_path = self.workspace_path / file_path
        
        if not self.config.is_file_allowed(full_path):
            raise PermissionError(f"File access not allowed: {file_path}")
        
        # Create parent directories if needed
        full_path.parent.mkdir(parents=True, exist_ok=True)
        
        with open(full_path, 'w', encoding='utf-8') as f:
            f.write(content)
        
        # Update cache
        self._file_cache[file_path] = content
Install Server

Other Tools

Related 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/TwT23333/mcp'

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