Turn your documents into searchable knowledge. Retrieve relevant passages with deterministic sub-6ms latency, generate grounded answers when a model is configured, and inspect the evidence behind every response.
Get Started • System Architecture • Glass Box UI • MCP Server • Evaluation Proof • Security Model
Illustrative Architecture Walkthrough: Ingestion sandboxing, sliding-window chunking, dense bi-encoder indexing, vector retrieval, and the dual relevance-gate outcome (τ = 0.35).
- Why DocuMind
- Key Features
- System Architecture
- Product Preview: Glass Box UI
- Quickstart
- Using DocuMind: CLI Workflow
- Model Context Protocol (MCP) Server
- Developer API Reference
- Configuration & Providers
- Empirical Benchmarks & Evaluation
- Security & Operational Controls
- Architecture Decision Records (ADRs)
- Testing & Verification
- Contributing & License
Modern RAG applications face a common failure mode: silent hallucinations masquerading as authoritative answers. When users query a document repository, standard language models frequently invent convincing explanations when relevant source text is missing, straddled across bad chunk boundaries, or semantically ambiguous.
DocuMind treats document intelligence as a deterministic systems engineering problem:
- Deterministic Relevance Gate ($ au = 0.35$): Before calling an LLM, the vector retrieval score is evaluated against an empirically calibrated threshold. If the indexed documents lack sufficient support, DocuMind suppresses generation and cleanly abstains (Exit Code 3).
- Verifiable Source Citations: When an answer is synthesized, every claim is bound to precise chunk anchors (
[S1],[S2]) with matching source filenames and cosine similarity scores. - Local-First & Zero-Key Operation: Fully functional out of the box without cloud API keys or external services. Fast semantic search runs locally via
BAAI/bge-small-en-v1.5embeddings on CPU. - Desktop AI Integration (MCP v0.7.0): Native Model Context Protocol (MCP) server running over
stdio. Desktop assistants like Claude Desktop and Claude Code query your private documents with zero internal LLM calls or network egress. - Glass Box Observability: Every internal operation—chunk token counts, candidate cosine scores, spend ledger reserves, and benchmark telemetry—is exposed through a zero-dependency web interface mounted at
/app.
|
|
|
|
DocuMind enforces a clean separation between offline / on-demand document ingestion and online question-retrieval:
Figure 1: Full DocuMind architecture showing ingestion sandboxing, storage layers, access interfaces, and the deterministic relevance gate.
Documents undergo strict validation, sandboxed extraction, sliding-window chunking, dense vector transformation, and atomic storage commits:
[ PDF / MD / TXT ] ──> [ Magic Byte Check ] ──> [ POSIX Subprocess Sandbox ]
│
▼ (Pure Text Layer)
[ Sliding Window (200w / 30w overlap) ]
│
▼ (Normalized Chunks)
[ Dense Bi-Encoder (BGE-Small 384d) ]
│
▼ (L2 Unit Norm ||v||=1.0)
[ Atomic ChromaDB Commit (Chunk 0 Last) ]
Figure 2: Ingestion pipeline validating binary headers, isolating extraction to POSIX subprocesses, and enforcing atomic commit order.
-
Binary Magic-Byte Validation: Inspects raw file signatures (e.g.
%PDF-1.7) before parsing. Malformed or poisoned files are rejected before invoking complex parsers. -
Subprocess Sandboxing: PDF parsing executes in isolated child processes with address-space caps (
resource.RLIMIT_AS), 500-page limits, and 60-second timeouts. -
Sliding-Window Chunking: Text is partitioned into 200-word tiles with a calibrated 30-word overlap zone, preserving sentence boundaries and guaranteeing zero answer loss (
no_gold = 0on SQuAD 2.0 evaluation sets). -
Dense Bi-Encoder: Local
BAAI/bge-small-en-v1.5embeds each chunk into a 384-dimensional dense vector with$L_2$ unit normalization. - Atomic Storage Commit: Monotonic insertion into persistent ChromaDB with Chunk 0 written last as an atomic commit marker. Interrupted uploads never leak orphaned chunks into the search index.
When a query is received, DocuMind evaluates candidate chunk similarity against the relevance threshold ($ au = 0.35$):
- Multi-Turn Condensation: In conversational mode (
/api/demo/chat/stream), the context condenser synthesizes previous turns into an independent standalone search query. - Neighbor Expansion: For adjacent chunks, DocuMind expands context boundaries to preserve surrounding definitions and formulas.
- Citation Reconciliation: Generated tokens are audited against retrieved chunks. Unverified citations are purged before streaming.
DocuMind includes a built-in, zero-dependency web interface mounted at /app. It provides deep operational visibility into every stage of the document lifecycle:
DocuMind requires Python 3.10+. Dependencies are grouped into modular extras in pyproject.toml:
# Clone the repository
git clone https://github.com/httpmonish/DOCUMIND.git
cd DOCUMIND
# Create and activate a clean virtual environment
python3 -m venv .venv
source .venv/bin/activate
# Choose installation tier:
# Tier A: Core CLI + Local Dense Embeddings (Recommended)
pip install -e ".[embed]"
# Tier B: Full Web Console + REST API
pip install -e ".[embed,api]"
# Tier C: Model Context Protocol (MCP) for Claude Desktop / Claude Code
pip install -e ".[embed,mcp]"
# Tier D: Full Development Suite (Tests, Linting, Audit)
pip install -e ".[dev]"Note
The repository explicitly defines embed, api, mcp, and dev extras. Avoid using .[all] as it is not defined in pyproject.toml.
DocuMind defaults to zero-key retrieval-only mode (DOCUMIND_LLM_PROVIDER=none). To enable natural-language generation, configure your preferred provider in .env:
cp .env.example .envEdit .env to configure your preferred backend:
# Option 1: Zero-Key Retrieval-Only Mode (Default - No API Keys Needed)
DOCUMIND_LLM_PROVIDER=none
# Option 2: Local Free Inference via Ollama (Llama 3, Mistral, Qwen)
DOCUMIND_LLM_PROVIDER=ollama
DOCUMIND_OPENAI_BASE_URL=http://localhost:11434/v1
DOCUMIND_MODEL=llama3
# Option 3: Anthropic Claude (Claude Haiku Default)
DOCUMIND_LLM_PROVIDER=anthropic
ANTHROPIC_API_KEY=<YOUR_ANTHROPIC_API_KEY>
DOCUMIND_MODEL=claude-haiku-4-5-20251001
# Option 4: OpenAI-Compatible Endpoints (Groq, Together, vLLM)
DOCUMIND_LLM_PROVIDER=openai_compat
DOCUMIND_OPENAI_BASE_URL=https://api.groq.com/openai/v1
DOCUMIND_OPENAI_API_KEY=<YOUR_GROQ_API_KEY>
DOCUMIND_MODEL=llama-3.1-8b-instantRun documind doctor to confirm python runtime, vector stores, and model dependencies:
$ documind doctor
[ok] python: Python 3.12.14
[ok] home: Home directory exists at /Users/monish/.documind
[ok] index meta: Embedding model: BAAI/bge-small-en-v1.5
[ok] embedder: sentence-transformers is installed
[ok] vector store: chromadb is installed
[ok] mcp: mcp SDK is installed (v1.29.0)Parse, chunk, and index PDFs, Markdown, and text files into persistent storage:
$ documind index ./docs
indexed operating_systems.md
indexed memory_management.pdf
2 indexed, 0 skipped, 0 failed, 8 chunks in 0.4sRetrieve ranked candidate chunks without invoking any external model:
$ documind search "how does virtual memory paging work?" --top-k 2
[S1] memory_management.pdf#c2 (0.8142) Virtual memory divides addressable space into fixed-size pages...
[S2] operating_systems.md#c5 (0.6420) Paging prevents external fragmentation by mapping non-contiguous blocks...When an LLM provider is configured, ask questions and receive cited answers:
$ documind ask "what is a semaphore?"
A semaphore is a synchronization primitive that uses an integer counter to control access to shared system resources. [S1] When initialized to 1, it functions as a mutual exclusion lock (mutex). [S2]
Sources:
[S1] operating_systems.md#0 (0.8142) A semaphore is a synchronization variable that controls access...
[S2] operating_systems.md#1 (0.6420) Binary semaphores restrict access to a single thread at any moment...Request structured, machine-parseable JSON via stdout:
$ documind ask "what is a semaphore?" --json
{
"text": "A semaphore is a synchronization primitive...",
"outcome": "answered",
"abstain_reason": null,
"citations": [
{
"marker": "S1",
"source": "operating_systems.md",
"chunk_index": 0,
"snippet": "A semaphore is a synchronization variable...",
"score": 0.8142
}
],
"model": "claude-haiku-4-5-20251001",
"usage": { "input_tokens": 1700, "output_tokens": 300 },
"latency_ms": 1120
}When a question cannot be supported by indexed documents, DocuMind cleanly abstains:
$ documind ask "who won the 1994 World Cup final?"
I cannot answer this question based on the indexed documents. No retrieved passages met the minimum relevance threshold (tau = 0.35).
$ echo $?
3| Command | Description |
|---|---|
documind index PATH [--root DIR] [--json] |
Parse, chunk, and index PDFs, text, and markdown files |
documind ask QUESTION [--top-k N] [--json] [--no-llm] [--show-prompt] |
Query documents with grounded citation generation |
documind search QUESTION [--top-k N] [--json] |
Perform pure semantic similarity search returning ranked chunks |
documind ls [--json] |
List all indexed documents and chunk counts |
documind rm SOURCE [--yes] |
Delete an indexed document and its vector records |
documind doctor [--json] |
Run diagnostic environment and index consistency checks |
documind stats [--days N] [--json] |
Analyze query volume, abstention rates, and latency percentiles |
documind mcp config |
Print ready-to-paste Claude Desktop JSON and Claude Code CLI command |
documind mcp serve |
Run the native stdio Model Context Protocol server |
documind serve [--host IP] [--port N] |
Start unified REST API and Glass Box UI web server |
| Code | Status | Meaning |
|---|---|---|
0 |
Success | Answer generated, passages returned, document indexed or deleted |
1 |
Internal Error | Unexpected internal exception (re-run with --debug for traceback) |
2 |
Usage Error | Invalid arguments, top_k out of bounds, or non-interactive rm without --yes
|
3 |
Abstention | Unanswerable query, insufficient retrieval score ($ au < 0.35$), or empty index |
4 |
Input Error | Unreadable document, missing path, or deleting unknown document |
5 |
Configuration | Missing extra dependency or invalid API key |
6 |
Index Error | Corrupt index metadata or mismatched embedding schema |
DocuMind provides a native, secure, read-only MCP server (v0.7.0) allowing desktop AI agents (Claude Desktop and Claude Code) to directly inspect and cite your local knowledge base.
-
Transport: Standard input/output (
stdio) only (no listening network sockets). - Zero Cloud Egress: Client desktop models perform their own synthesis; DocuMind runs purely as a local vector retriever requiring zero internal API keys.
-
Available Tools:
-
search_documents: Retrieve top-$k$ relevant passages with cosine similarity scores. -
get_chunk: Fetch full textual contents and metadata for a specific chunk. -
list_documents: Enumerate all indexed sources with chunk counts. -
index_info: Inspect model name, dimensional topology, and total indexed chunks.
-
Run documind mcp config or add the following to ~/Library/Application Support/Claude/claude_desktop_config.json:
{
"mcpServers": {
"documind": {
"command": "/ABSOLUTE/PATH/TO/DOCUMIND/.venv/bin/documind",
"args": ["mcp", "serve"],
"env": {
"DOCUMIND_HOME": "/Users/<YOUR_USERNAME>/.documind"
}
}
}
}See docs/MCP.md for full configuration, security model, and troubleshooting.
DocuMind enforces a strict boundary between public visitor sessions and authenticated administrative services:
Client Requests
│
┌───────────────────────┴───────────────────────┐
▼ ▼
[ Public Demo Gateway ] [ Admin Microservices ]
• Route: /api/demo/* • Route: /v1/*
• Auth: Session Token Header • Auth: 32+ char X-API-Key
• Storage: Ephemeral SQLite / Hash Dir • Storage: ~/.documind/ Base
• Rate Limit: 30 req/min per IP • Rate Limit: Configurable
The demo gateway provides tenant-isolated document upload, multi-turn chat persistence, and live Server-Sent Events (SSE).
$ curl -s -X POST "http://127.0.0.1:8000/api/demo/session"{
"session_token": "a1b2c3d4e5f60718293a4b5c6d7e8f90...",
"created_at": 1728564000,
"expires_at": 1728650400
}$ curl -N -X POST "http://127.0.0.1:8000/api/demo/chat/stream" -H "X-Session-ID: <SESSION_TOKEN>" -H "Content-Type: application/json" -d '{
"message": "how does the operating system handle context switching?",
"top_k": 3
}'Live stream response format:
event: meta
data: {"conversation_id": "c-4f1b...", "session_id": "...", "model": "claude-haiku-4-5-20251001"}
event: retrieval
data: {"chunks_retrieved": 3, "top_score": 0.8142, "abstained": false}
event: token
data: {"token": "Context "}
event: token
data: {"token": "switching "}
event: citations
data: [{"marker": "S1", "source": "os_kernel.pdf", "chunk_index": 2, "score": 0.8142}]
event: done
data: {"status": "completed", "latency_ms": 640}
All /v1 endpoints require X-API-Key: <DOCUMIND_API_KEY> (hmac.compare_digest).
$ curl -s -X POST "http://127.0.0.1:8000/v1/documents?replace=true" -H "X-API-Key: $DOCUMIND_API_KEY" -F "file=@tests/fixtures/os_notes.md"{
"status": "indexed",
"source": "os_notes.md",
"chunks": 9,
"sha256": "949a699b56a40c113b45340115b4c68eef4d9309ba1f7e1314683cedea1ec1ae"
}$ curl -s -X POST "http://127.0.0.1:8000/v1/ask" -H "X-API-Key: $DOCUMIND_API_KEY" -H "Content-Type: application/json" -d '{"question": "what is a semaphore", "top_k": 2}'$ curl -s -X DELETE "http://127.0.0.1:8000/v1/documents/os_notes.md" -H "X-API-Key: $DOCUMIND_API_KEY"
# Returns HTTP 204 No ContentDocuMind is configured via environment variables or a local .env file:
| Variable | Default | Description |
|---|---|---|
DOCUMIND_HOME |
~/.documind |
Root directory for vector storage, logs, and session databases |
DOCUMIND_LLM_PROVIDER |
none |
Active provider: none, ollama, openai_compat, gemini, anthropic
|
DOCUMIND_MODEL |
Provider default | Target model (e.g. claude-haiku-4-5-20251001, llama3) |
DOCUMIND_MIN_SCORE |
0.35 |
Deterministic relevance gate threshold ($ au$) |
DOCUMIND_CHUNK_SIZE |
200 |
Sliding window chunk size in words |
DOCUMIND_OVERLAP |
30 |
Overlap between adjacent chunks in words |
DOCUMIND_TOP_K |
5 |
Maximum number of candidate chunks passed to context assembler |
DOCUMIND_API_KEY |
(None) | Secret key for administrative /v1/* endpoints ( |
DOCUMIND_MAX_UPLOAD_MB |
50 |
Maximum file upload size limit |
DOCUMIND_MAX_PAGES |
500 |
Maximum page count for PDF text extraction |
DocuMind evaluates retrieval and generation quality against deterministic splits of SQuAD 2.0 evaluation sets. Full benchmark methodologies and statistical distributions are documented in evals/REPORT.md.
- Generator Model:
claude-haiku-4-5-20251001(Prompt Version:p1) - Judge Model:
claude-sonnet-5-5/ Calibrated Evaluator (Judge Version:j1, 100% agreement on calibration set) - Embedder:
BAAI/bge-small-en-v1.5(Cosine similarity, exactNumpyStore)
| Metric | Measured Value | 95% Wilson CI | Target Gate | Status |
|---|---|---|---|---|
| Recall@5 | 1.000 (22/22) | [0.851, 1.000] | PASS | |
| MRR@10 | 0.947 | — | PASS | |
| Faithfulness |
1.000 ( |
[0.851, 1.000] | PASS | |
| Correctness |
1.000 ( |
[0.851, 1.000] | PASS | |
| False-Abstain Rate | 0.000 (0/22) | [0.000, 0.149] | PASS | |
| Off-Topic Abstain Rate | 1.000 (5/5) | [0.566, 1.000] | PASS | |
| Citation Precision | 0.909 (20/22) | [0.722, 0.975] | PASS | |
| Warm Retrieval Latency (p95) | 5.0 ms | — | PASS | |
| Generation Cost / Query | $0.00214 | — | $\le |
PASS |
| SQuAD Impossible Abstain Rate | 0.000 (0/6) | [0.000, 0.390] | FAIL |
Evaluated over BAAI/bge-small-en-v1.5:
| Metric | Measured Score | 95% Wilson CI | Target Gate |
|---|---|---|---|
| Recall@1 | 0.575 | [0.506, 0.641] | Baseline |
| Recall@3 | 0.795 | [0.734, 0.845] | — |
| Recall@5 | 0.840 | [0.783, 0.884] | |
| Recall@10 | 0.930 | [0.886, 0.958] | — |
| MRR@10 | 0.692 | — | |
Chunk Deficit (no_gold) |
0 (0/200) | — | 0 |
| Warm Retrieval Latency | 4.8 ms (p50) / 5.9 ms (p95) | — |
In the interest of technical integrity, DocuMind openly discloses its gate failures:
-
SQuAD Impossible Questions (Adversarial Hard Negatives):
-
Target: Abstain rate
$\ge 0.60$ . Measured:$0.000$ (0/6 on Test) and$0.250$ (1/4 on Dev). -
Root Cause: SQuAD 2.0 unanswerable questions were adversarially designed to share near-identical vocabulary and syntactic structure with indexed paragraphs. The dense bi-encoder scores these passages between
$0.65 - 0.70$ (well above $ au = 0.35$). -
Mitigation Plan: Implementing a cross-encoder reranker stage (
cross-encoder/ms-marco-MiniLM-L-6-v2) to perform token-level interaction scoring before context assembly. Documented indocs/limitations.mdanddocs/ERROR_ANALYSIS.md.
-
Target: Abstain rate
DocuMind treats security and cost controls as first-class architectural invariants. See docs/SECURITY.md and docs/THREAT_MODEL.md for full audit reports.
-
POSIX Subprocess Sandboxing: PDF extraction executes in dedicated worker processes constrained by POSIX
resource.setrlimit(resource.RLIMIT_AS). Processes encountering decompression bombs or infinite loops are terminated after 60 seconds without affecting the host API server. - Two-Phase Spend Ledger: Allocates query budget atomically before initiating provider API calls. Spend is hard-capped at $2.00/day globally and $0.25/day per IP. When limits are exceeded, the system fails closed to local retrieval mode.
-
Token-Bucket Rate Limiting: Enforces 10 asks/min, 5 uploads/hr, and 5 sessions/hr with IPv6
/64subnet aggregation to thwart rotating proxy attacks. -
Tenant Session Isolation: Public demo sessions are segregated into
~/.documind/sessions/{session_hash}/with distinct ChromaDB collections and SQLite conversation logs. -
Constant-Time Authentication: Administrative
/v1/*routes evaluate API keys usinghmac.compare_digestto prevent timing side-channel attacks. -
Strict Stream Discipline: Machine-readable payloads (answers, search results, JSON) are emitted strictly to
stdout. Diagnostic logs, token consumption stats, and warnings route tostderr, ensuring reliable piping (e.g.documind ask ... --json | jq .).
All core engineering decisions are tracked in formal Architecture Decision Records under docs/decisions/:
| ADR | Title | Decision Summary |
|---|---|---|
| 0001 | Embedding Model |
BAAI/bge-small-en-v1.5 for local CPU execution, 384d density, and high MTEB benchmark ranking |
| 0002 | Vector Store | In-memory NumpyStore for exact evaluation; embedded ChromaDB for persistent local storage |
| 0003 | Chunking Topology | 200-word window with 30-word overlap preventing cross-boundary definition loss |
| 0004 | LLM Provider | Claude Haiku default with strict XML source isolation tags; extensible provider protocol |
| 0005 | Interface Boundaries | Administrative /v1/* (HMAC API key) isolated from Public Demo /api/demo/* (sessions) |
| 0006 | Concurrency Model | Non-blocking async FastAPI endpoints with thread-pool delegation for CPU-bound embeddings |
| 0007 | Storage Layout | Quarantined storage under ~/.documind/ with dedicated session subtrees |
| 0008 | Abstention Threshold | Calibrated relevance gate $ au = 0.35$ balancing recall and false abstentions |
| 0009 | CLI Framework | Standard library argparse with subcommands and strict stream separation |
| 0010 | MCP Server | Secure, read-only stdio MCP server for Claude Desktop and Claude Code |
DocuMind maintains a comprehensive test suite across unit, integration, and security boundaries:
# Run full test suite (370+ tests)
.venv/bin/pytest
# Run static analysis and linting checks
.venv/bin/ruff check .
# Run strict type checking across all modules
.venv/bin/mypy documind
# Run security vulnerability audit
.venv/bin/pip-auditContributions are welcome! Please follow our established development practices:
- Maintain documentation integrity and record architectural shifts in new ADRs under
docs/decisions/. - Ensure all changes pass
pytest,ruff check ., andmypy documindwith zero warnings. - Keep public and administrative interface boundaries strictly segregated.
DocuMind is open-source software licensed under the MIT License.

