Codegraph Rust

by Jakedismo

330 downloads
Not rated
GitHub

About

A blazingly fast codebase graphRAG implementation in 100% Rust

Details

Author
Jakedismo
Downloads
330
Categories
Developer Tools, Knowledge Base, Other

- Multi-language code parsing with Tree-sitter
- Dual transport support: STDIO and HTTP streaming
- Vector search with FAISS-powered embeddings
- Graph-based architecture with RocksDB storage
- High performance: 170K lines in 0.49 seconds
- Incremental indexing with file watching

Setting up with Highlight

This MCP is not yet compatible with Highlight’s one-click setup. However, you can still use it with Highlight by following these steps:

  1. Download and install Highlight from highlightai.com/download
  2. Navigate to the plugins tab and select "Add Custom Plugin"
  3. Configure the plugin with the settings below
    Plugin Name Codegraph Rust
    Command (node, npx, python, etc.)

    Please refer to the README for specific instructions on how to obtain API keys or other required environment variables.

  4. Enable "Start Automatically" if you want the plugin to start when Highlight launches

From the repository

Install and run via CLI. Use commands for project indexing, MCP server management (STDIO, HTTP, or both simultaneously), code search (semantic, exact, fuzzy, regex, AST), and architecture analysis. Specific configuration options include embedding models, performance tuning, and background daemon mode with PID management.

Claude Desktop / Cursor

Paste into your MCP client config file to install this server.

{
    "mcpServers": {
        "codegraph rust": {
            "codegraph": {
                "command": "codegraph",
                "args": [
                    "start",
                    "stdio"
                ],
                "env": {
                    "CODEGRAPH_CONFIG": "~/.codegraph/config.toml"
                }
            }
        }
    }
}

McpServers

{
    "codegraph": {
        "command": "codegraph",
        "args": [
            "start",
            "stdio"
        ],
        "env": {
            "CODEGRAPH_CONFIG": "~/.codegraph/config.toml"
        }
    }
}

CodeGraph transforms your entire codebase into a semantically searchable knowledge graph that AI agents can actuallyreasonabout—not just grep through.

Ready to get started?Jump to theInstallation Guidefor step-by-step setup instructions.

Already set up?See theUsage Guidefor tips on getting the most out of CodeGraph with your AI assistant.

AI coding assistants are powerful, but they're flying blind. They see files one at a time, grep for patterns, and burn tokens trying to understand your architecture. Every conversation starts from zero.

What if your AI assistant already knew your codebase?

1. Graph + Embeddings = True Understanding

Most semantic search tools create embeddings and call it a day. CodeGraph builds areal knowledge graph:

Your Code → Build Context → AST + FastML → LSP Resolution → Enrichment → Graph + Embeddings ↓ ↓ ↓ ↓ ↓ ↓ Packages Nodes/edges Type-aware API surface Graph Semantic Features Fast patterns linking Module graph traversal search Targets Spans Definitions Dataflow/Docs (hybrid)

When you search, you don't just get "similar code"—you get code with itsrelationships intact. The function that matches your query, plus what calls it, what it depends on, and where it fits in the architecture.

- Module nodes and module-level import/containment edges for cross-file navigation
- Rust-local dataflow edges (defines,uses,flows_to,returns,mutates) for impact analysis
- Document/spec nodes linked to backticked symbols inREADME.md,docs//.md, andschema//.surql
- Architecture signals (package cycles + optional boundary violations)

Indexing is tiered so you can choose between speed/storage and graph richness. The default isfast.

- fast: disables build context, LSP, enrichment, module linking, dataflow, docs/contracts, and architecture; filters outUses/Referencesedges.
- balanced: enables build context, LSP symbols, enrichment, module linking, and docs/contracts; filters outReferencesedges.
- full: enables all analyzers and LSP definitions; no edge filtering.

- CLI:codegraph index --index-tier balanced
- Env:CODEGRAPH_INDEX_TIER=balanced
- Config:
[indexing] tier = "balanced"

Indexing prerequisites (LSP-enabled tiers)

When the tier enables LSP (balanced/full), indexingfails fastif required external tools are missing.

- Rust:rust-analyzer
- TypeScript/JavaScript:nodeandtypescript-language-server
- Python:nodeandpyright-langserver
- Go:gopls
- Java:jdtls
- C/C++:clangd

If indexing appears to stall during LSP resolution, you can adjust the per-request timeout:

- CODEGRAPH_LSP_REQUEST_TIMEOUT_SECS(default600, minimum5)

If LSP resolution fails immediately and the error includes something likeUnknown binary 'rust-analyzer' in official toolchain ..., yourrust-analyzeris a rustup shim without an installed binary. Install a runnablerust-analyzer(e.g. viabrew install rust-analyzeror by switching to a toolchain that provides it).

If you want CodeGraph to flag forbidden package dependencies, addcodegraph.boundaries.tomlat the project root:

[[deny]] from = "your_crate" to = "forbidden_crate" reason = "explain the boundary"

Indexing will emitviolates_boundaryedges when adepends_onrelationship matches a deny rule.

CodeGraph doesn't return a list of files and wish you luck. It ships4 consolidated agentic toolsthat do the thinking:

Each tool accepts an optionalfocusparameter for precision when needed:

Each tool runs areasoning agentthat plans, searches, analyzes graph relationships, and synthesizes an answer. Not a search result—ananswer.

View Agent Context Gathering Flow- Interactive diagram showing how agents use graph tools to gather context.

CodeGraph implements agents usingRigthe default and recommended choice (legacyreactandlatsimplemented with autoagents still work). Selectable at runtime viaCODEGRAPH_AGENT_ARCHITECTURE=rig:

Why Rig is Default:The Rig-based backend delivers the best performance with modern thinking and reasoning models. It is a native Rust implementation that supports internal sub-architectures and provides features likeTrue Token StreamingandAutomatic Recovery.

Internal Rig Sub-Architectures:When using therigbackend, the system automatically maps theconsolidated agentic toolsto the most effective reasoning strategy:

- LATS (Tree Search): Deep multi-path exploration for complex, non-linear tasks.

- Automatically used for:agentic_architecture(structure),agentic_quality, andagentic_context(question).

- Automatically used for:agentic_context(search/builder),agentic_impact, andagentic_architecture(api_surface).

Agents can start with lightweight project context so their first tool calls are not blind. Enable via env:

- CODEGRAPH_ARCH_BOOTSTRAP=true— includes a brief directory/structure bootstrap + contents of README.md and CLAUDE.md+AGENTS.md or GEMINI.md (if present) in the agent’s initial context.
- CODEGRAPH_ARCH_PRIMER="<primer text>"— optional custom primer injected into startup instructions (e.g., areas to focus on).

Why? Faster, more relevant early steps, fewer wasted graph/semantic queries, and better architecture answers on large repos.

- Bootstrap is small (top directories summary), not a replacement for graph queries.
- Uses the same project selection as indexing (CODEGRAPH_PROJECT_IDor current working directory).

# Use Rig for best performance with thinking and reasoning models (recommended) CODEGRAPH_AGENT_ARCHITECTURE=rig ./codegraph start stdio # Use default ReAct for traditional instruction models ./codegraph start stdio # Use LATS for complex analysis CODEGRAPH_AGENT_ARCHITECTURE=lats ./codegraph start stdio

All architectures use the same 4 consolidated agentic tools (backed by 6 internal graph analysis tools) and tier-aware prompting—only the reasoning strategy differs.

Here's something clever: CodeGraph automatically adjusts its behavior based on the LLM's context window that you configured for the codegraph agent.

Running a small local model? Get focused, efficient queries.

Using GPT-5.1 or Claude with 200K context? Get comprehensive, exploratory analysis.

Using grok-4-1-fast-reasoning with 2M context? Get detailed analysis with intelligent result management.

The Agent only uses the amount of steps that it requires to produce the answer so tool execution times vary based on the query and amount of data indexed in the database.

During development the agent used 3-6 steps on average to produce answers for test scenarios.

The Agent is stateless it only has conversational memory for the span of tool execution it does not accumulate context/memory over multiple chained tool calls this is already handled by your client of choice, it accumulates that context so codegraph needs to just provide answers.

Hard cap:Maximum 8 steps regardless of tier (10 with env override). This prevents runaway costs and context overflow while still allowing thorough analysis.

Same tool, automatically optimized for your setup.

CodeGraph includes multi-layer protection against context overflow—preventing expensive failures when tool results exceed your model's limits.

- Each tool result is limited based on your configured context window
- Large results (e.g., dependency trees with 1000+ nodes) are intelligently truncated
- Truncated results include_truncated: truemetadata so the agent knows data was cut
- Array results keep the most relevant items that fit within limits

- Monitors total accumulated context across multi-step reasoning
- Fails fast with clear error message if accumulated tool results exceed safe threshold
- Threshold: 80% of context window × 4 (conservative estimate for token overhead)

# CRITICAL: Set this to match your agent's LLM context window CODEGRAPH_CONTEXT_WINDOW=128000 # Default: 128K # Per-tool result limit derived automatically: context_window × 2 bytes # Accumulation limit derived automatically: context_window × 4 × 0.8 bytes

Why this matters:Without these guards, a singleagentic_impactquery on a large codebase could return 6M+ tokens—far exceeding most models' limits and causing expensive failures.

We don't pick sides in the "embeddings vs keywords" debate. CodeGraph combines:

- 70% vector similarity(semantic understanding)
- 30% lexical search(exact matches matter)
- Graph traversal(relationships and context)
- Optional reranking(cross-encoder precision)

The result? You findhandleUserAuthwhen you search for "login logic"—but also when you search for "handleUserAuth".

When you connect CodeGraph to Claude Code, Cursor, or any MCP-compatible agent:

Before:Your AI reads files one by one, grepping around, burning tokens on context-gathering.

After:Your AI callsagentic_impact({"query": "UserService"})and instantly knows what breaks if you refactor it.

This isn't incremental improvement. It's the difference between an AI thatsearchesyour code and one thatunderstandsit.

CodeGraph shifts thecognitive load(search + relevance + dependency reasoning) into CodeGraph’s agentic tools, so your code agent can spend its context budget onmaking the change, notdiscovering what to change.

agentic_impactreturns structured output (file paths, line numbers, and bounded snippets/highlights) plus analysis:

{ "analysis_type": "dependency_analysis", "query": "PromptSelector", "structured_output": { "analysis": "…what depends on PromptSelector and why…", "highlights": [ { "file_path": "crates/codegraph-mcp-server/src/prompt_selector.rs", "line_number": 42, "snippet": "pub struct PromptSelector { … }" } ], "next_steps": ["…"] }, "steps_taken": "5", "tool_use_count": 5 }

What a code agent would otherwise have to do

Without CodeGraph’s agentic tools, a code agent typically needs multiple “single-purpose” calls to reach the same confidence:

- search for the symbol (often multiple strategies: text + semantic + ripgrep-style search)
- open and read multiple files (definition + usages + callers + related modules)
- reconstruct dependency/call graphs mentally from partial evidence
- repeat when a guess is wrong (more reads, more tokens)

This burns context quickly: reading “just” a handful of medium-sized files + surrounding context can easily consume tens of thousands of tokens, and larger repos can push into hundreds of thousands depending on how much code gets pulled into context.

With CodeGraph, the agent getspinpointed locations and relationships(plus bounded context) and can keep far more of the context window available for planning and implementing changes.

# Clone and build with all features git clone https://github.com/yourorg/codegraph-rust cd codegraph-rust ./install-codegraph-full-features.sh

If you develop on macOS, you can opt into LLVM'slldlinker for faster linking:

# Install LLVM so ld64.lld is on PATH (Homebrew) brew install llvm # Use the repo-provided Makefile targets make build-llvm make test-llvm
# Local persistent storage surreal start --bind 0.0.0.0:3004 --user root --pass root file://$HOME/.codegraph/surreal.db
codegraph index /path/to/project -r -l rust,typescript,python

🔒 Security Note:Indexing automatically respects.gitignoreand filters out common secrets patterns (.env,credentials.json,.pem, API keys, etc.). Your secrets won't be embedded or exposed to the agent.

{ "mcpServers": { "codegraph": { "command": "/full/path/to/codegraph", "args": ["start", "stdio", "--watch"] } } }

That's it.Your AI now understands your codebase.

View Interactive Architecture Diagram- Explore the full workspace structure with clickable components and layer filtering.

┌─────────────────────────────────────────────────────────────────┐ │ Claude Code / MCP Client │ └─────────────────────────────────┬───────────────────────────────┘ │ MCP Protocol ▼ ┌─────────────────────────────────────────────────────────────────┐ │ CodeGraph MCP Server │ │ ┌───────────────────────────────────────────────────────────┐ │ │ │ Agentic Tools Layer │ │ │ │ ┌─────────┐ ┌─────────┐ ┌─────────┐ ┌─────────────────┐ │ │ │ │ │ Rig │ │ ReAct │ │ LATS │ │ Tool Execution │ │ │ │ │ │ Agent │ │ Agent │ │ Agent │ │ Pipeline │ │ │ │ │ └────┬────┘ └────┬────┘ └────┬────┘ └────────┬────────┘ │ │ │ └───────┼───────────┼───────────┼───────────────┼───────────┘ │ │ └───────────┴───────────┴───────────────┘ │ │ │ │ │ ┌───────────────────────────┼───────────────────────────────┐ │ │ │ Inner Graph Tools │ │ │ │ ┌──────────────┐ ┌──────────────┐ ┌──────────────────┐ │ │ │ │ │ Transitive │ │ Call │ │ Coupling │ │ │ │ │ │ Dependencies │ │ Chains │ │ Metrics │ │ │ │ │ └──────────────┘ └──────────────┘ └──────────────────┘ │ │ │ │ ┌──────────────┐ ┌──────────────┐ ┌──────────────────┐ │ │ │ │ │ Reverse │ │ Cycle │ │ Hub │ │ │ │ │ │ Deps │ │ Detection │ │ Nodes │ │ │ │ │ └──────────────┘ └──────────────┘ └──────────────────┘ │ │ │ └───────────────────────────┬───────────────────────────────┘ │ └──────────────────────────────┼──────────────────────────────────┘ │ ┌──────────────────────────────┼──────────────────────────────────┐ │ SurrealDB │ │ ┌─────────────┐ ┌─────────────┐ ┌─────────────────────────┐ │ │ │ Nodes │ │ Edges │ │ Chunks + Embeddings │ │ │ │ (AST + │ │ (calls, │ │ (HNSW vector index) │ │ │ │ FastML) │ │ imports) │ │ │ │ │ └─────────────┘ └─────────────┘ └─────────────────────────┘ │ │ │ │ ┌────────────────────────────────────────────────────────────┐ │ │ │ SurrealQL Graph Functions │ │ │ │ fn::semantic_search_nodes_via_chunks │ │ │ │ fn::semantic_search_chunks_with_context │ │ │ │ fn::get_transitive_dependencies │ │ │ │ fn::trace_call_chain │ │ │ │ fn::calculate_coupling_metrics │ │ │ └────────────────────────────────────────────────────────────┘ │ └─────────────────────────────────────────────────────────────────┘

Key insight:The agentic tools don't just call one function. Theyreason*about which graph operations to perform, chain them together, and synthesize results. A singleagentic_impactcall might:
- Search for the target component semantically
- Get its direct dependencies
- Trace transitive dependencies
- Check for circular dependencies
- Calculate coupling metrics
- Identify hub nodes that might be affected
- Synthesize all findings into an actionable answer

CodeGraph uses tree-sitter for initial parsing and enhances results with FastML algorithms and supports:

No reviews yet — be the first

Sign in to leave a review

Use Google, GitHub, or an email account so ratings stay tied to real people.

Email sign in

No reviews posted yet.