Skip to main content
Glama
A-Niranjan

MCP Filesystem Server

by A-Niranjan

write_file

Create new files or replace existing ones with specified content in allowed directories using proper text encoding. Use caution as it overwrites files 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
pathYesPath where to write the file
contentYesContent to write to the file
encodingNoFile encodingutf-8

Implementation Reference

  • The main handler function for the write_file tool. Validates the path, checks content size against limits, creates parent directory if needed, writes the file using fs.writeFile, and returns a success message.
    export async function writeFile(
      args: z.infer<typeof WriteFileArgsSchema>,
      config: Config
    ): Promise<string> {
      const endMetric = metrics.startOperation('write_file')
      try {
        const validPath = await validatePath(args.path, config)
    
        // Check if content size exceeds limits
        if (config.security.maxFileSize > 0) {
          const contentSize = Buffer.byteLength(args.content, args.encoding as BufferEncoding)
          if (contentSize > config.security.maxFileSize) {
            metrics.recordError('write_file')
            throw new FileSizeError(args.path, contentSize, config.security.maxFileSize)
          }
        }
    
        // Create parent directory if needed
        const parentDir = path.dirname(validPath)
        await fs.mkdir(parentDir, { recursive: true })
    
        // Write the file
        await fs.writeFile(validPath, args.content, args.encoding)
        await logger.debug(`Successfully wrote to file: ${validPath}`)
    
        endMetric()
        return `Successfully wrote to ${args.path}`
      } catch (error) {
        metrics.recordError('write_file')
        throw error
      }
    }
  • Zod schema defining the input arguments for the write_file tool: path, content, and optional encoding.
    export const WriteFileArgsSchema = z.object({
      path: z.string().describe('Path where to write the file'),
      content: z.string().describe('Content to write to the file'),
      encoding: z
        .enum(['utf-8', 'utf8', 'base64'])
        .optional()
        .default('utf-8')
        .describe('File encoding'),
    })
  • src/index.ts:255-261 (registration)
    Tool registration in the list_tools response, defining name, description, and input schema for write_file.
      name: '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: zodToJsonSchema(WriteFileArgsSchema) as ToolInput,
    },
  • src/index.ts:440-454 (registration)
    Dispatch handler in the CallToolRequestSchema switch case that parses arguments with the schema and calls the writeFile handler function.
    case 'write_file': {
      const parsed = WriteFileArgsSchema.safeParse(a)
      if (!parsed.success) {
        throw new FileSystemError(`Invalid arguments for ${name}`, 'INVALID_ARGS', undefined, {
          errors: parsed.error.format(),
        })
      }
    
      const result = await writeFile(parsed.data, config)
    
      endMetric()
      return {
        content: [{ type: 'text', text: result }],
      }
    }

Schema Changelog

Changes observed during successful MCP inspections.

  1. First observed

TDQS

A4.2/5.0
Behavior4/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 effectively describes key behaviors: the destructive overwrite nature ('overwrite existing files without warning'), content handling ('Handles text content with proper encoding'), and security constraints ('Only works within allowed directories'). This covers safety, scope, and limitations well 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 efficiently structured in three sentences: purpose, warning, and constraints. Each sentence adds distinct value without redundancy, making it easy to parse and understand the tool's core functionality and limitations.

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 mutation tool with no annotations and no output schema, the description does well by covering purpose, destructive behavior, encoding support, and directory restrictions. However, it doesn't mention error handling, file size limits, or return values, leaving some gaps in operational context.

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 three parameters thoroughly. The description adds minimal parameter semantics beyond the schema, only implying that 'content' is text and 'path' must be within allowed directories. This meets the baseline for high schema coverage.

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 verb ('Create' and 'overwrite') and resource ('file'), specifying it handles both new file creation and complete overwriting of existing files. It distinguishes from sibling tools like 'edit_file' by emphasizing complete overwriting rather than partial modification.

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 provides clear context about when to use ('Create a new file or completely overwrite an existing file') and includes a caution about overwriting. However, it doesn't explicitly mention when NOT to use or name specific alternatives like 'edit_file' for partial modifications, which would be helpful for sibling differentiation.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.