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 });
Behavior2/5

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

With no annotations provided, the description carries full burden but only mentions the search/replace mechanism. It doesn't disclose critical behavioral traits like whether updates are atomic, if file permissions are required, error handling for missing files, or what happens on failure. For a mutation tool with zero annotation coverage, this is insufficient.

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

Conciseness5/5

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

The description is a single, efficient sentence that immediately conveys the core functionality without any wasted words. It's appropriately sized and front-loaded with the essential information.

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

Completeness2/5

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

For a mutation tool with no annotations and no output schema, the description is incomplete. It doesn't explain what happens on success/failure, return values, or important constraints like file size limits or encoding considerations. Given the complexity of file updates, more context is needed.

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

Parameters3/5

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

Schema description coverage is 100%, so the schema fully documents all parameters. The description adds no additional meaning beyond implying search/replace operations, which is already covered in the schema's updates property description. Baseline 3 is appropriate when schema does the heavy lifting.

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

Purpose5/5

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

The description clearly states the verb 'update' and resource 'file' with specific method 'using search and replace', distinguishing it from siblings like append_to_file (adds content) or rename_file (changes name). It precisely communicates the tool's function beyond just the name.

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 is provided on when to use this tool versus alternatives like append_to_file (for adding content without replacement) or batch_file_operations (for multiple files). The description only states what it does, not when it's appropriate compared to sibling tools.

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

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