Skip to main content
Glama

write

Create new files or overwrite existing files by writing complete content to specified paths, with optional parent directory creation.

Instructions

Write complete file contents (create new files or overwrite existing files)

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
pathYesFile path to write
contentYesComplete file content to write
createParentDirNoCreate parent directories if they don't exist (default: false)

Implementation Reference

  • Core handler function that validates input, checks safety conditions, ensures parent directories, writes the file content, and formats the response.
    async execute(args: any): Promise<any> {
      try {
        // Validate and parse input using Zod schema
        const validatedArgs = WriteToolInputSchema.parse(args);
        const { path: filePath, content, createParentDir } = validatedArgs;
    
        const resolvedPath = resolve(filePath);
    
        // Security validation
        await ToolValidation.validateFileAccess(resolvedPath);
    
        // Check if file exists and enforce read requirement for existing files
        let fileExists = false;
        try {
          await access(resolvedPath);
          fileExists = true;
        } catch {
          // File doesn't exist, which is fine for write operations
        }
    
        if (fileExists && !fileReadTracker.isFileRead(resolvedPath)) {
          throw ToolError.createValidationError(
            "filePath",
            filePath,
            `File must be read first. Use read(path="${filePath}") before overwriting to ensure safety`
          );
        }
    
        ToolValidation.validateContentSize(content, "write operation");
    
        // Ensure parent directory exists if needed
        await this.ensureParentDirectory(resolvedPath, createParentDir);
    
        // Write the file
        await writeFile(resolvedPath, content, "utf-8");
    
        // Mark file as read after writing (for subsequent edits)
        fileReadTracker.markFileAsRead(resolvedPath);
    
        // Generate result display
        const resultDisplay = await ResultFormatter.generateFilePreview(
          filePath,
          `Successfully wrote ${content.length} characters to ${filePath}`,
          undefined,
          content.length
        );
    
        return ResultFormatter.createResponse(resultDisplay);
      } catch (error: any) {
        // Handle Zod validation errors
        if (error instanceof Error && error.name === "ZodError") {
          throw ToolError.createValidationError("input", args, `Invalid input: ${error.message}`);
        }
        throw ToolError.wrapError("Write operation", error);
      }
    }
  • Zod input schema for the write tool used for validation in the execute method.
    // Write tool input schema
    export const WriteToolInputSchema = z.object({
      path: FilePathSchema,
      content: FileContentSchema,
      createParentDir: BooleanFlagSchema,
    });
  • Registration of the write tool's definition in the server's list of available tools via getTools().
    protected getTools(): Tool[] {
      return [
        this.readTool.getDefinition(),
        this.findTool.getDefinition(),
        this.grepTool.getDefinition(),
        this.writeTool.getDefinition(),
        this.editTool.getDefinition(),
        this.moveTool.getDefinition(),
        this.copyTool.getDefinition(),
      ];
    }
  • Dispatch logic in handleToolCall that routes 'write' tool calls to the WriteTool.execute method.
    case "write":
      return await this.writeTool.execute(args);
  • Helper method to ensure the parent directory exists before writing the file, creating it if createParentDir is true.
    private async ensureParentDirectory(filePath: string, createParentDir: boolean): Promise<void> {
      const parentDir = dirname(filePath);
    
      try {
        await access(parentDir);
      } catch {
        if (createParentDir) {
          await mkdir(parentDir, { recursive: true });
        } else {
          throw ToolError.createValidationError(
            "parentDir",
            parentDir,
            "Parent directory does not exist.\nTo create parent directories automatically, re-run with: createParentDir=true"
          );
        }
      }
    }
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. It mentions 'overwrite existing files', which implies destructive behavior, but fails to disclose critical traits like error handling (e.g., if the path is invalid), side effects (e.g., data loss on overwrite), or performance considerations (e.g., file size limits). This leaves significant gaps for a mutation tool.

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 a single, efficient sentence that is front-loaded with the core action ('Write complete file contents') and includes essential details ('create new files or overwrite existing files'). There is zero waste, making it highly concise and well-structured.

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 of a file write operation with no annotations and no output schema, the description is incomplete. It lacks information on return values (e.g., success/failure indicators), error conditions, or behavioral nuances like atomicity, which are crucial for safe usage in a tool that performs destructive actions.

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?

Schema description coverage is 100%, so the schema already documents all parameters thoroughly. The description adds no additional meaning beyond what the schema provides, such as explaining the implications of 'createParentDir' or format details for 'content'. Baseline 3 is appropriate when the schema does the heavy lifting.

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 tool's purpose with a specific verb ('Write') and resource ('complete file contents'), and distinguishes it from siblings by specifying it handles both creation and overwriting. It explicitly mentions 'create new files or overwrite existing files', which differentiates it from tools like 'edit' or 'read'.

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 like 'edit' for partial updates or 'copy'/'move' for file operations. It lacks context about prerequisites, such as file permissions or system constraints, leaving the agent with no usage differentiation.

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/d-issy/mcp'

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