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}`);
        }
      }
    });
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