How to Perform Text Search Within Indexed Files Using Codebase-Memory-MCP

The search_code tool enables fast, graph-augmented text searches across pre-indexed project files by running a secure grep subprocess against the indexed file set, supporting regex patterns, glob filtering, and three output modes while enriching results with knowledge graph metadata.

Codebase-Memory-MCP provides a specialized mechanism to perform text search within indexed files that outperforms naive filesystem scans by limiting the search scope to already-indexed assets. Unlike standard grep utilities that traverse the entire directory tree, this tool queries the project's knowledge graph to identify searchable files, then executes a sandboxed grep operation that returns context-rich results. This guide covers the architectural implementation, parameter schema, and practical usage patterns for the search_code tool as defined in the DeusData/codebase-memory-mcp repository.

Architecture of the search_code Tool

The search_code implementation follows a secure, multi-stage pipeline that balances speed with safety. The tool is registered as one of 14 built-in MCP tools in src/mcp/mcp.c, with its JSON schema defined around lines 460–474 here and the core handler handle_search_code beginning at line 4891 here.

When invoked, the server executes the following sequence:

  1. Schema Validation – Validates the request against the JSON schema, ensuring required parameters (project, pattern) are present and optional flags (regex, file_pattern, path_filter) are correctly typed.

  2. Index-Based Prefiltering – Retrieves the list of indexed files for the specified project from the knowledge graph. If file_pattern (glob) or path_filter (regex) is provided, the server narrows the candidate set before spawning the search process.

  3. Secure Pattern Handling – Writes the search pattern to a temporary file to prevent shell injection attacks, rather than passing the pattern directly on the command line.

  4. Subprocess Execution – Spawns a subprocess running grep (or rg where available) with the sanitized pattern file and the prefiltered file list. The command respects the context parameter for showing surrounding lines.

  5. Result Enrichment – Parses the raw grep output, correlates each match with node metadata from the graph (including qualified_name and file_path), and formats the response according to the requested mode.

Command-Line Usage

You can invoke search_code via the CLI wrapper documented in src/cli/cli.c. The tool accepts a JSON payload containing search parameters and returns enriched matches.

Search for a literal string across all indexed files in compact mode (default):

codebase-memory-mcp cli search_code \
  '{"project":"myproj","pattern":"TODO"}'

Regex Pattern Matching

Enable regex mode to search for patterns such as function definitions:

codebase-memory-mcp cli search_code \
  '{"project":"myproj","pattern":"^\\s*\\w+\\s+get_\\w+\\s*\\(","regex":true}'

File-Type Restriction

Limit the search to specific file types using the file_pattern glob:

codebase-memory-mcp cli search_code \
  '{"project":"myproj","pattern":"malloc","file_pattern":"*.c"}'

Output Modes

Control the verbosity of returned snippets using the mode parameter:

  • compact – Returns short signatures with optional context lines and a total_grep_matches count (default).
  • full – Returns complete source snippets for each match.
  • files – Returns only the list of matching file paths without line content.

# Return full source snippets limited to 5 results

codebase-memory-mcp cli search_code \
  '{"project":"myproj","pattern":"FIXME","mode":"full","limit":5}'

MCP JSON-RPC Integration

For agent-based workflows, call search_code through the standard MCP JSON-RPC interface. The following example demonstrates a tool call with regex enabled and a file pattern filter:

{
  "jsonrpc": "2.0",
  "id": 1,
  "method": "tools/call",
  "params": {
    "name": "search_code",
    "arguments": {
      "project": "myproj",
      "pattern": "^\\s*def\\s+\\w+",
      "regex": true,
      "file_pattern": "*.py",
      "limit": 10
    }
  }
}

The server returns a structured JSON object containing match metadata:

{
  "result": {
    "total_grep_matches": 42,
    "total_results": 10,
    "results": [
      {
        "file_path": "src/util.py",
        "line": 123,
        "snippet": "def process_data():",
        "qualified_name": "myproj.src.util.process_data"
      }
    ]
  }
}

Key Source Files and Implementation Details

Understanding the source locations helps when debugging or extending the tool:

  • src/mcp/mcp.c (lines 460–474) – Defines the JSON schema for search_code parameters including pattern, project, file_pattern, path_filter, regex, mode, and limit view source.

  • src/mcp/mcp.c (line 4891) – Contains the handle_search_code function that orchestrates the temporary file creation, subprocess spawning, and result enrichment logic view source.

  • src/cli/cli.c – Implements the command-line wrapper that parses CLI arguments and forwards them to the MCP server view source.

  • README.md – Provides high-level documentation of the search_code tool and its role in the broader MCP toolset view documentation.

Summary

  • Graph-augmented search – search_code queries only pre-indexed files, making it significantly faster than filesystem-wide grep on large codebases.
  • Security-first design – Patterns are written to temporary files to prevent shell injection, while file_pattern and path_filter parameters are strictly validated.
  • Flexible output – Three modes (compact, full, files) accommodate different use cases from quick audits to detailed code review.
  • MCP-native – The tool conforms to the Model Context Protocol and can be invoked via CLI or JSON-RPC from any MCP-compatible agent.
  • Rich metadata – Results include qualified_name and file_path from the knowledge graph, enabling precise navigation to specific code entities.

Frequently Asked Questions

How does search_code differ from using regular grep?

Unlike standard grep, search_code operates exclusively on the indexed file set maintained by Codebase-Memory-MCP's knowledge graph. This prefiltering eliminates noise from build artifacts, dependencies, and ignored files (as defined by .cbmignore rules), while enriching matches with semantic metadata such as qualified names. The tool also handles pattern sanitization automatically, removing the risk of shell injection that comes with ad-hoc grep commands.

Can I use regular expressions with search_code?

Yes. Set the regex parameter to true in your request payload. When enabled, the tool passes the -E flag to the underlying grep subprocess, allowing POSIX extended regular expressions. Note that you must escape backslashes in JSON strings (e.g., "^\\s*function").

What is the difference between compact and full mode?

Compact mode returns abbreviated snippets suitable for quick scanning, including the matched line and configurable context lines, along with a total_grep_matches count indicating how many additional hits exist beyond the returned limit. Full mode returns the complete source block for each match, which is useful when you need to view the surrounding function or class definition. Files mode returns only unique file paths, functioning as a "find files containing" operation.

How do I restrict searches to specific directories or file types?

Use the file_pattern parameter to specify a glob (e.g., *.c, *.py) that is passed to grep's --include flag. For more complex path filtering, use the path_filter parameter, which accepts a regular expression applied to the full file path before the grep subprocess executes. Both filters leverage the knowledge graph to avoid scanning excluded files, improving performance on large projects.

Have a question about this repo?

These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:

Share the following with your agent to get started:
curl -s "https://instagit.com/install.md"

Works with
Claude Codex Cursor VS Code OpenClaw Any MCP Client

Maintain an open-source project? Get it listed too →