write_file
Write content to files for editing, saving, or creating documents. Specify file path, content, and optional encoding to manage file operations.
Instructions
Write content to a file
Input Schema
TableJSON Schema
| Name | Required | Description | Default |
|---|---|---|---|
| path | Yes | Path to the file to write | |
| content | Yes | Content to write to the file | |
| encoding | No | Encoding to use when writing the file (default: utf8) |
Implementation Reference
- src/index.ts:161-188 (registration)Registration of the 'write_file' tool including full input schema and annotations.mcpServer.registerTool({ name: 'write_file', description: 'Write content to a file', inputSchema: { type: 'object', properties: { path: { type: 'string', description: 'Path to the file to write' }, content: { type: 'string', description: 'Content to write to the file' }, encoding: { type: 'string', description: 'Encoding to use when writing the file (default: utf8)' } }, required: ['path', 'content'] }, annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: true, openWorldHint: false } });
- src/core/mcp-server.ts:397-424 (handler)Generic handler for tools/call requests. Validates tool existence and currently returns a placeholder response. Specific execution logic for 'write_file' would be implemented here./** * Handles the tools/call request */ private async handleToolsCall(params: { name: string, arguments?: any }): Promise<CallToolResult> { const { name, arguments: args } = params; if (!name) { throw new Error('Tool name is required'); } const tool = this.tools.get(name); if (!tool) { throw new Error(`Tool not found: ${name}`); } // In a real implementation, we would execute the tool here // For now, we'll just return a placeholder return { content: [ { type: 'text', text: `Executed tool ${name} with arguments: ${JSON.stringify(args)}` } as TextContent ] }; }
- Core file writing implementation using promisified fs.writeFile, with directory creation and change event emission. This is the intended logic for the write_file tool.public async writeFile(filePath: string, content: string, encoding: BufferEncoding = 'utf8'): Promise<void> { try { // Ensure the directory exists await this.ensureDirectoryExists(path.dirname(filePath)); await writeFile(filePath, content, { encoding }); this.emitChangeEvent('update', filePath); } catch (error: any) { throw new Error(`Failed to write file ${filePath}: ${error.message}`); }
- Promisified fs.writeFile utility used by the writeFile handler.const writeFile = util.promisify(fs.writeFile);