{
  "markdown": "# NervaPack\n\n[![PyPI version](https://img.shields.io/pypi/v/nervapack.svg)](https://pypi.org/project/nervapack/)\n[![Python Versions](https://img.shields.io/pypi/pyversions/nervapack.svg)](https://pypi.org/project/nervapack/)\n[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)\n[![Token Reduction](https://img.shields.io/badge/Token_Reduction-91.2%25-brightgreen.svg)](docs/BENCHMARKS.md)\n[![Verified](https://img.shields.io/badge/Performance-Verified-blue.svg)](docs/BENCHMARKS.md)\n[![MCP Registry](https://img.shields.io/badge/MCP_Registry-listed-blue.svg)](https://registry.modelcontextprotocol.io)\n\n<!-- mcp-name: io.github.ramdhavepreetam/nervapack -->\n\n**NervaPack** is a privacy-first, offline knowledge graph for your codebase. It solves two fundamental problems with standard Vector RAG:\n\n- **Token waste** — chunk-based RAG retrieves blobs of text that may only tangentially relate to your query, bloating your context window.\n- **Privacy risk** — sending code to cloud embedding APIs leaks your proprietary logic.\n\nNervaPack runs 100% on your machine. It uses `tree-sitter` to parse your codebase into a deterministic Abstract Syntax Tree graph, then uses a local Ollama model to draw hard semantic edges between your documentation and your code. Queries traverse this graph with a K-Hop BFS, returning a hyper-targeted, token-efficient context window — no cloud required.\n\n---\n\n## Verified Performance\n\n**91.2% Average Token Reduction** — independently verified on real-world codebases.\n\n| Test Type | Tokens (Naive) | Tokens (NervaPack) | Reduction |\n|-----------|----------------|-------------------|-----------|\n| Simple Query | 10,926 | 101 | **99.1%** |\n| Medium Query | 13,092 | 164 | **98.7%** |\n| Complex Query | 3,290 | 1,102 | **66.5%** |\n| **Average** | **52,037** | **2,459** | **91.2%** |\n\n**Cost Savings:** $181–$724 per developer per year (GPT-4o to Claude Sonnet)\n\n📊 **[View Full Benchmarks](docs/BENCHMARKS.md)** · 🧪 **[Messy Code Performance](docs/MESSY_CODE_PERFORMANCE.md)**\n\n> **Code quality impact:** 90–99% reduction on clean code, 50–75% on legacy/messy code. Even poorly structured codebases benefit significantly.\n\n---\n\n## Why NervaPack vs. standard Vector RAG\n\n| | Standard Vector RAG | NervaPack |\n|---|---|---|\n| **Parsing** | Arbitrary text chunks | Deterministic AST nodes (class, function, import) |\n| **Retrieval** | Nearest-neighbour blob | K-Hop BFS on a structural graph |\n| **Doc ↔ Code links** | None | Hard `EXPLAINS` edges drawn by local LLM |\n| **Privacy** | Cloud embeddings | 100% local (ChromaDB + ONNX + optional Ollama) |\n| **Incremental sync** | Re-index everything | Surgical per-file update via GitPython diff |\n| **Token savings** | No measurement | Built-in dashboard shows exact reduction per query |\n| **Graph visibility** | Black box | Interactive HTML visualization of every node and edge |\n| **Duplicate-safe** | Repeated ingest = duplicate data | `upsert` — re-ingest is idempotent |\n| **Agent memory** | None | 17-tool MCP server for cross-session memory |\n\n---\n\n## Prerequisites\n\n- **Python 3.10+**\n- **Git** — your project must be a git repository (`git init` if not)\n\n*(Optional for semantic code-doc binding)* — an LLM provider. Structural graph indexing and basic queries work out-of-the-box with zero configuration and no cloud connection.\n\n| Provider | Setup | Cost | Privacy |\n|----------|-------|------|---------|\n| **Ollama** (default) | `brew install ollama && ollama pull llama3` | Free | 100% local |\n| **Claude API** | `pip install \"nervapack[claude]\"` + `ANTHROPIC_API_KEY` | ~$0.25/1k calls | Cloud |\n| **OpenAI API** | `pip install \"nervapack[openai]\"` + `OPENAI_API_KEY` | ~$0.15/1k calls | Cloud |\n| **MCP (Claude Code)** | Zero config | Included in subscription | Cloud |\n\n---\n\n## Installation\n\n```bash\n# Recommended\npip install nervapack\n\n# With optional features\npip install \"nervapack[mcp]\"          # MCP server for Claude Code / Cursor\npip install \"nervapack[memory]\"       # agent memory MCP server\npip install \"nervapack[metrics]\"      # exact token counts (tiktoken)\npip install \"nervapack[dashboard]\"    # web dashboard (streamlit + plotly)\npip install \"nervapack[claude]\"       # Claude API support\npip install \"nervapack[openai]\"       # OpenAI API support\npip install \"nervapack[all]\"          # everything\n```\n\n> On first run, ChromaDB downloads an ONNX embedding model (~30 MB) to `~/.cache/chroma/`. This is a one-time download.\n\n---\n\n## Quick Start\n\n```bash\ncd your-project/\n\n# 1. Build the knowledge graph (runs locally, no LLM required for basic use)\nnervapack ingest .\n\n# 2. Query for context — get focused results + token savings dashboard\nnervapack query \"How does authentication work?\"\n\n# 3. Add semantic doc-to-code edges (requires an LLM)\nnervapack enrich .\n\n# 4. Visualize the full graph\nnervapack visualize --enhanced --communities\n\n# 5. After changing files, sync incrementally (fast — only changed files)\nnervapack sync .\n\n# 6. If you ingested wrong data or need a fresh start\nnervapack clean --all\nnervapack ingest .\n\n# 7. Check system health\nnervapack doctor\n```\n\n---\n\n## Command Reference\n\n### `nervapack ingest [PATH]` — Build the graph\n\nScans `PATH` (default: `.`) and builds the full knowledge graph.\n\n**What happens:**\n1. Walks the directory tree with tree-sitter, skipping `dist/`, `build/`, `node_modules/`, `venv/`, `site/`, `.tox/`, and dozens of other build directories automatically.\n2. Parses source files into exact AST nodes: classes, functions, imports.\n3. Chunks all `.md` files by header hierarchy.\n4. Embeds every entity into a local ChromaDB vector store (ONNX by default, Ollama optional).\n5. Optionally binds doc chunks to code nodes via an LLM, adding `EXPLAINS` edges.\n6. Saves the graph once to `.nervapack/graph.graphml`.\n\n**Re-ingesting is safe** — `upsert` is used throughout, so running `ingest` twice does not duplicate data.\n\n```bash\nnervapack ingest .                           # auto-detect LLM\nnervapack ingest . --llm ollama              # force Ollama\nnervapack ingest . --llm claude              # use Claude API\nnervapack ingest . --llm openai --model gpt-4o-mini\nnervapack ingest . --embeddings ollama       # use Ollama for embeddings too\n```\n\n**Supported languages (bundled):** Python, JavaScript, JSX, TypeScript, TSX\n\n**Additional languages:**\n```bash\npip install \"nervapack[go]\"            # Go\npip install \"nervapack[rust]\"          # Rust\npip install \"nervapack[java]\"          # Java\npip install \"nervapack[c]\"             # C / C headers\npip install \"nervapack[cpp]\"           # C++\npip install \"nervapack[ruby]\"          # Ruby\npip install \"nervapack[csharp]\"        # C#\npip install \"nervapack[all-languages]\" # all of the above\n```\n\n**Exclude directories** — create `.nervapackignore` in your project root (gitignore syntax):\n```\ndist/\nbuild/\nsite/\ngenerated/\n*.egg-info/\n```\n\n---\n\n### `nervapack query PROMPT` — Query the graph\n\nRetrieves focused context for a natural-language prompt and prints a token savings dashboard.\n\n**What happens:**\n1. Intent detection — \"what breaks if I change X\" routes to impact analysis (reverse BFS); exact symbol names bypass vector search.\n2. ChromaDB returns the top-3 most semantically similar nodes.\n3. Those nodes seed a K-Hop BFS through the NetworkX graph (default: 1 hop, both directions).\n4. Adjacent nodes — including any markdown docs via `EXPLAINS` edges and memory notes via `TOUCHES` edges — are collected.\n5. A focused Markdown context block is printed, ready to paste into an LLM prompt.\n6. Token efficiency panel shows savings vs. naive \"dump the whole file\" RAG.\n\n```bash\nnervapack query \"How does authentication work?\"\nnervapack query \"What calls VectorStore?\"\nnervapack query \"what breaks if I change GraphBuilder\"  # impact analysis\n```\n\n**Example output:**\n```\nQuery: \"How does authentication work?\"\n\nQuery Router: Intent: semantic, Direction: both\nVector Search: Found 3 seed nodes\n\nRetrieved Context:\n──────────────────────────────────────────────────────────\n# NervaPack Context Retrieval\n## File: `src/auth/middleware.py`\n### CLASS: AuthMiddleware (L15-L42)\n...\n──────────────────────────────────────────────────────────\n\n╭──────────────  NervaPack Token Efficiency  ──────────────╮\n│  Strategy              Tokens   Reduction                 │\n│  Naive RAG (3 files)   12,840   100% (base)              │\n│  NervaPack              1,180     9.2%                    │\n│ ─────────────────────────────────────────────────────────│\n│  Tokens saved: 11,660   Reduction: 90.8%                 │\n│  Cost saved (GPT-4o $2.50/1M): $0.0292 per query         │\n╰───────────────────────────────────────────────────────────╯\n```\n\n---\n\n### `nervapack sync [PATH]` — Incremental update\n\nUpdates only the files that changed since the last ingest. Uses `GitPython` to diff the working tree.\n\n```bash\nnervapack sync .\n```\n\nA full ingest on a large project can take minutes. `sync` turns that into a 2–5 second surgical update per file. Re-parses changed files, batch-upserts new vectors, and saves the graph once at the end.\n\n---\n\n### `nervapack clean [OPTIONS]` — Remove ingested data\n\nWipe graph data and start fresh. Use this when you have duplicate vectors, ingested the wrong directory, or need to reduce disk usage.\n\n```bash\nnervapack clean --vectors          # wipe ChromaDB only (chroma_db/)\nnervapack clean --graph            # delete graph.graphml only\nnervapack clean --history          # clear query + graph history logs\nnervapack clean --all              # everything above (keeps memory.db)\nnervapack clean --all --yes        # skip confirmation (CI / scripts)\n```\n\n**Never deleted by `clean`:** `memory.db` — your agent memory is always safe.\n\n**Typical workflow after a bad ingest:**\n```bash\nnervapack clean --all\nnervapack ingest .\n```\n\n---\n\n### `nervapack enrich [PATH]` — Add semantic edges\n\nRuns LLM doc-to-code binding on an already-ingested graph. Use this if you:\n- Ran `ingest` without an LLM and want to add `EXPLAINS` edges now.\n- Added new documentation and want to bind it without a full re-ingest.\n\n```bash\nnervapack enrich .                           # auto-detect LLM\nnervapack enrich . --llm ollama --model llama3\nnervapack enrich . --llm claude              # shows cost estimate before proceeding\n```\n\n---\n\n### `nervapack status [--detailed]` — Graph health\n\n```bash\nnervapack status            # node/edge counts + unsynced files\nnervapack status --detailed # full analytics: health score, language distribution, coverage\n```\n\nHealth score (0–100) factors in documentation coverage, node connectivity, graph density, and edge diversity. A structural-only graph typically scores 30–40; after `enrich` it rises to 70–90.\n\n---\n\n### `nervapack visualize [OPTIONS]` — Interactive HTML graph\n\n```bash\nnervapack visualize                           # basic visualization\nnervapack visualize --enhanced                # + real-time search + path finder\nnervapack visualize --enhanced --communities  # + community detection (Louvain)\nnervapack visualize --output ~/my-graph.html  # custom output path\nnervapack visualize --no-browser              # generate without opening\n```\n\nProduces a standalone HTML file with no external dependencies — drag, zoom, search, find shortest paths between nodes.\n\n---\n\n### `nervapack explore TARGET [--hops N]` — Focused subgraph\n\nExtract and visualize the N-hop neighbourhood of a specific file, class, or function.\n\n```bash\nnervapack explore GraphBuilder --hops 2\nnervapack explore src/auth/middleware.py --hops 1\nnervapack explore \"function:parse\"\n```\n\n---\n\n### `nervapack dependencies [FILE]` — Import dependency analysis\n\nAnalyze file-level import chains, detect circular dependencies, and visualize the dependency graph.\n\n```bash\nnervapack dependencies                        # full project analysis\nnervapack dependencies src/graph/builder.py   # single file\nnervapack dependencies --no-cycles            # skip cycle detection\n```\n\n---\n\n### `nervapack hotspots [OPTIONS]` — Change frequency analysis\n\nShow which files change most often in git history — prime targets for documentation and review.\n\n```bash\nnervapack hotspots                            # top 20 by commit count\nnervapack hotspots --since \"6 months ago\"    # recent history only\nnervapack hotspots --ext .py --churn         # Python files, sort by lines changed\n```\n\n---\n\n### `nervapack history [OPTIONS]` — Query history\n\n```bash\nnervapack history              # last 10 queries with token savings\nnervapack history --limit 50   # last 50\nnervapack history --stats      # aggregate: total savings, cost avoided, top topics\nnervapack history --clear      # delete history\n```\n\n---\n\n### `nervapack serve [--port N]` — Web dashboard\n\n```bash\nnervapack serve                # http://localhost:8501\nnervapack serve --port 8080    # custom port\n```\n\nRequires `nervapack[dashboard]`. Shows graph overview, language distribution, analytics, query history trends, and an interactive graph explorer.\n\n---\n\n### `nervapack doctor` — Environment check\n\n```bash\nnervapack doctor\n```\n\nVerifies Python version, tree-sitter grammars, embedding backend, Ollama connectivity, and MCP config. Run this after installation or when troubleshooting.\n\n---\n\n## Storage Layout\n\nEverything lives in `.nervapack/` inside your project root:\n\n```\n.nervapack/\n├── graph.graphml          # NetworkX DiGraph (AST + EXPLAINS edges)\n├── chroma_db/             # ChromaDB vector store (ONNX embeddings)\n├── memory.db              # Agent memory (SQLite + FTS5, bi-temporal)\n├── query_history.jsonl    # Per-query token savings log\n└── graph_history.jsonl    # Ingest/sync event log\n```\n\nAdd `.nervapack/` to `.gitignore` to keep it out of version control.\n\n**Disk usage guide:**\n- `chroma_db/` — typically 10–100 MB depending on project size. Run `nervapack clean --vectors && nervapack ingest .` if it grows unexpectedly.\n- `graph.graphml` — typically 0.5–5 MB.\n- `memory.db` — grows with agent usage; rarely exceeds a few MB.\n\n---\n\n## MCP Integration (Claude Code, Cursor, Windsurf)\n\nNervaPack ships two MCP servers in the same package. Drop this `.mcp.json` in your project root:\n\n```json\n{\n  \"mcpServers\": {\n    \"nervapack\": {\n      \"command\": \"nervapack-mcp\",\n      \"description\": \"NervaPack knowledge graph (v0.6.1) — query, graph_status, explore, impact\"\n    },\n    \"nervapack-memory\": {\n      \"command\": \"nervapack-memory-mcp\",\n      \"description\": \"NervaPack agent memory (v0.6.1) — store, recall, and reason over facts across sessions\"\n    }\n  }\n}\n```\n\n### Knowledge Graph MCP tools (`nervapack-mcp`)\n\n| Tool | What it does |\n|------|-------------|\n| `query` | Vector search → K-Hop BFS → focused Markdown context + token savings |\n| `graph_status` | Node/edge counts, language breakdown, unsynced file warnings |\n| `explore` | Browse all indexed classes, functions, imports, markdown docs |\n| `impact` | Reverse dependency analysis — find what depends on a given entity |\n\n### Agent Memory MCP tools (`nervapack-memory-mcp`) — 17 tools\n\n| Tool | Purpose |\n|------|---------|\n| `memory_start_session` | Open a named session |\n| `memory_store` | Persist a fact, decision, outcome, procedure, preference, or action |\n| `memory_recall` | FTS5 search → graph expansion → scored, budget-capped recall |\n| `memory_about` | Entity dossier: all facts/decisions linked to one entity |\n| `memory_why` | Explain a decision: rationale, rejected alternatives, outcomes |\n| `memory_timeline` | Chronological trace including superseded versions |\n| `memory_end_session` | Close session with an outcome summary |\n| `memory_forget` | Tombstone or hard-purge nodes |\n| `memory_verify` | Confirm (confidence +0.1) or refute (close + confidence ×0.5) |\n| `memory_stats` | Node counts, DB size, top entities, all namespaces |\n| `memory_list_sessions` | List all sessions with node counts |\n| `memory_clear_session` | Delete a session and all its nodes |\n| `memory_for_code` | Memories that TOUCH a source file or specific line |\n| `memory_to_code` | Code locations a memory node TOUCHES |\n| `memory_import` | Bulk-seed memory from a JSON array |\n| `memory_switch_namespace` | Switch the active namespace |\n| `memory_verify_staleness` | Flag memories whose source file changed since stored |\n\n### CLAUDE.md template\n\nAdd to your `CLAUDE.md` to wire NervaPack into every Claude Code session:\n\n```markdown\n## Always use NervaPack MCP tools\n\nAt the start of every session:\n1. Call `memory_start_session(\"<task name>\")` to open a named session.\n2. Call `memory_recall(\"project context\", budget_tokens=400)` to load prior decisions.\n3. Call `query(\"<topic>\")` before answering any question about how the code works.\n\nDuring the session — call `memory_store` for:\n- Any decision made (kind=\"decision\" with rationale and alternatives_rejected)\n- Any fact discovered about system behaviour (kind=\"fact\")\n- Any procedure or convention established (kind=\"procedure\")\n\nAt session end — call `memory_end_session(\"<one-paragraph summary>\")`.\n```\n\n---\n\n## Architecture\n\n```\nnervapack ingest .\n       │\n       ├─ ASTParser (tree-sitter)               16 extensions, 10 languages\n       │    └─ ParsedEntity[]: class, function, import\n       │\n       ├─ GraphBuilder (NetworkX DiGraph)\n       │    ├─ Nodes: file, class, function, import, markdown\n       │    ├─ Edges: DEFINES (AST, confidence=1.0)\n       │    ├─ Edges: REFERENCES (heuristic name overlap, confidence=0.7)\n       │    └─ Edges: EXPLAINS (LLM or keyword binding, confidence=0.5–0.9)\n       │\n       ├─ VectorStore (ChromaDB)\n       │    ├─ Embedding: ONNX (default) or Ollama\n       │    └─ upsert — re-ingest is idempotent\n       │\n       └─ GraphHistory  — snapshot recorded after each ingest/sync\n\nnervapack query \"...\"\n       │\n       ├─ Intent detection (impact / exact / semantic)\n       ├─ VectorStore.search() → seed node IDs\n       ├─ GraphRetriever.retrieve_context()\n       │    └─ deque BFS, direction: forward / reverse / both\n       ├─ MemoryStore.get_touches_for_file() → memory context injection\n       └─ TokenMeter → savings vs. naive RAG\n\nnervapack clean --all\n       └─ Deletes chroma_db/, graph.graphml, history logs\n          Never touches memory.db\n```\n\n**Key source modules:**\n\n| Module | Responsibility |\n|--------|---------------|\n| `nervapack.parser.ast_parser` | tree-sitter parsing → `ParsedEntity`; shared singleton parser instance |\n| `nervapack.parser.md_chunker` | Markdown → header-delimited chunks; prunes build dirs from os.walk |\n| `nervapack.graph.builder` | NetworkX DiGraph; O(1) file-index for sync; compiled regex for REFERENCES |\n| `nervapack.graph.vector_store` | ChromaDB upsert (idempotent); pluggable embedding function |\n| `nervapack.graph.retrieval` | K-Hop BFS with `deque` (O(n) not O(n²)) |\n| `nervapack.graph.token_meter` | tiktoken singleton; token savings panel |\n| `nervapack.graph.query_history` | Tail-read JSONL — O(limit) not O(total) |\n| `nervapack.graph.analytics` | Bulk `graph.degree()` — single call not per-node loop |\n| `nervapack.llm.base` | `bind_docs_to_ast` with keyword pre-filter (top-12 candidates) |\n| `nervapack.llm.providers.ollama` | `ollama.list()` cached 60 s |\n| `nervapack.memory.store` | SQLite + FTS5; bi-temporal; `batch_neighbors` for O(1) hop expansion |\n| `nervapack.memory.recall` | Batched hop expansion; audit trail on recall |\n| `nervapack.mcp_server` | FastMCP — `query`, `graph_status`, `explore`, `impact` |\n| `nervapack.memory.mcp_server` | FastMCP — 17 memory tools |\n\n---\n\n## nervapack.memory — Agent Memory\n\nStop re-pasting project context into every new chat.\n\n```python\n# Store a decision\nmemory_store(\n    \"Chose JWT over session cookies for auth_service — stateless horizontal scaling\",\n    kind=\"decision\",\n    entities=[\"auth_service\"],\n    confidence=0.9,\n    rationale=\"Stateless tokens enable horizontal scaling without shared session store.\",\n    alternatives_rejected=[\"server-side sessions\", \"PASETO\"],\n)\n\n# Recall in any future session\nmemory_recall(\"project context\", budget_tokens=400)\n```\n\n```\n## Memory recall: \"project context\" (6 items · 171/400 tokens)\n\n### Decisions\n- [d_0019f2] 2026-06-05 · conf 0.90 — Chose JWT for auth_service\n\n### Facts\n- [f_0019f3] 2026-06-05 · conf 1.00 — auth_service issues 15-min access tokens\n\n### Procedures\n- [p_0019f5] 2026-06-12 · conf 1.00 — Deploy: GitHub Actions → staging → prod manual\n```\n\n**Token efficiency:**\n\n| Approach | Tokens per session | After 20 sessions |\n|----------|--------------------|-------------------|\n| Manual paste (architecture doc) | ~2,400 | ~48,000 |\n| `memory_recall` | **~171** | **~3,420** |\n| **Savings** | | **93% fewer tokens** |\n\n**CLI:**\n```bash\nnervapack-memory init                          # create schema\nnervapack-memory stats                         # counts + top entities\nnervapack-memory search \"JWT auth\"             # FTS search\nnervapack-memory timeline \"auth service\"       # chronological trace\nnervapack-memory audit d_0019f2abc             # access audit trail\nnervapack-memory rebind old/path.py new/path.py  # update file links after rename\nnervapack-memory export --out dump.json        # JSON dump\n```\n\n**Data model:** 8 node kinds, 7 edge kinds, bi-temporal (`valid_from`/`valid_until`), never hard-deletes by default.\n\n---\n\n## Privacy\n\nNervaPack is 100% offline by default:\n\n- Embeddings use ChromaDB's built-in ONNX model (runs on CPU, no cloud).\n- LLM calls (when using Ollama) go to `localhost:11434` only.\n- All graph and vector data lives in `.nervapack/` inside your project.\n- No telemetry, no analytics, no network calls at runtime.\n\nOnly if you explicitly pass `--llm claude` or `--llm openai` does any code leave your machine.\n\n---\n\n## Contributing\n\n1. Fork the repo and create a branch.\n2. Run tests: `python3 -m pytest tests/memory/ -q`\n3. Run docs check: `python3 -m mkdocs build --strict`\n4. Open a pull request against `master`.\n\nBug reports and feature requests: [issue tracker](https://github.com/ramdhavepreetam/NervaPack/issues).\n\n---\n\n## License\n\nMIT — see [LICENSE](LICENSE).\n",
  "bytes": 22016,
  "sha": "36b60c6afa365173500296634ad2b8430b237bb282923e27715bee97504e73f7",
  "repo_slug": "ramdhavepreetam/nervapack",
  "fonte": "repo",
  "truncated": false,
  "api": "https://agentalog.com/api/listings/mcp_io_github_ramdhavepreetam_nervapack_3cdb0ecc/readme"
}