Skip to main content
Glama

Knowerage — Управление покрытием анализа ИИ

Локальный MCP-сервер, который отслеживает покрытие анализа устаревшего кода и его актуальность.

Исходный код: github.com/MTimma/knowerage

Быстрый старт

Требования: Node.js 18 или новее — npx должен быть в вашем PATH (он поставляется вместе с npm, который включен в Node).

Related MCP server: Atlas

Конфигурация MCP-сервера

Зарегистрируйте Knowerage там, где ваш MCP-хост ожидает определения серверов (например, некоторые клиенты используют .cursor/mcp.json или .vscode/mcp.json; другие используют переменные окружения или интерфейс — следуйте документации вашего хоста). Используйте следующую структуру записи сервера:

{
  "mcpServers": {
    "knowerage": {
      "command": "npx",
      "args": ["@mtimma/knowerage"],
      "env": {
        "KNOWERAGE_WORKSPACE_ROOT": "${workspaceFolder}",
        "KNOWERAGE_AUTO_FULL_RECONCILE": "true"
      }
    }
  }
}

Замените ${workspaceFolder} на корневой каталог вашего проекта, если ваш хост не раскрывает эту переменную автоматически.

KNOWERAGE_AUTO_FULL_RECONCILE является необязательным: если параметр не задан, пуст или не имеет истинного значения, файловый наблюдатель по умолчанию выключен. Установите значение 1, true, yes или on (без учета регистра, пробелы обрезаются), чтобы включить его. Когда параметр включен, сервер отслеживает директорию knowerage/ и после короткой задержки (debounce) запускает knowerage_reconcile_all при изменениях в файловой системе. Это не то же самое, что запуск полной сверки после каждого вызова инструмента MCP — он реагирует только на изменения файлов внутри knowerage/. Записи реестра в registry.json игнорируются наблюдателем, поэтому сохранения не вызывают циклов.

Как использовать Knowerage

После настройки MCP-сервера вы общаетесь со своим помощником обычными предложениями. Вам не нужно запоминать названия инструментов.

Анализ или документирование кода

Указывайте на файлы, классы или поведение, которые вас интересуют. Например:

  • Используя Knowerage, проанализируй логику алгоритма в main.java.

  • Проанализируй логику сверки сущностей данных и версионирования в сервисе ETL.

Помощник создает или обновляет Markdown-файлы в knowerage/analysis/ и записывает покрытие в knowerage/registry.json (см. Как это работает ниже).

Покрытие и пробелы (тот же проект, последующий чат или другой агент)

Когда у вас уже есть анализы в дереве, вы можете спросить:

  • В процентах, какая часть кода покрыта нашим анализом?

  • Какая часть этой кодовой базы еще не проанализирована?

Knowerage отвечает на эти вопросы, основываясь на реестре и вспомогательных средствах покрытия (например, обзор, статус по файлам и списки устаревших данных) — а не на общих фразах о репозитории.

Альтернативные подходы

Установка через npm

npx @mtimma/knowerage

Или сборка из исходного кода

cargo build --release
./target/release/knowerage-mcp

Как это работает

  1. ИИ-агент создает .md файлы анализа с YAML-заголовком (frontmatter), объявляющим исходный файл и диапазоны покрытых строк

  2. Реестр (knowerage/registry.json) отслеживает записи анализа с хешами SHA-256 для проверки актуальности

  3. Инструменты MCP предоставляют операции создания, сверки, запроса и экспорта

  4. Агент говорит "проанализируй X" → автоматически запускается полный рабочий процесс (создание → сверка → запись)

Структура файла реестра (knowerage/registry.json)

Формат на диске представляет собой JSON-объект, ключами которого являются пути к анализам (строки). Каждое значение — это одна запись (см. contracts/contracts.md). Полный пример с двумя записями находится в examples/registry.sample.json.

flowchart TB
  subgraph file["knowerage/registry.json"]
    O["Top-level JSON object"]
    O --> K["Each key: analysis markdown path, e.g. knowerage/analysis/.../topic.md"]
    K --> V["Value: one RegistryRecord"]
  end

  subgraph rec["RegistryRecord fields"]
    ap["analysis_path · source_path"]
    cr["covered_ranges: [[start,end], ...]"]
    h["analysis_hash · source_hash (sha256:… )"]
    t["record_created_at · record_updated_at (ISO 8601)"]
    st["status: fresh | stale_doc | stale_src | missing_src | dangling_doc"]
  end

  V --> rec

Заголовки (frontmatter) для .md файлов анализа определяются отдельно в документации по контрактам (схема метаданных), а не внутри registry.json.

Инструменты MCP

Инструмент

Назначение

knowerage_create_or_update_doc

Создать/обновить документ анализа

knowerage_parse_doc_metadata

Разобрать и проверить заголовки (frontmatter)

knowerage_reconcile_record

Сверить одну запись анализа

knowerage_reconcile_all

Полное повторное сканирование/перестроение

knowerage_get_file_status

Проанализированные vs отсутствующие диапазоны

knowerage_list_stale

Список устаревших/проблемных записей

knowerage_list_registry

Полный снимок реестра (та же форма, что и registry.json, отсортированные ключи)

knowerage_get_tree

Дерево/группировка покрытия

registry_export_report

Экспорт снимка (JSON/YAML/TXT/HTML)

knowerage_generate_bundle

Частичный экспорт выбранных анализов (toc*.md, combined*.md, manifest.json)

Структура проекта

knowerage/                  # Created per-project
├── analysis/              # Analysis markdown files
│   └── **/*.md
└── registry.json          # Coverage registry

src/                       # Rust MCP server
├── main.rs
├── lib.rs
├── types.rs
├── parser.rs
├── registry.rs
├── mcp.rs
├── security.rs
└── export.rs

Документация

Безопасность

  • Все пути проверяются относительно корня рабочей области

  • Обход путей (..) отклоняется

  • Атомарная запись для реестра (защита от сбоев)

  • Никаких секретов в файлах анализа или отчетах

  • Актуальность на основе хеша SHA-256 (сохраняется после git pull)

Лицензия

MIT — авторское право Martins Timma.

Части этого проекта были написаны или доработаны с помощью генеративных ИИ-помощников для написания кода. Человеческая проверка применяется к дизайну, критически важным для безопасности аспектам и релизам.

Available Tools

11 tools
knowerage_coverage_overviewA

Batch coverage overview for all source files. Returns per-source coverage percentage, analyzed/missing ranges, range attribution, stale records, and project-wide file/line totals. Uses fresh records only for coverage calculation. Optional extensions filter applies to sources, stale list, and project scan.

Inputs: extensions.

knowerage_create_or_update_docA

PRIMARY tool for persisting legacy/source code analysis: create or update an analysis markdown file under knowerage/analysis/ with YAML frontmatter (source path, covered line ranges, dates). Use this whenever the user asks to analyze, document, or explain a source file and Knowerage is in the tool list—do not use generic file-write tools alone for knowerage analysis paths, or the registry will not stay consistent. Follow with knowerage_reconcile_record on the same analysis_path.

Inputs: analysis_path (required), content (required), covered_lines (required), source_path (required).

knowerage_generate_bundleA

Export selected analysis markdown files into chunked NotebookLM-style bundles under output_dir: writes toc.md + combined.md for part 1, toc_N.md + combined_N.md for further parts when size limits require splitting, plus manifest.json (files, errors, part metadata). Every analysis_paths entry is validated under the workspace (no traversal). Per-file and per-part size limits apply (see contracts).

Inputs: analysis_paths (required), output_dir (required).

knowerage_get_file_statusA

Per-source coverage: total lines, analyzed vs missing ranges, and which analysis paths claim them. Prefer this over guessing from open files when answering 'what is documented for this source?' while Knowerage is enabled.

Inputs: source_path (required).

knowerage_get_treeC

Get a tree view of analysis records grouped by directory

Inputs: group_by, root.

knowerage_list_registryA

Return the full analysis coverage registry in one structured JSON response. USE THIS when you need an inventory of which source files are documented, where the analysis markdown lives, which line ranges are claimed, and freshness (fresh/stale_doc/stale_src/missing_src/dangling_doc). The records object is the same shape as the entire knowerage/registry.json file (sorted keys for stable reading). Call early when planning documentation work, finding gaps, or mapping analysis paths to sources—instead of opening registry.json by hand. Optional filters: analysis_path_prefix narrows by analysis key; statuses limits to given status values (same strings as in each record). After reconcile_record/reconcile_all, call again if you need the latest snapshot.

Inputs: analysis_path_prefix, statuses.

knowerage_list_staleB

List registry records filtered by staleness status

Inputs: statuses.

knowerage_parse_doc_metadataB

Parse YAML frontmatter from an analysis markdown file

Inputs: analysis_path (required).

knowerage_reconcile_allA

Rescan all analysis markdown files matching the glob and rebuild registry entries. Use after git pull, bulk edits, or when the registry may be empty or out of date; prefer reconcile_record when only one file changed.

Inputs: analysis_glob.

knowerage_reconcile_recordA

MANDATORY after every create_or_update_doc (or manual edit) to one analysis file: reconciles that analysis into knowerage/registry.json (hashes, covered_ranges, freshness). Call immediately after writing analysis content so coverage is recorded; skipping this leaves the registry wrong or stale.

Inputs: analysis_path (required).

registry_export_reportB

Export the registry as a report file in json, yaml, txt, or html format

Inputs: format (required), output_path (required).

Tool Schema Changelog

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

Loading tool schema changelog…

    TDQS

    A3.7/5.0

    Scored across 11 tools

    Disambiguation5/5

    Each tool targets a distinct operation: coverage overview per batch, per-source status, registry listing with filters, doc creation/update, reconciliation, bundle generation, tree view, metadata parsing, stale listing, and export. Even overlapping tools like list_registry and list_stale are clearly differentiated by filters and purpose.

    Naming Consistency3/5

    All tools use the 'knowerage_' prefix except for 'registry_export_report', which breaks the pattern. Within the prefixed group, naming follows a consistent verb_noun style (e.g., get_file_status, create_or_update_doc, reconcile_record). The one outlier lowers the score.

    Tool Count5/5

    With 11 tools, the server covers the core operations of a documentation coverage system (CRUD-like, reconciliation, reporting, exploration) without being excessive. Each tool serves a clear purpose and none feel redundant.

    Completeness4/5

    The tool surface covers creation/update, reconciliation (single and bulk), listing, coverage overview, bundle generation, metadata parsing, and export. Missing a direct delete tool for docs, but the create_or_update tool may handle updates. Overall, agents can perform most tasks without dead ends.

    Related MCP Connectors

    Related MCP Servers

    • F
      license
      Not graded
      quality
      D
      maintenance
      Local MCP server that indexes documentation from URLs/files into a vector database, enabling coding agents to search and use up-to-date library and API documentation.
      1
      -