Skip to main content
Glama

file_write

Write content to files for storing notes, documents, or operational data within the AI Ops Hub environment.

Instructions

Записать содержимое в файл

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
pathYesПуть к файлу
contentYesСодержимое для записи

Implementation Reference

  • Core handler function for the file_write tool. Sanitizes the path, creates directories as needed, writes content using fs.writeFile, with logging and error handling.
    async writeFile(filePath: string, content: string): Promise<void> {
      try {
        // Проверяем безопасность пути
        const safePath = this.sanitizePath(filePath);
        
        console.log(`✏️ Запись в файл: ${safePath}`);
        
        // Создаем директорию если её нет
        const dir = path.dirname(safePath);
        await fs.mkdir(dir, { recursive: true });
        
        await fs.writeFile(safePath, content, 'utf-8');
        
        console.log(`✅ Файл записан: ${safePath} (${content.length} символов)`);
      } catch (error) {
        console.error('Ошибка записи файла:', error);
        throw new Error(`Ошибка записи файла: ${error}`);
      }
    }
  • src/server.ts:99-116 (registration)
    Tool registration in the main MCP server's ListToolsRequestSchema handler, defining name, description, and input schema.
    {
      name: 'file_write',
      description: 'Записать содержимое в файл',
      inputSchema: {
        type: 'object',
        properties: {
          path: {
            type: 'string',
            description: 'Путь к файлу',
          },
          content: {
            type: 'string',
            description: 'Содержимое для записи',
          },
        },
        required: ['path', 'content'],
      },
    },
  • Dispatch case in main server's CallToolRequestSchema handler delegating to FileService.writeFile.
    case 'file_write':
      await this.fileService.writeFile(args.path as string, args.content as string);
      return { content: 'Файл записан' };
  • Dispatch case in HTTP transport's /call endpoint handler delegating to FileService.writeFile.
    case 'file_write':
      await this.fileService.writeFile(args.path, args.content);
      result = { message: 'Файл записан' };
  • Security helper to sanitize file paths, preventing path traversal attacks by restricting access to the notes directory.
    private sanitizePath(filePath: string): string {
      // Убираем потенциально опасные символы
      const cleanPath = filePath.replace(/[<>:"|?*]/g, '');
      
      // Разрешаем только относительные пути
      if (path.isAbsolute(cleanPath)) {
        throw new Error('Абсолютные пути не разрешены');
      }
      
      // Разрешаем только файлы в notes директории
      const resolvedPath = path.resolve(this.notesDir, cleanPath);
      const notesDirResolved = path.resolve(this.notesDir);
      
      if (!resolvedPath.startsWith(notesDirResolved)) {
        throw new Error('Доступ к файлу вне notes директории запрещен');
      }
      
      return resolvedPath;
    }

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/Galiusbro/MCP'

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