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 }],
      }
    }
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 traits: the destructive nature ('overwrite existing files without warning'), scope ('Only works within allowed directories'), and content handling ('Handles text content with proper encoding'). However, it does not mention permissions, rate limits, or error behavior, leaving some 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 front-loaded with the core purpose, followed by warnings and constraints in three concise sentences. Each sentence adds value: the first defines the action, the second warns about overwriting, and the third clarifies encoding and directory limits, with zero wasted words.

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?

Given the tool's complexity (a destructive write operation) and lack of annotations and output schema, the description does well by covering purpose, risks, and constraints. However, it could be more complete by mentioning return values (e.g., success/failure indicators) or error handling, which are important for a tool with potential side effects.

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 parameters (path, content, encoding) with descriptions and enum values. The description adds no additional parameter semantics beyond what the schema provides, such as format examples or constraints, meeting 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 specific action ('Create a new file or completely overwrite an existing file') and resource ('file'), distinguishing it from sibling tools like edit_file (which implies modification rather than creation/overwrite) and read_file (which only reads). The verb 'write' is precise and matches the tool name without being tautological.

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 for usage ('Use with caution as it will overwrite existing files without warning') and constraints ('Only works within allowed directories'), but does not explicitly name alternatives or specify when not to use it versus tools like edit_file or move_file. This gives practical guidance but lacks 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

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

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