Metadata-Version: 2.4
Name: contextcode
Version: 0.1.1
Summary: Code retrieval tool for coding agents
Requires-Python: >=3.11
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: chromadb>=1.5.9
Requires-Dist: click>=8.4.1
Requires-Dist: einops>=0.8.2
Requires-Dist: httpx>=0.28.1
Requires-Dist: mcp>=1.27.1
Requires-Dist: neo4j>=6.2.0
Requires-Dist: platformdirs>=4.9.6
Requires-Dist: pyyaml>=6.0.3
Requires-Dist: sentence-transformers>=5.5.1
Requires-Dist: tree-sitter>=0.25.2
Requires-Dist: tree-sitter-c>=0.24.2
Requires-Dist: tree-sitter-cpp>=0.23.4
Requires-Dist: tree-sitter-go>=0.25.0
Requires-Dist: tree-sitter-java>=0.23.5
Requires-Dist: tree-sitter-javascript>=0.25.0
Requires-Dist: tree-sitter-python>=0.25.0
Requires-Dist: tree-sitter-rust>=0.24.2
Requires-Dist: tree-sitter-typescript>=0.23.2
Requires-Dist: tree-sitter-c-sharp>=0.23.5
Requires-Dist: tree-sitter-dart>=0.1.0
Requires-Dist: tree-sitter-bash>=0.25.1
Requires-Dist: tree-sitter-sql>=0.3.11
Requires-Dist: tree-sitter-hcl>=1.2.0
Requires-Dist: tree-sitter-powershell>=0.26.4
Requires-Dist: pyvis>=0.3.2
Requires-Dist: tqdm>=4.66.0
Requires-Dist: watchdog>=6.0.0
Requires-Dist: pypdf>=6.13.2
Requires-Dist: llama-cpp-python>=0.3.31
Requires-Dist: networkx>=3.4
Requires-Dist: python-louvain>=0.16
Requires-Dist: pathspec>=0.12.1
Requires-Dist: tree-sitter-c-sharp>=0.23.5
Requires-Dist: tree-sitter-bash>=0.25.1
Requires-Dist: tree-sitter-sql>=0.3.11
Requires-Dist: pyvis>=0.3.2
Requires-Dist: tree-sitter-dart>=0.1.0
Requires-Dist: tree-sitter-hcl>=1.2.0
Requires-Dist: tree-sitter-powershell>=0.26.4
Dynamic: license-file

<p align="center">
  <img src="https://img.shields.io/badge/CodeContext-Multi_Engine_Code_Intelligence-0f172a?style=for-the-badge&labelColor=0f172a" alt="CodeContext" />
</p>

<h1 align="center">CodeContext</h1>

<p align="center">
  <em>High-performance local MCP server that merges vector, lexical, and graph search into one retrieval engine for AI coding agents.</em>
</p>

<p align="center">
  <a href="https://github.com/VardhmanSurana/CodeContext/blob/main/LICENSE"><img src="https://img.shields.io/badge/license-MIT-00AB6B?style=for-the-badge" alt="MIT License" /></a>
  <img src="https://img.shields.io/badge/MCP-11_Tools-000000?style=for-the-badge&logo=modelcontextprotocol&logoColor=white" alt="MCP Compatible" />
  <img src="https://img.shields.io/badge/python-3.11+-3776AB?style=for-the-badge&logo=python&logoColor=white" alt="Python 3.11+" />
  <img src="https://img.shields.io/badge/tests-221_passing-brightgreen?style=for-the-badge" alt="Tests" />
</p>

<p align="center">
  <a href="#quickstart">Quick Start</a> &bull;
  <a href="#features">Features</a> &bull;
  <a href="#architecture">Architecture</a> &bull;
  <a href="#mcp-tools">MCP Tools</a> &bull;
  <a href="#wiki">Wiki</a> &bull;
  <a href="#installation">Install</a> &bull;
  <a href="#cli">CLI</a> &bull;
  <a href="#contributing">Contributing</a>
</p>

---

Stop guessing. Give your AI agents the precise codebase context they need to write production-grade code.

---

## Quick Start

```bash
# 1. Install
pip install contextcode

# 2. Index your project (interactive config on first run)
cd /path/to/your/project
cctx index

# 3. Start the MCP server
cctx mcp
```

That's it. Your AI agent now has multi-stage retrieval across lexical, vector, and graph engines.

---

## Features

| Feature | Description |
|---------|-------------|
| 🔍 **Multi-Stage Search** | Lexical (FTS5) + Vector (ChromaDB) + Graph expansion + CrossEncoder reranking |
| 🌲 **AST-Aware Chunking** | Tree-sitter parses 14 languages: Python, JS, TS, Go, Rust, Java, C/C++, C#, Dart, Bash, SQL, HCL, PowerShell, Markdown |
| 🧠 **Graph Intelligence** | Dead code detection, call tracing, architecture overview, community detection |
| 📖 **Knowledge Wiki** | LLM-maintained persistent wiki with OKF v0.1 compliance |
| 🔗 **Cross-Service Linking** | HTTP route detection and inter-service call graph edges |
| ⚡ **GPU Embeddings** | llama.cpp with Snowflake Arctic (Q8) for indexing, tiny model for queries |
| 🔄 **Incremental Indexing** | Content-hash-based — only re-indexes changed files |
| 🏗️ **Pluggable Graph Store** | Neo4j, AWS Neptune, DataStax Astra DB, and GraphRAG export adapters via a unified factory |
| 🕸️ **Static Call Graphs** | Cross-language call extraction + import resolution, hub detection, and blast-radius analysis |
| 📊 **5-Signal Scoring** | FTS + vector + name + signature + graph proximity composite ranking |
| 🚀 **Runtime Trace Ingestion** | OTLP-style spans augment the static call graph with live data |

---

## Architecture

```mermaid
flowchart TD
    subgraph Ingestion["Ingestion Pipeline"]
        A[Codebase Files] --> B["Tree-sitter AST Chunker"]
        A --> C["Pattern Scanner"]
        A --> CX["Call Extractor + Import Resolver"]
        A --> D2["File Discovery<br/>.gitignore + .cctxignore"]
        B --> D[("SQLite FTS5<br/>Lexical Store")]
        B --> E[("ChromaDB<br/>Vector Store")]
        C --> F[("Graph Store<br/>Hierarchy Call Graph")]
        CX --> F
        F --> FB["GraphStoreFactory"]
        FB --> FN["Neo4j"]
        FB --> FP["AWS Neptune"]
        FB --> FD["DataStax Astra"]
        FB --> FG["GraphRAG Adapter"]
    end

    subgraph Retrieval["Retrieval Pipeline"]
        G[Agent Query] --> H["Parallel Dual Retrieval"]
        D -.-> H
        E -.-> H
        H --> I["RRF Fusion Ranker"]
        I --> J["Graph Expansion"]
        F -.-> J
        J --> K["CrossEncoder Reranker"]
        K --> L["High-Fidelity Context"]
    end

    subgraph Analysis["Graph Intelligence"]
        F --> M1["Dead Code Detection"]
        F --> M2["Call Path Tracing"]
        F --> M3["Architecture Overview"]
        F --> M4["Community Detection"]
        F --> M5["Git Diff Impact"]
    end

    subgraph Wiki["Knowledge Wiki"]
        L --> W1["Auto-sync on index"]
        W1 --> W2[("Markdown Wiki")]
        W2 --> W3["WikiQuery / WikiLint"]
    end

    style Ingestion fill:#0f172a,stroke:#38bdf8,stroke-width:2px,color:#fff
    style Retrieval fill:#0f172a,stroke:#34d399,stroke-width:2px,color:#fff
    style Analysis fill:#0f172a,stroke:#f59e0b,stroke-width:2px,color:#fff
    style Wiki fill:#0f172a,stroke:#a78bfa,stroke-width:2px,color:#fff
```

---

## MCP Tools

CodeContext registers **11 MCP tools** for AI agents:

| Tool | Category | Description |
|------|----------|-------------|
| `CodeContext` | Search | Multi-stage search: lexical + vector + graph expansion + reranking |
| `WikiQuery` | Wiki | Search the knowledge wiki for synthesized answers |
| `WikiLint` | Wiki | Health-check wiki for orphan pages, broken links, stale content |
| `QueryGraph` | Graph | Execute read-only Cypher queries against the knowledge graph |
| `DeadCodeScan` | Intelligence | Detect functions with zero callers (excluding entry points) |
| `TracePath` | Intelligence | BFS call tracing — who calls a function and what it calls (depth 1-5) |
| `GetArchitecture` | Intelligence | Architecture overview: languages, hotspots, entry points, modules |
| `DetectChanges` | Intelligence | Map git diff to affected symbols with blast radius and risk classification |
| `DetectCommunities` | Intelligence | Louvain community detection on the function call graph |
| `LinkRoutes` | Intelligence | Detect HTTP route handlers and create Route/HANDLES/HTTP_CALLS edges |
| `IngestTraces` | Intelligence | Ingest OTLP-style runtime traces to augment the static call graph |

<details>
<summary><strong>Usage Examples</strong></summary>

```bash
# Multi-stage code search
cctx tools search "how does authentication work" --top-k 5

# Trace function call chains
cctx tools trace process_payment --direction outbound --depth 3

# Detect dead code
cctx tools dead-code

# Execute Cypher query
cctx tools query-graph "MATCH (f:Function)-[:CALLS]->(g:Function) RETURN f.name, g.name LIMIT 10"

# Architecture overview
cctx tools architecture
```

</details>

---

## Wiki

CodeContext includes an [LLM Wiki](https://gist.github.com/karpathy/442a6bf555914893e9891c11519de94f) integration compliant with the [Open Knowledge Format (OKF) v0.1](https://github.com/GoogleCloudPlatform/knowledge-catalog/blob/main/okf/SPEC.md). Instead of re-deriving knowledge on every query, the LLM builds and maintains a persistent wiki of interlinked markdown pages.

```
.codecontext/wiki/
  index.md              # OKF-compliant catalog
  log.md                # Update history
  modules/              # Module documentation
  patterns/             # Recurring patterns
  decisions/            # Architecture Decision Records
  concepts/             # Conceptual explanations
```

**Page types:** `overview`, `module`, `pattern`, `decision`, `entity`, `comparison`, `concept`, `source`, `custom`

---

## Installation

### Via pip

```bash
pip install contextcode
```

### Via uv (recommended)

```bash
uv pip install contextcode
```

### From Source

```bash
git clone https://github.com/VardhmanSurana/CodeContext.git
cd CodeContext
uv sync
```

### Prerequisites

| Requirement | Purpose | Required? |
|-------------|---------|-----------|
| Python 3.11+ | Runtime | ✅ Yes |
| CUDA 12.x/13.x | GPU embedding acceleration | ⚡ Recommended |
| Neo4j | Graph store (auto-starts if installed, unique constraints created on connect) | ⚡ Recommended |
| AWS Neptune / DataStax Astra | Alternative managed graph backends | ⬜ Optional |

```bash
# Start Neo4j (optional — CodeContext also auto-starts it when installed)
sudo systemctl start neo4j
export NEO4J_PASSWORD='your-local-password'
```

Configure an alternative backend in `.codecontext.yaml`:

```yaml
storage:
  graph:
    type: neptune        # neo4j | neptune | datastax | graphrag
    uri: wss://your-neptune-endpoint:8182/gremlin
    aws_region: us-east-1
```

---

## Client Integration

Add to your MCP client config:

```json
{
  "mcpServers": {
    "codecontext": {
      "command": "cctx",
      "args": ["mcp"]
    }
  }
}
```

**Supported clients:** Codex, Claude Desktop, Cursor, Windsurf, Hermes, OpenCode, Antigravity

### Codex plugin

This repository includes a multi-client bundle at [`plugins/codecontext`](plugins/codecontext/) for
Codex, Claude Code, Antigravity, and OpenCode. It exposes the CodeContext MCP server plus the
`codecontext` and `wiki-workflow` skills. The bundle's MCP configurations are set for this source
checkout; adjust the repository path when using a different checkout, then index the target
project with `cctx index` before starting an agent.

---

## CLI

| Command | Description |
|---------|-------------|
| `cctx index` | Index the current project |
| `cctx index --rebuild` | Force full rebuild |
| `cctx index -v` | Verbose output |
| `cctx mcp` | Start MCP server |
| `cctx watch` | Watch for file changes + auto-reindex |
| `cctx wiki init` | Initialize wiki directory |
| `cctx wiki ingest` | Ingest a file into the wiki |
| `cctx wiki lint` | Wiki health check |
| `cctx tools search` | Search codebase from CLI |
| `cctx tools query-graph` | Execute Cypher query |
| `cctx tools trace` | Trace function call chains |
| `cctx tools dead-code` | Detect dead code |
| `cctx tools architecture` | Architecture overview |
| `cctx tools detect-changes` | Git diff impact mapping |
| `cctx tools communities` | Community detection |
| `cctx tools link-routes` | Detect HTTP routes |
| `cctx tools ingest-traces` | Ingest runtime traces |
| `cctx export` | Export index for team sharing |
| `cctx import` | Import teammate's index |
| `cctx graph migrate` | Migrate the graph store to a new backend |
| `cctx graph export` | Export graph to Mermaid, D3, or interactive PyVis HTML |
| `cctx graph viz` | Run interactive call-graph visualization web server |
| `cctx graph ingest` | Ingest custom JSON code graphs |

---

## Graph Visualization & Exploration

The `cctx graph` command group turns the indexed call graph into shareable and interactive artifacts.

**Export to multiple formats:**

```bash
# Interactive PyVis HTML (default) — open in a browser to explore
cctx graph export -f html -o graph.html

# Mermaid diagram for docs
cctx graph export -f mermaid -o graph.md

# D3 JSON for custom dashboards
cctx graph export -f d3 -o graph.json
```

**Live visualization server:**

```bash
cctx graph viz --port 8765
# Open http://localhost:8765 and filter by search term or node type
```

**Ingest custom graphs** (e.g. runtime traces from another tool) as JSON:

```json
{
  "nodes": [{ "labels": ["Function"], "properties": { "name": "main", "file_path": "app.py" } }],
  "edges": [{ "type": "CALLS", "source_node_id": "...", "target_node_id": "..." }]
}
```

```bash
cctx graph ingest -f graph.json
```

---

## Contributing

1. Fork this repository
2. Create a feature branch: `git checkout -b feat/my-feature`
3. Make your changes and add tests
4. Run the test suite: `pytest`
5. Submit a Pull Request targeting `feat/codecontext`

Please report bugs and feature requests via [GitHub Issues](https://github.com/VardhmanSurana/CodeContext/issues).

---

## License

[MIT](LICENSE) — Crafted with care by the Advanced Agentic Coding Team.
