# Clangd Graph Rag

> Source code graph RAG (GraphRAG) for C/C++ development based on clang/clangd

- **Type:** MCP server
- **Install:** `agentstack add mcp-2015xli-clangd-graph-rag`
- **Verified:** Yes — security-reviewed for prompt injection and unsafe behavior
- **Seller:** [2015xli](https://agentstack.voostack.com/s/2015xli)
- **Installs:** 0
- **Category:** [AI & ML](https://agentstack.voostack.com/c/ai-and-ml)
- **Latest version:** 0.1.0
- **License:** Apache-2.0
- **Upstream author:** [2015xli](https://github.com/2015xli)
- **Source:** https://github.com/2015xli/clangd-graph-rag

## Install

```sh
agentstack add mcp-2015xli-clangd-graph-rag
```

Requires the [AgentStack CLI](https://agentstack.voostack.com/docs/cli). Works with Claude Code, Cursor, and any MCP-compatible agent.

## About

# C/C++ Source Code Graph RAG (using Clang/Clangd)

This project builds a Neo4j graph RAG (Retrieval-Augmented Generation) for a C/C++ software project based on clang/clangd, which can be queried for deep software project analysis. It works well with large and complex codebases like the Linux, llvm, llama.cpp, etc. 

The project includes an example MCP server and an AI expert agent. You can also develop your own MCP servers and agents around the graph RAG for your specific purposes, such as:

**Software Analysis**
*   Analyze project organization (folders, files, modules)
*   Analyze code patterns and structures
*   Understand call chains and class relationships
*   Examine architectural design and workflows
*   Trace dependencies and interactions

**Expert Assistance**
*   **Code Refactoring Advice**: Provide guidance on design improvements and optimizations
*   **Bug Analysis**: Help identify root causes of bugs or race conditions
*   **Documentation**: Assist with software design documentation
*   **Feature Implementation**: Guide on implementing features based on requirements
*   **Architecture Review**: Analyze and suggest improvements to system architecture

---

### Current Schema
Here is a simplified version of the [current neo4j schema](neo4j_simplified_schema.txt) for AI agent to use.

---
### A benchmark: The Linux Kernel

When building a code graph for the Linux kernel (WSL2 release) on a workstation (12 cores, 64GB RAM), it takes about ~4 hours using 10 parallel worker processes, with peak memory usage at ~32GB. Note this process does not include the LLM summary generation, so the total time (and cost) may vary based on your LLM provider. Local LLM API with Ollama is supported.

## Table of Contents
- [Why This Project?](#why-this-project)
- [Why Clang instead of Tree-sitter?](#why-clang-instead-of-tree-sitter)
- [Key Features & Design Principles](#key-features--design-principles)
- [Prerequisites](#prerequisites)
- [Primary Usage](#primary-usage)
  - [Full Graph Build](#full-graph-build)
  - [Incremental Graph Update](#incremental-graph-update)
  - [Common Options](#common-options)
- [Interacting with the Graph: MCP and Agent](#interacting-with-the-graph-ai-agent)
- [Supporting Scripts](#supporting-scripts)
- [Rebuild or Clean Up Graph](#rebuild-or-clean-up-graph)
- [Documentation & Contributing](#documentation--contributing)

## Why This Project?

For C/C++ project, Clangd language server has been very useful for developers using an IDE. The symbols in the code are represented in an intermediate data format from [Clangd-indexer](https://clangd.llvm.org/design/indexing.html) containing detailed syntactical information used by language servers for code navigation and completion. However, while powerful for IDEs, the raw index data doesn't expose the full graph structure of a codebase (e.g., the call graph, header dependence graph, macro expansion graph, etc.) or integrate the semantic understanding that Large Language Models (LLMs) can leverage.

This project fills that gap. It reconciles the Clangd index data and Clang parsing data, and ingests them into a Neo4j graph database, reconstructing the complete file, symbol, and relationship hierarchy. It then enriches this structure with AI-generated summaries and vector embeddings, transforming the raw compiler index into a semantically rich knowledge graph. In essence, `clangd-graph-rag` extends Clangd's powerful foundation into an AI-ready code graph, enabling LLMs to reason about a codebase's structure and behavior for advanced tasks like in-depth code analysis, refactoring, and automated reviewing.

Another powerful feature is that this project supports building the graphRAG incrementally, which means it can update the graph based on the diff of git commits without rebuilding the entire graph from scratch. This significantly reduces the time and cost of maintaining the graphRAG.

Note, this is an independent project and is not affiliated with the official Clang or clangd projects.

## Why Clang instead of Tree-sitter?

While Tree-sitter is an excellent tool for syntax highlighting and simple code navigation, it falls short when building a high-fidelity, semantically accurate code graph for C/C++, especially for large-scale production codebases. This project deliberately leverages Clang for several critical reasons:

*   **Macro and Preprocessor Awareness**: C/C++ development relies heavily on the preprocessor. Tree-sitter is purely syntactic and lacks a preprocessor; it cannot resolve macro expansions or track the relationship between a macro definition and the code it generates. Clang provides "causality tracking" for macro-expanded entities.
*   **Semantic Accuracy with Conditional Compilation**: In real-world code, `#ifdef` and `#else` blocks are ubiquitous. Tree-sitter often sees both branches of a conditional block simultaneously and may give dependence relationships incorrectly. Clang (using `compile_commands.json`) knows exactly which code path is actually compiled and "visible" to the compiler.
*   **Global Symbol Identity (USR)**: This project uses Unified Symbol Resolution (USR) to uniquely identify entities across the entire codebase. E.g., USRs allow the graph to link template specializations to their primary templates and resolve overloads accurately—tasks that are impossible with a file-local syntactic parser.
*   **Cross-File Semantic Integrity**: Many C/C++ constructs are fragmented across files (e.g., a struct whose fields are defined in an included header). Because Tree-sitter parses files in isolation, it cannot "see" the complete definition of such entities. Clang parses Translation Units (TUs) with full header context and preprocessing, ensuring a complete and accurate model.
*   **Compiler-Grade Fidelity**: By leveraging the same engine used for compilation, we ensure the graph reflects the code exactly as it is understood by the compiler, including complex C++ template metaprogramming and name lookup rules.

## Key Features & Design Principles

*   **AI-Enriched Code Graph**: Builds a comprehensive graph of files, folders, symbols, and function calls, then enriches it with AI-generated summaries and vector embeddings for semantic understanding.
*   **Robust Dependency Analysis**: Builds a complete graph for call chain, header inclusion, macro expansion, class specialization, and type alias relationships, enabling accurate code structure and architecture analysis.
*   **Compiler-Accurate Parsing**: Leverages `clang` via its compilation database (the `compile_commands.json` file) to parse source code with full semantic context, correctly handling complex macros and include paths.
*   **Incremental Updates**: Includes a Git-aware updater script that efficiently processes only the files changed between commits, avoiding the need for a full rebuild.
*   **AI Agent Interaction**: Provides a tool server and an example agent to allow for interactive, natural language-based exploration and analysis of the code graph.
*   **High-Performance & Memory Efficient**: Designed for performance with multi-process, multi-threaded, and asyncio coroutine parallelism, efficient batching for database operations, and intelligent memory management to handle large codebases.
*   **Modular & Reusable**: The core logic is encapsulated in modular classes and helper scripts, promoting code reuse and maintainability.

## Prerequisites
### Input file dependencies
To successfully build the graph, this project leverages the power of the LLVM ecosystem. Before starting, ensure you have the following two files ready:

1. **JSON Compilation Database (.json)**
 
    The project requires a compilation database file, usually named `compile_commands.json`, which provides the necessary compiler flags and include paths for your source code. This file is usually generated by your build system. There are usually two ways:
   - If you are using CMake, you can use the following command:
     ```
     cmake -DCMAKE_EXPORT_COMPILE_COMMANDS=ON 
     ```
   - If you are using Make, you can use the following command: 
     ```
     bear -- make 
     ```
   For other build system like Bazel, please refer to [LLVM original document](https://clang.llvm.org/docs/JSONCompilationDatabase.html) for more details.

   By default, the system looks for the `compile_commands.json` files in the root of your project path. If they are located  or with a different name, you can point to them using the `--compile-commands` option. For more details on customizing paths, see the [Common Options](#common-options) section.

2. **Clangd Index File (.yaml)**

   In addition to the compilation database, you will need a static index generated by clangd-indexer （version >= 21.0.0). (If you don't have it, you can download the indexing-tools directly from the official [clangd releases](https://github.com/clangd/clangd/releases), or you can build it from [llvm source](https://github.com/llvm/llvm-project).)

   Then you can use the following command to generate the index file:
   ```
   clangd-indexer --executor=all-TUs --format=yaml  > your-clangd-index.yaml
   ```
   The `` can be `.` (a dot) if it is in the current directory.

   By default, the system does not assume the index file is in the root of your project path. You should specify its path explicitly in command line as the first argument. For more details, see the [Primary Usage](#primary-usage) section.

### Other installation dependencies
1. **clang**
 
   The project requires a clang installed on your system (that has libclang included). Your system usually has it by default. If not, you can download it from the official [clang website](https://clang.llvm.org/)， version >= 21.0.0. (The project originally targeted clang version >= 16.x, but versions below 21.0.0 are not actively maintained.)

2. **Neo4j**

   The project requires a Neo4j database running to store the graph data. Check if your system supports neo4j in its package management (like apt). Or you can download its Desktop version (encouraged) or service version (the Community version works fine) from the official [Neo4j website](https://neo4j.com/download/), version >= 5.0.0. (I used to work with version 4.x. Not sure if it still works.) 

   The project also needs the neo4j's APOC plugin (core + extension), which can be easily installed from the Desktop version. That's why the Desktop version is suggested. If you use neo4j service version, you need download [APOC core](https://github.com/neo4j/apoc/releases) and [APOC extension](https://github.com/neo4j-contrib/neo4j-apoc-procedures/releases), and put them to your neo4j's plugins folder (mine is at /var/lib/neo4j/plugins) then restart neo4j service. Note the downloaded APOC version should match with your neo4j version. 
   
   The project by default uses the neo4j default values for its `NEO4J_URI/NEO4J_USER/NEO4J_PASSWORD`. If you use different values, please set them in your environment variables or modify the default values in the following lines of `neo4j_manager/base.py`: 
    ```
    NEO4J_URI = os.getenv("NEO4J_URI", "bolt://localhost:7687") 
    NEO4J_USER = os.getenv("NEO4J_USER", "neo4j")
    NEO4J_PASSWORD = os.getenv("NEO4J_PASSWORD", "neo4j")
    ```

3. **LLM model and its API key**

   If you want to generate summaries in the neo4j graph with LLM, you need have access to an LLM model service either remotely or locally. The project uses Litellm package to access LLM APIs, which can virtually support almost all popular LLM services. You need set environment variable for the API key for your remote LLM service, such as OPENAI_API_KEY, or DEEPSEEK_API_KEY, etc. If you want to use your specific model, you can simply add it in file `llm_client.py`, by modifying the constructor `__init__()` of the `LiteLlmClient` class. The code retrieves the max context window size from the service by default. You can also specify a window size by modifying the code there.

4. **Python**

   The project requires `Python 3.13` (or higher). 
   Actually `Python 3.11 (or higher)` is enough, if you only want to build the graphRAG and don't plan to run the example AI agent. The example agent is developed using Google ADK that requires `Python 3.13`. Then you can remove the `google-adk` dependency from the provided `requirements.txt`, and maintain your own requirements file.

## Primary Usage

**Note 1**: To build graph, please follow [the prerequisites](#prerequisites) to prepare the clang compilation database file `compile_commands.json` and the clangd index `.yaml` file, and have the neo4j server started. The examples below assume the `compile_commands.json` file is located in the root of your project path. If it is located elsewhere, you must specify its location with the `--compile-commands` option (see [Common Options](#common-options)).  

**Note 2**: To generate LLM summaries for the graph, it is highly recommended to create a `project-info.md` file in the project root folder as the project context information, which is extremely useful for the LLM to have a right context. The file content can be a few words or a few paragraphs as you want, such as "This LLVM project is a collection of modular compiler and toolchain technologies."

   Before building graph for your C/C++ code, checkout a copy of the project:
   ```
   git clone https://github.com/2015xli/clangd-graph-rag.git
   cd clangd-graph-rag
   ```
   Then you need install the required packages using the following command:
   ```
   #If you don't want to run the example AI agent, you can remove the `google-adk` dependence
   pip install -r requirements.txt
   ```

The two main entry points of the project are the graph builder and the graph updater.
For all the scripts that can run standalone, you can always use `--help` to see the full CLI options.

### Full Graph Build

Used for the initial, from-scratch ingestion of a project. Orchestrated by `graph_builder.py`.

```bash
# Build the graph only (no LLM summary generation, which you can generate separately later)
python3 graph_builder.py /path/to/clangd-index.yaml /path/to/project/

# Build the graph with LLM summary generation (single command for both graph construction and summary generation)
python3 graph_builder.py /path/to/clangd-index.yaml /path/to/project/ --generate-summary [--llm-api [openai|deepseek|ollama|fake]]
```
* Without `--generate-summary`, the tool will only perform the graph construction phase. This is to give you an option to check the graph results before generating LLM summaries that may cost time and money.
* With `--generate-summary` enabled, the tool will generate summary. By default it will use `--llm-api fake` to test the summary generation without actually calling an LLM API. You can use `--llm-api [openai|deepseek|ollama|fake]` to specify the LLM API to use. Adding an API for your use case is super easy. Please check the `llm_client.py` file for the details. 
* The generated summaries are cached in two levels of caches, so that you don't need to regenerate them if the source code of the project remains unchanged. If you used the default `fake` llm client in previous run, and now you specify a real LLM API, the fake summaries will be removed automatically, so that your graphRAG does not have mixed fake and real summaries. 

Please check the detailed design document for more details: [Graph Builder](./docs/graph_builder.md) or go to the [Documentation](#documentation) section for a full description.

### Summary RAG Data Generation

After the graph is fully built (without --generate-summary enabled), you can generate LLM summary RAG data with the following command. If you don't specify the --llm-api, it will use the `fake` llm client for testing purpose.
```bash
python3 -m summary_driver /path/to/clangd-index.yaml /path/to/project/ --llm-api [openai|deepseek|ollama|fake]
```
Please check the detailed design document for more details: [Summary Generation](./summary_driver/README.md)

…

## Source & license

This open-source MCP server is cataloged on AgentStack and links to its original source — we do not rehost the code.

- **Author:** [2015xli](https://github.com/2015xli)
- **Source:** [2015xli/clangd-graph-rag](https://github.com/2015xli/clangd-graph-rag)
- **License:** Apache-2.0

Install and usage instructions live in the source repository linked above.

## Pricing

- **Free** — Free

## Security capabilities

Automated source analysis of v0.1.0 — what this tool can access:

- **Network access:** no
- **Filesystem access:** no
- **Shell / process execution:** no
- **Environment & secrets:** yes
- **Dynamic code execution:** no

*"Yes" means the capability is present in the source — more access means more to trust, not that it is unsafe.*


## Versions

- **0.1.0** — security scan: passed — Imported from the upstream source.

## Links

- Listing page: https://agentstack.voostack.com/l/mcp-2015xli-clangd-graph-rag
- Seller: https://agentstack.voostack.com/s/2015xli
- Browse the marketplace: https://agentstack.voostack.com/browse

---
Listed on AgentStack — the marketplace for AI agent skills and MCP servers. Every listing is security-reviewed. Creators keep 70%.
