Skip to main content
Glama

write

Write content to files, overwriting existing content and creating files or directories as needed for the filesystem-mcp server.

Instructions

Write content to a file, OVERWRITING ALL existing content. Creates the file and parent directories if needed.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
pathYesAbsolute path to file or directory.
contentYesContent to write

Implementation Reference

  • The `handleWriteFile` function implements the logic for writing content to a file, including path validation and directory creation.
    async function handleWriteFile(
      args: z.infer<typeof WriteFileInputSchema>,
      signal?: AbortSignal
    ): Promise<ToolResponse<z.infer<typeof WriteFileOutputSchema>>> {
      const validPath = await validatePathForWrite(args.path, signal);
    
      // Ensure parent directory exists
      await withAbort(
        fs.mkdir(path.dirname(validPath), { recursive: true }),
        signal
      );
    
      await atomicWriteFile(validPath, args.content, { encoding: 'utf-8', signal });
    
      const bytesWritten = Buffer.byteLength(args.content, 'utf-8');
    
      return buildToolResponse(`Successfully wrote to file: ${args.path}`, {
        ok: true,
        path: validPath,
        bytesWritten,
      });
    }
  • The `WRITE_FILE_TOOL` constant defines the name, description, and input/output schemas for the 'write' tool.
    export const WRITE_FILE_TOOL: ToolContract = {
      name: 'write',
      title: 'Write File',
      description:
        'Write content to a file, OVERWRITING ALL existing content. Creates the file and parent directories if needed.',
      inputSchema: WriteFileInputSchema,
      outputSchema: WriteFileOutputSchema,
      annotations: DESTRUCTIVE_WRITE_TOOL_ANNOTATIONS,
      taskSupport: 'forbidden',
    } as const;
  • The `registerWriteFileTool` function registers the 'write' tool with the MCP server.
    export function registerWriteFileTool(
      server: McpServer,
      options: ToolRegistrationOptions = {}
    ): void {
      const handler = (
        args: z.infer<typeof WriteFileInputSchema>,
        extra: ToolExtra
      ): Promise<ToolResult<z.infer<typeof WriteFileOutputSchema>>> =>
        executeToolWithDiagnostics({
          toolName: 'write',
          extra,
          outputSchema: WriteFileOutputSchema,
          timedSignal: {},
          context: { path: args.path },
          run: (signal) => handleWriteFile(args, signal),
          onError: (error) =>
            buildToolErrorResponse(error, ErrorCode.E_UNKNOWN, args.path),
        });
    
      const wrappedHandler = wrapToolHandler(handler, {
        guard: options.isInitialized,
        progressMessage: (args) => `🛠 write: ${path.basename(args.path)}`,
        completionMessage: (args, result) => {
          const name = path.basename(args.path);
          if (result.isError) return `🛠 write: ${name} • failed`;
          const sc = result.structuredContent;
          return `🛠 write: ${name} • ${formatBytes(sc.bytesWritten ?? 0)}`;
        },
      });
    
      const validatedHandler = withValidatedArgs(
        WriteFileInputSchema,
        wrappedHandler
      );
    
      if (
        registerToolTaskIfAvailable(
          server,
          'write',
          WRITE_FILE_TOOL,
          validatedHandler,
          options.iconInfo,
          options.isInitialized
        )
      )
        return;
      server.registerTool(
        'write',
        withDefaultIcons({ ...WRITE_FILE_TOOL }, options.iconInfo),
        validatedHandler
      );
    }

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/j0hanz/filesystem-mcp'

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