knowledge-rag 4.8.5 → 4.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (4) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +739 -716
  3. package/bin/cli.js +254 -254
  4. package/package.json +42 -42
package/README.md CHANGED
@@ -1,716 +1,739 @@
1
- <!--
2
- knowledge-rag — Local RAG server for Claude Code, Cursor, Windsurf and other MCP clients.
3
- SEO keywords: local rag, mcp server, self-hosted rag, hybrid search, cross-encoder reranking, claude code rag, cursor rag, python rag, chromadb rag, fastembed rag, air-gapped rag, gdpr rag, retrieval augmented generation, model context protocol server, zero cloud rag.
4
-
5
- Structured data (schema.org SoftwareApplication) — indexed by search engines, invisible on GitHub render:
6
- {
7
- "@context": "https://schema.org",
8
- "@type": "SoftwareApplication",
9
- "name": "knowledge-rag",
10
- "applicationCategory": "DeveloperApplication",
11
- "operatingSystem": "Windows, Linux, macOS",
12
- "description": "Local-first RAG server for AI agents. Hybrid search, MCP-native, zero cloud, enterprise-grade plumbing (bearer auth, Prometheus metrics, rate limiting, health probes, structured JSON logging, zero-downtime reindex).",
13
- "offers": { "@type": "Offer", "price": "0", "priceCurrency": "USD" },
14
- "license": "https://opensource.org/licenses/MIT",
15
- "downloadUrl": "https://pypi.org/project/knowledge-rag/",
16
- "codeRepository": "https://github.com/lyonzin/knowledge-rag",
17
- "programmingLanguage": "Python",
18
- "runtimePlatform": "Python 3.11+"
19
- }
20
- -->
21
-
22
- # knowledge-rag
23
-
24
- <div align="center">
25
-
26
- [![PyPI](https://img.shields.io/pypi/v/knowledge-rag)](https://pypi.org/project/knowledge-rag/)
27
- [![NPM](https://img.shields.io/npm/v/knowledge-rag)](https://www.npmjs.com/package/knowledge-rag)
28
- [![PyPI Downloads](https://static.pepy.tech/personalized-badge/knowledge-rag?period=total&units=INTERNATIONAL_SYSTEM&left_color=BLACK&right_color=GREEN&left_text=downloads)](https://pepy.tech/projects/knowledge-rag)
29
- ![Python](https://img.shields.io/badge/python-3.11%2B-green.svg)
30
- ![License](https://img.shields.io/badge/license-MIT-yellow.svg)
31
- ![Platform](https://img.shields.io/badge/platform-Windows%20%7C%20Linux%20%7C%20macOS-lightgrey.svg)
32
- ![GPU](https://img.shields.io/badge/GPU-NVIDIA%20CUDA-76B900.svg?logo=nvidia)
33
- [![CI](https://github.com/lyonzin/knowledge-rag/actions/workflows/ci.yml/badge.svg)](https://github.com/lyonzin/knowledge-rag/actions/workflows/ci.yml)
34
- [![CodeQL](https://github.com/lyonzin/knowledge-rag/actions/workflows/security.yml/badge.svg)](https://github.com/lyonzin/knowledge-rag/actions/workflows/security.yml)
35
- [![Quality Gate](https://github.com/lyonzin/knowledge-rag/actions/workflows/quality-gate.yml/badge.svg)](https://github.com/lyonzin/knowledge-rag/actions/workflows/quality-gate.yml)
36
- [![Glama Score](https://glama.ai/mcp/servers/lyonzin/knowledge-rag/badges/score.svg)](https://glama.ai/mcp/servers/lyonzin/knowledge-rag)
37
- [![OpenSSF Best Practices](https://bestpractices.coreinfrastructure.org/projects/13864/badge)](https://bestpractices.coreinfrastructure.org/projects/13864)
38
-
39
- ### The MCP-first local RAG server for Claude Code, Cursor, and every AI agent.
40
-
41
- **Hybrid search · Cross-encoder reranking · 20 file formats · 100% local · Zero cloud · Enterprise-grade plumbing built-in.**
42
-
43
- ```bash
44
- pip install knowledge-rag → restart Claude Code → search_knowledge("your query")
45
- ```
46
-
47
- [Quick Start](#quick-start-3-minutes-from-zero-to-your-first-query) ·
48
- [Why knowledge-rag](#why-knowledge-rag) ·
49
- [Compare](#how-knowledge-rag-compares-to-other-rag-frameworks) ·
50
- [Enterprise Features](#enterprise-features-built-in-zero-configuration) ·
51
- [Docs](#documentation)
52
-
53
- </div>
54
-
55
- ---
56
-
57
- ## ⭐ Star History
58
-
59
- <div align="center">
60
-
61
- <a href="https://www.star-history.com/?repos=lyonzin%2Fknowledge-rag&type=date&legend=top-left">
62
- <img alt="knowledge-rag star history chart — GitHub star growth over time" src="./docs/star-history.svg" width="720" />
63
- </a>
64
-
65
- <sub>Chart updated daily by <a href="./.github/workflows/update-star-history.yml">GitHub Action</a></sub>
66
-
67
- </div>
68
-
69
- ---
70
-
71
- ## 🎯 Why knowledge-rag
72
-
73
- Most RAG frameworks fall into one of three traps: (1) they require you to ship your data to a cloud API, (2) they hand you 300 building blocks and 0 opinionated defaults, or (3) they bundle RAG as a 5% feature of a much bigger platform you didn't ask for.
74
-
75
- **knowledge-rag does one thing well:** it is the MCP-native local RAG server that Claude Code, Cursor, Windsurf, VS Code, Cline, Gemini CLI and Zed can search out of the box — with enterprise plumbing (bearer auth, Prometheus metrics, rate limiting, health probes, structured JSON logging, zero-downtime reindex) that no other RAG-focused OSS ships built-in.
76
-
77
- <table>
78
- <tr>
79
- <td width="50%" valign="top">
80
-
81
- ### 🔒 100% local, 0% cloud
82
- Your files never leave the machine. No vendor lock-in, no data-residency headache, no forced cloud dependency. **LGPD / GDPR / HIPAA compliant by architecture** — because there is nothing to comply about when nothing leaves.
83
-
84
- </td>
85
- <td width="50%" valign="top">
86
-
87
- ### 🚀 Zero-friction setup
88
- `pip install knowledge-rag` → restart your MCP client → done. **No Docker mandatory. No Ollama required. No separate embedding server.** Everything runs in-process via FastEmbed ONNX. **Works offline** after the first model download.
89
-
90
- </td>
91
- </tr>
92
- <tr>
93
- <td width="50%" valign="top">
94
-
95
- ### 🛡️ Production-grade OSS
96
- 7-pillar quality gate on every PR (**35+ automated checks**), 9-cell OS×Python CI matrix (Linux + Windows + macOS × 3.11/3.12/3.13), nightly chaos + 50K-iteration soak + mutation testing. **700+ tests. 0 known regressions.**
97
-
98
- </td>
99
- <td width="50%" valign="top">
100
-
101
- ### 💰 Zero ongoing cost
102
- No token bills. No SaaS tier. No paid features hidden behind a wall. **MIT license, forever.** Runs on the laptop you already have — GPU optional, CPU works fine with FastEmbed ONNX.
103
-
104
- </td>
105
- </tr>
106
- </table>
107
-
108
- ---
109
-
110
- ## 📊 How knowledge-rag compares to other RAG frameworks
111
-
112
- We audited **16 popular RAG frameworks and platforms** (LlamaIndex, LangChain, ChromaDB, Weaviate, Qdrant, RAGFlow, LightRAG, DSPy, GraphRAG, Haystack, RAG-Anything, kotaemon, txtai, llmware, Dify, open-webui, FastGPT) so you can pick honestly.
113
-
114
- **Legend:** ✅ built-in · 🟡 plugin / paid tier / partial · ❌ not available · ⚠️ license or default concern
115
-
116
- | Dimension | 🎯 **knowledge-rag** | LlamaIndex | LangChain | Haystack | RAGFlow | txtai | open-webui | Dify | Qdrant |
117
- |---|:---:|:---:|:---:|:---:|:---:|:---:|:---:|:---:|:---:|
118
- | **100% local, zero cloud** | ✅ | 🟡 | ✅ | 🟡 | 🟡 | ✅ | ✅ | 🟡 | 🟡 |
119
- | **MCP native (Claude/Cursor)** | ✅ 13 tools | 🟡 pkg | 🟡 adapter | 🟡 wrapper | 🟡 add-on | ✅ | ✅ consumer | ✅ | ❌ |
120
- | **Hybrid BM25 + semantic** | ✅ 128× faster | 🟡 | 🟡 | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
121
- | **Cross-encoder rerank** | ✅ builtin | ❌ | 🟡 | ✅ | ✅ fused | ❌ | ✅ | 🟡 | 🟡 |
122
- | **Bearer auth builtin** | ✅ | ❌ | ❌ | ❌ core | ❌ | 🟡 | ✅ RBAC | ✅ OAuth2 | ✅ |
123
- | **Prometheus `/metrics`** | ✅ | ❌ | ❌ | ❌ core | ❌ | ❌ | ✅ OTel | ❌ | ✅ |
124
- | **Rate limiting** | ✅ sliding-window | ❌ | ❌ | ❌ | ❌ | ❌ | ✅ | ✅ | ✅ |
125
- | **Health probes** (`/health`) | ✅ | ❌ | ❌ | ❌ | ❌ | ❌ | 🟡 | 🟡 | ✅ |
126
- | **Structured JSON logging** | ✅ opt-in | ❌ | ❌ | ❌ | ❌ | ❌ | ✅ OTel | 🟡 | ✅ |
127
- | **Zero-downtime reindex** | ✅ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ✅ |
128
- | **Async background reindex** | ✅ + polling | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | 🟡 |
129
- | **GPU CUDA optional** | ✅ 12 auto | ❌ | 🟡 | ✅ | ✅ | ✅ | ✅ | 🟡 | 🟡 |
130
- | **File formats builtin** | ✅ **20** | 0 (LlamaParse=$) | 50+ plugins | ✅ **36+** | 8+ | ? | ? | ~10 | ❌ |
131
- | **Setup < 5 min POC** | ✅ pip 1-liner | ✅ | ✅ | ✅ | ❌ 16GB RAM | ✅ | ✅ docker | ✅ docker | ✅ |
132
- | **Nightly chaos + soak + mutation** | ✅ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ |
133
- | **License** | ✅ MIT | MIT | MIT | Apache-2.0 | Apache-2.0 | Apache-2.0 | ⚠️ preserving | ⚠️ restrictive | Apache-2.0 |
134
-
135
- > **The 5 dimensions where knowledge-rag is unique:** health probes + JSON logging + Prometheus + rate limit + bearer auth **simultaneously built-in on an OSS RAG-focused MCP server**. Zero-downtime reindex + async background reindex + nightly chaos/soak/mutation are documented on nobody else's README.
136
-
137
- ---
138
-
139
- ## 🚀 Quick Start (3 minutes, from zero to your first query)
140
-
141
- Pick your integration path — knowledge-rag ships the same server through every channel.
142
-
143
- ### Path 1 — Claude Code, Cursor, Windsurf, Cline, VS Code, Gemini CLI, Zed (MCP)
144
-
145
- ```bash
146
- pip install knowledge-rag
147
- knowledge-rag init # scaffolds config.yaml + documents/
148
- ```
149
-
150
- Drop your PDFs, markdown, code files into `documents/`. Restart your MCP client. Ask it:
151
-
152
- ```
153
- search_knowledge("your query")
154
- ```
155
-
156
- That's it. First query loads the ONNX embedding model (~200MB, one-off download). Subsequent queries are cached and hit sub-second latency.
157
-
158
- ### Path 2 — HTTP / SSE server (multi-user, air-gapped, load-balanced)
159
-
160
- ```yaml
161
- # config.yaml
162
- server:
163
- transport: "sse" # or "streamable-http"
164
- host: "0.0.0.0"
165
- port: 8179
166
- auth:
167
- bearer_token: "your-secret-token"
168
- rate_limit:
169
- enabled: true
170
- requests_per_minute: 60
171
- metrics:
172
- enabled: true
173
- port: 9179
174
- logging:
175
- format: "json" # ELK / Loki / Datadog / CloudWatch ready
176
- ```
177
-
178
- ```bash
179
- knowledge-rag --transport sse
180
- ```
181
-
182
- - Health probe: `curl http://your-host:8179/health` → 200 + JSON payload
183
- - Prometheus scrape: `http://your-host:9179/metrics`
184
- - MCP dispatcher: authenticated via `Authorization: Bearer your-secret-token`
185
-
186
- ### Path 3 — Docker (models pre-downloaded, air-gapped ready)
187
-
188
- ```bash
189
- docker pull ghcr.io/lyonzin/knowledge-rag:latest
190
- docker run -v $(pwd)/documents:/app/documents -p 8179:8179 ghcr.io/lyonzin/knowledge-rag:latest
191
- ```
192
-
193
- **Full installation guide with all 5 methods, 8 MCP client configurations, and GPU setup:** [docs/INSTALLATION.md →](docs/INSTALLATION.md)
194
-
195
- ---
196
-
197
- ## 🤖 Ready-to-use skills for AI agents
198
-
199
- Installing knowledge-rag gives your agent 13 MCP tools. It does not tell the agent **when** to use them. That is what the [`skills/`](skills/) folder solves — drop-in behavioural skills for Claude Code, Cursor, Windsurf, Cline, Zed, VS Code Copilot that turn "AI with access to RAG" into "AI that actually uses RAG first".
200
-
201
- **10 skills, MIT licensed, organized by kind:**
202
-
203
- | # | Skill | What it does |
204
- |---|---|---|
205
- | 1 | [`rag-check-first`](skills/foundation/rag-check-first/SKILL.md) | Search the corpus **before** answering any technical claim |
206
- | 2 | [`rag-cite-sources`](skills/foundation/rag-cite-sources/SKILL.md) | Every claim ships with `path:line` citations |
207
- | 3 | [`rag-onboard-context`](skills/foundation/rag-onboard-context/SKILL.md) | First interaction of a session probes what is indexed |
208
- | 4 | [`rag-deep-dive`](skills/workflow/rag-deep-dive/SKILL.md) | 3-step drill: `search` → `fetch` → `find similar` |
209
- | 5 | [`rag-web-fallback`](skills/workflow/rag-web-fallback/SKILL.md) | Only hit the web when local RAG comes back empty |
210
- | 6 | [`rag-troubleshoot`](skills/workflow/rag-troubleshoot/SKILL.md) | Bug / error → RAG first for prior fixes |
211
- | 7 | [`rag-code-review`](skills/workflow/rag-code-review/SKILL.md) | Review consults ADRs / patterns before commenting |
212
- | 8 | [`rag-index-decisions`](skills/maintenance/rag-index-decisions/SKILL.md) | After a decision, index it back — close the feedback loop |
213
- | 9 | [`rag-security-first`](skills/domain/rag-security-first/SKILL.md) | Security tasks: MITRE / CVE / runbook first |
214
- | 10 | [`rag-evaluate-quality`](skills/maintenance/rag-evaluate-quality/SKILL.md) | Weekly checkup — MRR@5 · Recall@5 · Precision@5 |
215
-
216
- **Install — pick the shortest path for your machine:**
217
-
218
- ```bash
219
- # Option 1 — Via skills.sh (needs Node — one command, zero clone)
220
- npx skills add lyonzin/knowledge-rag
221
-
222
- # Option 2 — Via our install.sh (no Node needed; works on Linux/macOS/WSL/Git Bash)
223
- curl -fsSL https://raw.githubusercontent.com/lyonzin/knowledge-rag/master/skills/install.sh | bash
224
- ```
225
-
226
- Both restart-Claude-Code and you are done. Option 2 supports `--project`, `--only rag-check-first,rag-cite-sources`, `--dry-run`, `--help`.
227
-
228
- For Cursor, Windsurf, Cline and full manual instructions → [skills/README.md](skills/README.md) · Full catalog with skill chains → [skills/CATALOG.md](skills/CATALOG.md)
229
-
230
- ---
231
-
232
- ## 🛠️ The 13 MCP tools your agent gets
233
-
234
- Once installed, your AI agent gets these 13 tools automatically:
235
-
236
- | Tool | Purpose |
237
- |---|---|
238
- | `search_knowledge` | Hybrid semantic + BM25 with cross-encoder rerank |
239
- | `get_document` | Retrieve full content of one document |
240
- | `search_similar` | Find documents similar to a reference |
241
- | `evaluate_retrieval` | Measure MRR@5 · Recall@5 · Precision@5 |
242
- | `add_document` | Index a new document via MCP |
243
- | `update_document` | Re-index a changed document |
244
- | `remove_document` | Drop a document + all its chunks |
245
- | `add_from_url` | Fetch, sanitize, and index a URL |
246
- | `list_documents` | Enumerate indexed documents |
247
- | `list_categories` | Auto-tagged by folder path |
248
- | `get_index_stats` | Corpus size, cache hit rate, embedding dim |
249
- | `reindex_documents` | Smart incremental OR nuclear rebuild |
250
- | `get_reindex_status` | Live progress polling (async reindex) |
251
-
252
- **Full API reference with parameter details, return schemas, examples:** [docs/API.md →](docs/API.md)
253
-
254
- ---
255
-
256
- ## 🏢 Enterprise Features (built-in, zero configuration)
257
-
258
- Every RAG framework claims "production-ready." Here is what knowledge-rag ships **in the OSS core, verified by regression tests, that competitors either paywall, plugin-ify, or simply don't have.**
259
-
260
- <table>
261
- <tr>
262
- <td valign="top" width="50%">
263
-
264
- ### Security
265
-
266
- - **Bearer token auth** on SSE / HTTP transports — constant-time comparison (`hmac.compare_digest`), RFC 6750 challenge, 401 fenced with `WWW-Authenticate` header
267
- - **Path traversal + symlink escape defenses** — `validate_path_within` guarding 6 CRUD tools (CWE-22, CWE-59)
268
- - **Prompt injection 3-layer defense** — sentinel neutralization + provenance fence + `external_source` flag (OWASP LLM01:2025)
269
- - **OpenSSF Best Practices badge** verified · **CodeQL** weekly scan · **Bandit + Semgrep + Gitleaks + pip-audit** on every PR
270
- - **PyPI Trusted Publishing** via OIDC (zero long-lived tokens in CI)
271
-
272
- </td>
273
- <td valign="top" width="50%">
274
-
275
- ### Observability
276
-
277
- - **Prometheus `/metrics` endpoint** — custom histogram buckets tuned for RAG (p95 ≤ 10ms fast-path targets), 7 canonical metrics via `@instrument` decorator on all 13 tools
278
- - **Rate limiting** — thread-safe sliding-window counter, per-client RPM + burst, zero overhead when disabled
279
- - **Health probes** — `GET /health` and `/healthz` returning `{status, version, uptime_seconds, cache}` in front of the auth middleware (probes always succeed)
280
- - **Structured JSON logging** — opt-in via `server.logging.format: "json"`, one JSON object per record ready for ELK / Loki / Datadog / CloudWatch
281
- - **Public benchmark dashboard** on GitHub Pages
282
-
283
- </td>
284
- </tr>
285
- <tr>
286
- <td valign="top" width="50%">
287
-
288
- ### Scale & performance
289
-
290
- - **SSE / streamable-http transport** — 1 server serves N MCP clients, ChromaDB WAL mode enabled automatically, shared embedding model + query cache
291
- - **BM25 inverted-index** — **128× faster** than linear scan (custom implementation, replaces `rank-bm25`)
292
- - **FTS5 SQLite fast-path** (opt-in, ADR-002/003/006/008) — <10ms cold, <2ms hot on lexical queries
293
- - **Cross-encoder reranking** — Xenova/ms-marco-MiniLM-L-6-v2, +1.88pp Recall@10 (p<0.001)
294
- - **GPU CUDA 12** with auto DLL discovery + graceful CPU fallback
295
- - **Query cache** — LRU + 5-min TTL, cuts p95 latency ~40%
296
- - **Zero-downtime reindex** — staging populate + validation + atomic swap + durable metadata rollback
297
- - **Async background reindex** with `get_reindex_status()` polling
298
-
299
- </td>
300
- <td valign="top" width="50%">
301
-
302
- ### Reliability
303
-
304
- - **Nightly chaos injection** — HuggingFace Hub offline · ONNX zero-byte replay · watchdog crash recovery (3 scenarios in `tests/chaos/`)
305
- - **50 000-iteration soak test** — proves no memory leak after 1h of continuous queries (`KNOWLEDGE_RAG_SOAK_ITERATIONS=50000`)
306
- - **Mutation testing** (mutmut) on `instance_lock` + `preflight` — catches tests that are too weak
307
- - **Determinism check** — full test suite × 3, catches flakes
308
- - **Backwards-compat frozen** — 13 MCP tool parameter names guarded by `tests/test_backwards_compat.py` + legacy YAML fixtures (v3.6.0 / v3.7.0) still parse
309
- - **API surface AST diff** — `check_api_surface.py` blocks any breaking change at PR time
310
- - **9-cell CI matrix** — Linux + Windows + macOS × 3.11 + 3.12 + 3.13
311
-
312
- </td>
313
- </tr>
314
- </table>
315
-
316
- ---
317
-
318
- ## 💼 Use Cases (real corpora, real teams)
319
-
320
- ### Security Teams — Red / Blue / CTF
321
-
322
- **Preset:** [`cybersecurity.yaml`](presets/cybersecurity.yaml) · 8 categories · 200+ routing keywords · 69 query expansions
323
-
324
- Ingest MITRE ATT&CK, threat reports, exploit writeups, incident reports. Search from Claude Code with `search_knowledge("privilege escalation windows")` and get instant recall across your entire corpus. Air-gapped — nothing leaves the laptop.
325
-
326
- ### Development Teams — Design Docs, Runbooks, Code
327
-
328
- **Preset:** [`developer.yaml`](presets/developer.yaml) · 9 categories · 150+ routing keywords · 50+ expansions
329
-
330
- Replace Confluence hunting. Ingest architecture docs, ADRs, runbooks, code, API specs. Devs ask their AI agent "how do we authenticate the payment service" and get the exact ADR + implementation file citation.
331
-
332
- ### Research Labs — Papers, Notebooks, Datasets
333
-
334
- **Preset:** [`research.yaml`](presets/research.yaml) · 9 categories · 100+ routing keywords · 40+ expansions
335
-
336
- Index arXiv papers, lab notebooks, dataset documentation. Semantic search finds papers by intent, not just keywords — cross-encoder reranking surfaces the actually-relevant one instead of five that share a term.
337
-
338
- ### Enterprise Knowledge Base — Air-gapped, Auditable
339
-
340
- **Preset:** [`general.yaml`](presets/general.yaml) · blank slate, pure semantic search
341
-
342
- Deploy via SSE on a single VM. 40+ users authenticated via bearer token, rate-limited, Prometheus-monitored, `/health` probes wired to your load balancer, JSON logs shipped to Datadog. No cloud calls. Meets LGPD, GDPR, HIPAA data-locality requirements by design.
343
-
344
- **Verified at scale:** production reproduction on a **5 889-doc / 75 016-chunk corpus** with concurrent queries during a nuclear rebuild — zero downtime, zero errors (see [CHANGELOG v4.8.3](CHANGELOG.md#v483-2026-08-10--critical-hotfix-nuclear-rebuild--smart-reindex-hardening)).
345
-
346
- ---
347
-
348
- ## 🏗️ Architecture at a glance
349
-
350
- End-to-end view of how MCP clients, the retrieval pipeline, storage, and enterprise plumbing connect. Every arrow is a real code path — nothing pictured here is aspirational.
351
-
352
- ```mermaid
353
- flowchart TB
354
- subgraph CLIENTS["MCP Clients (any of these)"]
355
- C1[Claude Code]
356
- C2[Claude Desktop]
357
- C3[Cursor]
358
- C4[Windsurf]
359
- C5[VS Code · Cline · Gemini CLI · Zed]
360
- end
361
-
362
- subgraph TRANSPORT["Transport Layer"]
363
- T1[stdio<br/>1 process per client]
364
- T2[SSE / streamable-http<br/>1 server serves N clients]
365
- end
366
-
367
- subgraph MIDDLEWARE["ASGI Middleware Chain (HTTP mode)"]
368
- M1[HealthMiddleware<br/>/health · /healthz]
369
- M2[BearerAuthMiddleware<br/>constant-time compare]
370
- M3[Rate Limiter<br/>sliding window]
371
- end
372
-
373
- subgraph MCP["13 MCP Tools (frozen contract)"]
374
- MT1[search_knowledge]
375
- MT2[get_document · search_similar]
376
- MT3[add_document · add_from_url · update · remove]
377
- MT4[reindex_documents · get_reindex_status]
378
- MT5[list_documents · list_categories · get_index_stats · evaluate_retrieval]
379
- end
380
-
381
- subgraph SEARCH["Retrieval Pipeline"]
382
- R[Query Router<br/>lexical vs semantic]
383
- F[FTS5 Fast-Path<br/>opt-in · lt 10ms]
384
- BM[BM25 Inverted Index<br/>128x faster than baseline]
385
- SE[Semantic Search<br/>FastEmbed ONNX lazy-loaded]
386
- RRF[Reciprocal Rank Fusion]
387
- CE[Cross-Encoder Rerank<br/>MiniLM-L-6-v2]
388
- QC[Query Cache<br/>LRU + 5-min TTL]
389
- end
390
-
391
- subgraph STORAGE["Storage (100% local)"]
392
- CH[ChromaDB<br/>vectors + metadata<br/>WAL mode]
393
- FT[SQLite FTS5<br/>lexical index<br/>WAL + busy-timeout]
394
- MD[index_metadata.json<br/>durable state]
395
- end
396
-
397
- subgraph INGEST["Document Ingestion"]
398
- FS[documents/ folder]
399
- WD[Watchdog<br/>10s debounce]
400
- PA[20 Parsers<br/>MD · PDF · DOCX · code · IPYNB]
401
- CK[Chunker<br/>markdown-aware · code-aware]
402
- EM[FastEmbed ONNX<br/>384D bge-small-en-v1.5]
403
- DD[SHA256 Dedup]
404
- SW[Zero-downtime Staging Swap<br/>rollback on validation fail]
405
- end
406
-
407
- subgraph OBS["Enterprise Observability (opt-in)"]
408
- PM[Prometheus /metrics<br/>7 canonical + histograms]
409
- LG[Structured JSON logs<br/>ELK · Loki · Datadog · CloudWatch]
410
- HC[Health payload<br/>version · uptime · cache stats]
411
- end
412
-
413
- subgraph CFG["Configuration"]
414
- YM[config.yaml<br/>+ 5 domain presets]
415
- end
416
-
417
- C1 & C2 & C3 & C4 & C5 -->|MCP protocol| T1
418
- C1 & C2 & C3 & C4 & C5 -.->|remote deploy| T2
419
- T1 --> MCP
420
- T2 --> M1 --> M2 --> M3 --> MCP
421
-
422
- MT1 --> QC
423
- QC -->|cache miss| R
424
- R -->|lexical| F
425
- R -->|semantic| SE
426
- R -->|hybrid| BM
427
- F --> CH
428
- F --> FT
429
- BM --> CH
430
- SE --> CH
431
- BM --> RRF
432
- SE --> RRF
433
- RRF --> CE
434
- CE --> QC
435
-
436
- MT2 --> CH
437
- MT3 --> INGEST
438
- MT4 --> SW
439
- MT5 --> CH
440
-
441
- FS --> WD --> PA
442
- PA --> CK --> EM --> DD --> CH
443
- SW -.->|atomic swap| CH
444
- SW -.-> FT
445
- CH -.-> MD
446
-
447
- MCP -.->|instrumented| PM
448
- MCP -.->|logs| LG
449
- M1 --> HC
450
-
451
- YM -.-> SEARCH
452
- YM -.-> STORAGE
453
- YM -.-> OBS
454
- YM -.-> MIDDLEWARE
455
-
456
- classDef client fill:#3776AB,stroke:#1e5a8a,color:#fff
457
- classDef transport fill:#00A67E,stroke:#006e54,color:#fff
458
- classDef middleware fill:#6b46c1,stroke:#4c1d95,color:#fff
459
- classDef storage fill:#4b5563,stroke:#1f2937,color:#fff
460
- classDef obs fill:#dc2626,stroke:#7f1d1d,color:#fff
461
- classDef ingest fill:#f59e0b,stroke:#78350f,color:#fff
462
-
463
- class C1,C2,C3,C4,C5 client
464
- class T1,T2 transport
465
- class M1,M2,M3 middleware
466
- class CH,FT,MD storage
467
- class PM,LG,HC obs
468
- class FS,WD,PA,CK,EM,DD,SW ingest
469
- ```
470
-
471
- **Reading the diagram (top → bottom):**
472
-
473
- 1. **Any MCP client** — Claude Code, Cursor, Windsurf, and 5 others — connects via the transport of your choice (stdio for personal use, SSE/streamable-http for teams).
474
- 2. **HTTP mode chains 3 ASGI middlewares in order**: health probes first (always answered), then bearer auth (fenced with `WWW-Authenticate`), then rate limiter (sliding window).
475
- 3. **All 13 MCP tools** are decorated with `@rate_limited` + `@instrument` — Prometheus counts every call, rate limiter enforces RPM+burst, both zero-cost when disabled.
476
- 4. **`search_knowledge` checks the query cache first**; cache miss routes through the Query Router (regex classifier) to either the FTS5 fast-path (lexical) or the hybrid pipeline (BM25 + semantic + RRF + cross-encoder rerank).
477
- 5. **Storage is 100% local**: ChromaDB (WAL mode) for vectors + metadata, SQLite FTS5 (WAL + busy-timeout) for lexical fast-path, `index_metadata.json` for durable state.
478
- 6. **Document ingestion runs continuously**: watchdog observes `documents/`, 20 parsers handle each format, chunker respects language boundaries, FastEmbed ONNX generates embeddings, SHA256 deduplicates, and a staging swap performs zero-downtime rebuilds with rollback-on-failure.
479
- 7. **Enterprise observability** (opt-in) — Prometheus `/metrics`, structured JSON logs, `/health` payload — attaches to the same instrumentation points, no code changes required.
480
- 8. **`config.yaml` (with 5 domain presets)** controls every subsystem — no environment variable spaghetti, no hardcoded paths.
481
-
482
- **Complete architecture — 4 detailed Mermaid diagrams (System Overview · Query Flow · Document Ingestion · hybrid_alpha effect):** [docs/ARCHITECTURE.md](docs/ARCHITECTURE.md)
483
-
484
- ---
485
-
486
- ## 📄 20 File Formats — parsed natively, no plugins needed
487
-
488
- Every parser is **chunk-aware** — Markdown splits at `##` headers, code splits at function/class boundaries, notebooks skip base64 outputs, PDFs use PyMuPDF, spreadsheets extract sheet-by-sheet. **18 formats are enabled by default**; the 2 MetaTrader formats are opt-in (add to `documents.supported_formats` in `config.yaml`).
489
-
490
- | # | Format | Extension | Parser | Default | Notes |
491
- |---|--------|-----------|--------|:-------:|-------|
492
- | 1 | Markdown | `.md` | Section-aware (splits at `##`) | Yes | Headers preserved as chunk boundaries |
493
- | 2 | Plain Text | `.txt` | Fixed-size chunking | Yes | 1000 chars + 200 overlap |
494
- | 3 | PDF | `.pdf` | PyMuPDF extraction | Yes | Text-based PDFs only (no OCR) |
495
- | 4 | Word | `.docx` | python-docx | Yes | Headings preserved as markdown |
496
- | 5 | Excel | `.xlsx` | openpyxl | Yes | Sheet-by-sheet extraction |
497
- | 6 | PowerPoint | `.pptx` | python-pptx | Yes | Slide-by-slide extraction |
498
- | 7 | Jupyter Notebook | `.ipynb` | Cell-aware parser | Yes | Markdown + code cells only; skips outputs/base64 |
499
- | 8 | JSON | `.json` | Structure-aware | Yes | Flattened key-value extraction |
500
- | 9 | CSV | `.csv` | Row-based parser | Yes | Headers + rows as text |
501
- | 10 | XML | `.xml` | XML parser | Yes | Root element + namespace metadata |
502
- | 11 | Python | `.py` | Code-aware parser | Yes | Functions/classes as chunks |
503
- | 12 | C Source | `.c` | Code-aware parser | Yes | Functions / structs / includes extracted |
504
- | 13 | C/C++ Header | `.h` | Code-aware parser | Yes | Function declarations + structs extracted |
505
- | 14 | C++ Source | `.cpp` | Code-aware parser | Yes | Classes / structs / includes extracted |
506
- | 15 | JavaScript | `.js` | Code-aware parser | Yes | Functions / classes / imports (ESM + CJS) |
507
- | 16 | React JSX | `.jsx` | Code-aware parser | Yes | Same as JS parser |
508
- | 17 | TypeScript | `.ts` | Code-aware parser | Yes | Functions / classes / interfaces / enums / imports |
509
- | 18 | React TSX | `.tsx` | Code-aware parser | Yes | Same as TS parser |
510
- | 19 | MQL4 Source | `.mq4` | Code parser | **No** | MetaTrader — opt-in via `documents.supported_formats` |
511
- | 20 | MQL4 Header | `.mqh` | Code parser | **No** | MetaTrader — opt-in via `documents.supported_formats` |
512
-
513
- > **Enable an opt-in format** — add the extension to `documents.supported_formats` in your `config.yaml`:
514
- > ```yaml
515
- > documents:
516
- > supported_formats: [".md", ".pdf", ".mq4", ".mqh"]
517
- > ```
518
-
519
- **Full parser reference with per-format notes:** [docs/CONFIGURATION.md](docs/CONFIGURATION.md)
520
-
521
- ---
522
-
523
- ## 🔌 Choose your MCP integration
524
-
525
- <table>
526
- <tr>
527
- <td align="center" width="14%">
528
-
529
- **Claude Code**<br/>
530
- `~/.claude.json`
531
-
532
- </td>
533
- <td align="center" width="14%">
534
-
535
- **Claude Desktop**<br/>
536
- `claude_desktop_config.json`
537
-
538
- </td>
539
- <td align="center" width="14%">
540
-
541
- **Cursor**<br/>
542
- `~/.cursor/mcp.json`
543
-
544
- </td>
545
- <td align="center" width="14%">
546
-
547
- **Windsurf**<br/>
548
- `~/.codeium/windsurf/mcp_config.json`
549
-
550
- </td>
551
- <td align="center" width="14%">
552
-
553
- **VS Code**<br/>
554
- Copilot Chat `mcp.json`
555
-
556
- </td>
557
- <td align="center" width="14%">
558
-
559
- **Cline · Gemini CLI · Zed**<br/>
560
- Native MCP
561
-
562
- </td>
563
- </tr>
564
- </table>
565
-
566
- **Complete client configuration guide with JSON schemas per client:** [docs/INSTALLATION.md#use-with-other-mcp-clients →](docs/INSTALLATION.md#use-with-other-mcp-clients)
567
-
568
- ---
569
-
570
- ## ⚙️ Configuration in 30 seconds
571
-
572
- ```yaml
573
- # config.yaml — everything is optional; defaults just work
574
-
575
- paths:
576
- documents_dir: "./documents"
577
- data_dir: "./data"
578
-
579
- models:
580
- embedding:
581
- profile: "compact" # "compact" | "quality" | "multilingual" | "custom"
582
- gpu: "auto" # "auto" | "true" | "false"
583
- reranker:
584
- enabled: true # cross-encoder rerank
585
-
586
- search:
587
- default_results: 5
588
- max_results: 100
589
-
590
- server: # optional — SSE / HTTP mode
591
- transport: "stdio" # or "sse" / "streamable-http"
592
- auth:
593
- bearer_token: "" # set a secret to enable auth
594
- rate_limit:
595
- enabled: false
596
- metrics:
597
- enabled: false
598
- logging:
599
- format: "text" # or "json"
600
- ```
601
-
602
- **Pre-built presets:** [`cybersecurity.yaml`](presets/cybersecurity.yaml) · [`developer.yaml`](presets/developer.yaml) · [`research.yaml`](presets/research.yaml) · [`general.yaml`](presets/general.yaml) · [`multilingual.yaml`](presets/multilingual.yaml)
603
-
604
- **Complete configuration reference — every field, every default, tuning guide:** [docs/CONFIGURATION.md →](docs/CONFIGURATION.md)
605
-
606
- ---
607
-
608
- ## 🔒 Security & Compliance
609
-
610
- knowledge-rag is designed for teams that cannot let their documents leave the perimeter.
611
-
612
- | Requirement | How knowledge-rag delivers |
613
- |---|---|
614
- | **Data locality (LGPD / GDPR / HIPAA)** | 100% on-premise, zero egress network calls after initial model download |
615
- | **Air-gapped deployment** | ONNX models pre-cached; set `HF_HUB_OFFLINE=1` to enforce zero-network |
616
- | **CVE monitoring** | Dependabot (weekly) + pip-audit + Socket + CodeQL |
617
- | **Supply chain security** | PyPI Trusted Publishing via OIDC (no long-lived tokens) |
618
- | **Vulnerability disclosure** | Private security advisory via [SECURITY.md](SECURITY.md) |
619
- | **Signed release attestations** | GitHub release attestations on every published version |
620
- | **Reproducible builds** | Locked `requirements.txt` with pinned versions |
621
- | **Authenticated access** | Bearer token middleware on SSE / HTTP transports (constant-time compare, RFC 6750) |
622
- | **Rate limiting** | Sliding-window per-client RPM + burst (opt-in, zero-cost when disabled) |
623
- | **Audit-ready logging** | Opt-in structured JSON logs → ship to your SIEM |
624
- | **Path traversal defenses** | CWE-22 / CWE-59 guards on 6 CRUD tools |
625
- | **Prompt injection defense** | 3-layer sanitization on `add_from_url` (OWASP LLM01:2025) |
626
-
627
- **OpenSSF Best Practices** badge: passing · project ID [#13864](https://bestpractices.coreinfrastructure.org/projects/13864)
628
-
629
- ---
630
-
631
- ## 📈 Numbers that matter
632
-
633
- - **26 000+** total downloads on PyPI · **250+** GitHub stars · **70+** enterprise teams (private + community)
634
- - **700+ tests** collected · **1.33:1** test-to-code ratio · **codecov trend gate** ±0.5pp
635
- - **35+ status checks** on every PR (9-cell OS×Python matrix · 7 quality pillars)
636
- - **20 file formats** parsed natively · **13 MCP tools** frozen · **5 domain presets** (cyber · dev · research · multilingual · general)
637
- - **BM25 128× faster** than baseline · **cross-encoder +1.88pp** Recall@10 (p<0.001) · **cache −40%** p95 latency
638
- - **1 800+ files / 39 K chunks indexed in < 3 min** on a modern laptop (typical developer corpus)
639
- - **Verified in production** on 5 889-doc / 75 016-chunk corpora
640
-
641
- **Public benchmark dashboard:** https://lyonzin.github.io/knowledge-rag/
642
-
643
- ---
644
-
645
- ## 📚 Documentation
646
-
647
- | Doc | What's inside |
648
- |---|---|
649
- | [**Installation guide**](docs/INSTALLATION.md) | 5 install methods · 8 MCP client integrations · GPU setup |
650
- | [**API reference**](docs/API.md) | Complete reference for all 13 MCP tools |
651
- | [**Configuration reference**](docs/CONFIGURATION.md) | Every `config.yaml` field · presets · tuning |
652
- | [**Architecture**](docs/ARCHITECTURE.md) | 4 Mermaid diagrams: System Overview · Query Flow · Ingestion · hybrid_alpha |
653
- | [**Troubleshooting**](docs/TROUBLESHOOTING.md) | 11 common issues + solutions |
654
- | [**FTS5 fast-path guide**](docs/features/fts5_fast_path.md) | Opt-in lexical fast-path — when and how |
655
- | [**Reindex operations**](docs/reindex-operations.md) | Zero-downtime rebuild · resume · checkpoint |
656
- | [**GPU setup**](docs/gpu-setup.md) | CUDA 12 installation + troubleshooting |
657
- | [**Migration to v4.8.0**](docs/migration-v4.8.0.md) | Embedding profile · multilingual · zero-downtime |
658
- | [**Security policy**](SECURITY.md) | Threat model · disclosure channel |
659
- | [**Contributing**](CONTRIBUTING.md) | Development · testing · PR process |
660
- | [**Changelog**](CHANGELOG.md) | All release notes since v1.0.0 |
661
-
662
- ---
663
-
664
- ## 🤝 Community & Support
665
-
666
- - **Report a bug** → [Open an issue](https://github.com/lyonzin/knowledge-rag/issues/new/choose)
667
- - **Ask a question** → [GitHub Discussions](https://github.com/lyonzin/knowledge-rag/discussions)
668
- - **Report a vulnerability** → [Security advisory](https://github.com/lyonzin/knowledge-rag/security/advisories/new) (private)
669
- - **Contribute** → [CONTRIBUTING.md](CONTRIBUTING.md)
670
-
671
- **Response SLA (best-effort, community project):**
672
- - Security reports: within 48 h
673
- - Bug reports with reproduction: within 5 business days
674
- - Feature requests: triaged on next release cycle
675
-
676
- ---
677
-
678
- ## 🗺️ Recent releases
679
-
680
- - **v4.8.5** (2026-08-13) — Enterprise observability: `/health` endpoint + opt-in JSON structured logging
681
- - **v4.8.4** (2026-08-13) — Patch: security + durability + defensive fixes
682
- - **v4.8.3** (2026-08-10) — Critical hotfix: nuclear-rebuild + smart-reindex hardening on 50k+ chunk corpora
683
- - **v4.8.2** (2026-08-10) — FTS5 lexical fast-path opt-in release
684
- - **v4.8.0** (2026-08-06) — Multilingual foundation + zero-downtime reindex
685
-
686
- **Full history:** [CHANGELOG.md →](CHANGELOG.md)
687
-
688
- ---
689
-
690
- ## 📜 License
691
-
692
- **MIT License** — [LICENSE](LICENSE). Forever. No cloud upsell, no dual-licensing, no restrictive clauses. Fork it, sell derivatives, embed it in commercial products — the license does not care.
693
-
694
- ---
695
-
696
- ## 🙏 Acknowledgments
697
-
698
- Built on the shoulders of amazing open-source projects:
699
-
700
- - [**Anthropic MCP**](https://modelcontextprotocol.io/) — Model Context Protocol spec + Python SDK
701
- - [**ChromaDB**](https://www.trychroma.com/) — vector database that just works
702
- - [**FastEmbed**](https://github.com/qdrant/fastembed) — ONNX embeddings, no PyTorch bloat
703
- - [**HuggingFace**](https://huggingface.co/) — model hosting + `Xenova/ms-marco-MiniLM-L-6-v2` cross-encoder
704
- - [**BAAI**](https://huggingface.co/BAAI) — the `bge-small-en-v1.5` embedding model
705
-
706
- **Community contributors:** [@Hohlas](https://github.com/Hohlas) · [@eeshsaxena](https://github.com/eeshsaxena) · Sergey Khokhlov · and everyone who filed issues or PRs.
707
-
708
- ---
709
-
710
- <div align="center">
711
-
712
- **Built by [Ailton Rocha (Lyon.)](https://github.com/lyonzin)** · Star ⭐ if this saves you time · [Report an issue](https://github.com/lyonzin/knowledge-rag/issues/new/choose) · [Contribute](CONTRIBUTING.md)
713
-
714
- *knowledge-rag — the MCP-first local RAG server for Claude Code, Cursor, Windsurf, and every AI agent.*
715
-
716
- </div>
1
+ <!--
2
+ knowledge-rag — Local RAG server for Claude Code, Cursor, Windsurf and other MCP clients.
3
+ SEO keywords: local rag, mcp server, self-hosted rag, hybrid search, cross-encoder reranking, claude code rag, cursor rag, python rag, chromadb rag, fastembed rag, air-gapped rag, gdpr rag, retrieval augmented generation, model context protocol server, zero cloud rag.
4
+
5
+ Structured data (schema.org SoftwareApplication) — indexed by search engines, invisible on GitHub render:
6
+ {
7
+ "@context": "https://schema.org",
8
+ "@type": "SoftwareApplication",
9
+ "name": "knowledge-rag",
10
+ "applicationCategory": "DeveloperApplication",
11
+ "operatingSystem": "Windows, Linux, macOS",
12
+ "description": "Local-first RAG server for AI agents. Hybrid search, MCP-native, zero cloud, enterprise-grade plumbing (bearer auth, Prometheus metrics, rate limiting, health probes, structured JSON logging, zero-downtime reindex).",
13
+ "offers": { "@type": "Offer", "price": "0", "priceCurrency": "USD" },
14
+ "license": "https://opensource.org/licenses/MIT",
15
+ "downloadUrl": "https://pypi.org/project/knowledge-rag/",
16
+ "codeRepository": "https://github.com/lyonzin/knowledge-rag",
17
+ "programmingLanguage": "Python",
18
+ "runtimePlatform": "Python 3.11+"
19
+ }
20
+ -->
21
+
22
+ <p align="center">
23
+ <img
24
+ src="./assets/knowledge-rag-banner.png"
25
+ alt="knowledge-rag — Local Hybrid RAG for MCP"
26
+ width="100%"
27
+ />
28
+ </p>
29
+
30
+ # knowledge-rag
31
+
32
+ <div align="center">
33
+
34
+ [![PyPI](https://img.shields.io/pypi/v/knowledge-rag)](https://pypi.org/project/knowledge-rag/)
35
+ [![NPM](https://img.shields.io/npm/v/knowledge-rag)](https://www.npmjs.com/package/knowledge-rag)
36
+ [![PyPI Downloads](https://static.pepy.tech/personalized-badge/knowledge-rag?period=total&units=INTERNATIONAL_SYSTEM&left_color=BLACK&right_color=GREEN&left_text=downloads)](https://pepy.tech/projects/knowledge-rag)
37
+ ![Python](https://img.shields.io/badge/python-3.11%2B-green.svg)
38
+ ![License](https://img.shields.io/badge/license-MIT-yellow.svg)
39
+ ![Platform](https://img.shields.io/badge/platform-Windows%20%7C%20Linux%20%7C%20macOS-lightgrey.svg)
40
+ ![GPU](https://img.shields.io/badge/GPU-NVIDIA%20CUDA-76B900.svg?logo=nvidia)
41
+ [![CI](https://github.com/lyonzin/knowledge-rag/actions/workflows/ci.yml/badge.svg)](https://github.com/lyonzin/knowledge-rag/actions/workflows/ci.yml)
42
+ [![CodeQL](https://github.com/lyonzin/knowledge-rag/actions/workflows/security.yml/badge.svg)](https://github.com/lyonzin/knowledge-rag/actions/workflows/security.yml)
43
+ [![Quality Gate](https://github.com/lyonzin/knowledge-rag/actions/workflows/quality-gate.yml/badge.svg)](https://github.com/lyonzin/knowledge-rag/actions/workflows/quality-gate.yml)
44
+ [![Glama Score](https://glama.ai/mcp/servers/lyonzin/knowledge-rag/badges/score.svg)](https://glama.ai/mcp/servers/lyonzin/knowledge-rag)
45
+ [![OpenSSF Best Practices](https://bestpractices.coreinfrastructure.org/projects/13864/badge)](https://bestpractices.coreinfrastructure.org/projects/13864)
46
+
47
+ ### The MCP-first local RAG server for Claude Code, Cursor, and every AI agent.
48
+
49
+ **Hybrid search · Cross-encoder reranking · 35 file formats · 100% local · Zero cloud · Enterprise-grade plumbing built-in.**
50
+
51
+ ```bash
52
+ pip install knowledge-rag → restart Claude Code → search_knowledge("your query")
53
+ ```
54
+
55
+ [Quick Start](#quick-start-3-minutes-from-zero-to-your-first-query) ·
56
+ [Why knowledge-rag](#why-knowledge-rag) ·
57
+ [Compare](#how-knowledge-rag-compares-to-other-rag-frameworks) ·
58
+ [Enterprise Features](#enterprise-features-built-in-zero-configuration) ·
59
+ [Docs](#documentation)
60
+
61
+ </div>
62
+
63
+ ---
64
+
65
+ ## ⭐ Star History
66
+
67
+ <div align="center">
68
+
69
+ <a href="https://www.star-history.com/?repos=lyonzin%2Fknowledge-rag&type=date&legend=top-left">
70
+ <img alt="knowledge-rag star history chart — GitHub star growth over time" src="./docs/star-history.svg" width="720" />
71
+ </a>
72
+
73
+ <sub>Chart updated daily by <a href="./.github/workflows/update-star-history.yml">GitHub Action</a></sub>
74
+
75
+ </div>
76
+
77
+ ---
78
+
79
+ ## 🎯 Why knowledge-rag
80
+
81
+ Most RAG frameworks fall into one of three traps: (1) they require you to ship your data to a cloud API, (2) they hand you 300 building blocks and 0 opinionated defaults, or (3) they bundle RAG as a 5% feature of a much bigger platform you didn't ask for.
82
+
83
+ **knowledge-rag does one thing well:** it is the MCP-native local RAG server that Claude Code, Cursor, Windsurf, VS Code, Cline, Gemini CLI and Zed can search out of the box — with enterprise plumbing (bearer auth, Prometheus metrics, rate limiting, health probes, structured JSON logging, zero-downtime reindex) that no other RAG-focused OSS ships built-in.
84
+
85
+ <table>
86
+ <tr>
87
+ <td width="50%" valign="top">
88
+
89
+ ### 🔒 100% local, 0% cloud
90
+ Your files never leave the machine. No vendor lock-in, no data-residency headache, no forced cloud dependency. **LGPD / GDPR / HIPAA compliant by architecture** — because there is nothing to comply about when nothing leaves.
91
+
92
+ </td>
93
+ <td width="50%" valign="top">
94
+
95
+ ### 🚀 Zero-friction setup
96
+ `pip install knowledge-rag` → restart your MCP client → done. **No Docker mandatory. No Ollama required. No separate embedding server.** Everything runs in-process via FastEmbed ONNX. **Works offline** after the first model download.
97
+
98
+ </td>
99
+ </tr>
100
+ <tr>
101
+ <td width="50%" valign="top">
102
+
103
+ ### 🛡️ Production-grade OSS
104
+ 7-pillar quality gate on every PR (**35+ automated checks**), 9-cell OS×Python CI matrix (Linux + Windows + macOS × 3.11/3.12/3.13), nightly chaos + 50K-iteration soak + mutation testing. **700+ tests. 0 known regressions.**
105
+
106
+ </td>
107
+ <td width="50%" valign="top">
108
+
109
+ ### 💰 Zero ongoing cost
110
+ No token bills. No SaaS tier. No paid features hidden behind a wall. **MIT license, forever.** Runs on the laptop you already have — GPU optional, CPU works fine with FastEmbed ONNX.
111
+
112
+ </td>
113
+ </tr>
114
+ </table>
115
+
116
+ ---
117
+
118
+ ## 📊 How knowledge-rag compares to other RAG frameworks
119
+
120
+ We audited **16 popular RAG frameworks and platforms** (LlamaIndex, LangChain, ChromaDB, Weaviate, Qdrant, RAGFlow, LightRAG, DSPy, GraphRAG, Haystack, RAG-Anything, kotaemon, txtai, llmware, Dify, open-webui, FastGPT) so you can pick honestly.
121
+
122
+ **Legend:** ✅ built-in · 🟡 plugin / paid tier / partial · ❌ not available · ⚠️ license or default concern
123
+
124
+ | Dimension | 🎯 **knowledge-rag** | LlamaIndex | LangChain | Haystack | RAGFlow | txtai | open-webui | Dify | Qdrant |
125
+ |---|:---:|:---:|:---:|:---:|:---:|:---:|:---:|:---:|:---:|
126
+ | **100% local, zero cloud** | ✅ | 🟡 | ✅ | 🟡 | 🟡 | ✅ | ✅ | 🟡 | 🟡 |
127
+ | **MCP native (Claude/Cursor)** | ✅ 13 tools | 🟡 pkg | 🟡 adapter | 🟡 wrapper | 🟡 add-on | ✅ | ✅ consumer | ✅ | ❌ |
128
+ | **Hybrid BM25 + semantic** | ✅ 128× faster | 🟡 | 🟡 | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
129
+ | **Cross-encoder rerank** | ✅ builtin | ❌ | 🟡 | ✅ | ✅ fused | ❌ | ✅ | 🟡 | 🟡 |
130
+ | **Bearer auth builtin** | ✅ | ❌ | ❌ | ❌ core | ❌ | 🟡 | ✅ RBAC | ✅ OAuth2 | ✅ |
131
+ | **Prometheus `/metrics`** | ✅ | ❌ | ❌ | ❌ core | ❌ | ❌ | ✅ OTel | ❌ | ✅ |
132
+ | **Rate limiting** | ✅ sliding-window | ❌ | ❌ | ❌ | ❌ | ❌ | ✅ | ✅ | ✅ |
133
+ | **Health probes** (`/health`) | ✅ | ❌ | ❌ | ❌ | ❌ | ❌ | 🟡 | 🟡 | ✅ |
134
+ | **Structured JSON logging** | ✅ opt-in | ❌ | ❌ | ❌ | ❌ | ❌ | ✅ OTel | 🟡 | ✅ |
135
+ | **Zero-downtime reindex** | ✅ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ✅ |
136
+ | **Async background reindex** | ✅ + polling | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | 🟡 |
137
+ | **GPU CUDA optional** | ✅ 12 auto | ❌ | 🟡 | ✅ | ✅ | ✅ | ✅ | 🟡 | 🟡 |
138
+ | **File formats builtin** | ✅ **20** | 0 (LlamaParse=$) | 50+ plugins | ✅ **36+** | 8+ | ? | ? | ~10 | ❌ |
139
+ | **Setup < 5 min POC** | ✅ pip 1-liner | ✅ | ✅ | ✅ | ❌ 16GB RAM | ✅ | ✅ docker | ✅ docker | ✅ |
140
+ | **Nightly chaos + soak + mutation** | ✅ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ |
141
+ | **License** | ✅ MIT | MIT | MIT | Apache-2.0 | Apache-2.0 | Apache-2.0 | ⚠️ preserving | ⚠️ restrictive | Apache-2.0 |
142
+
143
+ > **The 5 dimensions where knowledge-rag is unique:** health probes + JSON logging + Prometheus + rate limit + bearer auth **simultaneously built-in on an OSS RAG-focused MCP server**. Zero-downtime reindex + async background reindex + nightly chaos/soak/mutation are documented on nobody else's README.
144
+
145
+ ---
146
+
147
+ ## 🚀 Quick Start (3 minutes, from zero to your first query)
148
+
149
+ Pick your integration path — knowledge-rag ships the same server through every channel.
150
+
151
+ ### Path 1 — Claude Code, Cursor, Windsurf, Cline, VS Code, Gemini CLI, Zed (MCP)
152
+
153
+ ```bash
154
+ pip install knowledge-rag
155
+ knowledge-rag init # scaffolds config.yaml + documents/
156
+ ```
157
+
158
+ Drop your PDFs, markdown, code files into `documents/`. Restart your MCP client. Ask it:
159
+
160
+ ```
161
+ search_knowledge("your query")
162
+ ```
163
+
164
+ That's it. First query loads the ONNX embedding model (~200MB, one-off download). Subsequent queries are cached and hit sub-second latency.
165
+
166
+ ### Path 2 — HTTP / SSE server (multi-user, air-gapped, load-balanced)
167
+
168
+ ```yaml
169
+ # config.yaml
170
+ server:
171
+ transport: "sse" # or "streamable-http"
172
+ host: "0.0.0.0"
173
+ port: 8179
174
+ auth:
175
+ bearer_token: "your-secret-token"
176
+ rate_limit:
177
+ enabled: true
178
+ requests_per_minute: 60
179
+ metrics:
180
+ enabled: true
181
+ port: 9179
182
+ logging:
183
+ format: "json" # ELK / Loki / Datadog / CloudWatch ready
184
+ ```
185
+
186
+ ```bash
187
+ knowledge-rag --transport sse
188
+ ```
189
+
190
+ - Health probe: `curl http://your-host:8179/health` → 200 + JSON payload
191
+ - Prometheus scrape: `http://your-host:9179/metrics`
192
+ - MCP dispatcher: authenticated via `Authorization: Bearer your-secret-token`
193
+
194
+ ### Path 3 — Docker (models pre-downloaded, air-gapped ready)
195
+
196
+ ```bash
197
+ docker pull ghcr.io/lyonzin/knowledge-rag:latest
198
+ docker run -v $(pwd)/documents:/app/documents -p 8179:8179 ghcr.io/lyonzin/knowledge-rag:latest
199
+ ```
200
+
201
+ **Full installation guide with all 5 methods, 8 MCP client configurations, and GPU setup:** [docs/INSTALLATION.md →](docs/INSTALLATION.md)
202
+
203
+ ---
204
+
205
+ ## 🤖 Ready-to-use skills for AI agents
206
+
207
+ Installing knowledge-rag gives your agent 13 MCP tools. It does not tell the agent **when** to use them. That is what the [`skills/`](skills/) folder solves — drop-in behavioural skills for Claude Code, Cursor, Windsurf, Cline, Zed, VS Code Copilot that turn "AI with access to RAG" into "AI that actually uses RAG first".
208
+
209
+ **10 skills, MIT licensed, organized by kind:**
210
+
211
+ | # | Skill | What it does |
212
+ |---|---|---|
213
+ | 1 | [`rag-check-first`](skills/foundation/rag-check-first/SKILL.md) | Search the corpus **before** answering any technical claim |
214
+ | 2 | [`rag-cite-sources`](skills/foundation/rag-cite-sources/SKILL.md) | Every claim ships with `path:line` citations |
215
+ | 3 | [`rag-onboard-context`](skills/foundation/rag-onboard-context/SKILL.md) | First interaction of a session probes what is indexed |
216
+ | 4 | [`rag-deep-dive`](skills/workflow/rag-deep-dive/SKILL.md) | 3-step drill: `search` → `fetch` → `find similar` |
217
+ | 5 | [`rag-web-fallback`](skills/workflow/rag-web-fallback/SKILL.md) | Only hit the web when local RAG comes back empty |
218
+ | 6 | [`rag-troubleshoot`](skills/workflow/rag-troubleshoot/SKILL.md) | Bug / error → RAG first for prior fixes |
219
+ | 7 | [`rag-code-review`](skills/workflow/rag-code-review/SKILL.md) | Review consults ADRs / patterns before commenting |
220
+ | 8 | [`rag-index-decisions`](skills/maintenance/rag-index-decisions/SKILL.md) | After a decision, index it back — close the feedback loop |
221
+ | 9 | [`rag-security-first`](skills/domain/rag-security-first/SKILL.md) | Security tasks: MITRE / CVE / runbook first |
222
+ | 10 | [`rag-evaluate-quality`](skills/maintenance/rag-evaluate-quality/SKILL.md) | Weekly checkup — MRR@5 · Recall@5 · Precision@5 |
223
+
224
+ **Install — pick the shortest path for your machine:**
225
+
226
+ ```bash
227
+ # Option 1 — Via skills.sh (needs Node — one command, zero clone)
228
+ npx skills add lyonzin/knowledge-rag
229
+
230
+ # Option 2 — Via our install.sh (no Node needed; works on Linux/macOS/WSL/Git Bash)
231
+ curl -fsSL https://raw.githubusercontent.com/lyonzin/knowledge-rag/master/skills/install.sh | bash
232
+ ```
233
+
234
+ Both restart-Claude-Code and you are done. Option 2 supports `--project`, `--only rag-check-first,rag-cite-sources`, `--dry-run`, `--help`.
235
+
236
+ For Cursor, Windsurf, Cline and full manual instructions → [skills/README.md](skills/README.md) · Full catalog with skill chains → [skills/CATALOG.md](skills/CATALOG.md)
237
+
238
+ ---
239
+
240
+ ## 🛠️ The 13 MCP tools your agent gets
241
+
242
+ Once installed, your AI agent gets these 13 tools automatically:
243
+
244
+ | Tool | Purpose |
245
+ |---|---|
246
+ | `search_knowledge` | Hybrid semantic + BM25 with cross-encoder rerank |
247
+ | `get_document` | Retrieve full content of one document |
248
+ | `search_similar` | Find documents similar to a reference |
249
+ | `evaluate_retrieval` | Measure MRR@5 · Recall@5 · Precision@5 |
250
+ | `add_document` | Index a new document via MCP |
251
+ | `update_document` | Re-index a changed document |
252
+ | `remove_document` | Drop a document + all its chunks |
253
+ | `add_from_url` | Fetch, sanitize, and index a URL |
254
+ | `list_documents` | Enumerate indexed documents |
255
+ | `list_categories` | Auto-tagged by folder path |
256
+ | `get_index_stats` | Corpus size, cache hit rate, embedding dim |
257
+ | `reindex_documents` | Smart incremental OR nuclear rebuild |
258
+ | `get_reindex_status` | Live progress polling (async reindex) |
259
+
260
+ **Full API reference with parameter details, return schemas, examples:** [docs/API.md →](docs/API.md)
261
+
262
+ ---
263
+
264
+ ## 🏢 Enterprise Features (built-in, zero configuration)
265
+
266
+ Every RAG framework claims "production-ready." Here is what knowledge-rag ships **in the OSS core, verified by regression tests, that competitors either paywall, plugin-ify, or simply don't have.**
267
+
268
+ <table>
269
+ <tr>
270
+ <td valign="top" width="50%">
271
+
272
+ ### Security
273
+
274
+ - **Bearer token auth** on SSE / HTTP transports — constant-time comparison (`hmac.compare_digest`), RFC 6750 challenge, 401 fenced with `WWW-Authenticate` header
275
+ - **Path traversal + symlink escape defenses** — `validate_path_within` guarding 6 CRUD tools (CWE-22, CWE-59)
276
+ - **Prompt injection 3-layer defense** — sentinel neutralization + provenance fence + `external_source` flag (OWASP LLM01:2025)
277
+ - **OpenSSF Best Practices badge** verified · **CodeQL** weekly scan · **Bandit + Semgrep + Gitleaks + pip-audit** on every PR
278
+ - **PyPI Trusted Publishing** via OIDC (zero long-lived tokens in CI)
279
+
280
+ </td>
281
+ <td valign="top" width="50%">
282
+
283
+ ### Observability
284
+
285
+ - **Prometheus `/metrics` endpoint** — custom histogram buckets tuned for RAG (p95 ≤ 10ms fast-path targets), 7 canonical metrics via `@instrument` decorator on all 13 tools
286
+ - **Rate limiting** — thread-safe sliding-window counter, per-client RPM + burst, zero overhead when disabled
287
+ - **Health probes** — `GET /health` and `/healthz` returning `{status, version, uptime_seconds, cache}` in front of the auth middleware (probes always succeed)
288
+ - **Structured JSON logging** — opt-in via `server.logging.format: "json"`, one JSON object per record ready for ELK / Loki / Datadog / CloudWatch
289
+ - **Public benchmark dashboard** on GitHub Pages
290
+
291
+ </td>
292
+ </tr>
293
+ <tr>
294
+ <td valign="top" width="50%">
295
+
296
+ ### Scale & performance
297
+
298
+ - **SSE / streamable-http transport** — 1 server serves N MCP clients, ChromaDB WAL mode enabled automatically, shared embedding model + query cache
299
+ - **BM25 inverted-index** — **128× faster** than linear scan (custom implementation, replaces `rank-bm25`)
300
+ - **FTS5 SQLite fast-path** (opt-in, ADR-002/003/006/008) — <10ms cold, <2ms hot on lexical queries
301
+ - **Cross-encoder reranking** — Xenova/ms-marco-MiniLM-L-6-v2, +1.88pp Recall@10 (p<0.001)
302
+ - **GPU CUDA 12** with auto DLL discovery + graceful CPU fallback
303
+ - **Query cache** — LRU + 5-min TTL, cuts p95 latency ~40%
304
+ - **Zero-downtime reindex** — staging populate + validation + atomic swap + durable metadata rollback
305
+ - **Async background reindex** with `get_reindex_status()` polling
306
+
307
+ </td>
308
+ <td valign="top" width="50%">
309
+
310
+ ### Reliability
311
+
312
+ - **Nightly chaos injection** — HuggingFace Hub offline · ONNX zero-byte replay · watchdog crash recovery (3 scenarios in `tests/chaos/`)
313
+ - **50 000-iteration soak test** — proves no memory leak after 1h of continuous queries (`KNOWLEDGE_RAG_SOAK_ITERATIONS=50000`)
314
+ - **Mutation testing** (mutmut) on `instance_lock` + `preflight` — catches tests that are too weak
315
+ - **Determinism check** — full test suite × 3, catches flakes
316
+ - **Backwards-compat frozen** — 13 MCP tool parameter names guarded by `tests/test_backwards_compat.py` + legacy YAML fixtures (v3.6.0 / v3.7.0) still parse
317
+ - **API surface AST diff** — `check_api_surface.py` blocks any breaking change at PR time
318
+ - **9-cell CI matrix** — Linux + Windows + macOS × 3.11 + 3.12 + 3.13
319
+
320
+ </td>
321
+ </tr>
322
+ </table>
323
+
324
+ ---
325
+
326
+ ## 💼 Use Cases (real corpora, real teams)
327
+
328
+ ### Security Teams — Red / Blue / CTF
329
+
330
+ **Preset:** [`cybersecurity.yaml`](presets/cybersecurity.yaml) · 8 categories · 200+ routing keywords · 69 query expansions
331
+
332
+ Ingest MITRE ATT&CK, threat reports, exploit writeups, incident reports. Search from Claude Code with `search_knowledge("privilege escalation windows")` and get instant recall across your entire corpus. Air-gapped — nothing leaves the laptop.
333
+
334
+ ### Development Teams — Design Docs, Runbooks, Code
335
+
336
+ **Preset:** [`developer.yaml`](presets/developer.yaml) · 9 categories · 150+ routing keywords · 50+ expansions
337
+
338
+ Replace Confluence hunting. Ingest architecture docs, ADRs, runbooks, code, API specs. Devs ask their AI agent "how do we authenticate the payment service" and get the exact ADR + implementation file citation.
339
+
340
+ ### Research Labs — Papers, Notebooks, Datasets
341
+
342
+ **Preset:** [`research.yaml`](presets/research.yaml) · 9 categories · 100+ routing keywords · 40+ expansions
343
+
344
+ Index arXiv papers, lab notebooks, dataset documentation. Semantic search finds papers by intent, not just keywords — cross-encoder reranking surfaces the actually-relevant one instead of five that share a term.
345
+
346
+ ### Enterprise Knowledge Base — Air-gapped, Auditable
347
+
348
+ **Preset:** [`general.yaml`](presets/general.yaml) · blank slate, pure semantic search
349
+
350
+ Deploy via SSE on a single VM. 40+ users authenticated via bearer token, rate-limited, Prometheus-monitored, `/health` probes wired to your load balancer, JSON logs shipped to Datadog. No cloud calls. Meets LGPD, GDPR, HIPAA data-locality requirements by design.
351
+
352
+ **Verified at scale:** production reproduction on a **5 889-doc / 75 016-chunk corpus** with concurrent queries during a nuclear rebuild — zero downtime, zero errors (see [CHANGELOG v4.8.3](CHANGELOG.md#v483-2026-08-10--critical-hotfix-nuclear-rebuild--smart-reindex-hardening)).
353
+
354
+ ---
355
+
356
+ ## 🏗️ Architecture at a glance
357
+
358
+ End-to-end view of how MCP clients, the retrieval pipeline, storage, and enterprise plumbing connect. Every arrow is a real code path — nothing pictured here is aspirational.
359
+
360
+ ```mermaid
361
+ flowchart TB
362
+ subgraph CLIENTS["MCP Clients (any of these)"]
363
+ C1[Claude Code]
364
+ C2[Claude Desktop]
365
+ C3[Cursor]
366
+ C4[Windsurf]
367
+ C5[VS Code · Cline · Gemini CLI · Zed]
368
+ end
369
+
370
+ subgraph TRANSPORT["Transport Layer"]
371
+ T1[stdio<br/>1 process per client]
372
+ T2[SSE / streamable-http<br/>1 server serves N clients]
373
+ end
374
+
375
+ subgraph MIDDLEWARE["ASGI Middleware Chain (HTTP mode)"]
376
+ M1[HealthMiddleware<br/>/health · /healthz]
377
+ M2[BearerAuthMiddleware<br/>constant-time compare]
378
+ M3[Rate Limiter<br/>sliding window]
379
+ end
380
+
381
+ subgraph MCP["13 MCP Tools (frozen contract)"]
382
+ MT1[search_knowledge]
383
+ MT2[get_document · search_similar]
384
+ MT3[add_document · add_from_url · update · remove]
385
+ MT4[reindex_documents · get_reindex_status]
386
+ MT5[list_documents · list_categories · get_index_stats · evaluate_retrieval]
387
+ end
388
+
389
+ subgraph SEARCH["Retrieval Pipeline"]
390
+ R[Query Router<br/>lexical vs semantic]
391
+ F[FTS5 Fast-Path<br/>opt-in · lt 10ms]
392
+ BM[BM25 Inverted Index<br/>128x faster than baseline]
393
+ SE[Semantic Search<br/>FastEmbed ONNX lazy-loaded]
394
+ RRF[Reciprocal Rank Fusion]
395
+ CE[Cross-Encoder Rerank<br/>MiniLM-L-6-v2]
396
+ QC[Query Cache<br/>LRU + 5-min TTL]
397
+ end
398
+
399
+ subgraph STORAGE["Storage (100% local)"]
400
+ CH[ChromaDB<br/>vectors + metadata<br/>WAL mode]
401
+ FT[SQLite FTS5<br/>lexical index<br/>WAL + busy-timeout]
402
+ MD[index_metadata.json<br/>durable state]
403
+ end
404
+
405
+ subgraph INGEST["Document Ingestion"]
406
+ FS[documents/ folder]
407
+ WD[Watchdog<br/>10s debounce]
408
+ PA[35 Parsers<br/>MD · PDF · DOCX · code · IaC · IPYNB]
409
+ CK[Chunker<br/>markdown-aware · code-aware]
410
+ EM[FastEmbed ONNX<br/>384D bge-small-en-v1.5]
411
+ DD[SHA256 Dedup]
412
+ SW[Zero-downtime Staging Swap<br/>rollback on validation fail]
413
+ end
414
+
415
+ subgraph OBS["Enterprise Observability (opt-in)"]
416
+ PM[Prometheus /metrics<br/>7 canonical + histograms]
417
+ LG[Structured JSON logs<br/>ELK · Loki · Datadog · CloudWatch]
418
+ HC[Health payload<br/>version · uptime · cache stats]
419
+ end
420
+
421
+ subgraph CFG["Configuration"]
422
+ YM[config.yaml<br/>+ 5 domain presets]
423
+ end
424
+
425
+ C1 & C2 & C3 & C4 & C5 -->|MCP protocol| T1
426
+ C1 & C2 & C3 & C4 & C5 -.->|remote deploy| T2
427
+ T1 --> MCP
428
+ T2 --> M1 --> M2 --> M3 --> MCP
429
+
430
+ MT1 --> QC
431
+ QC -->|cache miss| R
432
+ R -->|lexical| F
433
+ R -->|semantic| SE
434
+ R -->|hybrid| BM
435
+ F --> CH
436
+ F --> FT
437
+ BM --> CH
438
+ SE --> CH
439
+ BM --> RRF
440
+ SE --> RRF
441
+ RRF --> CE
442
+ CE --> QC
443
+
444
+ MT2 --> CH
445
+ MT3 --> INGEST
446
+ MT4 --> SW
447
+ MT5 --> CH
448
+
449
+ FS --> WD --> PA
450
+ PA --> CK --> EM --> DD --> CH
451
+ SW -.->|atomic swap| CH
452
+ SW -.-> FT
453
+ CH -.-> MD
454
+
455
+ MCP -.->|instrumented| PM
456
+ MCP -.->|logs| LG
457
+ M1 --> HC
458
+
459
+ YM -.-> SEARCH
460
+ YM -.-> STORAGE
461
+ YM -.-> OBS
462
+ YM -.-> MIDDLEWARE
463
+
464
+ classDef client fill:#3776AB,stroke:#1e5a8a,color:#fff
465
+ classDef transport fill:#00A67E,stroke:#006e54,color:#fff
466
+ classDef middleware fill:#6b46c1,stroke:#4c1d95,color:#fff
467
+ classDef storage fill:#4b5563,stroke:#1f2937,color:#fff
468
+ classDef obs fill:#dc2626,stroke:#7f1d1d,color:#fff
469
+ classDef ingest fill:#f59e0b,stroke:#78350f,color:#fff
470
+
471
+ class C1,C2,C3,C4,C5 client
472
+ class T1,T2 transport
473
+ class M1,M2,M3 middleware
474
+ class CH,FT,MD storage
475
+ class PM,LG,HC obs
476
+ class FS,WD,PA,CK,EM,DD,SW ingest
477
+ ```
478
+
479
+ **Reading the diagram (top → bottom):**
480
+
481
+ 1. **Any MCP client** — Claude Code, Cursor, Windsurf, and 5 others — connects via the transport of your choice (stdio for personal use, SSE/streamable-http for teams).
482
+ 2. **HTTP mode chains 3 ASGI middlewares in order**: health probes first (always answered), then bearer auth (fenced with `WWW-Authenticate`), then rate limiter (sliding window).
483
+ 3. **All 13 MCP tools** are decorated with `@rate_limited` + `@instrument` — Prometheus counts every call, rate limiter enforces RPM+burst, both zero-cost when disabled.
484
+ 4. **`search_knowledge` checks the query cache first**; cache miss routes through the Query Router (regex classifier) to either the FTS5 fast-path (lexical) or the hybrid pipeline (BM25 + semantic + RRF + cross-encoder rerank).
485
+ 5. **Storage is 100% local**: ChromaDB (WAL mode) for vectors + metadata, SQLite FTS5 (WAL + busy-timeout) for lexical fast-path, `index_metadata.json` for durable state.
486
+ 6. **Document ingestion runs continuously**: watchdog observes `documents/`, 35 parsers handle each format, chunker respects language boundaries, FastEmbed ONNX generates embeddings, SHA256 deduplicates, and a staging swap performs zero-downtime rebuilds with rollback-on-failure.
487
+ 7. **Enterprise observability** (opt-in) — Prometheus `/metrics`, structured JSON logs, `/health` payload — attaches to the same instrumentation points, no code changes required.
488
+ 8. **`config.yaml` (with 5 domain presets)** controls every subsystem — no environment variable spaghetti, no hardcoded paths.
489
+
490
+ **Complete architecture — 4 detailed Mermaid diagrams (System Overview · Query Flow · Document Ingestion · hybrid_alpha effect):** [docs/ARCHITECTURE.md](docs/ARCHITECTURE.md)
491
+
492
+ ---
493
+
494
+ ## 📄 35 File Formats — parsed natively, no plugins needed
495
+
496
+ Every parser is **chunk-aware** — Markdown splits at `##` headers, code splits at function/class boundaries, notebooks skip base64 outputs, PDFs use PyMuPDF, spreadsheets extract sheet-by-sheet. **33 formats are enabled by default**; the 2 MetaTrader formats are opt-in (add to `documents.supported_formats` in `config.yaml`).
497
+
498
+ | # | Format | Extension | Parser | Default | Notes |
499
+ |---|--------|-----------|--------|:-------:|-------|
500
+ | 1 | Markdown | `.md` | Section-aware (splits at `##`) | Yes | Headers preserved as chunk boundaries |
501
+ | 2 | Plain Text | `.txt` | Fixed-size chunking | Yes | 1000 chars + 200 overlap |
502
+ | 3 | PDF | `.pdf` | PyMuPDF extraction | Yes | Text-based PDFs only (no OCR) |
503
+ | 4 | Word | `.docx` | python-docx | Yes | Headings preserved as markdown |
504
+ | 5 | Excel | `.xlsx` | openpyxl | Yes | Sheet-by-sheet extraction |
505
+ | 6 | PowerPoint | `.pptx` | python-pptx | Yes | Slide-by-slide extraction |
506
+ | 7 | Jupyter Notebook | `.ipynb` | Cell-aware parser | Yes | Markdown + code cells only; skips outputs/base64 |
507
+ | 8 | JSON | `.json` | Structure-aware | Yes | Flattened key-value extraction |
508
+ | 9 | CSV | `.csv` | Row-based parser | Yes | Headers + rows as text |
509
+ | 10 | XML | `.xml` | XML parser | Yes | Root element + namespace metadata |
510
+ | 11 | Python | `.py` | Code-aware parser | Yes | Functions/classes as chunks |
511
+ | 12 | C Source | `.c` | Code-aware parser | Yes | Functions / structs / includes extracted |
512
+ | 13 | C/C++ Header | `.h` | Code-aware parser | Yes | Function declarations + structs extracted |
513
+ | 14 | C++ Source | `.cpp` | Code-aware parser | Yes | Classes / structs / includes extracted |
514
+ | 15 | JavaScript | `.js` | Code-aware parser | Yes | Functions / classes / imports (ESM + CJS) |
515
+ | 16 | React JSX | `.jsx` | Code-aware parser | Yes | Same as JS parser |
516
+ | 17 | TypeScript | `.ts` | Code-aware parser | Yes | Functions / classes / interfaces / enums / imports |
517
+ | 18 | React TSX | `.tsx` | Code-aware parser | Yes | Same as TS parser |
518
+ | 19 | Go | `.go` | Code-aware parser | Yes | Functions / structs / imports extracted |
519
+ | 20 | Rust | `.rs` | Code-aware parser | Yes | Functions / structs / enums / traits / `use` imports |
520
+ | 21 | Kotlin | `.kt` | Code-aware parser | Yes | Functions (incl. class members) / classes extracted |
521
+ | 22 | YAML | `.yaml` | YAML parser | Yes | Kubernetes kind / apiVersion / name extracted |
522
+ | 23 | YAML | `.yml` | YAML parser | Yes | Same as YAML parser |
523
+ | 24 | HuJSON | `.hujson` | HuJSON parser | Yes | JSON with comments + trailing commas (e.g. Tailscale ACLs) |
524
+ | 25 | CUE | `.cue` | Code-aware parser | Yes | Imports / package extracted |
525
+ | 26 | Protocol Buffers | `.proto` | Proto parser | Yes | Services / messages / RPCs extracted |
526
+ | 27 | Rego | `.rego` | Code-aware parser | Yes | OPA policies — imports / package extracted |
527
+ | 28 | SQL | `.sql` | SQL parser | Yes | Table names + statement types extracted |
528
+ | 29 | Shell | `.sh` | Shell parser | Yes | Function names extracted |
529
+ | 30 | jq | `.jq` | Shell parser | Yes | Indexed as shell-style script |
530
+ | 31 | Dockerfile | `Dockerfile` | Text parser | Yes | Matched by exact filename (no extension) |
531
+ | 32 | Makefile | `Makefile` | Text parser | Yes | Matched by exact filename (no extension) |
532
+ | 33 | Tiltfile | `Tiltfile` | Code-aware parser | Yes | Starlark — `def` functions / `load()` extracted |
533
+ | 34 | MQL4 Source | `.mq4` | Code parser | **No** | MetaTrader — opt-in via `documents.supported_formats` |
534
+ | 35 | MQL4 Header | `.mqh` | Code parser | **No** | MetaTrader — opt-in via `documents.supported_formats` |
535
+
536
+ > **Enable an opt-in format** — add the extension to `documents.supported_formats` in your `config.yaml`:
537
+ > ```yaml
538
+ > documents:
539
+ > supported_formats: [".md", ".pdf", ".mq4", ".mqh"]
540
+ > ```
541
+
542
+ **Full parser reference with per-format notes:** [docs/CONFIGURATION.md](docs/CONFIGURATION.md)
543
+
544
+ ---
545
+
546
+ ## 🔌 Choose your MCP integration
547
+
548
+ <table>
549
+ <tr>
550
+ <td align="center" width="14%">
551
+
552
+ **Claude Code**<br/>
553
+ `~/.claude.json`
554
+
555
+ </td>
556
+ <td align="center" width="14%">
557
+
558
+ **Claude Desktop**<br/>
559
+ `claude_desktop_config.json`
560
+
561
+ </td>
562
+ <td align="center" width="14%">
563
+
564
+ **Cursor**<br/>
565
+ `~/.cursor/mcp.json`
566
+
567
+ </td>
568
+ <td align="center" width="14%">
569
+
570
+ **Windsurf**<br/>
571
+ `~/.codeium/windsurf/mcp_config.json`
572
+
573
+ </td>
574
+ <td align="center" width="14%">
575
+
576
+ **VS Code**<br/>
577
+ Copilot Chat `mcp.json`
578
+
579
+ </td>
580
+ <td align="center" width="14%">
581
+
582
+ **Cline · Gemini CLI · Zed**<br/>
583
+ Native MCP
584
+
585
+ </td>
586
+ </tr>
587
+ </table>
588
+
589
+ **Complete client configuration guide with JSON schemas per client:** [docs/INSTALLATION.md#use-with-other-mcp-clients →](docs/INSTALLATION.md#use-with-other-mcp-clients)
590
+
591
+ ---
592
+
593
+ ## ⚙️ Configuration in 30 seconds
594
+
595
+ ```yaml
596
+ # config.yaml — everything is optional; defaults just work
597
+
598
+ paths:
599
+ documents_dir: "./documents"
600
+ data_dir: "./data"
601
+
602
+ models:
603
+ embedding:
604
+ profile: "compact" # "compact" | "quality" | "multilingual" | "custom"
605
+ gpu: "auto" # "auto" | "true" | "false"
606
+ reranker:
607
+ enabled: true # cross-encoder rerank
608
+
609
+ search:
610
+ default_results: 5
611
+ max_results: 100
612
+
613
+ server: # optional — SSE / HTTP mode
614
+ transport: "stdio" # or "sse" / "streamable-http"
615
+ auth:
616
+ bearer_token: "" # set a secret to enable auth
617
+ rate_limit:
618
+ enabled: false
619
+ metrics:
620
+ enabled: false
621
+ logging:
622
+ format: "text" # or "json"
623
+ ```
624
+
625
+ **Pre-built presets:** [`cybersecurity.yaml`](presets/cybersecurity.yaml) · [`developer.yaml`](presets/developer.yaml) · [`research.yaml`](presets/research.yaml) · [`general.yaml`](presets/general.yaml) · [`multilingual.yaml`](presets/multilingual.yaml)
626
+
627
+ **Complete configuration reference — every field, every default, tuning guide:** [docs/CONFIGURATION.md →](docs/CONFIGURATION.md)
628
+
629
+ ---
630
+
631
+ ## 🔒 Security & Compliance
632
+
633
+ knowledge-rag is designed for teams that cannot let their documents leave the perimeter.
634
+
635
+ | Requirement | How knowledge-rag delivers |
636
+ |---|---|
637
+ | **Data locality (LGPD / GDPR / HIPAA)** | 100% on-premise, zero egress network calls after initial model download |
638
+ | **Air-gapped deployment** | ONNX models pre-cached; set `HF_HUB_OFFLINE=1` to enforce zero-network |
639
+ | **CVE monitoring** | Dependabot (weekly) + pip-audit + Socket + CodeQL |
640
+ | **Supply chain security** | PyPI Trusted Publishing via OIDC (no long-lived tokens) |
641
+ | **Vulnerability disclosure** | Private security advisory via [SECURITY.md](SECURITY.md) |
642
+ | **Signed release attestations** | GitHub release attestations on every published version |
643
+ | **Reproducible builds** | Locked `requirements.txt` with pinned versions |
644
+ | **Authenticated access** | Bearer token middleware on SSE / HTTP transports (constant-time compare, RFC 6750) |
645
+ | **Rate limiting** | Sliding-window per-client RPM + burst (opt-in, zero-cost when disabled) |
646
+ | **Audit-ready logging** | Opt-in structured JSON logs → ship to your SIEM |
647
+ | **Path traversal defenses** | CWE-22 / CWE-59 guards on 6 CRUD tools |
648
+ | **Prompt injection defense** | 3-layer sanitization on `add_from_url` (OWASP LLM01:2025) |
649
+
650
+ **OpenSSF Best Practices** badge: passing · project ID [#13864](https://bestpractices.coreinfrastructure.org/projects/13864)
651
+
652
+ ---
653
+
654
+ ## 📈 Numbers that matter
655
+
656
+ - **26 000+** total downloads on PyPI · **250+** GitHub stars · **70+** enterprise teams (private + community)
657
+ - **700+ tests** collected · **1.33:1** test-to-code ratio · **codecov trend gate** ±0.5pp
658
+ - **35+ status checks** on every PR (9-cell OS×Python matrix · 7 quality pillars)
659
+ - **35 file formats** parsed natively · **13 MCP tools** frozen · **5 domain presets** (cyber · dev · research · multilingual · general)
660
+ - **BM25 128× faster** than baseline · **cross-encoder +1.88pp** Recall@10 (p<0.001) · **cache −40%** p95 latency
661
+ - **1 800+ files / 39 K chunks indexed in < 3 min** on a modern laptop (typical developer corpus)
662
+ - **Verified in production** on 5 889-doc / 75 016-chunk corpora
663
+
664
+ **Public benchmark dashboard:** https://lyonzin.github.io/knowledge-rag/
665
+
666
+ ---
667
+
668
+ ## 📚 Documentation
669
+
670
+ | Doc | What's inside |
671
+ |---|---|
672
+ | [**Installation guide**](docs/INSTALLATION.md) | 5 install methods · 8 MCP client integrations · GPU setup |
673
+ | [**API reference**](docs/API.md) | Complete reference for all 13 MCP tools |
674
+ | [**Configuration reference**](docs/CONFIGURATION.md) | Every `config.yaml` field · presets · tuning |
675
+ | [**Architecture**](docs/ARCHITECTURE.md) | 4 Mermaid diagrams: System Overview · Query Flow · Ingestion · hybrid_alpha |
676
+ | [**Troubleshooting**](docs/TROUBLESHOOTING.md) | 11 common issues + solutions |
677
+ | [**FTS5 fast-path guide**](docs/features/fts5_fast_path.md) | Opt-in lexical fast-path — when and how |
678
+ | [**Reindex operations**](docs/reindex-operations.md) | Zero-downtime rebuild · resume · checkpoint |
679
+ | [**GPU setup**](docs/gpu-setup.md) | CUDA 12 installation + troubleshooting |
680
+ | [**Migration to v4.8.0**](docs/migration-v4.8.0.md) | Embedding profile · multilingual · zero-downtime |
681
+ | [**Security policy**](SECURITY.md) | Threat model · disclosure channel |
682
+ | [**Contributing**](CONTRIBUTING.md) | Development · testing · PR process |
683
+ | [**Changelog**](CHANGELOG.md) | All release notes since v1.0.0 |
684
+
685
+ ---
686
+
687
+ ## 🤝 Community & Support
688
+
689
+ - **Report a bug** → [Open an issue](https://github.com/lyonzin/knowledge-rag/issues/new/choose)
690
+ - **Ask a question** → [GitHub Discussions](https://github.com/lyonzin/knowledge-rag/discussions)
691
+ - **Report a vulnerability** → [Security advisory](https://github.com/lyonzin/knowledge-rag/security/advisories/new) (private)
692
+ - **Contribute** → [CONTRIBUTING.md](CONTRIBUTING.md)
693
+
694
+ **Response SLA (best-effort, community project):**
695
+ - Security reports: within 48 h
696
+ - Bug reports with reproduction: within 5 business days
697
+ - Feature requests: triaged on next release cycle
698
+
699
+ ---
700
+
701
+ ## 🗺️ Recent releases
702
+
703
+ - **v4.8.5** (2026-08-13) — Enterprise observability: `/health` endpoint + opt-in JSON structured logging
704
+ - **v4.8.4** (2026-08-13) — Patch: security + durability + defensive fixes
705
+ - **v4.8.3** (2026-08-10) — Critical hotfix: nuclear-rebuild + smart-reindex hardening on 50k+ chunk corpora
706
+ - **v4.8.2** (2026-08-10) — FTS5 lexical fast-path opt-in release
707
+ - **v4.8.0** (2026-08-06) — Multilingual foundation + zero-downtime reindex
708
+
709
+ **Full history:** [CHANGELOG.md →](CHANGELOG.md)
710
+
711
+ ---
712
+
713
+ ## 📜 License
714
+
715
+ **MIT License** — [LICENSE](LICENSE). Forever. No cloud upsell, no dual-licensing, no restrictive clauses. Fork it, sell derivatives, embed it in commercial products — the license does not care.
716
+
717
+ ---
718
+
719
+ ## 🙏 Acknowledgments
720
+
721
+ Built on the shoulders of amazing open-source projects:
722
+
723
+ - [**Anthropic MCP**](https://modelcontextprotocol.io/) — Model Context Protocol spec + Python SDK
724
+ - [**ChromaDB**](https://www.trychroma.com/) — vector database that just works
725
+ - [**FastEmbed**](https://github.com/qdrant/fastembed) — ONNX embeddings, no PyTorch bloat
726
+ - [**HuggingFace**](https://huggingface.co/) — model hosting + `Xenova/ms-marco-MiniLM-L-6-v2` cross-encoder
727
+ - [**BAAI**](https://huggingface.co/BAAI) — the `bge-small-en-v1.5` embedding model
728
+
729
+ **Community contributors:** [@Hohlas](https://github.com/Hohlas) · [@eeshsaxena](https://github.com/eeshsaxena) · Sergey Khokhlov · and everyone who filed issues or PRs.
730
+
731
+ ---
732
+
733
+ <div align="center">
734
+
735
+ **Built by [Ailton Rocha (Lyon.)](https://github.com/lyonzin)** · Star ⭐ if this saves you time · [Report an issue](https://github.com/lyonzin/knowledge-rag/issues/new/choose) · [Contribute](CONTRIBUTING.md)
736
+
737
+ *knowledge-rag — the MCP-first local RAG server for Claude Code, Cursor, Windsurf, and every AI agent.*
738
+
739
+ </div>