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
Behavior2/5

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

No annotations are provided, so the description carries the full burden of behavioral disclosure. It mentions that parent directories are created if needed, which is useful context, but it fails to disclose critical traits such as whether the operation overwrites existing files, requires specific permissions, handles errors (e.g., invalid paths), or has side effects. For a mutation tool with zero annotation coverage, this is a significant gap.

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 and front-loaded, consisting of only two sentences that directly state the tool's action and a key behavioral trait. Every word earns its place, with no redundant or vague language, making it efficient and easy to parse.

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 that this is a mutation tool with no annotations and no output schema, the description is incomplete. It lacks information on behavioral aspects like overwriting behavior, error handling, or return values, which are crucial for safe and effective use. The description does not compensate for the absence of structured data, leaving significant gaps in understanding.

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

Parameters3/5

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

The schema description coverage is 100%, meaning the input schema already fully documents both parameters ('content' and 'file_path'). The description does not add any additional meaning beyond what the schema provides, such as format details or constraints. However, since the schema coverage is high, the baseline score of 3 is appropriate as the description does not need to compensate.

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

Purpose5/5

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

The description clearly states the specific action ('Write content to a file') and resource ('a file'), distinguishing it from sibling tools like 'read_file' (which reads) and 'list_files' (which lists). It also mentions the additional behavior of creating parent directories, which further clarifies its purpose beyond basic file writing.

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. For example, it does not mention when to use 'write_file' over 'string_replace' (which modifies file content) or 'find_files' (which searches files), nor does it specify prerequisites like file permissions or workspace context. This lack of comparative context leaves usage unclear.

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

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