Skip to main content
Glama

write_content

Write or append content to multiple files in specific paths, creating necessary directories automatically. Ideal for managing and updating file content efficiently.

Instructions

Write or append content to multiple specified files (creating directories if needed).

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
itemsYesArray of {path, content, append?} objects.

Implementation Reference

  • Main handler function `handleWriteContentFunc` that validates arguments, processes multiple file write/append operations concurrently using Promise.allSettled, sorts results by original order, and returns JSON-formatted output.
    export const handleWriteContentFunc = async (
      // Added export
      deps: WriteContentDependencies,
      args: unknown,
    ): Promise<McpToolResponse> => {
      const { items: filesToWrite } = parseAndValidateArgs(args);
    
      const writePromises = filesToWrite.map((file) => processSingleWriteOperation(file, deps));
      const settledResults = await Promise.allSettled(writePromises);
    
      const outputResults = processSettledResults(settledResults, filesToWrite);
    
      // Sort results based on the original order
      const originalIndexMap = new Map(filesToWrite.map((f, i) => [f.path.replaceAll('\\', '/'), i]));
      outputResults.sort((a, b) => {
        const indexA = originalIndexMap.get(a.path) ?? Infinity;
        const indexB = originalIndexMap.get(b.path) ?? Infinity;
        return indexA - indexB;
      });
    
      return {
        content: [{ type: 'text', text: JSON.stringify(outputResults, null, 2) }],
      };
    };
  • Zod schemas: `WriteItemSchema` for individual file items and `WriteContentArgsSchema` for the tool input (array of items).
    export const WriteItemSchema = z
      .object({
        path: z.string().describe('Relative path for the file.'),
        content: z.string().describe('Content to write.'),
        append: z
          .boolean()
          .optional()
          .default(false)
          .describe('Append content instead of overwriting.'),
      })
      .strict();
    
    export const WriteContentArgsSchema = z
      .object({
        items: z
          .array(WriteItemSchema)
          .min(1, { message: 'Items array cannot be empty' })
          .describe('Array of {path, content, append?} objects.'),
      })
      .strict();
  • Tool definition object `writeContentToolDefinition` with name 'write_content', description, inputSchema, and handler function that initializes dependencies and calls the main handler.
    export const writeContentToolDefinition = {
      name: 'write_content',
      description:
        "Write or append content to multiple specified files (creating directories if needed). NOTE: For modifying existing files, prefer using 'edit_file' or 'replace_content' for better performance, especially with large files. Use 'write_content' primarily for creating new files or complete overwrites.",
      inputSchema: WriteContentArgsSchema,
      handler: (args: unknown): Promise<McpToolResponse> => {
        const deps: WriteContentDependencies = {
          writeFile: fs.writeFile,
          mkdir: fs.mkdir,
          stat: fs.stat,
          appendFile: fs.appendFile,
          resolvePath: resolvePath,
          PROJECT_ROOT: PROJECT_ROOT,
          pathDirname: path.dirname.bind(path),
        };
        return handleWriteContentFunc(deps, args);
      },
    };
  • Inclusion of `writeContentToolDefinition` in the `allToolDefinitions` array exported from handlers index.
    writeContentToolDefinition,
  • Helper function `parseAndValidateArgs` for parsing and validating tool input using the schema, throwing McpError on failure.
    function parseAndValidateArgs(args: unknown): WriteContentArgs {
      try {
        return WriteContentArgsSchema.parse(args);
      } catch (error) {
        if (error instanceof z.ZodError) {
          throw new McpError(
            ErrorCode.InvalidParams,
            `Invalid arguments: ${error.errors.map((e) => `${e.path.join('.')} (${e.message})`).join(', ')}`,
          );
        }
    
        throw new McpError(ErrorCode.InvalidParams, 'Argument validation failed');
      }
    }
Behavior2/5

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

With no annotations provided, the description carries the full burden of behavioral disclosure. It mentions 'creating directories if needed', which is useful context beyond basic write operations. However, it doesn't disclose critical behavioral traits such as file permissions, error handling (e.g., if a file already exists without append), encoding, or whether it's atomic. For a mutation tool with zero annotation coverage, this leaves significant gaps.

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 with zero waste. It front-loads the core action ('Write or append content') and includes essential details ('to multiple specified files', 'creating directories if needed') without redundancy. Every word earns its place.

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 this is a mutation tool with no annotations and no output schema, the description is incomplete. It lacks information on return values, error conditions, side effects (e.g., impact on existing files), and performance considerations. While it hints at directory creation, it doesn't fully compensate for the missing structured data, making it inadequate for safe and effective use.

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 the 'items' parameter and its nested properties (path, content, append). The description adds minimal value beyond the schema by implying batch operations ('multiple specified files') and directory creation, but doesn't provide additional syntax, format details, or constraints. 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.

Purpose4/5

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

The description clearly states the verb 'write or append' and the resource 'content to multiple specified files', with the additional detail 'creating directories if needed'. It distinguishes from siblings like 'read_content' and 'replace_content' by focusing on writing/appending rather than reading or in-place replacement. However, it doesn't explicitly differentiate from 'create_directories' which might overlap in directory creation functionality.

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 'replace_content' for overwriting specific content or 'create_directories' for just creating directories. It mentions 'append' as an option but doesn't clarify when appending is preferable to overwriting. No prerequisites or exclusions are stated.

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

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