Skip to main content
Glama
Platano78

Smart-AI-Bridge

write_files_atomic

Write, append, or modify multiple files atomically with automatic backup. Ensures data integrity and rollback safety for enterprise file modifications.

Instructions

Write multiple files atomically with backup - Enterprise-grade file modification with safety mechanisms

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
file_operationsYes
create_backupNo

Implementation Reference

  • WriteFilesAtomicHandler class - the main handler that executes atomic multi-file writes with backup. Accepts file_operations array (each with path, content, operation) and optional create_backup flag. Creates backups before writing, executes operations (write/append/modify), and supports rollback on failure.
    class WriteFilesAtomicHandler extends BaseHandler {
      async execute(args) {
        const { file_operations, create_backup = true } = args;
    
        if (!file_operations || file_operations.length === 0) {
          throw new Error('file_operations is required');
        }
    
        const results = [];
        const backups = [];
    
        try {
          // Create backups first if requested
          if (create_backup) {
            for (const op of file_operations) {
              try {
                const exists = await fs.access(op.path).then(() => true).catch(() => false);
                if (exists) {
                  const content = await fs.readFile(op.path, 'utf8');
                  const backupPath = `${op.path}.backup.${Date.now()}`;
                  await fs.writeFile(backupPath, content);
                  backups.push({ original: op.path, backup: backupPath });
                }
              } catch (e) {
                // File doesn't exist, no backup needed
              }
            }
          }
    
          // Execute all operations
          for (const op of file_operations) {
            const operation = op.operation || 'write';
            const dirPath = path.dirname(op.path);
    
            // Ensure directory exists
            await fs.mkdir(dirPath, { recursive: true });
    
            switch (operation) {
              case 'write':
                await fs.writeFile(op.path, op.content, 'utf8');
                break;
              case 'append':
                await fs.appendFile(op.path, op.content, 'utf8');
                break;
              case 'modify':
                // For modify, content should be the full new content
                await fs.writeFile(op.path, op.content, 'utf8');
                break;
            }
    
            results.push({
              path: op.path,
              operation,
              success: true,
              size: op.content.length
            });
          }
    
          return this.buildSuccessResponse({
            files_written: results.length,
            results,
            backups_created: backups.length,
            backups
          });
    
        } catch (error) {
          // Rollback on failure
          if (create_backup) {
            for (const backup of backups) {
              try {
                const backupContent = await fs.readFile(backup.backup, 'utf8');
                await fs.writeFile(backup.original, backupContent);
                await fs.unlink(backup.backup);
              } catch (e) {
                console.error(`Rollback failed for ${backup.original}: ${e.message}`);
              }
            }
          }
          throw error;
        }
      }
    }
  • Tool definition for 'write_files_atomic' including JSON Schema for input validation: file_operations array (items with path, content, operation enum) and create_backup boolean.
    {
      name: 'write_files_atomic',
      description: 'Write multiple files atomically with backup - Enterprise-grade file modification with safety mechanisms',
      handler: 'handleWriteFilesAtomic',
      schema: {
        type: 'object',
        properties: {
          file_operations: {
            type: 'array',
            items: {
              type: 'object',
              properties: {
                path: { type: 'string' },
                content: { type: 'string' },
                operation: {
                  type: 'string',
                  enum: ['write', 'append', 'modify'],
                  default: 'write'
                }
              },
              required: ['path', 'content']
            }
          },
          create_backup: { type: 'boolean', default: true }
        },
        required: ['file_operations']
      }
  • Handler registration mapping 'handleWriteFilesAtomic' string to the WriteFilesAtomicHandler class in the HANDLER_REGISTRY.
    const HANDLER_REGISTRY = {
      // Original handlers
      'handleReview': ReviewHandler,
      'handleAsk': AskHandler,
      'handleWriteFilesAtomic': WriteFilesAtomicHandler,
  • Export of WriteFilesAtomicHandler class from the handler index module.
      'handleBatchModify': BatchModifyHandler,
      'handleRefactor': RefactorHandler,
    
      // SAB v2.0: Dual Iterate (Internal generate->review->fix loop)
      'handleDualIterate': DualIterateHandler
    };
  • Suggested tool 'write_files_atomic' in role templates for writing test files and documentation.
    Use appropriate testing frameworks and follow testing best practices.`,
        suggested_tools: [
          'analyze_file',   // Analyze code to test
          'write_files_atomic', // Write test files
          'ask'             // Test strategy analysis
Behavior2/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

No annotations provided, so description must cover behavior. Mentions 'atomic' and 'backup' but lacks details like rollback on failure or backup behavior, leaving significant gaps.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness4/5

Is the description appropriately sized, front-loaded, and free of redundancy?

Single sentence with tagline, no wasted words. Front-loaded with core action, but could include more structure without becoming verbose.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness1/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

No output schema, no annotations, and minimal parameter info. The description fails to convey complete context for a file modification tool with safety mechanisms.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters1/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema description coverage is 0%. The description does not explain the structure of file_operations or the meaning of create_backup, despite the schema having two parameters.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose4/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states it writes multiple files atomically with backup, distinguishing it from siblings like 'modify_file' by emphasizing atomicity and safety mechanisms.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines2/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

No guidance on when to use this tool versus alternatives (e.g., batch_modify, modify_file). The description does not provide context for selection.

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/Platano78/Smart-AI-Bridge'

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