demo-kb
This server does not currently have a deployable release on Glama. Follow the repository's setup instructions to install and configure it for your MCP client, including any required credentials and local dependencies.
Grounded RAG Engine
A retrieval engine for research knowledge bases that answers only from its sources, with a full reference for every passage, and says so plainly when its sources do not cover a question. It plugs straight into Claude through the Model Context Protocol (MCP).
One engine serves many separate knowledge bases (KBs). Each KB keeps its own texts, settings and SQLite databases; the engine is never copied into it. Everything runs on an ordinary laptop: no vector-database server, no cloud bill for search.
This repository is a public showcase: the engine, the MCP connector, the source-collection pipeline and a small demo KB of 13 public-domain and official texts (571 passages), already built and ready to search.
Contents
Related MCP server: bible
What it does
Collects sources with provenance | Books, PDFs, court rulings, laws, official reports, papers and news are fetched politely, saved with a clean text copy, and logged with URL, author, year, licence, retrieval date and SHA-256. Nothing that fails is dropped silently: it goes to a manual-download list. |
Refuses unreadable text | A readability lock scores every text against word lists learned from correctly typed text. Broken OCR of a scan never enters the index. |
Hybrid search | Meaning search with BGE-M3 (multilingual: an English question finds an Arabic or French passage) fused with exact-word search in SQLite FTS5, by reciprocal-rank fusion. The exact-word list counts by how much of the typed quotation it really found. |
Grounded or silent | Every search also returns an evidence check. When nothing in the KB is close, the connector tells Claude "NOT IN THE KB" instead of letting it improvise. |
Search across languages | Passages in languages without an English text can get a machine translation (Claude Batch API, at half price) used only as a second search vector; the answer still quotes the original. |
Many KBs, one engine | A KB is a folder with |
Git-friendly storage | Databases are split into files under 90 MB with fixed id ranges, so a whole KB, index included, lives in an ordinary Git repository. Copyrighted material goes into a separate "private" database family that can be excluded from any shared copy. |
Safe changes | Moving the engine itself was done only after old and new code gave byte-identical results on 125 test questions, the connector's answers and its tool schemas (see Used in production). |
Why it is built this way
Most RAG demos optimise for an answer. Research work needs the right answer and the place it came from, and it needs the system to admit when it does not know. Three rules shape every part of this engine:
Provenance first. A passage is useless in a paper if you cannot cite it. Every file carries its full reference from the moment it is downloaded; every passage carries its book, section and line range or page.
Garbage never goes in. A wrong letter in an OCR'd scan becomes a wrong quotation later. The readability lock stops unreadable text at the door, and texts that fail are listed for repair rather than silently indexed.
Silence is an answer. A question the sources do not cover gets "not in the KB", with the nearest passages shown for the reader to judge, never an invented answer.
How it works
flowchart LR
subgraph Collect["1. Collect (collector/)"]
B[batch .jsonl] --> C[collect.py]
C -->|PDF / HTML / text| T[texts + clean .txt]
C -->|reference row| S[SOURCES.tsv]
C -->|refused / dead| M[Manual-Downloads.md]
end
subgraph Build["2. Build (kbengine/add.py)"]
T --> L{readability lock}
L -->|readable| P[passages with references]
L -->|broken OCR| X[left out, listed]
P --> F[(SQLite + FTS5<br/>exact words)]
P --> V[(BGE-M3 vectors<br/>.npy)]
end
subgraph Serve["3. Search and serve"]
Q[question + key words] --> H[hybrid search<br/>dense + FTS5, RRF]
F --> H
V --> H
H --> E{evidence check}
E --> MCP[MCP connector<br/>search_kb / read_passage / list_books]
MCP --> Claude[Claude Desktop / Claude Code]
endPassages. Books are cut at headings and at about 1,200 letters, never across a heading. Page marks such as
[p 12] or [vol 2 p 40] become the reference; texts without page marks are cited by section heading and line range.
Exact words. Each passage is indexed twice in FTS5: exact normalised words, and light stems (joined particles removed), so that a typed word finds its inflected form. Neighbouring word pairs are also searched, so a quotation scores above scattered words.
Fusion. Meaning list and exact-word list are fused by reciprocal rank. The exact-word list's weight is
2 × coverage², where coverage is the share of the typed words actually found in its best passage: a real quotation
is trusted fully; loose concept words count little. (On the first KB's held-out test, a fixed weight made results
worse than meaning search alone; the coverage-based weight removed that loss.)
Evidence. If both the best meaning score and the word coverage are low, the search reports "not in the KB". On the first KB this kept 8 of 8 far-off questions silent while silencing 0 of 83 answerable ones.
Try it in five minutes
git clone https://github.com/<you>/grounded-rag-engine
cd grounded-rag-engine
pip install -r requirements.txt # the first search downloads BAAI/bge-m3 (~2.3 GB) once
# the demo KB is already built (demo-kb/rag): list it
python -X utf8 kb.py add --kb demo-kb --listSearch from Python:
import sys; sys.path.insert(0, ".")
from kbengine.config import use
from kbengine.search import Index
ix = Index(kb=use("demo-kb"))
for i, score in ix.hybrid("Can the state force anyone to support a church?", "compelled to frequent or support", k=3):
r = ix.row(i)
print(r["ref"], "\n ", r["text"][:200], "\n")
print(ix.evidence("How do I cook biryani?")) # -> found: False (grounded or silent)Rebuild the demo from its texts (about 15 minutes on a laptop CPU):
python -X utf8 kb.py add --kb demo-kb --group church-and-state
python -X utf8 kb.py add --kb demo-kb --group founding-texts
python -X utf8 kb.py add --kb demo-kb --group un-and-official
python -X utf8 kb.py add --kb demo-kb --group court-rulingsConnect it to Claude (MCP)
The connector runs locally over stdio; Claude starts it when needed. It offers four tools: search_kb,
read_passage (a passage in full, with neighbours for context), list_books, and, for KBs that hold the Qur'an,
get_verse (switched off in the demo).
Claude Code
claude mcp add --scope user demo-kb -- python -X utf8 /full/path/grounded-rag-engine/kbengine/mcp_server.py --kb /full/path/grounded-rag-engine/demo-kbClaude Desktop (claude_desktop_config.json)
{
"mcpServers": {
"demo-kb": {
"command": "python",
"args": ["-X", "utf8", "/full/path/grounded-rag-engine/kbengine/mcp_server.py", "--kb", "/full/path/grounded-rag-engine/demo-kb"]
}
}
}Self-test without Claude: python -X utf8 kb.py mcp --kb demo-kb --selftest.
The model loads on the first question, not at start-up, so a Claude session that never asks the KB pays nothing.
The connector's rules for Claude (demo-kb/CONNECTOR.md) are "grounded or silent": answer only from returned
passages, cite each one, and say so when the KB does not cover the question.
Example answers from the demo KB
See examples/demo-queries.md for real output of the demo KB: questions about
toleration, the separation of church and state, the right to counsel and poverty, each with the passages and
references the engine returned, and one question it correctly refuses.
The collection pipeline
collector/ builds a KB's library before anything is indexed. One JSON line per source:
Kind | Fetches | Saved as |
| a PDF or web page (several copies may be listed; the first that works is kept) | original + clean |
| a public-domain book from the Internet Archive (Project Gutenberg's typed text first, else the scan's text) |
|
| a Wikipedia or Wikisource page, plus every outside link it cites (the primary sources to collect next) |
|
| a news or rights-group report; title, date and author read from the page itself |
|
| CSV / Excel / JSON datasets | the file (data is counted with code, never put in the RAG) |
Helpers: openalex_find.py and pick_papers.py (open-access papers from OpenAlex), retry_papers.py (other
open-access copies when a publisher refuses), archive_find.py (public-domain books), make_wiki_batch.py,
make_news_batch.py (the reports that background pages cite), update_manual_list.py (everything that could not be
fetched, with its reference), readability_report.py and make_parts.py (what may enter the RAG).
Polite by design: one request at a time, a fixed gap per site, Retry-After honoured, a --quick mode for news links
that are often dead, and no API keys or e-mail addresses sent anywhere.
Full guide: docs/ADD-YOUR-OWN-KB.md.
Used in production
The same engine runs two private research KBs on a laptop (their texts are not published here):
First KB | Second KB | |
Languages | Arabic, Urdu, English | English, French, some Spanish and Turkish |
Passages | 114,426 in 6 SQLite files (all under 90 MB) | about 59,000 (building) |
Sources | classical books, hadith collections, commentaries, modern books | about 800: books, constitutions, laws, court rulings, UN and official reports, about 190 open-access papers, datasets, news |
Search aids | about 15,000 passages with a Claude Batch translation as a second (English) search vector | readability lock on 778 texts: 758 readable, the rest listed |
Tests | three regression sets (27 standard questions, 28 verse questions, 28 held-out questions, plus 12 for newly added books) |
When the engine was moved out of the first KB into this shared package, the switch was made only after the old and the new code gave byte-identical results on: the full part list; 125 questions × six search modes (ids and scores); the connector's answers and its four tool schemas; a trial build of six kinds of text into empty folders; the readability lock; the translation cost count; and batch status.
Repository layout
kb.py run any engine command for any KB
kbengine/
config.py the KB (--kb or KB_ROOT), its kb.json + parts.json; database families and id ranges
text.py normalising, exact words and light stems (incl. Arabic and the Qur'an's spelling)
passages.py books / hadith / custom builders into passages with references
quality.py the readability lock
add.py build: lock -> passages -> exact-word index -> vectors (resumable, 90 MB cap)
search.py Index: dense + exact words, RRF fusion, English search vectors, evidence check
translate.py Claude Batch API translations used as search aids (exact cost count first)
embed.py vectors for those translations
scan.py Claude types out scanned pages that OCR cannot read
cards.py KBs of structured Markdown cards (a checked format instead of the lock)
mcp_server.py the MCP connector
collector/ the source-collection pipeline (see above)
demo-kb/ 13 public-domain / official texts, their references, settings and the built index
docs/ADD-YOUR-OWN-KB.md how to make and connect a new KB
examples/ real output of the demo KBEngine commands
python -I -X utf8 kb.py add --kb <KB> --list every part and its state
python -I -X utf8 kb.py add --kb <KB> --group <group> build a group (resumes where it stopped)
python -I -X utf8 kb.py quality --kb <KB> <file> ... readability verdicts
python -I -X utf8 kb.py translate --kb <KB> count --sources <part> exact token count and cost (free)
python -I -X utf8 kb.py translate --kb <KB> submit --sources <part> --model claude-opus-5-5
python -I -X utf8 kb.py embed --kb <KB> vectors for collected translations
python -I -X utf8 kb.py scan --kb <KB> submit <book.pdf> <out.txt> Claude types out a scanned book
python -X utf8 kb.py mcp --kb <KB> [--selftest] the connector-I (isolated mode) is used on purpose when reading downloaded files: Python then never imports code from the
current folder. Paid steps (translation, scan reading) always print an exact cost estimate first; the API key is read
from KB_ANTHROPIC_KEY, kept apart from ANTHROPIC_API_KEY.
Limits, honestly
Embedding speed. On a laptop CPU, BGE-M3 embeds about one passage a second: a 59,000-passage KB builds in about 21 hours, unattended and resumable. A CUDA GPU makes this many times faster; search itself is fast on CPU.
Stemming is tuned for Arabic. For English the exact-word list is plain FTS5 words; the meaning search does most of the work.
Numbers. A RAG is poor at arithmetic over tables. In these KBs, datasets are kept as files and counted with code; the connector's rules tell Claude to quote a figure only from a passage that states it.
Background pages are finding aids. Wikipedia pages in a KB are there for dates and links to primary sources; the primary source is what gets cited.
Disclaimer
The demo KB is here to show how the engine works. Its answers are passages quoted from the texts it holds, not legal,
financial or religious advice, and a KB can only be as complete as the sources collected into it. Machine translations
are used as search aids only; quote the original text. The demo texts are public domain or official documents; check
each source's own terms (see demo-kb/SOURCES.md) before reusing them elsewhere.
Licence
Code: MIT (see LICENSE). Demo texts: public domain or official UN / US government documents; each one's source and
licence is in demo-kb/SOURCES.md.
Built by IrshadOS: grounded AI systems for research, legal and business knowledge.
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
Loading tool schema changelog…
This server cannot be deployed
Maintenance
Related MCP Connectors
Search and cite passages from a vetted, rights-cleared reference library.
Read-only search of the Quran, hadith and classical books of the four Sunni schools, with citations.
Search your knowledge bases from any AI assistant using hybrid RAG.
Neural search synthesizer, deep research dossier compiler, and citation tools.
Related MCP Servers
- FlicenseNot gradedqualityBmaintenanceEnables semantic retrieval over a structured Quran and classical exegesis library, returning relevant source chunks and verified references for thematic research queries.1-
- AlicenseAqualityBmaintenanceEnables Claude to query an owned Bible study library read-only, retrieving passages, lexical data, search results, cross-references, commentaries, church fathers, translation notes, dictionaries, and citations, with quote verification and schema/source inspection.14MIT
- AlicenseNot gradedqualityBmaintenanceEnables AI agents to research a text corpus by retrieving exact original and translated passages, verifying quotes and citations against the source, and performing keyword or semantic search with cross-references and commentaries where available.1MIT
- AlicenseAqualityBmaintenanceEnables searching the turath.io Islamic library, reading book pages, and looking up books, authors, and categories from any MCP client. Exposes these capabilities as tools, resources, and prompts, with optional client features like sampling, roots, and elicitation for summarizing and exporting content.12MIT