Metadata-Version: 2.4
Name: ebook-rs
Version: 0.19.4
Classifier: Development Status :: 5 - Production/Stable
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Rust
Classifier: Programming Language :: Python :: Implementation :: CPython
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.8
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Classifier: Topic :: Text Processing :: Markup
License-File: LICENSE
Summary: Pure Rust multi-format eBook engine (EPUB 2/3, MOBI, AZW3, KFX, FB2, LIT, CBZ, PDF, ODT, DOCX, RTF, TXT, MD) featuring Mozilla UniFFI, Readium CFI/LCP, SpeechSynthesis TTS sync, AI RAG BM25 chunking, and Universal Exporter
Keywords: epub,reader,ebook,parser,cfi,mobi,kfx,pdf,rag
Home-Page: https://sv-stark.github.io/ebook-rs/
Author: SV-Stark
License: MIT
Requires-Python: >=3.8
Description-Content-Type: text/markdown; charset=UTF-8; variant=GFM
Project-URL: Changelog, https://github.com/SV-stark/ebook-rs/blob/main/CHANGELOG.md
Project-URL: Documentation, https://sv-stark.github.io/ebook-rs/
Project-URL: Homepage, https://sv-stark.github.io/ebook-rs/
Project-URL: Issues, https://github.com/SV-stark/ebook-rs/issues
Project-URL: Repository, https://github.com/SV-stark/ebook-rs

<div align="center">

# 📖 `ebook-rs`

**High-Performance Pure-Rust Multi-Format eBook Parsing & Reader Engine**

[![Crates.io Version](https://img.shields.io/crates/v/ebook-rs.svg?style=flat-square&color=orange)](https://crates.io/crates/ebook-rs)
[![Total Downloads (Crates.io + PyPI + GitHub Releases / binstall)](https://img.shields.io/endpoint?url=https%3A%2F%2Fraw.githubusercontent.com%2FSV-stark%2Febook-rs%2Fbadges%2Fdownloads.json&style=flat-square)](https://crates.io/crates/ebook-rs)
[![PyPI Version](https://img.shields.io/pypi/v/ebook-rs.svg?style=flat-square&logo=python&label=pypi)](https://pypi.org/project/ebook-rs/)
[![Docs.rs](https://img.shields.io/docsrs/ebook-rs?style=flat-square&logo=docs.rs)](https://docs.rs/ebook-rs)
[![Documentation](https://img.shields.io/badge/docs-sv--stark.github.io%2Febook--rs-0284c7?style=flat-square&logo=gitbook&logoColor=white)](https://sv-stark.github.io/ebook-rs/)
[![CI Build Status](https://img.shields.io/github/actions/workflow/status/SV-stark/ebook-rs/ci.yml?branch=main&style=flat-square&label=build)](https://github.com/SV-stark/ebook-rs/actions)
[![Fuzzing & Chaos Resilience](https://img.shields.io/badge/Fuzzing-Continuous%20libFuzzer%20%2B%20Chaos-informational?style=flat-square&logo=rust)](https://github.com/SV-stark/ebook-rs/actions)
[![Rust Edition](https://img.shields.io/badge/rust-2024%20%7C%201.88%2B-informational?style=flat-square&logo=rust)](https://www.rust-lang.org/)
[![License: MIT](https://img.shields.io/crates/l/ebook-rs.svg?style=flat-square&color=green)](LICENSE)

*Pure Rust multi-format eBook engine supporting **30 input & 27 output formats** (**EPUB 2/3, KEPUB, KFX, MOBI, AZW3, PDB, FB2, LIT, CBZ, PDF, DOCX, ODT, RTF, PPTX, HTML, HTMLZ, TXT, TXTZ, MD, OEB, ZIP, TCR, PMLZ, RB, Typst, AsciiDoc, Org, RST, LaTeX**) featuring Mozilla UniFFI mobile bindings, Readium CFI locators & LCP DRM, SpeechSynthesis TTS word sync, CJK vertical & RTL pagination, PDF two-column reflow, lossless EPUB3 optimizer, AI RAG BM25 chunking, zero-copy search, Zstd caching, Python/WASM bindings, and a native MCP server.*

</div>

---

## 📋 Table of Contents
- [⚡ Feature Parity Matrix](#-feature-parity-matrix)
- [📊 Conversion Benchmarks](#-format-conversion-benchmark-ebook-rs-vs-calibre-ebook-convert)
- [🛡️ Battle-Tested Resilience & Continuous Fuzzing](#️-battle-tested-resilience--continuous-fuzzing)
- [📦 Installation](#-installation)
- [🚀 Quick Start (Rust)](#-quick-start-rust)
- [🐍 Python Bindings](#-python-bindings)
- [🤖 Model Context Protocol (MCP) Server](#-model-context-protocol-mcp-server)
- [💻 CLI Usage](#-cli-usage)
- [📚 Complete API Reference](#-complete-api-reference)
- [🏗️ Architecture Overview](#-architecture-overview)
- [⚠️ Known Limitations](#️-known-limitations)
- [🤝 Contributing](#-contributing)
- [🙏 Acknowledgments](#-acknowledgments--credits)
- [📜 License](#-license)

---

## ⚡ Feature Parity Matrix

### 📂 Format Support

| Feature | 🚀 `ebook-rs` | 📦 `epub.js` | 📖 `foliate-js` | 🦀 `rbook` |
|---|:---:|:---:|:---:|:---:|
| **EPUB 2, EPUB 3 & KEPUB** | ✅ Full Read & Write (OPF, NCX/NAV, Kobo `koboSpan`) | ✅ EPUB 2/3 | ✅ EPUB 2/3 | ✅ EPUB 2/3 |
| **EPUB 3 Fixed-Layout (FXL)** | ✅ 2-page spread renderer | ✅ Yes | ✅ Yes | ❌ No |
| **Amazon KFX (KF10) Read & Write** | ✅ Clean-room Ion 1.0 `CONT` v2 (fonts, `font-family`, bidi/RTL, tables, links, TOC, cover/images) | ❌ No | ❌ No | ❌ No |
| **MOBI & AZW3 (KF8) Read & Write** | ✅ Native PalmDOC LZ77 + EXTH + image records | ❌ No | ✅ Read-only | ❌ No |
| **FB2 (FictionBook 2) Read & Write** | ✅ Native XML + base64 `<binary>` images | ❌ No | ✅ Read-only | ❌ No |
| **LIT (Microsoft Reader) Support** | ✅ Native ITOL/ITLS parser | ❌ No | ❌ No | ❌ No |
| **CBZ (Comic Book ZIP) Support** | ✅ Native ZIP pages + prefetch | ❌ No | ✅ Read-only | ❌ No |
| **PDF Read & Write** | ✅ `unpdf` (`pdf` feature) + zero-dep pure-Rust PDF 1.4 writer | ❌ No | ❌ No | ❌ No |
| **DOCX, ODT & PPTX Read & Write** | ✅ Native OOXML & ODF 1.2 + embedded images & slides | ❌ No | ❌ No | ❌ No |
| **RTF Read & Write** | ✅ Native Control Words, `\uN?` Unicode & `\pict` images | ❌ No | ❌ No | ❌ No |
| **HTML, HTMLZ, TXTZ, OEB & ZIP** | ✅ Full Read & Write (Calibre-compatible packages) | ❌ No | ❌ No | ❌ No |
| **PDB, TCR, PMLZ & Rocket eBook (RB)** | ✅ Pure-Rust binary/dictionary Read & Write | ❌ No | ❌ No | ❌ No |
| **TXT, MD, Typst, ADOC, Org, RST, TeX** | ✅ Full Read & Write + frontmatter, wikilinks & callouts | ❌ No | ❌ No | ❌ No |
| **Auto Format Detection** | ✅ Magic-byte + container inspection | ❌ No | ✅ Basic | ❌ No |

### 🧭 Navigation, Rendering & Security

| Feature | 🚀 `ebook-rs` | 📦 `epub.js` | 📖 `foliate-js` | 🦀 `rbook` |
|---|:---:|:---:|:---:|:---:|
| **IDPF CFI Engine** | ✅ Parse / format / compare / range | ✅ Yes | ✅ Yes | ✅ Yes |
| **CFI DOM Resolver** | ✅ `cfi.resolve_dom_path(html)` | ✅ Yes | ✅ Yes | ❌ No |
| **Readium CFI Unified Locator** | ✅ Full model | ✅ Yes | ✅ Yes | ❌ No |
| **Location / Reading Progress** | ✅ `Book::locations_from_sections()` | ✅ Yes | ✅ Yes | ✅ Yes |
| **SpeechSynthesis TTS Word Synchronizer** | ✅ `tokenize_tts_words()` token spans | ❌ No | ❌ No | ❌ No |
| **SMIL Media Overlays (Sync)** | ✅ NPT clock parser + karaoke highlight | ✅ Yes | ✅ Yes | ❌ No |
| **EPUB NCX / NAV TOC Parsing** | ✅ Deep recursive nav tree | ✅ Yes | ✅ Yes | ✅ Yes |
| **Popup Footnotes & Endnotes** | ✅ `Footnote` resolver (`epub:type="noteref"`) | ❌ No | ✅ Yes | ❌ No |
| **RTL & CJK Vertical Writing** | ✅ `direction: rtl` + `vertical-rl` | ✅ Yes | ✅ Yes | ❌ No |
| **Viewport Meta & Reflow Paginator** | ✅ `ReflowPaginator` + zero-alloc viewport | ✅ Yes | ✅ Yes | ❌ No |
| **Font Deobfuscation (IDPF / Adobe)** | ✅ `FontDeobfuscator` XOR | ❌ No | ✅ Yes | ❌ No |
| **Readium LCP DRM License Parser** | ✅ `LcpLicense` + AES-256-CBC decryption | ❌ No | ❌ No | ❌ No |
| **Security & DoS Hardening** | ✅ XSS/URI sanitizer, zip-bomb budget, XML depth & regex bounds | ❌ No | ❌ No | ❌ No |
| **Legacy Non-UTF-8 & Entity Decoding** | ✅ Auto Win-1252/Shift-JIS/GBK + single-pass entities | ❌ No | ❌ No | ❌ No |

### 🔍 Search, Analytics & AI RAG

| Feature | 🚀 `ebook-rs` | 📦 `epub.js` | 📖 `foliate-js` | 🦀 `rbook` |
|---|:---:|:---:|:---:|:---:|
| **Model Context Protocol (MCP 2024-11-05)** | ✅ Built-in Stdio & HTTP Server | ❌ No | ❌ No | ❌ No |
| **Okapi BM25 Relevance Scoring** | ✅ `rank_chunks_bm25()` TF-IDF | ❌ No | ❌ No | ❌ No |
| **AI & RAG Chunking Engine** | ✅ `to_rag_chunks()` + CFI citations | ❌ No | ❌ No | ❌ No |
| **SIMD Accelerated Full-Text Search** | ✅ SIMD + `memchr` match scanning | ❌ No | ✅ Basic | ❌ No |
| **Bounded Regex Search** | ✅ `Book::search_regex()` | ❌ No | ❌ No | ❌ No |
| **Search Context Snippets** | ✅ `<mark>` highlights + XSS guard | ❌ No | ✅ Yes | ❌ No |
| **Readium Search JSON Export** | ✅ Readium-compliant JSON | ❌ No | ✅ Yes | ❌ No |
| **NLP Reading Analytics** | ✅ Word count / reading time / complexity | ❌ No | ❌ No | ❌ No |
| **Auto Language Detection** | ✅ `detect_language` (`whatlang`) | ❌ No | ❌ No | ❌ No |

### 🌐 Interoperability, Exporters & Performance

| Feature | 🚀 `ebook-rs` | 📦 `epub.js` | 📖 `foliate-js` | 🦀 `rbook` |
|---|:---:|:---:|:---:|:---:|
| **Universal 27-Format Exporters** | ✅ `Book::export_format_bytes()` (EPUB, KEPUB, KFX, MOBI, AZW3, PDB, PDF, DOCX, ODT, RTF, PPTX, FB2, HTML/Z, TXT/Z, MD, OEB, ZIP, TCR, PMLZ, RB, Typst, ADOC, Org, RST, TeX) | ❌ No | ❌ No | ❌ No |
| **Lossless EPUB 3 Optimizer & Validator** | ✅ HTML/asset minifier + structural validator | ❌ No | ❌ No | ❌ No |
| **Academic Citations & Fingerprinting** | ✅ APA / MLA / Chicago / BibTeX + `BookFingerprint` | ❌ No | ❌ No | ❌ No |
| **OPDS 1.2 / 2.0 Catalog Client** | ✅ `opds` feed parser & download resolver | ❌ No | ✅ Yes | ❌ No |
| **Lazy Hydration & Streaming ZIP** | ✅ On-demand sections + HTTP Range ZIP | ✅ Partial | ✅ Partial | ✅ Partial |
| **Zstd Compressed State Caching** | ✅ Instant `export_zstd_cache()` | ❌ No | ❌ No | ❌ No |
| **Mobile, Python & C Bindings** | ✅ Mozilla UniFFI (Swift/Kotlin) + PyO3 + C ABI | ❌ No | ❌ No | ❌ No |
| **WASM SDK & Web Component** | ✅ `WasmBook` + `<ebook-reader>` | ✅ JS native | ✅ JS native | ❌ No |
| **W3C Web Annotation (JSON-LD)** | ✅ Full CRUD + `to_w3c_json` | ❌ No | ✅ Yes | ❌ No |
| **Readium WebPub Manifest Export** | ✅ `book.to_webpub_manifest()` | ❌ No | ✅ Yes | ❌ No |

---

## ⚡ Format Conversion Benchmark (`ebook-rs` vs Calibre `ebook-convert`)

Empirically measured 3-run median conversion benchmark on **ebook-rs v0.19.0** (`--release`) vs **Calibre 9.18** (`ebook-convert` / `KFX Input 2.34.2` / `KFX Output` + Kindle Previewer) on Windows 11 / AMD Ryzen 9 / PCIe 4.0 NVMe:

### Core & Legacy Formats → EPUB 3

| Conversion | Sample Book | 🚀 `ebook-rs` | 🐍 Calibre 9.18 | Speedup | Image Assets Extracted | Chapter Sections | Output Parity |
|---|---|:---:|:---:|:---:|:---:|:---:|:---:|
| **DOCX → EPUB** | *Alice in Wonderland (DOCX)* | **0.16s** ⚡ | 2.95s | **18.1× Faster** | 37 / 37 (100%) ✅ | 13 chapters | Fully Matched |
| **TXT → EPUB** | *Alice in Wonderland (TXT)* | **0.11s** ⚡ | 1.98s | **17.8× Faster** | — | 1 chapter | Fully Matched |
| **CBZ → EPUB** | *Jumbo Comics 099 (21 MB CBZ)* | **0.83s** ⚡ | 12.87s | **15.5× Faster** | 52 / 52 (100%) ✅ | 52 pages | Fully Matched |
| **TCR → EPUB** | *Alice in Wonderland (TCR)* | **0.14s** ⚡ | 2.08s | **15.0× Faster** | — | 1 chapter | Fully Matched |
| **AZW3 (KF8) → EPUB** | *Alice in Wonderland (AZW3)* | **0.15s** ⚡ | 2.19s | **14.7× Faster** | 38 / 38 (100%) ✅ | 14 chapters | Fully Matched |
| **PDB → EPUB** | *Alice in Wonderland (PalmDOC PDB)* | **0.15s** ⚡ | 2.15s | **14.7× Faster** | — | 1 chapter | Fully Matched |
| **FB2 → EPUB** | *Alice in Wonderland (FB2)* | **0.15s** ⚡ | 1.77s | **11.9× Faster** | 37 / 37 (100%) ✅ | 15 chapters | Fully Matched |
| **PMLZ → EPUB** | *Alice in Wonderland (PMLZ)* | **0.16s** ⚡ | 1.87s | **11.6× Faster** | 37 / 37 (100%) ✅ | 1 chapter | Fully Matched |
| **HTMLZ → EPUB** | *Alice in Wonderland (HTMLZ)* | **0.19s** ⚡ | 1.97s | **10.4× Faster** | 38 / 38 (100%) ✅ | 1 chapter | Fully Matched |
| **RB → EPUB** | *Alice in Wonderland (RB)* | **0.21s** ⚡ | 2.02s | **9.8× Faster** | 37 / 37 (100%) ✅ | 1 chapter | Fully Matched |
| **TXTZ → EPUB** | *Alice in Wonderland (TXTZ)* | **0.14s** ⚡ | 1.25s | **9.1× Faster** | 1 / 1 (100%) ✅ | 1 chapter | Fully Matched |
| **LIT → EPUB** | *Alice in Wonderland (LIT)* | **0.24s** ⚡ | 1.99s | **8.4× Faster** | 37 / 37 (100%) ✅ | 21 chapters | Fully Matched |
| **MOBI → EPUB** | *Alice in Wonderland (MOBI)* | **0.27s** ⚡ | 2.19s | **8.0× Faster** | 38 / 38 (100%) ✅ | 17 chapters | Fully Matched |
| **KFX → EPUB** | *Alice in Wonderland (Calibre/kfxgen KFX)* | **0.40s** ⚡ | 3.05s *(KFX Input)* | **7.6× Faster** | 38 / 38 (100%) ✅ | 16 chapters | Full Ion Text, Styles & Assets *(17.1× on `ebook-rs` KFX)* |
| **RTF → EPUB** | *Alice in Wonderland (RTF)* | **0.58s** ⚡ | 2.86s | **4.9× Faster** | 36 / 36 (100%) ✅ | 15 chapters | All 36 images preserved *(Calibre extracts 1)* |

### EPUB 3 → Multi-Format Exporters (Bidirectionally Verified with Calibre 9.18)

| Conversion | Sample Book | 🚀 `ebook-rs` | 🐍 Calibre 9.18 | Speedup |
|---|---|:---:|:---:|:---:|
| **EPUB → KFX** | *Alice in Wonderland (EPUB 3)* | **0.31s** ⚡ | 60.99s *(KFX Output + KP3)* | **~195× Faster** |
| **EPUB → PDF** | *Alice in Wonderland (EPUB 3)* | **0.26s** ⚡ | 15.62s *(Qt WebEngine)* | **60.3× Faster** |
| **EPUB → TXTZ** | *Alice in Wonderland (EPUB 3)* | **0.16s** ⚡ | 1.92s | **11.7× Faster** |
| **EPUB → RB** | *Alice in Wonderland (EPUB 3)* | **0.23s** ⚡ | 2.65s | **11.5× Faster** |
| **EPUB → RTF** | *Alice in Wonderland (EPUB 3)* | **0.25s** ⚡ | 2.41s | **9.8× Faster** |
| **EPUB → PMLZ** | *Alice in Wonderland (EPUB 3)* | **0.26s** ⚡ | 2.39s | **9.1× Faster** |
| **EPUB → TCR** | *Alice in Wonderland (EPUB 3)* | **0.36s** ⚡ | 3.16s | **8.8× Faster** |
| **EPUB → FB2** | *Alice in Wonderland (EPUB 3)* | **0.22s** ⚡ | 1.90s | **8.5× Faster** |
| **EPUB → ZIP** | *Alice in Wonderland (EPUB 3)* | **0.25s** ⚡ | 1.98s | **7.8× Faster** |
| **EPUB → MOBI** | *Alice in Wonderland (EPUB 3)* | **0.36s** ⚡ | 2.64s | **7.3× Faster** |
| **EPUB → HTMLZ** | *Alice in Wonderland (EPUB 3)* | **0.26s** ⚡ | 1.87s | **7.2× Faster** |
| **EPUB → AZW3** | *Alice in Wonderland (EPUB 3)* | **0.33s** ⚡ | 1.91s | **5.8× Faster** |
| **EPUB → DOCX** | *Alice in Wonderland (EPUB 3)* | **0.69s** ⚡ | 3.85s | **5.6× Faster** |
| **EPUB → PDB** | *Alice in Wonderland (EPUB 3)* | **0.35s** ⚡ | 1.70s | **4.9× Faster** |
| **EPUB → OEB** | *Alice in Wonderland (EPUB 3)* | **0.35s** ⚡ | 1.71s | **4.8× Faster** |
| **EPUB → KEPUB / ODT / PPTX / HTML / MD / Typst / ADOC / Org / RST / TeX** | *Alice in Wonderland (EPUB 3)* | **0.24s–0.27s** ⚡ | — *(Native pure-Rust)* | **Sub-300ms** |

---

## 🛡️ Battle-Tested Resilience & Continuous Fuzzing

`ebook-rs` is built to be the most resilient eBook engine in existence, specifically engineered to withstand the dirty long tail of corrupted, malformed, and non-spec files found across Project Gutenberg, Archive.org, and legacy digital archives:

- **Graceful Error Handling**: Every format boundary validates lengths and magic bytes and returns
  `Result<Book, EbookError>` instead of panicking. This is enforced by CI (`cargo test`) and a
  scheduled fuzz/chaos workflow, and regression-tested in `tests/test_security_regressions.rs`.
  See [`SECURITY.md`](SECURITY.md#threat-model) for the threat model and the known residual risks
  (notably slow-loris, which `tiny_http` cannot fully mitigate).
- **Continuous Coverage-Guided Fuzzing**: Continuous LLVM `libFuzzer` (`cargo-fuzz`) runs mutate raw byte streams over millions of iterations against `Book::from_bytes` and CFI locators.
- **Mass Corpus Stress Testing**: A dedicated chaos-testing runner (`examples/corpus_stress.rs`) evaluates real-world books across all 14 supported formats, injecting byte truncations (10% to 90%), zeroed headers, and bit-flipped noise.

### 📊 Real-World Resilience Scorecard *(Re-verified on v0.18.7)*

| Test Suite / Corpus | Formats / Vectors Evaluated | Ingestion Status | Panics / Crashes | Error Handling |
| :--- | :--- | :--- | :--- | :--- |
| **Real-World Sample Suite** (`corpus_stress` + `test_real_samples_golden`) | 14 files: EPUB2, EPUB3, KEPUB, MOBI, AZW3, KFX, FB2, LIT, CBZ, CBR, PDF, DOCX, RTF, TXT | ✅ 13/13 supported ingested (1.15s total) + CBR cleanly rejected | **0 Panics** | Graceful `Result` |
| **Chaos Mutation Sweep** (Header Zeroing, 10%/25%/50%/90% Truncation, Bit-Flips) | 84 mutated streams across all 14 samples | ⚠️ 45 fuzzy-recovered, 39 rejected (1.21s total) | **0 Panics** | Clean `Err(InvalidFormat)` |
| **Structured-Adversarial Sweep** (`tests/test_security_regressions.rs`) | 15 tests: deep XML nesting, decompression budget, LCP dates, hostile token counts, path traversal, ZIP EOCD, XSS/URI guards | ✅ 15/15 passed (0.02s) | **0 Panics** | Clean `Err` / Bounded |
| **KFX Fidelity & Round-Trip Suite** (`tests/test_kfx_issues.rs`) | 7 tests: Ion v2 IDs, images, TOC, links, RTL/bidi, tables, embedded fonts + `font-family` cascade, cover | ✅ 7/7 passed (0.03s) | **0 Panics** | Verified via KFX Input |
| **Coverage-Guided Fuzzing (libFuzzer)** | Arbitrary byte streams | Millions of mutations (scheduled CI) | **0 Panics** | 100% Memory-Safe |

These figures are snapshots from the v0.18.7 runs above, not a standing guarantee — they are
regression-tested in `tests/test_security_regressions.rs` and `tests/test_real_samples_golden.rs`,
and re-measured by the scheduled fuzz/chaos workflow.

#### Run the Automated Gutenberg Stress Test:
```bash
# 1. Automatically fetch 25 Project Gutenberg classics:
./scripts/fetch_gutenberg.sh 25 corpus/gutenberg      # Linux / macOS
pwsh scripts/fetch_gutenberg.ps1 -Count 25           # Windows

# 2. Run parallel resilience & chaos stress test:
cargo run --release --all-features --example corpus_stress -- corpus/gutenberg

# Or stress-test any local library directory:
cargo run --release --all-features --example corpus_stress -- /path/to/your/ebooks
```

---

## 📦 Installation

Add `ebook-rs` to your `Cargo.toml`:

```toml
[dependencies]
ebook-rs = "0.19.0"
```

Or install via `cargo`:

```bash
cargo add ebook-rs
```

For Python projects:

```bash
pip install ebook-rs
```

---

## 🚀 Quick Start (Rust)

```rust
use ebook_rs::{Book, SearchEngine, RagChunkConfig};

fn main() -> Result<(), Box<dyn std::error::Error>> {
    // 1. Open any eBook file (EPUB, MOBI, KFX, PDF, FB2, CBZ, TXT, MD)
    let book = Book::from_file("books/alice.epub")?;

    println!("📖 Title: {}", book.metadata().title);
    println!("✍️ Author: {}", book.metadata().creators.join(", "));
    println!("📚 Total Sections: {}", book.sections.len());

    // 2. Read chapter section content
    let section = book.get_section(0)?;
    println!("Chapter 1 Plain Text:\n{}", section.plain_text);

    // 3. Perform zero-allocation SIMD full-text search
    let results = book.search("Rabbit");
    for hit in results.iter().take(3) {
        println!("[Section {}] CFI: {}\nSnippet: {}\n", hit.spine_index, hit.cfi, hit.snippet);
    }

    // 4. Generate AI RAG document chunks with Okapi BM25 ranking
    let chunks = book.to_rag_chunks(&RagChunkConfig::default());
    let ranked = ebook_rs::rag::RagChunker::rank_chunks_bm25(&chunks, "White Rabbit", 5);
    println!("Top RAG Chunk Score: {}", ranked[0].bm25_score);

    Ok(())
}
```

---

## 🐍 Python Bindings

```python
from ebook_rs import Book

# Load eBook file
book = Book.open("sample.epub")

print(f"Title: {book.title}")
print(f"Authors: {book.authors}")
print(f"Sections: {book.section_count}")

# Read Section HTML & RAG JSON
html = book.get_section_html(0)
rag_json = book.to_rag_chunks_json(max_tokens=512)
```

---

## 🤖 Model Context Protocol (MCP) Server

`ebook-rs` includes a built-in **Model Context Protocol (MCP 2024-11-05)** JSON-RPC 2.0 server, available over **`stdio`** or as an **HTTP POST** endpoint (`/api/mcp`) on the reader server. Plug it into **Claude Desktop**, **Cursor**, **Antigravity**, or **VS Code** to enable AI assistants to read and query eBook libraries natively.

### Run Server:
```bash
ebook-rs mcp
```

The stdio server is sandboxed to the current working directory by default. To grant access to a
specific library, pass `--sandbox-root <dir>`:

```bash
ebook-rs mcp --sandbox-root /path/to/ebooks
```

> **Security:** MCP tools that read or write files (`get_metadata`, `read_section`, `convert_ebook`,
> ...) are **refused** unless a sandbox root is configured, and `convert_ebook` can only write inside
> it. See [`SECURITY.md`](SECURITY.md).

### Claude Desktop / Cursor Setup (`claude_desktop_config.json`):
```json
{
  "mcpServers": {
    "ebook-rs": {
      "command": "ebook-rs",
      "args": ["mcp"]
    }
  }
}
```

> See detailed MCP documentation in [`docs/MCP_SERVER.md`](docs/MCP_SERVER.md).

---

## 💻 CLI Usage

The `ebook-rs` executable provides several utility sub-commands:

```bash
# Parse metadata and TOC
ebook-rs parse sample.epub

# Perform full-text search
ebook-rs search sample.epub "query"

# Launch Model Context Protocol (MCP) AI server
ebook-rs mcp

# Convert formats (MOBI/FB2/PDF -> EPUB / KFX / RAG JSON)
ebook-rs convert sample.mobi output.epub

# Launch local HTTP Reader web server (Port 8080 via $PORT, default 8080)
ebook-rs serve sample.epub

# Protect the HTTP API with a bearer token (required for anything beyond localhost)
ebook-rs serve sample.epub --auth-token "$EBOOK_RS_AUTH_TOKEN"

# Confine MCP filesystem tools to a directory (defaults to the working directory)
ebook-rs serve sample.epub --sandbox-root /path/to/ebooks
```

Both flags also read from the environment: `EBOOK_RS_AUTH_TOKEN` and `EBOOK_RS_SANDBOX_ROOT`.
`ebook-rs serve` binds to `127.0.0.1` only and **prints a warning if no auth token is set**.

---

## 📚 Complete API Reference

For detailed function signatures, struct documentation, and module guides, refer to:
- **[`API.md`](API.md)**: Full API reference guide.
- **[`docs/MCP_SERVER.md`](docs/MCP_SERVER.md)**: Model Context Protocol (MCP) server specification.
- **[Docs.rs Documentation](https://docs.rs/ebook-rs)**: Generated Rust API docs.

---

## 🏗️ Architecture Overview

`ebook-rs` is designed around a zero-copy, highly modular system architecture:

```
                      ┌────────────────────────────────────────┐
                      │          Book (src/book.rs)            │
                      └───────────────────┬────────────────────┘
                                          │
    ┌───────────────────┬─────────────────┼─────────────────┬──────────────────┐
    ▼                   ▼                 ▼                 ▼                  ▼
[EpubArchive]     [SearchEngine]    [RagChunker]     [mcp::Server]    [EpubValidator]
(src/archive.rs)  (src/search.rs)   (src/rag.rs)     (src/mcp.rs)     (src/validator.rs)
```

- **`src/book.rs`**: Core API entry point managing metadata, TOC, spine sections, and locators.
- **`src/search.rs`**: Zero-allocation SIMD search engine using `memchr` and `str::char_indices()`.
- **`src/rag.rs`**: Okapi BM25 relevance scoring and AI document chunking engine.
- **`src/mcp.rs`**: Model Context Protocol (MCP 2024-11-05) JSON-RPC stdio & HTTP server.
- **`src/section.rs`**: Lazy on-demand section hydration and Base64 asset inlining.
- **`src/validator.rs`**: Structural EPUB 2/3 validator and multi-threaded EPUB3/KFX exporter.

---

## ⚠️ Known Limitations

Format support is broad but not uniformly deep. Know these before depending on a format:

| Area | Status |
|---|---|
| **EPUB 2/3, TXT, MD, FB2, CBZ** | Primary, best-tested paths. |
| **CBR (RAR)** | **Not supported.** Opening one returns an error asking you to convert to CBZ. |
| **PDF** | Behind the opt-in `pdf` Cargo feature (not in `default`, enabled by default in published Python wheels). Text is extracted via the third-party `unpdf` crate and rendered as Markdown sections; quality (reading order, columns, scanned/image-only PDFs) depends on that crate. No OCR. |
| **MOBI / AZW3 / KFX** | DRM-protected files are rejected with `DrmProtected`; DRM is never removed. KFX uses a clean-room Amazon Ion 1.0 `CONT` v2 / `YJ_symbols` codec (interoperable with Calibre `KFX Input` / `KFX Output` for reflowable text and metadata, not validated against every Amazon-produced file). |
| **LIT** | No LZX decompression is implemented, so LIT files that use compressed streams may not open. |
| **Readium LCP** | Parses licenses and AES-256-CBC-decrypts content given a passphrase. Does **not** verify the license signature or certificate chain, and is not a certified LCP implementation. |
| **Layout / pagination** | `ReflowPaginator` is an approximation with no real font metrics; do not expect pixel-identical pages to any reading system. |
| **HTTP reader server** | Binds to `127.0.0.1` only and is unauthenticated unless `--auth-token` / `EBOOK_RS_AUTH_TOKEN` is set. The bundled web UI does not send the token, so most routes work in the UI only when auth is disabled. Use only on trusted machines; there is no TLS. |
| **Benchmarks** | The Calibre comparison covers a handful of samples on one machine and is not a general performance guarantee. |

---

## 🤝 Contributing

Contributions are warmly welcomed! Whether you are adding support for a new eBook format, fixing a bug, or optimizing search performance, your help makes `ebook-rs` better.

### Development Workflow

1. **Clone & Build**:
   ```bash
   git clone https://github.com/SV-stark/ebook-rs.git
   cd ebook-rs
   cargo build --all-features
   ```
2. **Run Test Suite**:
   ```bash
   cargo test --all-features
   ```
3. **Check Code Formatting & Lints**:
   ```bash
   cargo fmt -- --check
   cargo clippy --all-targets --all-features
   ```
4. **Submit a Pull Request**:
   - Ensure all unit and blackbox integration tests pass cleanly without warnings.
   - Include a concise description of your changes in your PR description.

---

## 🙏 Acknowledgments & Credits

- Inspired by the feature capabilities of **[epub.js](https://github.com/futurepress/epub.js)** and **[foliate-js](https://github.com/johnfactotum/foliate-js)**.
- Compliant with **[W3C EPUB 3.3 Specifications](https://www.w3.org/publishing/epub33/)** and **[Readium Foundation Architecture](https://readium.org)**.

---

## 📜 License

Distributed under the **MIT License**. See [`LICENSE`](LICENSE) for more information.

