Skip to main content
Glama
pwilkin

MCP File Editor Server

by pwilkin

search_file

Find regex patterns in a file and display matching lines with specified context lines before and after each match for precise file analysis.

Instructions

Search for regex patterns in a file and show matching lines with context.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
file_pathYesAbsolute path to the file
lines_afterNoNumber of lines to show after each match
lines_beforeNoNumber of lines to show before each match
regexpYesRegular expression pattern to search for

Implementation Reference

  • The main handler function for the 'search_file' tool. It validates the file path, reads the file contents, splits into lines, searches each line using the provided regex, and for each match, includes context lines before and after with line numbers and a '>' marker on the matching line. Returns formatted matches or no-match message.
    execute: async ({ file_path, regexp, lines_before, lines_after }) => {
      const absolutePath = validateAbsolutePath(file_path, 'file_path');
      validateFileExists(absolutePath);
    
      try {
        const content = fs.readFileSync(absolutePath, 'utf-8');
        const lines = content.split('\n');
        const regex = new RegExp(regexp);
        const matches: string[] = [];
    
        lines.forEach((line, index) => {
          if (regex.test(line)) {
            const lineNumber = index + 1; // 1-based
            const startLine = Math.max(1, lineNumber - (lines_before || 0));
            const endLine = Math.min(lines.length, lineNumber + (lines_after || 0));
    
            const contextLines = lines.slice(startLine - 1, endLine);
            const context = contextLines.map((ctxLine, ctxIndex) => {
              const ctxLineNumber = startLine + ctxIndex;
              const marker = ctxLineNumber === lineNumber ? '>' : ' ';
              return `${marker} ${ctxLineNumber} | ${ctxLine}`;
            }).join('\n');
    
            matches.push(`Match at line ${lineNumber}:\n${context}`);
          }
        });
    
        if (matches.length === 0) {
          return `No matches found for pattern "${regexp}" in file "${absolutePath}".`;
        }
    
        return matches.join('\n\n');
      } catch (error: any) {
        if (error instanceof UserError) throw error;
        throw new UserError(`Error searching file "${absolutePath}": ${error.message}`);
      }
    }
  • Zod schema defining the input parameters for the 'search_file' tool: file_path (required string), regexp (required string), lines_before and lines_after (optional non-negative integers).
    parameters: z.object({
      file_path: z.string().describe('Absolute path to the file'),
      regexp: z.string().describe('Regular expression pattern to search for'),
      lines_before: z.number().int().min(0).optional().describe('Number of lines to show before each match'),
      lines_after: z.number().int().min(0).optional().describe('Number of lines to show after each match')
    }),
  • src/index.ts:435-481 (registration)
    The registration of the 'search_file' tool via server.addTool(), including name, description, parameters schema, and inline handler.
    server.addTool({
      name: 'search_file',
      description: 'Search for regex patterns in a file and show matching lines with context.',
      parameters: z.object({
        file_path: z.string().describe('Absolute path to the file'),
        regexp: z.string().describe('Regular expression pattern to search for'),
        lines_before: z.number().int().min(0).optional().describe('Number of lines to show before each match'),
        lines_after: z.number().int().min(0).optional().describe('Number of lines to show after each match')
      }),
      execute: async ({ file_path, regexp, lines_before, lines_after }) => {
        const absolutePath = validateAbsolutePath(file_path, 'file_path');
        validateFileExists(absolutePath);
    
        try {
          const content = fs.readFileSync(absolutePath, 'utf-8');
          const lines = content.split('\n');
          const regex = new RegExp(regexp);
          const matches: string[] = [];
    
          lines.forEach((line, index) => {
            if (regex.test(line)) {
              const lineNumber = index + 1; // 1-based
              const startLine = Math.max(1, lineNumber - (lines_before || 0));
              const endLine = Math.min(lines.length, lineNumber + (lines_after || 0));
    
              const contextLines = lines.slice(startLine - 1, endLine);
              const context = contextLines.map((ctxLine, ctxIndex) => {
                const ctxLineNumber = startLine + ctxIndex;
                const marker = ctxLineNumber === lineNumber ? '>' : ' ';
                return `${marker} ${ctxLineNumber} | ${ctxLine}`;
              }).join('\n');
    
              matches.push(`Match at line ${lineNumber}:\n${context}`);
            }
          });
    
          if (matches.length === 0) {
            return `No matches found for pattern "${regexp}" in file "${absolutePath}".`;
          }
    
          return matches.join('\n\n');
        } catch (error: any) {
          if (error instanceof UserError) throw error;
          throw new UserError(`Error searching 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 lacks important behavioral details. It doesn't disclose whether the tool requires file read permissions, how it handles large files, error conditions (e.g., missing files), or output format specifics beyond 'matching lines with context'. The description is minimal but doesn't contradict annotations.

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 with zero wasted words. It's front-loaded with the core purpose and includes essential details about pattern type and output format. Every element earns its place.

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 tool with 4 parameters, no annotations, and no output schema, the description is insufficient. It doesn't explain what the output looks like (structure, format), error handling, performance considerations, or important constraints. The 100% schema coverage helps with parameters but doesn't compensate for missing behavioral context.

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 already documents all four parameters thoroughly. The description adds minimal value by mentioning 'context' (which relates to lines_before/lines_after) but doesn't provide additional syntax, format, or usage details beyond what the schema specifies.

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 ('search for regex patterns'), target resource ('in a file'), and outcome ('show matching lines with context'). It distinguishes from siblings like list_files (listing), read_file (full content), and search_directory (directory-level search) by focusing on pattern matching within a single file.

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 content searching, but doesn't explicitly state when to use this versus alternatives like search_directory (for directory-wide searches) or read_file (for full file content). No guidance on prerequisites or exclusions 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