Skip to main content
Glama
PWalaGov

Enhanced Directory Context MCP Server

by PWalaGov

update_file

Modify file content by replacing specific text patterns with new values using search-and-replace operations.

Instructions

Update specific parts of a file using search and replace

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
pathYesFile path relative to working directory
updatesYesArray of search/replace operations
backupNoCreate backup before updating (.bak extension)

Implementation Reference

  • The handler function that executes the update_file tool: reads the file, optionally backs it up, applies a list of search/replace operations (supporting regex and all/first match), writes the updated content, and returns success message with stats.
    async handleUpdateFile(args) {
      const { path: filePath, updates, backup = true } = args;
      const fullPath = path.resolve(this.workingDirectory, filePath);
      
      try {
        // Read current content
        let content = await fs.readFile(fullPath, 'utf8');
        const originalContent = content;
        
        // Create backup if requested
        if (backup) {
          await fs.writeFile(`${fullPath}.bak`, originalContent, 'utf8');
        }
        
        // Apply updates
        let updateCount = 0;
        for (const update of updates) {
          const { search, replace, regex = false, all = true } = update;
          
          if (regex) {
            const flags = all ? 'g' : '';
            const pattern = new RegExp(search, flags);
            const matches = content.match(pattern);
            if (matches) {
              content = content.replace(pattern, replace);
              updateCount += matches.length;
            }
          } else {
            if (all) {
              const parts = content.split(search);
              if (parts.length > 1) {
                content = parts.join(replace);
                updateCount += parts.length - 1;
              }
            } else {
              const index = content.indexOf(search);
              if (index !== -1) {
                content = content.substring(0, index) + replace + content.substring(index + search.length);
                updateCount++;
              }
            }
          }
        }
        
        // Write updated content
        await fs.writeFile(fullPath, content, 'utf8');
        
        return {
          content: [
            {
              type: 'text',
              text: `File updated successfully: ${filePath}\nReplacements made: ${updateCount}${backup ? '\nBackup created: ' + filePath + '.bak' : ''}`,
            },
          ],
        };
      } catch (error) {
        throw new McpError(ErrorCode.InternalError, `Failed to update file: ${error.message}`);
      }
    }
  • Input schema for the update_file tool, defining parameters: path, array of updates (each with search, replace, optional regex and all flags), and optional backup.
    name: 'update_file',
    description: 'Update specific parts of a file using search and replace',
    inputSchema: {
      type: 'object',
      properties: {
        path: {
          type: 'string',
          description: 'File path relative to working directory',
        },
        updates: {
          type: 'array',
          description: 'Array of search/replace operations',
          items: {
            type: 'object',
            properties: {
              search: {
                type: 'string',
                description: 'Text to search for (exact match)',
              },
              replace: {
                type: 'string',
                description: 'Text to replace with',
              },
              regex: {
                type: 'boolean',
                description: 'Use regex for search',
                default: false,
              },
              all: {
                type: 'boolean',
                description: 'Replace all occurrences',
                default: true,
              },
            },
            required: ['search', 'replace'],
          },
        },
        backup: {
          type: 'boolean',
          description: 'Create backup before updating (.bak extension)',
          default: true,
        },
      },
      required: ['path', 'updates'],
    },
  • server.js:476-477 (registration)
    Registration in the tool call dispatcher switch statement, routing 'update_file' calls to the handleUpdateFile handler.
    case 'update_file':
      return await this.handleUpdateFile(args);
  • server.js:372-373 (registration)
    The tool is registered via the ListToolsRequestSchema handler, which returns the list of available tools including update_file with its schema. (Approximate lines; schema detailed separately.)
      };
    });
  • Usage of handleUpdateFile as a helper within the batch_file_operations tool, with backup disabled.
    case 'update':
      result = await this.handleUpdateFile({ ...params, backup: false });

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/PWalaGov/File-Control-MCP'

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