Skip to main content
Glama
NiKuma0
by NiKuma0

tolstoy-mcp — память Толстого для Claude

Локальный MCP-сервер с поиском по 90-томному Полному собранию сочинений Л. Н. Толстого (сочинения, дневники, записные книжки, письма), дневникам и воспоминаниям современников (Гусев, Гольденвейзер, Маковицкий, С. А. Толстая) и примечаниям редакторов.

  • recall — гибридный поиск фрагментов: по смыслу (bge-m3) и по словам (FTS5 со стеммингом), объединение через RRF;

  • read_document — дочитать письмо, дневниковую запись или главу целиком или окно вокруг найденного фрагмента;

  • промпт tolstoy — Claude говорит от лица Толстого, его орфографией, и ссылается на источники.

Всё работает локально, без API-ключей. При первом запуске скачивается около 800 МБ: база текстов (≈200 МБ сжатая, 500 МБ на диске) и модель для запросов (≈590 МБ).

Установка

Claude Desktop. Скачать tolstoy-<версия>-<ОС>.mcpb со страницы Releases и открыть его двойным щелчком (или «Настройки → Расширения → Установить расширение»). Пакеты: darwin (Apple Silicon), win32 (x64 и ARM), linux (x64 и ARM).

Claude Code и другие MCP-клиенты (нужен Node.js ≥ 22.13):

claude mcp add tolstoy -- npx -y tolstoy-mcp
npx -y tolstoy-mcp download        # по желанию: скачать данные заранее, а не при первом вопросе

Пока данные скачиваются, инструменты отвечают, сколько осталось. Данные лежат в системном каталоге данных приложения (~/.local/share/tolstoy-mcp, ~/Library/Application Support/tolstoy-mcp, %LOCALAPPDATA%\tolstoy-mcp); переопределить — переменной TOLSTOY_DATA_DIR.

npx tolstoy-mcp info                                       # что скачано и где
npx tolstoy-mcp search "что Толстой писал Фету о Шопенгауэре" --top 5
npx tolstoy-mcp search "непротивление злу насилием" --mine  # только тексты самого Толстого

Related MCP server: HomeKB MCP Server

Как устроено

TEI/XML ──tei-importer──▶ PostgreSQL + pgvector ──tei-importer export──▶ export/*.jsonl.gz + chunks.f32
   (репозиторий TEI, importer/: парсинг, чанки, векторы bge-m3)                    │
                                                                       npm run build:db
                                                                                  ▼
          GitHub Release data-v1 ◀──────────────── tolstoy-v1.db.gz (SQLite: тексты, FTS5, int8-векторы)
                     │ первый запуск: скачать и проверить sha256
                     ▼
Claude ◀──stdio──▶ tolstoy-mcp: bge-m3 (ONNX int8) векторизует запрос → перебор int8-векторов + FTS5 → RRF
  • SQLite через встроенный node:sqlite: без нативных аддонов, поэтому работает и во встроенном Node Claude Desktop (Electron), где аддоны под чужой ABI не грузятся.

  • Векторы — int8 в обычной таблице (113 МБ вместо 450), поиск полным перебором в JS за ~125 мс. sqlite-vec пробовали: без ANN-индекса он не быстрее, а нативную сборку тянет. Ранжирование int8 почти не отличается от float32 (топ-10 совпадает на 9–10 из 10).

  • Полнотекстовый поиск — FTS5 по основам слов: в SQLite нет русского стеммера, поэтому и текст, и запрос заранее прогоняются через Snowball (snowball-stemmers).

  • Модель запросов — Xenova/bge-m3 (ONNX int8) через onnxruntime-node и @huggingface/tokenizers; это та же BAAI/bge-m3, которой векторизован корпус (косинус с Python-версией 0,98).

Разработка

npm ci --ignore-scripts      # postinstall onnxruntime-node докачивает CUDA; нам нужен только CPU
npm test                     # vitest: юнит-тесты и MCP-сервер на мини-базе из test/fixture.ts
npm run lint && npm run typecheck
npm run build                # tsup → dist/index.js
npm run dev -- search "Ясная Поляна"

Сквозной тест на настоящих данных (собранный dist, stdio): положить базу и модель в .data/ (TOLSTOY_DATA_DIR=.data node dist/index.js download) и запустить TOLSTOY_E2E_DATA_DIR=.data npm test.

Новая версия данных

  1. В репозитории TEI: cd importer && uv run tei-importer export (дамп в importer/export/).

  2. Здесь: npm run build:db -- <путь к export> --gzip — соберёт build/tolstoy-v1.db(.gz) и впишет размер и sha256 в data/assets.json.

  3. Выложить: gh release create data-v1 build/tolstoy-v1.db.gz (или gh release upload data-v1 … --clobber), закоммитить data/assets.json. Если меняется схема, поднять DB_FORMAT в src/schema.ts: имя файла станет tolstoy-v2.db, и старые установки не подхватят несовместимую базу.

Релиз

npm version patch && git push --follow-tags. Workflow release.yml собирает .mcpb под каждую ОС, проверяет каждый на своей платформе (scripts/smoke.mjs: нативный onnxruntime грузится, сервер отвечает на initialize и tools/list), выкладывает их в GitHub Release и публикует пакет в npm (trusted publishing: репозиторий и release.yml нужно один раз указать в настройках пакета на npmjs.com).

Лицензия

Код — MIT. Тексты — корпус «Весь Толстой в TEI/XML» проекта Tolstoy Digital, CC BY-SA. Модель BAAI/bge-m3 — MIT.

Available Tools

2 tools
read_documentПрочитать документB
Read-only

Прочитать документ (письмо, дневниковую запись, главу) по порядку сегментов, с шапкой.

ParametersJSON Schema
NameRequiredDescriptionDefault
limitNo
startNoord, с которого читать (next_start)
doc_idYesdoc_id из recall
segment_idNoпоказать окно вокруг этого сегмента (segment_ids из recall)

Output Schema

ParametersJSON Schema
NameRequiredDescription
idYes
biblYesбиблиографическая ссылка
pagesYes
titleYes
voiceYes
authorYes
corpusYes
volumeYesтом ПСС
segmentsYes
addresseeYesадресат письма
date_textYes
next_startYesstart для следующей порции; null — документ дочитан
total_segmentsYes

TDQS

B3.2/5.0
Behavior3/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

Annotations already establish this as a safe read (readOnlyHint=true, openWorldHint=false). The description adds real behavioral context beyond them: results come back in segment order and include a header. It does not disclose pagination semantics (limit capped at 60, next_start continuation), which matters for a segment-windowed reader.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness4/5

Is the description appropriately sized, front-loaded, and free of redundancy?

A single front-loaded sentence opening with the verb, with no filler. It is efficient, though terseness here shades into under-specification rather than optimal density.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness3/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

The output schema covers return values and annotations cover safety, so the description is not obligated there. But for a four-parameter reader it omits the recall→read workflow, pagination via start/limit/next_start, and how segment_id windowing interacts with ordered reading, leaving real gaps.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters3/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema coverage is 75%, close to the high-coverage baseline, and the description adds no parameter meaning at all. `limit` has no description in the schema and is not compensated for here, so the one heavily-used knob (page size) remains opaque.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose4/5

Does the description clearly state what the tool does and how it differs from similar tools?

Names a concrete verb ("Прочитать") plus the resource ("документ") and concretizes it with examples (письмо, дневниковая запись, глава), and states the read mode: ordered segments with a header. However it never mentions the sibling `recall` or explains how this differs from it, so an agent must infer the relationship from the schema instead.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines2/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description gives no when-to-use or when-not-to-use guidance and never references the alternative `recall`. The workflow hint (doc_id/segment_ids come from recall) appears only inside the parameter descriptions, not in the description itself.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

recallВспомнитьB
Read-only

Найти фрагменты корпуса Толстого по теме (гибридный поиск: смысл + слова).

ParametersJSON Schema
NameRequiredDescriptionDefault
topNo
queryYesЧто вспомнить: имена, названия, тема, время. Современной орфографией.
only_mineNoТолько тексты самого Толстого, без современников и примечаний редакторов.

Output Schema

ParametersJSON Schema
NameRequiredDescription
hitsYes

TDQS

B3.2/5.0
Behavior3/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

Annotations already declare readOnlyHint=true and openWorldHint=false, so the safety profile is covered. The description usefully adds that retrieval is hybrid (meaning + words), which tells the agent query formulation matters. It does not mention the top cap of 10 or any ranking behavior, so the added context is modest.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness4/5

Is the description appropriately sized, front-loaded, and free of redundancy?

A single front-loaded sentence naming the action, scope and method, with no filler. It is efficient, though it is sparse enough that the brevity shades into under-specification rather than pure conciseness.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness3/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

An output schema exists, so return values need not be explained, and the annotations cover the read-only nature. What is missing is routing guidance relative to read_document and any hint about result size limits, leaving the definition only minimally complete for a tool that competes with a sibling.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters3/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema coverage is 67% – query and only_mine already carry descriptions, while top does not. The description only echoes the topical-query notion ('по теме', 'смысл + слова'), adding no detail about the top cap or only_mine scope beyond what the schema says. Baseline 3 is appropriate.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose4/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description gives a specific verb and resource ('Найти фрагменты корпуса Толстого по теме') and even names the retrieval method (hybrid semantic + lexical search), so the agent knows exactly what the tool returns. However, it never distinguishes this from the sibling read_document, so the boundary between the two remains unclear.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines2/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

Beyond the implied 'use this to search by topic', there is no explicit when-to-use, when-not-to-use, or comparison to the sibling read_document. An agent facing both tools has no stated rule for choosing between them.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

Tool Schema Changelog

Recent tool additions, removals, and schema changes observed during successful MCP inspections.

  1. 2 tool updatesv0.1.0
    • First observedread_document
    • First observedrecall

TDQS

B3.4/5.0

Scored across 2 tools

Disambiguation5/5

The two tools have clearly distinct purposes: 'recall' performs hybrid search for fragments by topic, while 'read_document' sequentially reads a full document. An agent can easily tell them apart without overlap.

Naming Consistency4/5

'read_document' follows a clear verb_noun pattern, but 'recall' is a bare verb without an object, deviating slightly. Both are lowercase and action-oriented, so the set is mostly consistent with minor variation.

Tool Count3/5

Two tools are borderline thin for a corpus server; typical well-scoped sets have 3–15 tools. While search and read cover a basic retrieval loop, additional tools for discovery or metadata could be expected.

Completeness3/5

The surface allows searching and reading documents, but there is no explicit way to list or browse available documents, nor to retrieve metadata such as dates or titles. This creates a notable gap for agents that need to discover what exists before reading.

Maintenance

ActivityMaintained
ResponsivenessNo issues

Related MCP Connectors

Related MCP Servers

  • A
    license
    Not graded
    quality
    B
    maintenance
    Enables Claude Code to search and retrieve from a local knowledge base of markdown notes using hybrid semantic+keyword search, keeping data entirely offline.
    13 npm
    MIT
  • A
    license
    Not graded
    quality
    C
    maintenance
    Enables natural language interaction with a personal knowledge base stored locally on your computer, supporting semantic search, note reading, and writing through Claude Code or mobile apps.
    11
    MIT
  • A
    license
    Not graded
    quality
    C
    maintenance
    Enables local RAG-based book and PDF search through Claude Desktop, using hybrid BM25 and vector retrieval with ChromaDB, plus optional OCR for scanned documents.
    MIT
  • A
    license
    Not graded
    quality
    A
    maintenance
    Enables Claude to search locally indexed exported chat history and project docs, retrieving full messages and conversation IDs via full-text search.
    1
    MIT