Metadata-Version: 2.4
Name: code-graph-rag
Version: 0.0.584
Summary: The ultimate RAG for your monorepo. Query, understand, and edit multi-language codebases with the power of AI and knowledge graphs
License-Expression: MIT
Keywords: rag,retrieval-augmented-generation,knowledge-graph,code-analysis,tree-sitter,mcp,mcp-server,llm,graph-database,semantic-search,codebase,memgraph,developer-tools,monorepo
Classifier: Development Status :: 4 - Beta
Classifier: Environment :: Console
Classifier: Intended Audience :: Developers
Classifier: Operating System :: OS Independent
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
Classifier: Topic :: Software Development :: Code Generators
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Requires-Python: >=3.12
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: loguru>=0.7.3
Requires-Dist: mcp>=1.28.1
Requires-Dist: pydantic-ai>=2.0.0
Requires-Dist: pydantic-settings>=2.12.0
Requires-Dist: pymgclient>=1.5.1
Requires-Dist: python-dotenv>=1.2.1
Requires-Dist: tiktoken>=0.12.0
Requires-Dist: toml>=0.10.2
Requires-Dist: tree-sitter-python>=0.25.0
Requires-Dist: tree-sitter==0.25.2
Requires-Dist: watchdog>=6.0.0
Requires-Dist: typer>=0.21.1
Requires-Dist: rich>=14.2.0
Requires-Dist: prompt-toolkit>=3.0.52
Requires-Dist: diff-match-patch>=20241021
Requires-Dist: click>=8.3.1
Requires-Dist: protobuf>=6.33.5
Requires-Dist: defusedxml>=0.7.1
Requires-Dist: huggingface-hub[hf-xet]>=1.7.2
Requires-Dist: pathspec>=1.0.4
Provides-Extra: test
Requires-Dist: pytest>=8.4.1; extra == "test"
Requires-Dist: pytest-asyncio>=1.0.0; extra == "test"
Requires-Dist: pytest-cov>=4.0.0; extra == "test"
Requires-Dist: pytest-xdist>=3.8.0; extra == "test"
Requires-Dist: testcontainers>=4.9.0; extra == "test"
Requires-Dist: libclang>=18.1.1; extra == "test"
Requires-Dist: filelock>=3.12; extra == "test"
Requires-Dist: ast-grep-py>=0.44.0; extra == "test"
Requires-Dist: pyyaml>=6.0; extra == "test"
Provides-Extra: treesitter-full
Requires-Dist: tree-sitter-python>=0.23.6; extra == "treesitter-full"
Requires-Dist: tree-sitter-javascript>=0.23.1; extra == "treesitter-full"
Requires-Dist: tree-sitter-typescript>=0.23.2; extra == "treesitter-full"
Requires-Dist: tree-sitter-rust>=0.24.0; extra == "treesitter-full"
Requires-Dist: tree-sitter-go>=0.23.4; extra == "treesitter-full"
Requires-Dist: tree-sitter-scala>=0.24.0; extra == "treesitter-full"
Requires-Dist: tree-sitter-java>=0.23.5; extra == "treesitter-full"
Requires-Dist: tree-sitter-c>=0.24.1; extra == "treesitter-full"
Requires-Dist: tree-sitter-cpp>=0.23.0; extra == "treesitter-full"
Requires-Dist: tree-sitter-lua>=0.0.19; extra == "treesitter-full"
Requires-Dist: tree-sitter-php>=0.24.1; extra == "treesitter-full"
Requires-Dist: tree-sitter-c-sharp>=0.23.5; extra == "treesitter-full"
Requires-Dist: tree-sitter-dart>=0.1.0; extra == "treesitter-full"
Provides-Extra: semantic
Requires-Dist: qdrant-client>=1.9.0; extra == "semantic"
Requires-Dist: torch>=2.6.0; extra == "semantic"
Requires-Dist: transformers>=4.0.0; extra == "semantic"
Provides-Extra: milvus
Requires-Dist: pymilvus[milvus-lite]>=3.0.0; extra == "milvus"
Provides-Extra: ast-grep
Requires-Dist: ast-grep-py>=0.44.0; extra == "ast-grep"
Requires-Dist: pyyaml>=6.0; extra == "ast-grep"
Dynamic: license-file

# 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.
- 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

```bash
pip install code-graph-rag
```

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

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

With semantic code search (UniXcoder embeddings):

```bash
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:**

```bash
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:**

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

**Export knowledge graph to JSON:**

```bash
cgr export -o graph.json
```

**AI-guided optimisation:**

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

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

```bash
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](https://docs.code-graph-rag.com/guide/dead-code/).

**Group repositories into a workspace and query them together:**

```bash
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:**

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

## 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

```python
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

```python
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

```python
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.

```python
from cgr import embed_code

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

### Configuration

```python
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](https://docs.code-graph-rag.com)

## License

MIT

<!-- mcp-name: io.github.vitali87/code-graph-rag -->
