# How Code-Graph-RAG Works: A Deep Dive Into Multi-Language Code Graph Retrieval-Augmented Generation

> Discover how Code-Graph-RAG transforms code repos into a language-agnostic knowledge graph. Query your codebase with natural language using LLMs and Memgraph.

- Repository: [Vitali Avagyan/code-graph-rag](https://github.com/vitali87/code-graph-rag)
- Tags: deep-dive
- Published: 2026-08-14

---

**Code-Graph-RAG is an open-source framework that converts entire source code repositories into a unified, language-agnostic knowledge graph stored in Memgraph, enabling natural language queries via Tree-sitter parsing and LLM-powered Cypher generation.**

Code-Graph-RAG transforms how developers interact with large codebases by eliminating the need to manually navigate files and directories. By parsing Python, TypeScript, Rust, Go, Java, and 10+ other languages into a single graph schema, it allows you to ask questions like "Which functions in [`utils.py`](https://github.com/vitali87/code-graph-rag/blob/main/utils.py) call the database?" and receive precise, sourced answers with relevant code fragments.

## The Two-Layer Architecture of Code-Graph-RAG

Code-Graph-RAG operates through two tightly integrated layers: a parsing and graph construction pipeline, and a RAG interface for natural language interaction.

### Layer 1: Parsing and Graph Construction

The foundation of Code-Graph-RAG is **Tree-sitter**, the incremental parsing library developed by GitHub. Tree-sitter reads every file in your repository and produces an abstract syntax tree (AST) that captures structural entities and their relationships.

**Key components in this layer:**

- **Tree-sitter grammars** for Python, TypeScript/TSX, JavaScript, Rust, Go, Java, C, C++, C#, PHP, Lua, Dart, with experimental support for Scala and Ruby
- **Entity extraction** identifying functions, classes, modules, imports, and inheritance hierarchies
- **Relationship mapping** capturing `CALLS`, `IMPORTS`, `INHERITS`, and data-flow edges via `FLOWS_TO`

The parsing logic resides in the `codebase_rag` package. The **`GraphLoader`** class in [[`codebase_rag/graph_loader.py`](https://github.com/vitali87/code-graph-rag/blob/main/codebase_rag/graph_loader.py)](https://github.com/vitali87/code-graph-rag/blob/main/codebase_rag/graph_loader.py) reads the generated JSON graph file and builds in-memory indexes for fast lookup.

### Layer 2: RAG Interface and Natural Language Queries

Once your codebase is graphified, the RAG layer enables conversational interaction.

**The flow works as follows:**

1. User submits a natural language query
2. An LLM translates the query into **Cypher** (Memgraph's query language)
3. Cypher executes against the graph to retrieve relevant fragments
4. Results are fed back to the LLM for synthesis and response generation
5. The system can return source code, answer questions, or propose AST-based patches

The **CLI entry point** lives in [[`codebase_rag/cli.py`](https://github.com/vitali87/code-graph-rag/blob/main/codebase_rag/cli.py)](https://github.com/vitali87/code-graph-rag/blob/main/codebase_rag/cli.py). The **core RAG loop**—orchestrating state management and AI model interaction—is implemented in [[`codebase_rag/cgr_state.py`](https://github.com/vitali87/code-graph-rag/blob/main/codebase_rag/cgr_state.py)](https://github.com/vitali87/code-graph-rag/blob/main/codebase_rag/cgr_state.py).

## Data Flow Through the System

The complete data flow, as illustrated in the README (lines 95-104), follows this path:

```text
Source Code → Tree-sitter Parser → AST Analysis → Memgraph Knowledge Graph
                │
User Query → AI Model (Cypher generation) → Cypher → Graph Results → Response

```

This design decouples code analysis from query processing, allowing the graph to be built once and queried repeatedly without re-parsing.

## Key Architectural Features

### Unified, Language-Agnostic Graph Schema

All parsed code—regardless of source language—conforms to a single schema defined in [[`docs/architecture/graph-schema.md`](https://github.com/vitali87/code-graph-rag/blob/main/docs/architecture/graph-schema.md)](https://github.com/vitali87/code-graph-rag/blob/main/docs/architecture/graph-schema.md).

**Node structure:**
- `label`: entity type (`Function`, `Class`, `Module`, `Variable`, etc.)
- `properties`: metadata including `name`, `filepath`, `linenos`, `signature`, and `docstring`

**Relationship types:**
- Structural: `CALLS`, `IMPORTS`, `INHERITS`, `CONTAINS`
- Data-flow: `FLOWS_TO` for tracking value propagation

This unification means a Cypher query written for Python code will work unchanged on TypeScript or Rust codebases.

### Memgraph Backend for Interactive Speed

The graph is persisted in **Memgraph**, a high-performance in-memory graph database. This enables sub-second Cypher query execution even on large repositories, making the CLI experience responsive.

### Optional Semantic Search with Qdrant

For queries where symbolic matching falls short, Code-Graph-RAG supports **vector-based semantic search** via Qdrant. Enable this with the `semantic` extra:

```bash
pip install code-graph-rag[semantic]

```

Embeddings are cached and managed by [[`codebase_rag/embedder.py`](https://github.com/vitali87/code-graph-rag/blob/main/codebase_rag/embedder.py)](https://github.com/vitali87/code-graph-rag/blob/main/codebase_rag/embedder.py), allowing hybrid retrieval that combines graph traversal with semantic similarity.

### MCP Server for Agent Integration

External AI agents can interact with Code-Graph-RAG through the **Model Context Protocol (MCP)**. Running `cgr daemon` starts an MCP server that exposes graph query and modification capabilities to tools like Claude Code. See [[`docs/guide/mcp-server.md`](https://github.com/vitali87/code-graph-rag/blob/main/docs/guide/mcp-server.md)](https://github.com/vitali87/code-graph-rag/blob/main/docs/guide/mcp-server.md) for configuration details.

## How to Use Code-Graph-RAG: Practical Examples

### 1. Start the Infrastructure Stack

```bash
cgr daemon up

```

This launches bundled Memgraph and Qdrant containers.

### 2. Parse Your Repository

```bash
cgr start --repo-path /path/to/repo --update-graph

```

The `--update-graph` flag triggers full parsing and graph construction.

### 3. Query Interactively

```bash
cgr start --repo-path /path/to/repo

```

You'll enter an interactive prompt where natural language questions are automatically translated to Cypher:

```

> Which functions in `utils.py` call the database?

```

The system returns matching function definitions with source locations.

### 4. Programmatic Graph Access

For custom pipelines, use the Python SDK:

```python
from codebase_rag.graph_loader import load_graph

loader = load_graph("graph.json")
summary = loader.summary()
print(summary)

```

The `GraphLoader` class provides:

- `loader.nodes()` — iterate all graph nodes
- `loader.relationships()` — iterate all edges
- `loader.summary()` — human-readable repository statistics

### 5. Direct Cypher Execution

```python
from codebase_rag.graph_loader import load_graph
from codebase_rag.cypher_queries import find_functions_by_name

loader = load_graph("graph.json")
cypher = find_functions_by_name("calculate_total")
results = loader.graph.run(cypher)

```

Query helpers are documented in [[`docs/sdk/cypher-generator.md`](https://github.com/vitali87/code-graph-rag/blob/main/docs/sdk/cypher-generator.md)](https://github.com/vitali87/code-graph-rag/blob/main/docs/sdk/cypher-generator.md).

## Build Configuration and Dependencies

The project's [[`pyproject.toml`](https://github.com/vitali87/code-graph-rag/blob/main/pyproject.toml)](https://github.com/vitali87/code-graph-rag/blob/main/pyproject.toml) defines optional dependency groups:

- `treesitter-full` — complete Tree-sitter grammar support
- `semantic` — Qdrant vector search and embedding capabilities

These extras keep the base installation lightweight while allowing feature expansion as needed.

## Summary

- **Code-Graph-RAG** converts multi-language repositories into a unified Memgraph knowledge graph using Tree-sitter parsing
- The **unified schema** makes Cypher queries portable across Python, TypeScript, Rust, Go, Java, and other supported languages
- **Two-layer architecture** separates one-time graph construction from interactive natural language querying
- **MCP server support** enables external AI agents to query and modify codebases programmatically
- **Optional Qdrant integration** adds semantic search when symbolic graph traversal is insufficient

## Frequently Asked Questions

### What programming languages does Code-Graph-RAG support?

Code-Graph-RAG supports Python, TypeScript/TSX, JavaScript, Rust, Go, Java, C, C++, C#, PHP, Lua, and Dart through production Tree-sitter grammars. Scala and Ruby have experimental support. All languages map to the same unified graph schema, enabling cross-language queries and a consistent interaction model regardless of your codebase's primary language.

### How does Code-Graph-RAG differ from traditional code search tools?

Traditional tools rely on text search or language-specific static analysis. Code-Graph-RAG builds a **queryable knowledge graph** that captures semantic relationships like call graphs, inheritance hierarchies, and data flow. This enables questions like "What functions indirectly depend on the authentication module?" that text search cannot answer. The natural language interface also eliminates the need to learn grep patterns, regex, or language-specific query syntax.

### Can I use Code-Graph-RAG without installing Memgraph locally?

No—Memgraph is required as the graph backend. However, the `cgr daemon up` command launches Memgraph (and optional Qdrant) via containers, requiring no manual database configuration. For production deployments, you can point Code-Graph-RAG to an external Memgraph instance by configuring the connection parameters.

### What is the MCP server and when should I use it?

The **MCP (Model Context Protocol) server**, accessible via `cgr daemon`, exposes Code-Graph-RAG's capabilities to external AI agents like Claude Code. Use it when building automated workflows where an agent needs to explore codebases, understand dependencies, or propose modifications without human CLI interaction. The MCP protocol provides standardized tool definitions that LLMs can invoke automatically.