Skip to main content

Code-Graph-RAG

Code-Graph-RAG parses a multi-language codebase with Tree-sitter, builds a knowledge graph of its structure in Memgraph, and lets you query, edit, and optimise that code in plain English. It works across a monorepo of mixed languages under one unified graph schema.

What It Does

Point it at a repository and it reads every source file, extracts functions, classes, methods, and modules along with the relationships between them, and stores the result as an interconnected graph. Once the graph exists you can:

  • Ask questions about the codebase in natural language and get answers grounded in the real structure.
  • Retrieve the actual source of any function, class, or method by name or by intent.
  • Edit code through the agent with AST-based surgical patching and a diff preview before anything changes.
  • Search and rewrite code structurally by AST pattern with ast-grep, instead of text or regex.
  • Trace data flow through assignments, calls, and I/O sinks via FLOWS_TO taint edges.
  • Optimise code against language best practices or your own coding standards.
  • Find dead code by walking call and reference edges from entry points.
  • Overlay runtime behaviour: trace a test run (or pull production eBPF profiles) and merge the calls that actually happened into the graph, exposing dispatch that static analysis cannot see.
  • Group several repositories into a named workspace and query them as one graph.
  • Trace calls between microservices: route decorators become endpoint templates, and HTTP client URLs resolve to the handlers that serve them, linking services across project boundaries.

Supported Languages

Python, TypeScript, TSX, JavaScript, Rust, Go, Java, C, C++, C#, PHP, Lua, and Dart are fully supported. Scala is in development, and Ruby has structural support (modules, functions, classes, and imports) through the pluggable ast-grep tier, which requires the ast-grep extra (pip install 'code-graph-rag[ast-grep]').

Install

pip install code-graph-rag

With all Tree-sitter grammars (Python, JS, TS, Rust, Go, Java, Scala, C, C++, C#, PHP, Lua, Dart):

pip install 'code-graph-rag[treesitter-full]'

With semantic code search (UniXcoder embeddings):

pip install 'code-graph-rag[semantic]'

Qdrant is the default vector store for semantic search. To use Milvus Lite, install code-graph-rag[semantic,milvus], then set CGR_VECTOR_STORE_BACKEND=milvus and MILVUS_URI=./.milvus_code_embeddings.db before indexing.

To compute embeddings on an OpenAI-compatible endpoint (OpenAI, Ollama, vLLM) instead of locally, set CGR_EMBEDDING_PROVIDER=openai with OPENAI_EMBEDDING_BASE_URL and OPENAI_EMBEDDING_MODEL; torch and transformers are then not required locally.

Prerequisites

  • Python 3.12+
  • Docker (for Memgraph)
  • cmake (for building pymgclient)
  • ripgrep (rg) (for shell command text searching)

CLI Quick Start

The package installs a cgr command.

Start Memgraph, parse a repo, and query it:

cgr daemon up                              # start Memgraph + Qdrant
cgr start --repo-path ./my-project \
          --update-graph --clean           # parse & launch interactive chat

Index to protobuf for offline use:

cgr index -o ./index-output --repo-path ./my-project

Export knowledge graph to JSON:

cgr export -o graph.json

AI-guided optimisation:

cgr optimize python --repo-path ./my-project

Find dead code (functions unreachable from any entry point):

cgr dead-code                                   # scan the indexed project
cgr dead-code -e main --exclude '*.gen.*'       # add roots, skip generated code
cgr dead-code --format json --fail-on-found     # CI-friendly report

Results are candidates for review, not a guaranteed delete list. See the Dead Code Detection guide.

Group repositories into a workspace and query them together:

cgr workspace create my-platform
cgr workspace add-repo my-platform ./service-a
cgr workspace add-repo my-platform ./service-b
cgr start --workspace my-platform

Inspect the graph and the stack:

cgr stats                                  # node and relationship counts
cgr status                                 # stack state and last sync per project
cgr doctor                                 # check dependencies and configuration

Runtime Call Tracing

Static analysis cannot see calls through interfaces, reflection, registries, or framework routing. cgr trace records which functions actually called which while your code runs (typically the test suite) and merges the observations into the graph as CALLS edges with dynamic provenance: dynamic: true, observed call counts, the workloads (tests) that exercised each edge, and static_missed: true where no static edge existed.

Index the repository first (cgr start --repo-path ./my-project --update-graph), then:

Python (a pytest plugin ships with the package, inert unless enabled):

cd ./my-project
pytest --cgr-trace                              # writes cgr-trace.jsonl
cgr trace ingest cgr-trace.jsonl --repo-path .  # merge into the graph

Node.js / TypeScript (V8's built-in profiler, no agent needed; source maps are followed back to the original TypeScript):

node --cpu-prof --cpu-prof-name=run.cpuprofile app.js
cgr trace convert run.cpuprofile --repo-path ./my-project --workload smoke
cgr trace ingest cgr-trace.jsonl --repo-path ./my-project

Production overlay (eBPF continuous profilers: Parca, Pyroscope, OpenTelemetry). Fetch a pprof over HTTP and convert it in one step, re-anchoring build paths to your checkout:

cgr trace pull "https://parca.example/query?...&format=pprof" \
    --repo-path ./my-project --language go \
    --path-map /build/src/=./my-project/src/ \
    --label endpoint --header "Authorization=Bearer $TOKEN"
cgr trace ingest cgr-trace.jsonl --repo-path ./my-project

The JVM (Java, Scala), .NET, PHP, Lua, Dart, Go, Rust, and C/C++ each have a recording recipe in the Dynamic Call Tracing guide. Ingest is idempotent, so a cron'd pull plus ingest keeps a continuously refreshing production overlay. The absence of a dynamic edge never means dead code; it only means the traced workload did not exercise that path.

MCP Server

Run cgr mcp-server to serve the tools over stdio or HTTP for Claude Code and other MCP clients. The MCP surface registers:

  • Ask and retrieve: ask_agent, query_code_graph, get_code_snippet, and semantic_search (needs the semantic extra)
  • Structural editing: surgical_replace_code, plus structural_search and structural_replace (need the ast-grep extra)
  • Files and projects: read_file, write_file, list_directory, list_projects, index_repository, update_repository, delete_project, wipe_database

Python SDK

The cgr package provides short imports for programmatic use.

Load and query an exported graph

from cgr import load_graph

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

functions = graph.find_nodes_by_label("Function")
for fn in functions[:5]:
    rels = graph.get_relationships_for_node(fn.node_id)
    print(f"{fn.properties['name']}: {len(rels)} relationships")

Query Memgraph with Cypher

from cgr import MemgraphIngestor

with MemgraphIngestor(host="localhost", port=7687) as db:
    rows = db.fetch_all("MATCH (f:Function) RETURN f.name LIMIT 10")
    for row in rows:
        print(row)

Generate Cypher from natural language

import asyncio
from cgr import CypherGenerator

async def main():
    gen = CypherGenerator()
    cypher = await gen.generate("Find all classes that inherit from BaseModel")
    print(cypher)

asyncio.run(main())

Semantic code search

Requires the semantic extra.

from cgr import embed_code

embedding = embed_code("def authenticate(user, password): ...")
print(f"Embedding dimension: {len(embedding)}")

Configuration

from cgr import settings

settings.set_orchestrator("openai", "gpt-5.6-terra", api_key="sk-...")
settings.set_cypher("google", "gemini-3.5-flash-lite", api_key="your-key")

Environment Variables

Configure via .env or environment variables:

Variable Default Description
MEMGRAPH_HOST localhost Memgraph hostname
MEMGRAPH_PORT 7687 Memgraph port
ORCHESTRATOR_PROVIDER Provider: google, openai, anthropic, azure, ollama, minimax, litellm_proxy
ORCHESTRATOR_MODEL Model ID (e.g. gpt-5.6-terra, gemini-3.6-flash, claude-sonnet-5, qwen2.5-coder)
ORCHESTRATOR_API_KEY API key for the provider (not needed for ollama)
CYPHER_PROVIDER Provider for Cypher generation
CYPHER_MODEL Model ID for Cypher generation (e.g. qwen2.5-coder, gpt-5.6-luna, gemini-3.5-flash-lite)
CYPHER_API_KEY API key for Cypher provider (not needed for ollama)
TARGET_REPO_PATH . Default repository path

Documentation

Full documentation, architecture details, and contribution guide: docs.code-graph-rag.com

License

MIT

Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

code_graph_rag-0.0.670.tar.gz (920.0 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

code_graph_rag-0.0.670-py3-none-any.whl (1.1 MB view details)

Uploaded Python 3

File details

Details for the file code_graph_rag-0.0.670.tar.gz.

File metadata

  • Download URL: code_graph_rag-0.0.670.tar.gz
  • Upload date:
  • Size: 920.0 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.7

File hashes

Hashes for code_graph_rag-0.0.670.tar.gz
Algorithm Hash digest
SHA256 3df573cf9c128c0cab6be9698b679dbbbdc832bef6ca2609d20dcdce150f316d
MD5 21ab0e010099fc1350bb9932a7c580f9
BLAKE2b-256 e51f680161c166140855ac7ce99e37797d7b2aa9662754ba4be482949bc2634b

See more details on using hashes here.

Provenance

The following attestation bundles were made for code_graph_rag-0.0.670.tar.gz:

Publisher: publish.yml on vitali87/code-graph-rag

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file code_graph_rag-0.0.670-py3-none-any.whl.

File metadata

File hashes

Hashes for code_graph_rag-0.0.670-py3-none-any.whl
Algorithm Hash digest
SHA256 95d2d9310b35decf763ccb5cf32a39b02d5ab3eef9251e6f6d4956a11ae40b24
MD5 f92447cb2f6b8dad86b2391693ae8f91
BLAKE2b-256 becb18c13b56d28dcaa8da0644a650dd95d30183ec140d8c061c9711550659a1

See more details on using hashes here.

Provenance

The following attestation bundles were made for code_graph_rag-0.0.670-py3-none-any.whl:

Publisher: publish.yml on vitali87/code-graph-rag

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page