Skip to main content
Glama
gabrielmaialva33

MCP Filesystem Server

write_file

Create or overwrite files with specified content in predefined directories using proper text encoding. Ensures controlled filesystem access for secure file management within the MCP Filesystem Server.

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
contentYesContent to write to the file
encodingNoFile encodingutf-8
pathYesPath where to write the file

Implementation Reference

  • Core handler function that implements the write_file tool logic: validates path and content size, creates parent directories, writes file using fs.writeFile, handles errors and metrics.
    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 input arguments for the write_file tool: path, content, and optional encoding.
     * Schema for write_file arguments
     */
    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:254-261 (registration)
    Tool registration in the listTools 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,
    },
  • Dispatcher handler in the main CallToolRequestSchema handler that parses arguments, calls the writeFile implementation, and formats the MCP response.
    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 }],
      }
    }
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.

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

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