Skip to main content
Glama

file_write

Write content to a file, automatically creating parent directories if needed. Supports various encodings for saving code, configs, or reports.

Instructions

Write content to a file on the local filesystem.

Features:

  • Creates parent directories automatically if they don't exist

  • Overwrites existing files or creates new ones

  • Supports any text encoding (default: UTF-8)

Use cases:

  • Saving generated code, configs, or data

  • Creating log files

  • Writing reports or exports

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
filePathYesPath to the file to write.
contentYesContent to write to the file.
encodingNoCharacter encoding (default: utf-8).utf-8

Implementation Reference

  • The async handler function that executes the file_write tool logic. It resolves the path, creates parent directories via fs.mkdir(recursive), writes the file with the specified encoding, and returns a JSON result with success info (path, bytes written, timestamp). On error, returns an error message.
        async ({ filePath, content, encoding }) => {
          try {
            const resolvedPath = path.resolve(filePath);
    
            // Create parent directories if needed
            const dir = path.dirname(resolvedPath);
            await fs.mkdir(dir, { recursive: true });
    
            await fs.writeFile(resolvedPath, content, { encoding: encoding as BufferEncoding });
    
            const stats = await fs.stat(resolvedPath);
    
            return {
              content: [
                {
                  type: "text" as const,
                  text: JSON.stringify(
                    {
                      success: true,
                      path: resolvedPath,
                      bytesWritten: stats.size,
                      timestamp: stats.mtime.toISOString(),
                    },
                    null,
                    2
                  ),
                },
              ],
            };
          } catch (err: any) {
            return {
              content: [
                {
                  type: "text" as const,
                  text: `File Write Error: ${err.message}`,
                },
              ],
              isError: true,
            };
          }
        }
      );
    }
  • Zod schema definitions for file_write tool inputs: filePath (string), content (string), and encoding (string, default utf-8).
    {
      filePath: z.string().describe("Path to the file to write."),
      content: z.string().describe("Content to write to the file."),
      encoding: z
        .string()
        .default("utf-8")
        .describe("Character encoding (default: utf-8)."),
    },
  • src/index.ts:48-49 (registration)
    Registration call: registerFileWriteTool(this.server) invoked in the McpToolkitServer.registerTools() method.
    registerFileWriteTool(this.server);
    registerFileListTool(this.server);
  • The registerFileWriteTool function that registers the tool on the MCP server using server.tool('file_write', ...) with the schema, description, and handler.
    export function registerFileWriteTool(server: McpServer): void {
      server.tool(
        "file_write",
        `Write content to a file on the local filesystem.
    
    Features:
      - Creates parent directories automatically if they don't exist
      - Overwrites existing files or creates new ones
      - Supports any text encoding (default: UTF-8)
    
    Use cases:
      - Saving generated code, configs, or data
      - Creating log files
      - Writing reports or exports`,
        {
          filePath: z.string().describe("Path to the file to write."),
          content: z.string().describe("Content to write to the file."),
          encoding: z
            .string()
            .default("utf-8")
            .describe("Character encoding (default: utf-8)."),
        },
        async ({ filePath, content, encoding }) => {
          try {
            const resolvedPath = path.resolve(filePath);
    
            // Create parent directories if needed
            const dir = path.dirname(resolvedPath);
            await fs.mkdir(dir, { recursive: true });
    
            await fs.writeFile(resolvedPath, content, { encoding: encoding as BufferEncoding });
    
            const stats = await fs.stat(resolvedPath);
    
            return {
              content: [
                {
                  type: "text" as const,
                  text: JSON.stringify(
                    {
                      success: true,
                      path: resolvedPath,
                      bytesWritten: stats.size,
                      timestamp: stats.mtime.toISOString(),
                    },
                    null,
                    2
                  ),
                },
              ],
            };
          } catch (err: any) {
            return {
              content: [
                {
                  type: "text" as const,
                  text: `File Write Error: ${err.message}`,
                },
              ],
              isError: true,
            };
          }
        }
      );
    }
  • Helper types (ToolResult) and utility functions (textResult, errorResult, jsonResult) used by the handler for constructing responses. Though the handler inlines its own JSON.stringify(jsonResult-style) patterns.
    export interface ToolResult {
      content: Array<{ type: "text"; text: string }>;
      isError?: boolean;
    }
    
    /** Helper to build a success text response. */
    export function textResult(text: string): ToolResult {
      return { content: [{ type: "text" as const, text }] };
    }
    
    /** Helper to build an error text response. */
    export function errorResult(message: string): ToolResult {
      return {
        content: [{ type: "text" as const, text: message }],
        isError: true,
      };
    }
    
    /** Helper to JSON-stringify and wrap in a text result. */
    export function jsonResult(data: unknown, pretty = true): ToolResult {
      return {
        content: [
          {
            type: "text" as const,
            text: JSON.stringify(data, null, pretty ? 2 : 0),
          },
        ],
      };
    }
Behavior4/5

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

No annotations provided, so description must cover behavior. It discloses automatic parent directory creation, overwrite behavior, and encoding support (default UTF-8). Missing details on permissions or error handling, but adequate for typical usage.

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

Conciseness4/5

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

Well-structured with a one-line summary, then Features and Use cases in bullet points. Could be slightly more concise by merging use cases into a sentence, but overall efficient.

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?

For a simple write tool with 3 parameters and no output schema, the description covers purpose, features, and use cases adequately. Missing error handling or edge cases, but not critical for typical scenarios.

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 coverage is 100%, so baseline is 3. Description does not add significant meaning beyond the schema's parameter descriptions; it only states 'Supports any text encoding' which repeats the default.

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?

Description clearly states 'Write content to a file on the local filesystem' – a specific verb and resource. This distinguishes it from siblings like file_read and file_list.

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?

Lists concrete use cases (saving generated code, configs, log files, reports/exports) but does not explicitly exclude scenarios or compare with alternatives like api_call or db_query.

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/vyshnavi-nandyala/mcp-toolkit-server'

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