Преобразует электронные книги в чистые главы Markdown для обеспечения детерминированного RAG и проверки цитат ИИ-клиентами.
Также известен как Terobyte/librarian-cli, librarian-cli
- Звёзды
- 2
- Инструменты
- —
- Загрузки, 30 дней
- 169
- Последняя версия
- 0.1.1
- Последний коммит
- 1 сент. 2026 г.
- Лицензия
- MIT
Что такое Librarian MCP?
Librarian — это MCP server. Преобразует электронные книги в чистые главы Markdown для обеспечения детерминированного RAG и проверки цитат ИИ-клиентами.
Сводка сгенерирована из README проекта
О Librarian MCP server
Librarian позволяет разработчикам, использующим ИИ-клиенты, преобразовывать электронные книги в чистые главы Markdown для детерминированного RAG. Он трансформирует различные форматы, такие как EPUB, FB2, DOCX и PDF с текстовым слоем, в структурированную библиотеку глав с точным подсчетом токенов. Этот процесс происходит полностью локально, без доступа к сети, использования эмбеддингов или API-ключей, что гарантирует получение байт-в-байт идентичного результата при одних и тех же входных данных.
Пользователи могут подключить этот MCP server к Claude Desktop или Claude Code через stdio MCP соединение. После настройки пути к библиотеке сервер предоставляет шесть инструментов только для чтения, включая list_books, find и verify_quote. Эти инструменты позволяют ИИ просматривать каталог, выполнять полнотекстовый поиск с помощью BM25 и извлекать конкретные главы в рамках заданного лимита токенов. Он специально разработан, чтобы помочь ИИ-моделям проверять собственные цитаты по оригинальному тексту источника для предотвращения галлюцинаций.
Что вы можете с ним делать
- 1Поиск по библиотекам электронных книгВыполнение полнотекстового поиска по всем названиям и авторам в локальной коллекции.
- 2Извлечение текста в пределах лимита токеновПолучение последовательных глав книги при соблюдении определенного бюджета токенов.
- 3Аудит качества книгОценка структуры и качества кодировки загруженных файлов электронных книг.
Взято из README проекта. Каждый вариант использования проверен на соответствие цитате из него.
Как установить Librarian MCP
Форматы проверены 10 ноя 2026Добавить в CursorДобавить в GooseУстановка Librarian MCP в Claude Code
$ claude mcp add librarian-cli -- uvx librarian-cliУстановка Librarian MCP в Cursor
~/.cursor/mcp.json
{
"mcpServers": {
"librarian-cli": {
"command": "uvx",
"args": [
"librarian-cli"
]
}
}
}Установка Librarian MCP в VS Code
.vscode/mcp.json
{
"servers": {
"librarian-cli": {
"type": "stdio",
"command": "uvx",
"args": [
"librarian-cli"
]
}
}
}Установка Librarian MCP в VS Code CLI
$ code --add-mcp '{"name":"librarian-cli","type":"stdio","command":"uvx","args":["librarian-cli"]}'Установка Librarian MCP в Claude Desktop
claude_desktop_config.json
{
"mcpServers": {
"librarian-cli": {
"command": "uvx",
"args": [
"librarian-cli"
]
}
}
}Установка Librarian MCP в Codex
$ codex mcp add librarian-cli -- uvx librarian-cliУстановка Librarian MCP в Codex config.toml
~/.codex/config.toml
[mcp_servers.librarian-cli] command = "uvx" args = ["librarian-cli"]
Установка Librarian MCP в Gemini CLI
$ gemini mcp add -s user librarian-cli uvx -- librarian-cliУстановка Librarian MCP в Gemini settings.json
~/.gemini/settings.json
{
"mcpServers": {
"librarian-cli": {
"command": "uvx",
"args": [
"librarian-cli"
]
}
}
}Конфигурация
LIB_HOMELibrary root directory (default ./library)
| Название | Описание | Тип |
|---|---|---|
| LIB_HOME | Library root directory (default ./library) |
Автоматические проверки
Запущено 14 нояб. 2026 г.Полный отчёт →Прошло наши автоматизированные проверки. Это не аудит безопасности: изучите код и предоставьте серверу минимально необходимый доступ. Как работают проверки
- Связанный и доступный исходный репозиторийterobyte/librarian-cli is public and reachablegithub.com/terobyte/librarian-cli ↗Пройдено
- Пакет указывает этот репозиторий как источникlibrarian-cli names terobyte/librarian-cli as sourcepypi.org/project/librarian-cli/ ↗Пройдено
- Происхождение сборки (аттестация Sigstore)Sigstore attestation for librarian-clipypi.org/project/librarian-cli/ ↗Пройдено
- Open source лицензия (OSI)MITspdx.org/licenses/MIT.html ↗Пройдено
- Коммит или релиз за последний годLast commit or release 2026-09-01github.com/terobyte/librarian-cli ↗Пройдено
- OpenSSF ScorecardНе проверялось
- Имя пакета не похоже на популярный пакетNo popular package one edit away from librarian-cliПройдено
- Нет критических предупреждений в пакете или его зависимостях70 resolved dependencies checked; no critical advisoryosv.dev ↗Пройдено
- Нет скрытых инструкций для модели0 tool descriptions and the README read; no override phrases, credential paths or hidden charactersПройдено
- Деструктивные инструменты помеченыНе проверялось
- Удалённая конечная точка отвечает на рукопожатие MCPНе проверялось
README
Открыть на GitHub📚 librarian
Turn any ebook into clean, token-counted Markdown chapters — let Claude read your bookshelf over MCP and catch it misquoting your books. Deterministic RAG: no embeddings, no network, no API keys.

Any input format — FB2, EPUB, DOCX, HTML, TXT/MD, text-layer PDF — becomes a directory of clean chapters with token counts. No network, no LLM, no randomness: the same input always produces byte-identical output.
Install
uv tool install librarian-cli
# or: pipx install librarian-cli
Offline contract: install and runtime need no network (the tokenizer's vocabulary is vendored in the package).
Quick start
lib ingest examples/*.epub
lib list
lib find curiouser
lib get <book-id> --budget 3000
Commands
| Command | Purpose |
|---|---|
lib ingest <files…> [--force] [--no-keep-source] [--config cfg.toml] [--verbose] |
Process books into the library; prints a file · id · status · score table. |
lib list [<book-id>] |
No argument — all books; with an id — that book's chapters (n, title, tokens, summary). |
lib get <book-id> <spec> |
Print chapters by range (1-3,7) to stdout. |
lib get <book-id> --budget N [--from K] |
Greedily print consecutive chapters from K while the token sum stays ≤ N. |
lib find <query> [--limit 10] [--book <id>] [--reindex] [--json] |
Full-text search across chapters and titles/authors library-wide (bm25, snippets, RU/EN stemming). |
lib info <book-id> |
JSON: book metadata + quality metrics. |
lib doctor [<book-id>] |
No id — books in review and broken directories; with id — that book's report. |
lib reingest --all [--config cfg.toml] [--verbose] |
Rebuild the library from source/ with the current code/config. |
lib rm <book-id> |
Delete a book and rebuild the index. |
lib serve [--library <path>] |
Stdio MCP server over the library. |
lib verify "quote" [--book ID] [--json] [--limit N] |
Check a quote against one book or attribute it across the library. |
Library root: --library <path> (or the LIB_HOME env var, default ./library). Data goes
to stdout, diagnostics to stderr. Exit codes: 0 success, 1 runtime error, 2 usage error.
Give Claude your bookshelf
librarian-cli ships a built-in stdio MCP server with 6 read-only tools — list_books,
list_chapters, find, get_chapters, book_info, verify_quote — so Claude can browse
the catalog, search it, pull chapters under a token budget, and check its own quotes against
the source on its own: deterministic RAG with no embeddings, no network, and no API keys.
Claude Code:
claude mcp add librarian --env LIB_HOME=$HOME/books -- uvx librarian-cli
Claude Desktop (claude_desktop_config.json):
{
"mcpServers": {
"librarian": {
"command": "uvx",
"args": ["librarian-cli"],
"env": { "LIB_HOME": "/path/to/books" }
}
}
}
Verify quotes
An MCP server that catches Claude misquoting your books.
lib verify "quote" checks whether a quote actually appears in your library, verbatim —
punctuation, case, ё/е, and markdown formatting don't count. Two modes:
- Book mode (
--book <id>): full scan of one book — "does this book actually say this?" Works without the search index. - Shelf mode (no
--book): attribution across the whole library via FTS5 candidates — "which book is this from?" The quote needs at least 5 significant words (stop words don't count), or the check is skipped withverdict: null.
lib verify "Рукописи не горят" --book bulgakov-master-i-margarita
lib verify "рукописи не горят никогда"
| verdict | meaning |
|---|---|
exact |
matches after normalization (punctuation/case/ё/typography don't count) |
close |
similarity ≥ 0.95 — near-exact, differences shown as a word-diff |
distorted |
similarity ≥ 0.75 — the right place, but the quote is misremembered |
not_found |
similarity < 0.75 — nothing like it in the book/library |
null |
check wasn't run: empty quote, or a short quote without --book |
Exit codes (grep-style semantics, a deliberate departure from the project's usual
"1 = runtime error" — see docs/MILESTONES.md deviation 38):
| exit | case | stdout |
|---|---|---|
| 0 | exact / close — quote confirmed |
full report / JSON |
| 1 | distorted / not_found — not confirmed |
full report / JSON |
| 1 | runtime error (unknown book id, no search index, locked index) | empty |
| 2 | usage error: empty/short quote (verdict: null), --limit < 1 |
empty (message on stderr) |
Script discriminator: exit 1 with non-empty stdout means "checked, not confirmed"; exit
1 with empty stdout means an error (diagnostics went to stderr instead). Exit 0
includes close — a strict CI gate must check verdict == "exact" in the --json
output, not the exit code alone.
Quality
Every book gets a score from five metrics (coverage, structure, garbage, encoding,
dehyphenation): ok (score ≥ 0.90, no hard triggers) — saved silently; review
(0.60 ≤ score < 0.90, or triggers present) — saved with a warning, details via
lib doctor <id>; failed (score < 0.60) — not saved. Scans and password-protected PDFs
honestly fail (OCR and DRM removal are out of scope).
Determinism
The pipeline has no network access, no LLM calls, and no randomness — the same input file
always produces byte-identical output. That makes ingestion reproducible and cacheable, and
it's what makes lib serve's RAG deterministic: no embeddings to drift, no model calls to
vary between runs.
Limitations
- PDF: works well on typographically normal books; complex layouts may land in
review. - DRM is not circumvented; source legality is the user's responsibility.
- Networked filesystems (NFS/SMB) are not supported (the advisory lock isn't reliable there).
- MOBI/DJVU and text-less scans are not supported (v3 candidates: OCR, calibre).
- CLI messages are currently in Russian; English output is planned.
lib verify: quotes spanning a chapter boundary are not supported (v1) — the best you'll get isdistortedon one half.lib verify:closeon a single-word replacement is realistic from ~150 characters of quote; shorter quotes with a replaced word honestly land indistorted— a third of a three-word quote really is a distortion.lib verifyshelf mode (no--book) needs the FTS5 search index; book mode (--book <id>) works without it in the CLI.lib serveas a whole still requires FTS5 — it syncs the index at startup regardless of which tool gets called.lib verifyin book mode scans the whole chapter text in pure Python; a long book can take a few seconds of CPU. The MCP tool runs it in a worker thread so it doesn't block the rest of the server.
Русская версия
See README.ru.md for the Russian documentation.
Вопросы о Librarian MCP
Как добавить Librarian MCP в Claude Code?
Выполните claude mcp add librarian-cli -- uvx librarian-cli в терминале. Добавьте --scope user, чтобы сервер был доступен во всех проектах.
Как добавить Librarian MCP в Cursor?
Откройте ~/.cursor/mcp.json и добавьте сервер в mcpServers, используя конфигурацию Cursor из раздела установки выше.
Требует ли Librarian подключения к интернету или API-ключей?
Нет, он работает полностью автономно, без доступа к сети, вызовов LLM и без необходимости использования API-ключей.
Какие форматы электронных книг поддерживаются?
Инструмент поддерживает форматы FB2, EPUB, DOCX, HTML, TXT/MD и PDF с текстовым слоем.
Как работает проверка цитат?
Он проверяет, встречается ли цитата в вашей библиотеке дословно, выдавая вердикты: точное совпадение, близкое, искаженное или не найдено.
Является ли результат консистентным?
Да, конвейер детерминирован, что означает, что одни и те же входные данные всегда создают байт-в-байт идентичный результат.