Skip to main content
Glama
pwilkin

MCP File Editor Server

by pwilkin

replace_in_file

Search and replace all occurrences of a regex pattern with a target string in a file, enabling precise content modifications with optional single-match enforcement.

Instructions

Replace all occurrences of a regex pattern with a target string in a file.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
file_pathYesAbsolute path to the file
multipleNoAllow multiple replacements. If false, fails if multiple matches found.
regex_sourceYesRegular expression pattern to search for
targetYesString to replace matches with

Implementation Reference

  • The handler function that reads the file content, performs global regex replacement if allowed, and writes the updated content back to the file.
    execute: async ({ file_path, regex_source, target, multiple }) => {
      const absolutePath = validateAbsolutePath(file_path, 'file_path');
      validateFileExists(absolutePath);
    
      try {
        const content = fs.readFileSync(absolutePath, 'utf-8');
        const regex = new RegExp(regex_source, 'g');
        const matches = content.match(regex);
    
        if (!matches) {
          throw new UserError(`No matches found for regex pattern "${regex_source}" in file "${absolutePath}".`);
        }
    
        if (!multiple && matches.length > 1) {
          throw new UserError(
            `Multiple matches found (${matches.length}) for regex pattern "${regex_source}" in file "${absolutePath}", ` +
            `but multiple=false. Either set multiple=true or refine your regex to match only one occurrence.`
          );
        }
    
        const newContent = content.replace(regex, target);
        fs.writeFileSync(absolutePath, newContent, 'utf-8');
    
        return `Successfully replaced ${matches.length} occurrence(s) of "${regex_source}" with "${target}" in "${absolutePath}".`;
      } catch (error: any) {
        if (error instanceof UserError) throw error;
        throw new UserError(`Error performing replacement in file "${absolutePath}": ${error.message}`);
      }
    }
  • Zod schema defining the input parameters for the replace_in_file tool.
    parameters: z.object({
      file_path: z.string().describe('Absolute path to the file'),
      regex_source: z.string().describe('Regular expression pattern to search for'),
      target: z.string().describe('String to replace matches with'),
      multiple: z.boolean().optional().describe('Allow multiple replacements. If false, fails if multiple matches found.')
    }),
  • src/index.ts:83-121 (registration)
    Registers the replace_in_file tool with the FastMCP server instance.
    server.addTool({
      name: 'replace_in_file',
      description: 'Replace all occurrences of a regex pattern with a target string in a file.',
      parameters: z.object({
        file_path: z.string().describe('Absolute path to the file'),
        regex_source: z.string().describe('Regular expression pattern to search for'),
        target: z.string().describe('String to replace matches with'),
        multiple: z.boolean().optional().describe('Allow multiple replacements. If false, fails if multiple matches found.')
      }),
      execute: async ({ file_path, regex_source, target, multiple }) => {
        const absolutePath = validateAbsolutePath(file_path, 'file_path');
        validateFileExists(absolutePath);
    
        try {
          const content = fs.readFileSync(absolutePath, 'utf-8');
          const regex = new RegExp(regex_source, 'g');
          const matches = content.match(regex);
    
          if (!matches) {
            throw new UserError(`No matches found for regex pattern "${regex_source}" in file "${absolutePath}".`);
          }
    
          if (!multiple && matches.length > 1) {
            throw new UserError(
              `Multiple matches found (${matches.length}) for regex pattern "${regex_source}" in file "${absolutePath}", ` +
              `but multiple=false. Either set multiple=true or refine your regex to match only one occurrence.`
            );
          }
    
          const newContent = content.replace(regex, target);
          fs.writeFileSync(absolutePath, newContent, 'utf-8');
    
          return `Successfully replaced ${matches.length} occurrence(s) of "${regex_source}" with "${target}" in "${absolutePath}".`;
        } catch (error: any) {
          if (error instanceof UserError) throw error;
          throw new UserError(`Error performing replacement in file "${absolutePath}": ${error.message}`);
        }
      }
    });
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 states the basic operation. It doesn't disclose critical behavioral traits like whether the operation is atomic, what happens on failure, if backups are created, or permission requirements. The description doesn't contradict annotations, but provides minimal behavioral context.

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 communicates the core purpose without any wasted words. It's appropriately sized for a tool with good schema documentation and gets straight to the point.

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 file modification tool with no annotations and no output schema, the description is insufficient. It doesn't explain what happens on success/failure, whether the operation is destructive, what permissions are needed, or what the return value might be. Given the complexity of file system operations, 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 parameter semantics beyond what's in the schema - it mentions 'regex pattern' and 'target string' which are already covered by schema descriptions for regex_source and target parameters.

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 specific action ('Replace all occurrences'), resource ('in a file'), and mechanism ('regex pattern with a target string'). It distinguishes from siblings like 'replace_lines_in_file' by focusing on pattern-based replacement rather than line-based operations.

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

Usage Guidelines3/5

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

The description implies usage for regex-based file modifications but doesn't explicitly state when to use this versus alternatives like 'replace_lines_in_file' or 'delete_from_file'. No guidance on prerequisites, file permissions, or error conditions is provided.

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

Related 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/pwilkin/mcp-file-edit'

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