grep
Search for text in files using a regular expression pattern, specify a directory or file type to narrow results, and locate matches efficiently.
Instructions
Search for text in files
Input Schema
TableJSON Schema
| Name | Required | Description | Default |
|---|---|---|---|
| include | No | File pattern to include in the search (e.g. "*.js", "*.{ts,tsx}") | |
| path | No | The directory to search in. Defaults to the current working directory. | |
| pattern | Yes | The regular expression pattern to search for in file contents |
Implementation Reference
- src/server/tools.ts:132-157 (registration)Registers the 'grep' MCP tool, including input schema validation with Zod, tool description, and inline handler function that delegates to grepSearch utility and formats the MCP response.// Grep Tool - Search for text in files server.tool( "grep", "Search for text in files", { pattern: z.string().describe("The regular expression pattern to search for in file contents"), path: z.string().optional().describe("The directory to search in. Defaults to the current working directory."), include: z.string().optional().describe("File pattern to include in the search (e.g. \"*.js\", \"*.{ts,tsx}\")") }, async ({ pattern, path, include }) => { try { const results = await grepSearch(pattern, path, include); return { content: [{ type: "text", text: results }] }; } catch (error) { return { content: [{ type: "text", text: error instanceof Error ? error.message : String(error) }], isError: true }; } } );
- src/utils/file.ts:82-105 (helper)Core implementation of grep search: runs system `grep -r` command recursively on path with optional include filter, captures stdout, handles exit code 1 for no matches gracefully./** * Search for text in files * @param pattern The pattern to search for * @param searchPath The path to search in * @param include Optional file pattern to include * @returns Search results */ export async function grepSearch( pattern: string, searchPath: string = process.cwd(), include?: string ): Promise<string> { try { const includeFlag = include ? `--include="${include}"` : ''; const { stdout } = await execPromise(`grep -r ${includeFlag} "${pattern}" ${searchPath}`); return stdout; } catch (error: any) { if (error.code === 1 && error.stdout === '') { // grep returns exit code 1 when no matches are found return 'No matches found'; } throw error; } }