Skip to main content
Glama
README.md
# Scriptorium (`scriptorium-mcp`)

**English** | [Español](README.es.md)

[![CI](https://github.com/JuanDie778/scriptorium-mcp/actions/workflows/ci.yml/badge.svg)](https://github.com/JuanDie778/scriptorium-mcp/actions/workflows/ci.yml)
[![Python 3.11–3.13](https://img.shields.io/badge/python-3.11%E2%80%933.13-blue)](pyproject.toml)
[![License: Apache-2.0](https://img.shields.io/badge/license-Apache--2.0-green)](LICENSE)
[![MCP Read-Only Server](https://img.shields.io/badge/MCP-Read--Only_Server-0ea5e9)](docs/DESIGN.md)

> **Turn messy, multilingual web archives into citable evidence for your AI agents — local-first, no GPU.**

Scriptorium (`scriptorium-mcp`) is an open-source, retrieval-only Model Context Protocol (MCP) knowledge engine designed for researchers, analysts, and agent builders who need a dedicated, verifiable assistant over a specific historical, literary, or web corpus.

![Scriptorium MCP Live Demo — Cross-lingual EN to RU retrieval, SHA-256 span verification, and multi-axis extraction on CPU](docs/assets/demo/mcp_demo.gif)

*100% live `stdio` tool calls against `scriptorium-mcp serve` over `chekhov_bilingual_v1` (`16` works, `989` chunks) running on local CPU (`paraphrase-multilingual-MiniLM-L12-v2`, `$0` inference API cost). Also available as [1080p MP4](docs/assets/demo/mcp_demo.mp4) and [Poster PNG](docs/assets/demo/mcp_demo_poster.png).*

> [!NOTE]
> **Disambiguation:** Scriptorium (`scriptorium-mcp`) is a retrieval-only MCP engine for web and document archives. It is **not affiliated with eScriptorium** (the OCR/HTR platform for handwritten text recognition).

---

## When to Use Scriptorium (vs. NotebookLM & Web Agents)

**The Tipping Point:** For `< 5` live web pages, a single-prompt web agent is faster; for `5–30` clean, public PDFs or URLs, **NotebookLM** is usually the better fit. Use **Scriptorium** once your project crosses any of these thresholds:
- **Scale & heterogeneity:** `50–1,000+` messy HTML captures, long-form e-books, or mixed formats.
- **Archival friction:** Downed websites recoverable only via the **Wayback Machine** or legacy encodings (`windows-1251`, `koi8-r`, `.fb2.zip`).
- **Strict privacy & zero API cost:** 100% local CPU execution with zero documents uploaded to third-party clouds (`$0` inference API cost).
- **Zero-hallucination auditability:** Every quote must be backed by a deterministic `sha256` hash and exact `char_start:char_end` offsets.
- **Programmatic agent workflows:** Your AI coding or research agent needs structured, read-only MCP tool calls (`search`, `get_source`, `extract_axes`).

| Capability | Single-Prompt Web Agent | NotebookLM | Scriptorium (`scriptorium-mcp`) |
|---|---|---|---|
| **Ideal Corpus Size & State** | `< 5` live web pages | `5–30` clean public PDFs / URLs | `50–1,000+` messy web & book archives |
| **Legacy Encodings & Wayback** | Fails on downed URLs / mojibake | Assumes clean UTF-8 / text | Strict `cp1251`/`koi8-r`/`.fb2.zip` + CDX `id_` |
| **Citation Verifiability** | Page URL only (no offset proof) | UI snippets (not hash-verifiable) | **Deterministic `sha256` + `char_start:char_end`** |
| **Privacy & Inference Cost** | Sends context to cloud LLM | Uploads corpus to Google cloud | **100% local CPU · `$0` API cost** |
| **Cross-Lingual & Acronym Control** | Prompt-dependent | Built-in Q&A, opaque ranking | **Hybrid RRF + language stopwords + acronym boundaries** |
| **Agent Integration (MCP)** | Built into chat UI | Closed web UI (no MCP server) | **4 read-only MCP tools (`stdio`)** |

---

## How It Works in 3 Steps

1. **Ingest & index locally once:** Run `scriptorium-mcp ingest` and `scriptorium-mcp index` on your config (or run `uv run scriptorium-mcp demo` to test end-to-end on the public-domain Chekhov corpus).
2. **Connect your MCP host in 6 lines of JSON:** Add `scriptorium-mcp serve` to Antigravity, Claude Code, Cursor, or any MCP-compatible client (see [Connecting to an MCP Host](#connecting-to-an-mcp-host)).
3. **Ask in your language & verify every quote:** Your agent searches across scripts (`search`), inspects surrounding context (`get_source`), and proves every claim against `sha256` and exact character offsets—never fabricating prose.

---

## Why Scriptorium? (Manifesto & Engineering Safeguards)

Most off-the-shelf RAG pipelines assume clean, UTF-8 PDFs and emit free-form answers without proof. Real archival research faces harder constraints:

1. **Messy, legacy, and multilingual corpora:** Primary sources live across legacy encodings (`windows-1251`, `koi8-r`), HTML templates (`~88%` boilerplate in real web captures), downed websites preserved only in the Wayback Machine, and languages outside the researcher's native fluency.
2. **Zero-tolerance for silent corruption or fabricated citations:** An AI agent analyzing primary sources must return machine-verifiable evidence—not ungrounded summaries or silently corrupted spans.

Scriptorium solves this on standard CPU hardware (`$0` inference API cost) with **two core pillars** and **six field-tested safeguards**:

- **Resilient Local-First ETL:** Normalizes legacy encodings and multi-format archives into clean UTF-8 Markdown under explicit memory governance (`ResourceGuard`).
- **Deterministic Verifiable Citations:** Every indexed chunk carries `doc_id`, `source_url`, `heading_path`, `lang`, exact `char_start:char_end` offsets, temporal provenance (`date_value`, `date_source`, `technical_format`), and the normalized document's `sha256` digest (`content_hash`). The engine **never generates prose**—it returns verified evidence payloads for your host agent (Antigravity, Claude Code, Cursor) to synthesize.

### Six Field-Tested Safeguards (`docs/DESIGN.md § 5.4`)
- **Strict encoding & double-mojibake guard:** Bans silent `errors="replace"` across HTML, text, and e-book connectors, and catches double-decoded `U+FFFD` triplets before indexing.
- **Auto language detection & near-duplicate control:** Infers language from normalized content, filters configurable stubs, and deduplicates by `content_hash` and canonical `normalized_url`.
- **Temporal provenance & format stratification:** Separates verified `published` dates from `first_seen_archive` upper bounds and tags `technical_format` to prevent timeline distortion.
- **Hard embedding-model guard & hash-based chunk IDs:** Persists model name, dimensions, and metric in the corpus manifest, rejecting mismatched queries and preventing duplicate re-indexing.
- **Post-indexing vector-density anomaly check:** Flags anomalous non-adjacent similarity clusters (`cos > 0.99`) caused by corrupted text or boilerplate collapse.
- **Language-aware BM25 & Unicode word boundaries:** Strips query-language stopwords during lexical search and enforces script-aware boundaries for short technical acronyms.

---

## Architecture

```mermaid
flowchart LR
    subgraph CLI["CLI (Human-Controlled Ingestion)"]
        W["connectors/web<br/>robots.txt + delay + cache"]
        A["connectors/wayback"]
        F["connectors/files<br/>HTML, TXT, MD, EPUB, FB2"]
    end
    W --> N["ingest/encoding<br/>strict decode + mojibake guard"]
    A --> N
    F --> N
    N --> M["ingest/html_to_md<br/>Markdown + lang + dedup"]
    M --> C["index/chunker<br/>hierarchical + offsets + sha256"]
    C --> V[("ChromaDB<br/>multilingual dense")]
    C --> B[("BM25<br/>stopwords + lexical")]
    V --> R["retrieve/hybrid<br/>RRF fusion"]
    B --> R
    R --> S["mcp/server<br/>read-only"]
    S --> H["Host Agent<br/>Antigravity, Claude Code, Cursor"]
    R --> E["evaluate/<br/>benchmarks & anomaly gate"]
```

---

## MCP Interface (Read-Only)

Ingestion runs strictly through the human-controlled CLI to enforce polite crawling (`robots.txt`, rate limits) and hardware governance. The MCP server exposes four read-only tools:

| Tool | Inputs | Purpose |
|---|---|---|
| `list_corpora` | — | List indexed corpora, document/chunk counts, languages, and embedding contract metadata. |
| `search` | `query, corpus, k=8, mode="hybrid", lang?` | Run hybrid (BM25 + dense RRF), dense, or lexical retrieval returning scored chunks and citation objects. |
| `get_source` | `chunk_id \| doc_id, window=200` | Fetch the exact normalized substring (`±window` characters) plus full citation metadata to verify claims before quoting. |
| `extract_axes` | `corpus, axes, k=5` | Structured retrieval across user-defined conceptual or analytical axes defined in YAML or passed as a list. |

A companion agent skill is included at [`skills/scriptorium/SKILL.md`](skills/scriptorium/SKILL.md).

---

## Two-Layer Evidence & Benchmarks

Scriptorium separates **why the architecture exists** (real archival friction observed in practice) from **how anyone can audit it end-to-end** (an open, public-domain benchmark):

### Layer 1 — Real-World Field Study (Anonymized)
Scriptorium originated from an archival research commission spanning multi-format, predominantly non-Latin web and book collections with downed URLs and legacy encoding failures. Every safeguard in [`docs/DESIGN.md`](docs/DESIGN.md) traces directly to measured incidents from that commission (including silent e-book double-mojibake, mixed embedding spaces, and archive-vs-publication date skew).
- **Published field study:** Read the complete anonymized English study and 10 empirical charts at [`docs/field_study.md`](docs/field_study.md) (159 independently audited metrics, zero-leak privacy verified).

### Layer 2 — Reproducible Public-Domain Benchmark (`chekhov_bilingual_v1`)
> [!TIP]
> **Published & Reproducible (Milestone M4):** Full CPU benchmark results over 16 parallel Russian/English Anton Chekhov stories (**Wikisource RU** pinned `oldid` + **Project Gutenberg EN** Constance Garnett, 989 chunks, 32 curated queries) are published in [`docs/benchmarks.md`](docs/benchmarks.md). Reproduce locally with `uv run scriptorium-mcp demo` (`$0` API cost).

| Benchmark Dimension | Metric | Baseline Comparison | Observed Result (`chekhov_bilingual_v1`) |
|---|---|---|---|
| **Retrieval Quality** | `Recall@5`, `Recall@10`, `MRR@10` | BM25-only (`62.5%` Doc R@5 / `0.6042` MRR@10) vs. Dense-only (`93.8%` / `0.8617`) vs. **Hybrid RRF (`k=60`)** | **Hybrid: `96.9%` Doc R@5, `0.9531` Doc MRR@10, `90.6%` Passage R@10, `0.7970` Passage MRR@10** (`91.7%` Cross-Lingual EN→RU Doc R@5 / `83.3%` Passage R@5 vs `0.0%` BM25) |
| **Citation Verifiability** | Deterministic exact-span & `sha256` match rate | Target: `100%` verifiable spans + Gate 5 `cos > 0.99` audit | **`100.0%`** (`989/989` corpus chunks + `1190/1190` live query hits; `0` Gate 5 anomalies) |
| **ETL Encoding & Corruption Resilience** | Exact-match recovery rate, CER & double-mojibake recall | Naive UTF-8 (`25.0%` exact, `0.464` CER) vs. `<meta>`+`chardet` (`37.5%` exact, `0.363` CER) vs. Scriptorium | **`100.0%` exact recovery, `0.000000` CER, `100.0%` double-mojibake recall, `0.0%` false quarantines** |
| **Hardware Efficiency** | Process RSS peak RAM, CPU latency & index footprint | Local CPU-only (`paraphrase-multilingual-MiniLM-L12-v2`), `$0.00` API cost | **Hybrid warm latency `46.27 ms` p50 (`52.60 ms` p90), `1435.9 MB` peak RSS, `16.38 MB` index disk footprint (`18.18x`)** |

---

## Quickstart

Requires Python `3.11–3.13` and [`uv`](https://docs.astral.sh/uv/).

```bash
# Install dependencies (pinned to Python 3.12 via .python-version)
uv sync --dev

# Inspect CLI and validate the sample config
uv run scriptorium-mcp --help
uv run scriptorium-mcp version
uv run scriptorium-mcp validate-config configs/example.yaml

# Run the reproducible public-domain bilingual Chekhov demo & CPU benchmark ($0 API cost)
uv run scriptorium-mcp demo --output-json data/corpora/chekhov_bilingual_v1/benchmark_report.json

# Run lint and offline unit tests
uv run ruff check .
uv run pytest -v
```

### Connecting to an MCP Host

Configure your MCP client (Antigravity, Claude Code, Cursor, etc.) to launch the read-only stdio server from your cloned repository:

```json
{
  "mcpServers": {
    "scriptorium": {
      "command": "uv",
      "args": ["--directory", "/path/to/scriptorium-mcp", "run", "scriptorium-mcp", "serve"]
    }
  }
}
```

*(Once published to PyPI, this simplifies to `"command": "uvx", "args": ["scriptorium-mcp", "serve"]`.)*

---

## Roadmap

- [x] **M0 — Scaffold:** Package structure, `Citation` & `Chunk` contracts, config validation, read-only MCP server skeleton, pytest & GitHub Actions CI.
- [x] **M0.5 — Narrative Alignment & M1 Blueprint:** Two-layer validation narrative, extended `Citation`/`CorpusInfo` provenance contracts, six field-tested engineering gates, [`docs/M1_PLAN.md`](docs/M1_PLAN.md), and Node 24 CI.
- [x] **M1 — Resilient Ingestion:** `files`, `web`, and `wayback` connectors, process-RSS `ResourceGuard`, strict encoding + double-mojibake guard, HTML→Markdown converter, and ETL CER benchmark.
- [x] **M2 — Indexing & Hybrid Retrieval:** Hierarchical offset-preserving chunker (`chunk_id` hashes), hard embedding-model guard, ChromaDB + stopword-aware `bm25s`, RRF fusion, post-index vector anomaly check, and 100% citation verifiability.
- [x] **M3 — Full MCP Wiring:** End-to-end tool execution backed by persisted corpora + `SKILL.md` host verification.
- [x] **M4 — Reproducible Evaluation & Demo:** `scriptorium-mcp demo` (`chekhov_bilingual_v1`), 32-query monolingual & cross-lingual golden set, and published CPU benchmarks ([`docs/benchmarks.md`](docs/benchmarks.md)).
- [ ] **M5 — Post-MVP Extensions:** Generic forum (phpBB/SMF) and blog connectors, optional LLM-as-a-Judge faithfulness suite, and published time-saved case study.

See [`docs/DESIGN.md`](docs/DESIGN.md) for the technical specification and [`docs/M1_PLAN.md`](docs/M1_PLAN.md) for the M1 implementation plan.

---

## License

Licensed under the [Apache License 2.0](LICENSE).

TDQS

B3.2/5.0

Scored across 4 tools

Disambiguation4/5

Each tool targets a distinct stage of the retrieval workflow: enumerate corpora, free-text search, fetch an exact verified span, and aggregate evidence by axes. The only mild overlap is between search and extract_axes, both of which retrieve evidence, but the descriptions make the difference (scored chunks vs. structured axis-grouped evidence) clear enough.

Naming Consistency4/5

Three of four tools follow a verb_noun pattern (list_corpora, get_source, extract_axes) in consistent snake_case. The bare verb 'search' is a minor deviation but is unambiguous and readable in context.

Tool Count4/5

Four tools is a lean but coherent surface for a read-only corpus retrieval server; each tool covers a distinct step (discover, search, verify, structure). It is slightly minimal, but nothing feels redundant or missing for the core loop.

Completeness4/5

The read path is fully covered: list corpora, search, fetch verified source text, and structured extraction, which closes the loop from discovery to citation. Write-side operations (indexing or creating corpora) appear intentionally out of scope, leaving only minor gaps such as metadata-only or filtered listing.

Maintenance

ActivityMaintained
ResponsivenessNo recent community issues