write_file
Create and save text files to specified paths with configurable encoding and directory creation options.
Input Schema
TableJSON Schema
| Name | Required | Description | Default |
|---|---|---|---|
| path | Yes | ||
| content | Yes | ||
| encoding | No | utf8 | |
| createDirectories | No |
Implementation Reference
- src/tools/file-tools.ts:62-83 (handler)The handler function for the 'write_file' tool. It validates the file path, optionally creates parent directories, writes the content to the file using fs.writeFile, and returns a success message.async ({ path: filePath, content, encoding, createDirectories }) => { return wrapToolExecution(async () => { const validatedPath = await validatePath(filePath); if (createDirectories) { const dir = path.dirname(validatedPath); await fs.mkdir(dir, { recursive: true }); } await fs.writeFile(validatedPath, content, { encoding: encoding as FileEncoding }); return { content: [{ type: "text" as const, text: `Successfully wrote ${content.length} characters to ${validatedPath}` }] }; }, { errorCode: ERROR_CODES.FILE_OPERATION, context: "Failed to write file" }); }
- src/tools/file-tools.ts:56-61 (schema)Zod input schema for the 'write_file' tool defining parameters: path (required string), content (string), encoding (optional enum), createDirectories (optional boolean).{ path: z.string().min(1, "Path is required"), content: z.string(), encoding: z.enum(["utf8", "utf-16le", "latin1"]).optional().default(DEFAULTS.FILE_ENCODING), createDirectories: z.boolean().optional().default(DEFAULTS.CREATE_DIRECTORIES) },
- src/tools/file-tools.ts:54-85 (registration)The registerWriteFile function that registers the 'write_file' tool on the MCP server, including the schema and handler.function registerWriteFile(server: McpServer): void { server.tool("write_file", { path: z.string().min(1, "Path is required"), content: z.string(), encoding: z.enum(["utf8", "utf-16le", "latin1"]).optional().default(DEFAULTS.FILE_ENCODING), createDirectories: z.boolean().optional().default(DEFAULTS.CREATE_DIRECTORIES) }, async ({ path: filePath, content, encoding, createDirectories }) => { return wrapToolExecution(async () => { const validatedPath = await validatePath(filePath); if (createDirectories) { const dir = path.dirname(validatedPath); await fs.mkdir(dir, { recursive: true }); } await fs.writeFile(validatedPath, content, { encoding: encoding as FileEncoding }); return { content: [{ type: "text" as const, text: `Successfully wrote ${content.length} characters to ${validatedPath}` }] }; }, { errorCode: ERROR_CODES.FILE_OPERATION, context: "Failed to write file" }); } ); }
- src/index.ts:65-65 (registration)Call to registerFileTools(server) which includes registration of the write_file tool among file tools.registerFileTools(server);