Search Code MCP
One-line summary: This MCP server gives AI coding agents a fast, unified toolkit for searching, counting, listing, and structurally refactoring code across a repository using ripgrep, ast-grep, and ctags under the hood.
Search code (6 modes) with
search: PCRE2/Rust regex (default), literal text, structural AST patterns ($VAR/$$$ARGS), relational YAML rules (ast_rule), andhybrid(ripgrep pre-filter + ast-grep) for 10x–50x speedups on large repos — with glob filters, context lines, word matching, multiline, hidden/ignored-file control, andcontent/compact/files_only/jsonoutput.Paginate large result sets cheaply: when matches exceed
limit, you get asearchIdso you can scroll pages instantly viaoffset/limitwithout re-scanning disk.Refactor code safely with
replace: structural AST rewrites (default), regex, or literal replacement, running as a dry-run unified diff first, capped bymaxReplacements(default 50) before writing to disk.Count matches with
countto gauge blast radius before searching or replacing — totals or per-file breakdowns, without returning match content (token savings).Navigate symbols with
find_symbols: locate functions, classes, interfaces, methods, types, structs, enums, traits, and modules via ctags → ast-grep → regex fallback, filter bykinds/exactMatch, include locals, or get a whole-file symbol outline.Inspect syntax trees with
dump_tree(ast / cst / pattern formats) to discover exact nodekindnames for YAML rules or debug why an AST pattern failed.List files fast with
list_filesby glob pattern, respecting.gitignoreand hiding dotfiles by default.Work safely and token-efficiently: gitignore respected by default,
.gitexcluded, ANSI codes stripped, long lines trimmed, relative-path output option, and automatic engine fallback (rg → ugrep → git grep, etc.) so it runs out of the box.
Click on "Deploy Server".
Wait a few minutes for the server to deploy. Once ready, it will show a "Started" state.
In the chat, type
@followed by the MCP server name and your instructions, e.g., "@Search Code MCP find all TODO comments in the codebase"
That's it! The server will respond to your query, and you can continue using it as needed.
Here is a step-by-step guide with screenshots.
Search Code MCP
A high-performance, unified Model Context Protocol (MCP) server combining the blazing speed of ripgrep (regex/text search) with the deep structural syntax awareness of ast-grep (AST pattern matching and refactoring).
Designed specifically for AI Coding Agents (Cursor, Claude Desktop, Kiro, Antigravity, Cline / Roo Code, Windsurf, Zed).
⚡ Highlights & Key Features
6 Unified Tools (Zero Prefix Noise): Clean tool names without redundant prefixes:
search,replace,count,find_symbols,dump_tree, andlist_files.Multi-Engine Driver Fallback (Zero Setup Friction): Automatically discovers and uses the best available CLI tool on your system without manual configuration:
Text & Regex:
ripgrep(rg) ➜ugrep➜git grep(runs out of the box on any developer machine with Git installed!).Symbol Search: Universal Ctags (
ctags) ➜ast-grep➜ripgrep/git grepregex heuristic.AST Search:
ast-grep➜ aliassg.File Listing:
rg --files➜git ls-files➜ Native Node.js recursive directory walk.
Hybrid 2-Tier Search (
type: "hybrid"): Scans candidate files with ripgrep in ~30ms, then parses AST with ast-grep only on matching files—giving 10x–50x speedups over pure AST searches on large codebases.Fast Pagination Cache:
Automatically activates only when results exceed your chunk limit.
Returns a
searchIdfor instant sub-millisecond scrolling through next pages (offset/limit) without re-scanning disk.Stored in isolated system temp storage without creating untracked files or polluting git working trees.
Gitignore Respected by Default: Both ripgrep and ast-grep automatically respect your project's
.gitignore(noIgnore: falseby default). PassnoIgnore: trueonly when you need to inspect ignored files.Safe Structural Refactoring (
replace): Defaults todryRun: trueto generate unified git-style diff previews and safety limits (maxReplacements: 50) before writing any changes to disk.Flexible Path Handling: Supports both relative paths (e.g.
".","./src") and absolute paths as input. By default, tool outputs return absolute paths. SetRELATIVE_PATHS=truein environment (or pass--relative-paths) to format output paths as clean relative paths to save LLM context window tokens.Token Protection & Truncation: Automatically trims overly long single lines (
maxLineLength: 500) and strips ANSI color codes to protect LLM context windows.Actionable Diagnostics: Syntax errors in AST patterns or YAML rules return helpful self-correction hints (e.g. suggesting
dump_treeorstopBy: end).Agent Skill Included (
skills/search-code): Pre-configured Agent Skill for Claude Code, Cursor, Antigravity, and Cline to automatically write AST patterns, YAML rules, and select optimal engines.Zero-Dependency Single-File Bundle: Packaged with
esbuildinto a self-contained single executable bundle for instant startup vianpx.
Related MCP server: MCP Smart Filesystem Server
📦 Prerequisites & Engine Setup
🔧 Interactive Engine Manager (search-code-mcp engine)
Instead of installing binaries manually, you can run the built-in interactive engine manager to inspect your environment and automatically install missing tools with arrow keys (↑ / ↓) and [Enter]:
npx search-code-mcp engineIt automatically detects which text, AST, and symbol engines are installed, and presents an interactive selector to install any missing tools (via npm, choco, winget, or brew).
Manual Installation (Optional)
If you prefer to install engines manually, ensure the following CLI binaries are accessible in your system PATH:
1. ripgrep (rg) — Text & Regex Search
Windows:
winget install BurntSushi.ripgrep.MSVCorchoco install ripgrepmacOS:
brew install ripgrepLinux (Debian/Ubuntu):
sudo apt install ripgrepLinux (Arch):
sudo pacman -S ripgrep
2. ast-grep (ast-grep) — Structural AST Search & Refactoring
npm (Recommended):
npm install -g @ast-grep/climacOS:
brew install ast-grepCargo (Rust):
cargo install ast-grep --lockedWindows:
choco install ast-greporwinget install ast-grep
3. universal-ctags (ctags) — Symbol Search (Optional)
Note: If ctags is not installed, the server automatically falls back to ripgrep regex heuristics.
Windows:
choco install universal-ctagsorwinget install universal-ctags.universal-ctagsmacOS:
brew install universal-ctagsLinux (Debian/Ubuntu):
sudo apt install universal-ctags
🚀 Quick Start & Configuration
You can run search-code-mcp directly via npx without manual installation.
Add the following configuration to your client's MCP configuration file:
{
"mcpServers": {
"search-code": {
"command": "npx",
"args": ["-y", "search-code-mcp"]
}
}
}Token-Saving Relative Paths: Add "env": { "RELATIVE_PATHS": "true" } (or pass "--relative-paths" in args) if you want tool outputs to return clean relative paths instead of full absolute paths.
📍 Configuration File Locations
Client | Configuration File Path |
Kiro | Workspace: |
Cursor | Workspace: |
Claude Desktop | macOS: |
Antigravity IDE |
|
Windsurf |
|
Cline / Roo Code | Click MCP Servers icon ➜ Configure MCP Servers |
🧠 Install Agent Skill (Optional but Recommended)
Teach your AI coding agent (Cursor, Claude Code, Antigravity, Cline, Kiro) how to write high-precision ast-grep patterns, YAML rules, and choose the optimal search engine:
npx skills add joutvhu/search-code-mcpOr install locally in your project:
npx skills add ./skills/search-code🛠️ Tool Reference
1. search
Unified search engine supporting regex, literal text, AST patterns, relational YAML rules, and hybrid searches.
Parameter | Type | Default | Description |
|
| - | Search query: text, regex, AST pattern, or YAML rule. (Optional if |
|
|
| Target directory or file to search |
|
|
| Search engine mode: |
|
| - | ID of a previous search to view remaining results instantly from cache |
|
|
| Starting result index for pagination (1-based) |
|
|
| Maximum matches to return in this chunk |
|
| - | Glob pattern to filter files (e.g. |
|
| - | Glob pattern to exclude (e.g. |
|
|
| If |
|
| smart-case | Case sensitivity |
|
|
| Number of context lines before and after match ( |
|
|
| Match whole words only ( |
|
|
| Match regex across line breaks ( |
|
|
| Search hidden files and folders ( |
|
| auto | Programming language for AST mode (auto-detected from file extension if omitted) |
|
|
|
|
Examples:
// Fast regex or text search
search({ query: "handleRequest", path: "./src" });
search({ query: "class.*Controller", type: "regex", context: 2 });
// AST structural pattern (ignores whitespace & formatting differences)
search({ query: "console.log($$$ARGS)", type: "ast", language: "typescript" });
// Hybrid 2-tier search: 10x-50x faster on huge codebases
search({ query: "class $NAME extends BaseService { $$$ }", type: "hybrid" });
// Complex relational YAML rule
search({
query: `
id: find-async-arrow
language: typescript
rule:
all:
- kind: arrow_function
- has:
pattern: await $EXPR
stopBy: end
`,
type: "ast_rule",
});
// Retrieve next chunk from cache using searchId
search({ searchId: "s_9f2a7b12", offset: 51, limit: 50 });2. replace
Structural code refactoring and replacement engine. Supports AST rewrite patterns and Regex/Text replacements.
Parameter | Type | Default | Description |
|
| Required | Search pattern to replace (AST pattern or regex) |
|
| Required | Replacement string or AST rewrite pattern |
|
|
| Target directory or file |
|
|
| Replacement mode: |
|
|
| If |
|
|
| Safety limit on maximum matches to replace |
|
|
| Case sensitivity for |
|
| - | Glob pattern to filter files |
|
| - | Glob pattern to exclude |
|
| auto | Programming language for AST mode |
Examples:
// 1. Dry run preview (safe default, outputs unified git diff)
replace({
query: "fetchData($A, $B)",
replacement: "fetchData({ url: $A, options: $B })",
type: "ast",
dryRun: true,
});
// 2. Apply modifications to disk
replace({
query: "fetchData($A, $B)",
replacement: "fetchData({ url: $A, options: $B })",
type: "ast",
dryRun: false,
});3. count
Count matching occurrences across files without returning match content, saving tokens.
Parameter | Type | Default | Description |
|
| Required | Search pattern to count |
|
|
| Target directory or file |
|
|
| Engine mode: |
|
|
| Show breakdown of matches per file |
|
| smart-case | Case sensitivity ( |
|
| - | Glob pattern filter |
|
| - | Glob exclude filter |
|
|
| Search inside ignored files |
|
| auto | Language for AST mode |
Examples:
count({ query: "TODO:", type: "text" });
count({ query: "catch ($ERR) { $$$ }", type: "ast", perFile: true });4. find_symbols
Find and navigate code definitions (functions, classes, interfaces, methods, types, variables, structs, enums) across the codebase. Automatically selects the best available engine: Universal Ctags ➜ ast-grep ➜ ripgrep / git-grep regex heuristic.
Parameter | Type | Default | Description |
|
|
| Symbol name or substring to find (leave empty to list all symbols in target directory/file) |
|
|
| Target directory or file path |
|
| - | Filter by symbol kinds: |
|
|
| If |
|
| - | Glob pattern to filter files (e.g. |
|
| - | Glob pattern to exclude |
|
|
| Maximum number of symbols to return |
|
|
| If |
Examples:
// Find exact function or class by name
find_symbols({ name: "handleSearch", exactMatch: true });
// List all functions in a module/directory
find_symbols({ path: "src/handlers", kinds: ["function"] });
// Outline of a single file
find_symbols({ path: "src/index.ts" });5. dump_tree
Inspect concrete syntax trees (CST) or AST node structures to craft precise ast-grep patterns.
Parameter | Type | Default | Description |
|
| Required | Code snippet to inspect |
|
| Required | Programming language (e.g. |
|
|
| Tree format: |
Example:
dump_tree({
code: "const calculate = (a, b) => a + b;",
language: "typescript",
});6. list_files
Enumerate files matching glob patterns without scanning file contents.
Parameter | Type | Default | Description |
|
|
| Directory to search |
|
| - | Glob pattern filter (e.g. |
|
| - | Glob pattern to exclude |
|
|
| List files ignored by |
|
|
| Include hidden files (excludes |
Example:
list_files({ path: "./src", filePattern: "*.service.ts" });🔍 Development & Contributing
# 1. Clone the repository
git clone https://github.com/joutvhu/search-code-mcp.git
cd search-code-mcp
# 2. Install dependencies
npm install
# 3. Type check
npm run check
# 4. Run automated test suite
npm test
# 5. Build single-file bundle
npm run build
# 6. Test with MCP Inspector
npx @modelcontextprotocol/inspector node dist/index.js📄 License
This project is licensed under the MIT License.
Available Tools
6 toolscountCount MatchesARead-onlyIdempotent
Count matching lines or occurrences of a regex, literal text, or AST pattern without returning match content. Use before 'search' or 'replace' to gauge blast radius and save context tokens.
Inputs: query (required), path, type, perFile, +6 more.
dump_treeInspect Syntax TreeARead-onlyIdempotent
Inspect the Tree-sitter syntax tree of a short code snippet or pattern via ast-grep. Call this BEFORE writing 'ast_rule' YAML queries (use format='ast' to discover exact node 'kind' names) or when debugging why an 'ast' pattern didn't match (use format='pattern').
Inputs: code (required), language (required), format.
find_symbolsFind SymbolsARead-onlyIdempotent
Locate symbol definitions (functions, classes, interfaces, methods, types, variables, structs, enums, traits, modules) with filtering by 'kinds' and 'exactMatch'. Pass a single file as 'path' with empty 'name' to get a full symbol outline without reading the whole file.
Inputs: name, path, kinds, exactMatch, +4 more.
list_filesList FilesARead-onlyIdempotent
Fast file enumeration matching glob patterns or file types without scanning file contents. Respects .gitignore and excludes hidden files by default.
Inputs: path, noIgnore, filePattern, includeHidden, +1 more.
replaceReplace / Refactor CodeADestructive
Refactor or replace code using structural AST rewrites ('ast', DEFAULT) or regex/literal matching ('regex', 'text'). Runs in dryRun=true by default to return a unified diff preview without modifying files; inspect the diff first, then re-run with dryRun=false to write changes. Capped at maxReplacements (default 50) matches per call. Note: 'regex' mode uses ripgrep for discovery and JavaScript RegExp for replacement.
Inputs: query (required), replacement (required), path, type, +9 more.
searchSearch CodeARead-onlyIdempotent
Search code across files using ripgrep ('regex' default, 'text'), ast-grep ('ast' pattern, 'ast_rule' YAML rule), or 'hybrid' (ripgrep pre-filter + ast-grep for large repos). Returns paginated results with a 'searchId' when total matches exceed 'limit'. Prefer 'find_symbols' when you want structured symbol tables or a single-file outline, and 'count' when you only need match counts.
Inputs: path, type, limit, query, +12 more.
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
Loading tool schema changelog…
TDQS
Scored across 6 tools
Each tool has a clearly distinct role: search retrieves matches, count only tallies them, find_symbols returns structured symbol data, list_files enumerates files, dump_tree inspects ASTs, and replace modifies code. The descriptions explicitly guide when to prefer find_symbols or count over search, removing the main potential overlap.
All names are snake_case and action-oriented, but the pattern mixes bare verbs (search, replace, count) with verb_noun forms (dump_tree, find_symbols, list_files). This is a minor stylistic deviation rather than a confusing inconsistency.
Six tools is well-scoped for a code search and refactoring server, with each tool covering a distinct operation. There are no redundant or filler tools.
The surface covers discovery (list_files, search, count, find_symbols), AST inspection (dump_tree), and modification (replace) with dry-run previews. No obvious lifecycle gaps remain for a code search/refactor domain.
Maintenance
Related MCP Connectors
Code intelligence for coding agents: semantic, AST, graph, and full-text search. 279+ languages.
Code intelligence platform for AI agents. 20 tools for architecture, security & impact analysis.
One searchable history across every AI coding tool, with secret scanning and a shared task board.
Code intelligence for LLMs. Analyze, search, and retrieve code from any public git repository.
Related MCP Servers
- AlicenseAqualityCmaintenanceEnables AI assistants to understand and navigate codebases through structural analysis. Provides code mapping, symbol search, and impact analysis using ast-grep for accurate parsing of Python, JavaScript, TypeScript, and Go projects.452MIT
- AlicenseAqualityDmaintenanceProvides LLM-optimized filesystem access with intelligent file pagination for large files, lightning-fast ripgrep-powered code search with regex support, and security sandboxing to safely explore and search codebases.71MIT
- FlicenseDqualityDmaintenanceEnables AI agents to perform semantic search over codebases by converting natural language queries into efficient search patterns like grep and ripgrep. It utilizes LLMs to verify relevance and find code snippets that traditional keyword-based searches might miss.1-
- AlicenseAqualityDmaintenanceProvides AI assistants with progressive code intelligence to explore repository structure, find symbols, and assess the impact of changes using ast-grep.3MIT