Skip to main content
Glama

fileWrite

Create, edit, and write files using specified modes (write, append, JSON) with options to create directories and format content.

Instructions

檔案寫入功能,為文件提供建立、編輯與寫入功能

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
contentYes
createDirsNo
filePathYes
modeNowrite
prettifyNo

Implementation Reference

  • main.ts:139-172 (handler)
    Main handler logic for the 'fileWrite' tool. Dispatches to appropriate FileWriterTool method based on 'mode' parameter (write, append, json). Handles JSON parsing and errors.
    async ({ filePath, content, mode = 'write', createDirs = true, prettify = true }) => { try { let result = ''; // 根據模式選擇適當的方法 switch (mode) { case 'write': result = await FileWriterTool.writeTextToFile(filePath, content, createDirs); break; case 'append': result = await FileWriterTool.appendTextToFile(filePath, content, createDirs); break; case 'json': try { // 嘗試解析JSON const jsonData = JSON.parse(content); result = await FileWriterTool.writeJsonToFile(filePath, jsonData, prettify, createDirs); } catch (parseError) { return { content: [{ type: "text", text: `JSON格式錯誤: ${parseError instanceof Error ? parseError.message : "未知錯誤"}` }] }; } break; } return { content: [{ type: "text", text: result }] }; } catch (error) { return { content: [{ type: "text", text: `檔案寫入失敗: ${error instanceof Error ? error.message : "未知錯誤"}` }] }; } }
  • Zod input schema validation for the fileWrite tool parameters.
    { filePath: z.string(), content: z.string(), mode: z.enum(['write', 'append', 'json']).default('write'), createDirs: z.boolean().optional(), prettify: z.boolean().optional()
  • main.ts:130-173 (registration)
    Registration of the 'fileWrite' MCP tool with name, description, schema, and handler function.
    server.tool("fileWrite", "檔案寫入功能,為文件提供建立、編輯與寫入功能", { filePath: z.string(), content: z.string(), mode: z.enum(['write', 'append', 'json']).default('write'), createDirs: z.boolean().optional(), prettify: z.boolean().optional() }, async ({ filePath, content, mode = 'write', createDirs = true, prettify = true }) => { try { let result = ''; // 根據模式選擇適當的方法 switch (mode) { case 'write': result = await FileWriterTool.writeTextToFile(filePath, content, createDirs); break; case 'append': result = await FileWriterTool.appendTextToFile(filePath, content, createDirs); break; case 'json': try { // 嘗試解析JSON const jsonData = JSON.parse(content); result = await FileWriterTool.writeJsonToFile(filePath, jsonData, prettify, createDirs); } catch (parseError) { return { content: [{ type: "text", text: `JSON格式錯誤: ${parseError instanceof Error ? parseError.message : "未知錯誤"}` }] }; } break; } return { content: [{ type: "text", text: result }] }; } catch (error) { return { content: [{ type: "text", text: `檔案寫入失敗: ${error instanceof Error ? error.message : "未知錯誤"}` }] }; } } );
  • Core helper method implementing text file write, including directory creation.
    static async writeTextToFile(filePath: string, content: string, createDirs: boolean = true): Promise<string> { try { // 獲取目錄路徑 const directory = path.dirname(filePath); // 檢查並創建目錄(如果不存在且createDirs為true) if (createDirs && !existsSync(directory)) { mkdirSync(directory, { recursive: true }); console.log(`已創建目錄: ${directory}`); } // 寫入檔案 await fs.writeFile(filePath, content, 'utf8'); return `檔案已成功寫入: ${filePath}`; } catch (error) { console.error(`寫入檔案時發生錯誤: ${error}`); return `寫入檔案時發生錯誤: ${error instanceof Error ? error.message : '未知錯誤'}`; } }
  • Helper method for writing JSON data to file, optionally prettified, delegates to writeTextToFile.
    static async writeJsonToFile(filePath: string, data: any, pretty: boolean = true, createDirs: boolean = true): Promise<string> { try { // 將數據轉換為JSON字符串 const jsonContent = pretty ? JSON.stringify(data, null, 2) : JSON.stringify(data); // 使用文本寫入方法寫入JSON內容 return await this.writeTextToFile(filePath, jsonContent, createDirs); } catch (error) { console.error(`將JSON寫入檔案時發生錯誤: ${error}`); return `將JSON寫入檔案時發生錯誤: ${error instanceof Error ? error.message : '未知錯誤'}`; } }
  • Core helper method for appending text to a file, creates if not exists.
    static async appendTextToFile(filePath: string, content: string, createIfNotExist: boolean = true): Promise<string> { try { // 檢查檔案是否存在 const fileExists = existsSync(filePath); // 如果檔案不存在且不需要創建,則返回錯誤 if (!fileExists && !createIfNotExist) { return `錯誤: 檔案 ${filePath} 不存在`; } // 獲取目錄路徑(如果需要創建文件) if (!fileExists && createIfNotExist) { const directory = path.dirname(filePath); if (!existsSync(directory)) { mkdirSync(directory, { recursive: true }); } } // 追加內容到檔案 await fs.appendFile(filePath, content, 'utf8'); return `內容已成功追加到檔案: ${filePath}`; } catch (error) { console.error(`追加內容到檔案時發生錯誤: ${error}`); return `追加內容到檔案時發生錯誤: ${error instanceof Error ? error.message : '未知錯誤'}`; } }

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/GonTwVn/GonMCPtool'

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