Skip to main content
Glama
modelcontextprotocol

Filesystem MCP Server

Official

Write File

write_file
DestructiveIdempotent

Write text content to a file at a specified path, creating or overwriting the file. Use with caution as overwrites occur without warning.

Instructions

Create a new file or completely overwrite an existing file with new content. Use with caution as it will overwrite existing files without warning. Handles text content with proper encoding. Only works within allowed directories.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
pathYes
contentYes

Output Schema

TableJSON Schema
NameRequiredDescriptionDefault
contentYes

Implementation Reference

  • Core function that writes file content with security measures: uses 'wx' flag for exclusive creation (fails if file/symlink exists), and falls back to atomic rename with a temp file if the file already exists (to prevent symlink race conditions).
    export async function writeFileContent(filePath: string, content: string): Promise<void> {
      try {
        // Security: 'wx' flag ensures exclusive creation - fails if file/symlink exists,
        // preventing writes through pre-existing symlinks
        await fs.writeFile(filePath, content, { encoding: "utf-8", flag: 'wx' });
      } catch (error) {
        if ((error as NodeJS.ErrnoException).code === 'EEXIST') {
          // Security: Use atomic rename to prevent race conditions where symlinks
          // could be created between validation and write. Rename operations
          // replace the target file atomically and don't follow symlinks.
          const tempPath = `${filePath}.${randomBytes(16).toString('hex')}.tmp`;
          try {
            await fs.writeFile(tempPath, content, 'utf-8');
            await fs.rename(tempPath, filePath);
          } catch (renameError) {
            try {
              await fs.unlink(tempPath);
            } catch {}
            throw renameError;
          }
        } else {
          throw error;
        }
      }
    }
  • Registration of the 'write_file' tool on the MCP server, with its metadata (title, description, annotations) and the handler that validates the path then calls writeFileContent.
    server.registerTool(
      "write_file",
      {
        title: "Write File",
        description:
          "Create a new file or completely overwrite an existing file with new content. " +
          "Use with caution as it will overwrite existing files without warning. " +
          "Handles text content with proper encoding. Only works within allowed directories.",
        inputSchema: {
          path: z.string(),
          content: z.string()
        },
        outputSchema: { content: z.string() },
        annotations: { readOnlyHint: false, idempotentHint: true, destructiveHint: true }
      },
      async (args: z.infer<typeof WriteFileArgsSchema>) => {
        const validPath = await validatePath(args.path);
        await writeFileContent(validPath, args.content);
        const text = `Successfully wrote to ${args.path}`;
        return {
          content: [{ type: "text" as const, text }],
          structuredContent: { content: text }
        };
      }
    );
  • Zod schema defining the input arguments for write_file: path (string) and content (string).
    const WriteFileArgsSchema = z.object({
      path: z.string(),
      content: z.string(),
    });
  • Import of the writeFileContent helper function from lib.js into the main index.ts file.
    import { getValidRootDirectories } from './roots-utils.js';
    import {
Behavior5/5

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

The description adds context beyond annotations: it specifies complete overwrite, lack of warning, handling of text encoding, and directory restrictions. This aligns with annotations (destructiveHint true, idempotentHint true) and provides actionable behavioral details.

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 concise with three sentences: first states primary action, second warns about caution, third adds handling and constraints. No redundant or missing information.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness4/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

The description covers purpose, caution, and constraints. It assumes output schema documents return values. However, parameter details are sparse, and error conditions are not mentioned. Still adequate for a simple write tool with annotations.

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

Parameters2/5

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

Schema descriptions are missing (0% coverage). The description only implies path and content, but does not explain file path format, encoding specifics, or content constraints (e.g., size limits). This is insufficient given the lack of schema descriptions.

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 'Create a new file or completely overwrite an existing file with new content,' which provides a specific verb and resource. It distinguishes this tool from siblings like edit_file (which modifies partially) and create_directory.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines4/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description warns about overwriting without warning and mentions the constraint of working only within allowed directories. However, it does not explicitly state when not to use it or suggest alternatives like edit_file for partial updates.

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/modelcontextprotocol/filesystem'

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