Skip to main content
Glama
kingcool0072000

grammar-kb-mcp

grammar-kb

Монорепозиторий базы знаний + учебного фронтенда для конспектов по английской грамматике, состоящий из двух уровней:

  • grammar_kb/ (Python-бэкенд): очищает и структурирует PDF-учебники/конспекты в поисковую базу фрагментов знаний с прослеживаемостью источников — автоматически удаляет водяные знаки, восстанавливает таблицы, разбивает на фрагменты знаний, извлекает ключевые слова и связи, сохраняет в локальную SQLite (полнотекстовый поиск FTS5), предоставляет CLI, HTTP API и MCP-сервис.

  • web/ (фронтенд на Vite): учебный интерфейс для студентов — просмотр конспектов тремя способами: по курсам / глоссарию / системе знаний, плюс запись оценок за домашние задания (CRUD, сохраняется в iCloud Drive, синхронизация между устройствами).

Подходит для любых учебных/технических PDF с «относительно единообразной вёрсткой, водяными знаками в колонтитулах и таблицами».

Возможности

  • 🧹 Удаление водяных знаков: по шрифту + направлению текста отсекаются колонтитулы и наклонные фоновые водяные знаки (включая префиксы subset-шрифтов PDF)

  • 📊 Восстановление таблиц: автоматически обнаруживает таблицы с линиями и восстанавливает их как GFM Markdown-таблицы

  • 🧩 Разбиение на фрагменты знаний: по уровням заголовков (глава/раздел/подраздел/пункт/пример/упражнение) на отдельные независимо искомые единицы

  • 🏷️ Классификация и связи: классификация по темам, извлечение ключевых слов/слов-маркеров и связей между фрагментами знаний (например, «главное — будущее, придаточное — настоящее», «согласование времён»)

  • 🎯 Экзаменационные сигналы: каждый фрагмент знаний помечается измерением экзаменационного аспекта (время/залог/написание/придаточные…), поддерживается «обратный поиск фрагментов знаний по экзаменационному аспекту»

  • 📖 Словарь: на основе корпуса конспектов формируется словарь (значение / часть речи / словоформы / прослеживание источника)

  • 🔍 Прослеживаемость: каждый фрагмент знаний содержит 讲次 · 节路径 · 页码, можно вернуться к исходнику

  • 🗄️ Без обрезки: текст хранится в SQLite TEXT (без ограничения длины), FTS используется только для поиска совпадений

  • 🌐 HTTP API: встроенный REST-сервис (FastAPI, с интерактивной документацией /docs)

  • 🔌 Готовность к MCP: встроенный MCP-сервис, клиенты вроде Claude могут выполнять запросы напрямую

Related MCP server: PDF RAG MCP Server

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

uv sync                          # 安装依赖(含开发依赖)
uv run grammar-kb ingest ./pdfs  # 导入一个 PDF 目录(全量重建,id 可复现)
uv run grammar-kb stats          # 查看统计

Не установлен uv? curl -LsSf https://astral.sh/uv/install.sh | sh

Часто используемые команды

uv run grammar-kb ingest ./pdfs               # 导入目录(或单个 PDF 文件)
uv run grammar-kb lecture 25                   # 输出某讲的完整 Markdown(表格已还原)
uv run grammar-kb lecture 25 --format html     # 输出某讲的 HTML(表格渲染为 <table>)
uv run grammar-kb kp 173                       # 输出某知识点的完整 Markdown
uv run grammar-kb search "关键词"              # 全文检索知识点
uv run grammar-kb search "since" --category 时态
uv run grammar-kb markers --category 时态      # 列出某类下所有关键词/标志词
uv run grammar-kb markers --tense 现在完成时   # 列出某时态的标志词
uv run grammar-kb relation 主将从现            # 按关系类型查知识点
uv run grammar-kb exam-signal 从句             # 按考点信号反查知识点(反之亦然)
uv run grammar-kb exam-signal --list           # 列出所有考点信号维度
uv run grammar-kb words --limit 100            # 单词表(释义/词性/词形变化/来源)
uv run grammar-kb stats                        # 统计
uv run grammar-kb serve --port 8000            # 启动 HTTP 查询服务(见 http://127.0.0.1:8000/docs)

По умолчанию база данных находится в data/grammar.db в рабочем каталоге; её можно переопределить с помощью --db или переменной окружения GRAMMAR_KB_DB.

Использование готового набора данных напрямую (необязательно)

Если не хотите выполнять ingest самостоятельно, скачайте grammar.db нужной версии из GitHub Releases, поместите в data/grammar.db (или укажите путь через GRAMMAR_KB_DB) — и можно сразу выполнять запросы. Номер версии набора данных указан в теге релиза (например, data-v1); таблица meta в базе также хранит версию и время генерации.

Архитектура

PDF ──► pdf_parser   去水印(字体+方向过滤)+ 重排行 + 还原表格
      └─► structure    文本 → 大纲树 → 知识点切分(分类 + 关键词 + 关系)
                      └─► db          SQLite(lecture / knowledge_point / marker / relation / block + FTS5)
                                      └─► query  查询 API(CLI 与 MCP 共用)

Модуль

Назначение

pdf_parser.py

fitz извлекает span (шрифт/позиция/направление) → фильтрация водяных знаков → перестройка строк; pdfplumber восстанавливает таблицы по отфильтрованным символам

structure.py

Классификация строк (раздел/подраздел/пункт/пример/упражнение) → разбиение на фрагменты знаний

classify.py

Правила классификации, словарь ключевых слов, обнаружение связей, экзаменационные сигналы (чистые функции)

vocabulary.py

Словарь на основе корпуса (значение / часть речи / словоформы)

markdown.py

Таблицы → GFM, рендеринг фрагментов знаний и лекций

db.py

schema + CRUD + FTS5(trigram, external-content), без обрезки

query.py

API запросов для вызова

ingest.py

PDF → запись в БД (импорт каталога = полное пересоздание, id воспроизводимы)

exam_store.py

Отдельная SQLite-база оценок за работы (CRUD; по умолчанию в iCloud Drive)

cli.py

Командная строка

server.py

HTTP-сервис (опциональный extra)

mcp_server.py

MCP-сервис (опциональный extra)

web/

Учебный фронтенд (Vite, подробнее см. ниже «Web-фронтенд» и web/README.md)


Схема базы данных (кратко)

lecture(number UNIQUE, title, full_title, category, subcategory, source_file, page_count)
knowledge_point(lecture_id, lecture_number, title, category, section_path,
                body_md, examples_md, table_md, is_table, source_page, source_bbox, tags_json, ord)
marker(kp_id, lecture_number, marker, marker_type, tense, note)        -- 关键词/标志词
relation(kp_id, type, to_kp_id, note)                                  -- 关系:主将从现/时态呼应…
lecture_block(lecture_id, page, seq, kind, text_md)                    -- 整讲还原用

-- 全文检索(external-content + trigram,中文子串命中)
CREATE VIRTUAL TABLE kp_fts USING fts5(title, body_md, examples_md, table_md,
    content='knowledge_point', content_rowid='id', tokenize='trigram');

Настройка вашего набора данных

Инструмент по умолчанию настроен на «учебные конспекты с единообразной вёрсткой»; при смене набора данных обычно нужно изменить только три места (все в grammar_kb/):

  • Шрифты водяных знаков — WATERMARK_FONTS в pdf_parser.py: добавьте имена шрифтов ваших колонтитулов/водяных знаков. Быстрый скрипт для диагностики шрифтов нового PDF:

    uv run python -c "import fitz; d=fitz.open('某.pdf'); \
    import collections; c=collections.Counter(s['font'] for b in d[0].get_text('dict')['blocks'] if b.get('type',0)==0 for l in b['lines'] for s in l['spans'] if s['text'].strip()); print(c)"
  • Правила классификации — _TITLE_RULES в classify.py: сопоставление ключевых слов заголовков с тематическими категориями.

  • Словарь ключевых слов — TENSE_MARKERS в classify.py (или собственный аналогичный словарь).

  • Регулярные выражения вёрстки — structure.py: если уровни заголовков используют другие обозначения (например, 一、 / (一)), настройте соответствующие регулярные выражения.

В качестве HTTP-сервиса

uv sync --extra server                       # 安装 server 依赖(fastapi + uvicorn)
uv run grammar-kb serve --port 8000          # 经由 CLI
# 或独立入口:
uv run grammar-kb-server --host 0.0.0.0 --port 8000

После запуска откройте http://127.0.0.1:8000/docs для просмотра интерактивной документации API. Эндпоинты:

Метод

Путь

Описание

GET

/stats

Статистика и метаинформация набора данных

GET

/lectures

Список лекций

GET

/lectures/{number}?format=markdown|html

Содержимое лекции (с восстановлением таблиц)

GET

/kp/{id}?format=markdown|html

Конкретный фрагмент знаний

GET

/search?q=...&category=...&limit=...

Полнотекстовый поиск

GET

/markers?category=时态&tense=...

Слова-маркеры

GET

/relation?type=主将从现

Поиск по связи

GET

/exam-signals

Все измерения экзаменационных сигналов

GET

/exam-signal?signal=时态

Обратный поиск фрагментов знаний по экзаменационному аспекту

GET

/vocabulary?limit=300&min_freq=2

Словарь (значение / часть речи / словоформы)

GET

/taxonomy

Дерево тематической системы фрагментов знаний (категория → тема)

GET

/dict/{word}

Поиск любого слова (полный словарь ECDICT)

GET/POST

/exams

Оценки за работы: список / добавление

PUT/DELETE

/exams/{id}

Оценки за работы: изменение / удаление

Где хранятся данные об оценках

Оценки хранятся в отдельной SQLite-базе (отдельно от базы конспектов data/grammar.db), путь определяется в следующем порядке:

  1. Переменная окружения GRAMMAR_KB_EXAM_DB

  2. iCloud Drive: ~/Library/Mobile Documents/com~apple~CloudDocs/grammar-kb/exam.db (на macOS, если доступен iCloud) — объём данных небольшой, размещается в облаке и синхронизируется iCloud между устройствами

  3. Запасной вариант data/exam.db

База намеренно не использует режим WAL (один самодостаточный файл — синхронизация iCloud целого файла надёжнее); на других устройствах после установки этого репозитория и входа в тот же аккаунт iCloud при запуске сервиса вы получите те же оценки.

Пример:

curl "http://127.0.0.1:8000/search?q=现在完成时&limit=3"
curl "http://127.0.0.1:8000/lectures/25?format=html"

Единый формат ответа: все эндпоинты возвращают {code, message, data}.

// 成功(HTTP 200)
{ "code": 0, "message": "ok", "data": { "knowledge_points": 359, ... } }
// 错误(HTTP 与 code 一致)
{ "code": 404, "message": "第 99 讲不存在", "data": null }

CORS: по умолчанию разрешены все источники (Access-Control-Allow-Origin: *), фронтенд может вызывать API напрямую с другого домена. Чтобы ужесточить белый список: GRAMMAR_KB_CORS_ORIGINS=https://a.com,https://b.com grammar-kb-server.

В качестве MCP-сервиса

uv sync --extra mcp
uv run grammar-kb-mcp

Предоставляемые инструменты: search_knowledge_points, get_knowledge_point, get_lecture_markdown, list_lectures, list_markers, find_by_relation, stats. Каждый инструмент — тонкая обёртка над Query.

Пример конфигурации Claude Desktop:

{
  "mcpServers": {
    "grammar-kb": {
      "command": "uv",
      "args": ["run", "--directory", "/path/to/grammar-kb", "grammar-kb-mcp"],
      "env": { "GRAMMAR_KB_DB": "/path/to/grammar-kb/data/grammar.db" }
    }
  }
}

Web-фронтенд для обучения (web/)

Учебный интерфейс для студентов, зависит от локально запущенного бэкенда (по умолчанию http://127.0.0.1:8000``, на этапе разработки Vite проксирует /api/*` на него).

# 终端 1:先起后端
uv sync --extra server && uv run grammar-kb-server

# 终端 2:再起前端
cd web && npm install && npm run dev     # http://localhost:5180

Возможности:

  • Просмотр по курсам: 48 лекций сгруппированы по грамматической системе (морфология / времена / залог / неличные формы глагола / синтаксис / комплексное повторение), открывайте и читайте содержимое лекции целиком.

  • Глоссарий: 600+ частотных слов (значение / часть речи / словоформы / источник в конспектах), фильтрация по части речи, поиск, сортировка.

  • Система знаний: 359 разрозненных фрагментов знаний объединены в двухуровневое дерево «грамматическая категория → тема», включая таблицу устойчивых сочетаний.

  • 🎯 Экзаменационные сигналы (двунаправленные): взаимные переходы между фрагментами знаний ↔ словами-маркерами/временами — «видишь это слово — значит, какие знания проверяются».

  • 📝 Оценки за работы: к каждой лекции — лист с заданиями (35 вопросов, максимум 100 баллов). Клик по номеру вопроса отмечает правильность, баллы считаются автоматически; все попытки сохраняются, их можно изменять и удалять; журнал ошибок сводит количество ошибок по «лекция + номер вопроса»; данные через бэкенд /exams сохраняются в iCloud (см. выше), не теряются между браузерами/устройствами, старые записи localStorage автоматически мигрируют при первом открытии.

Технологический стек: Vite + нативные ES-модули · marked (рендеринг Markdown), без зависимостей от фреймворков. Подробнее см. web/README.md.

Тестирование

uv run pytest                           # 全部(含真实 PDF 集成)
uv run pytest -m "not integration"      # 仅纯单测(无需 PDF,秒级)

Покрытие: фильтрация водяных знаков / перестройка строк / восстановление таблиц / разбиение на фрагменты знаний / классификация / извлечение ключевых слов / безобрезной цикл записи и чтения БД / полнотекстовый поиск FTS на китайском и английском / каскадная очистка / воспроизводимое пересоздание id / запросы / сквозная интеграция.

Для интеграционных тестов нужен каталог с PDF, задаваемый переменной окружения GRAMMAR_TEST_PDF_DIR; если он не задан или не существует, тесты автоматически пропускаются.

Компромиссы в дизайне и известные ограничения

  • Таблицы без рамок: восстанавливаются только ruled table, которые pdfplumber может обнаружить по линиям; небольшое количество безрамочных многоколоночных сопоставлений сохраняется как обычные абзацы (информация не теряется). Позже можно добавить запасное обнаружение по «выравниванию по пробелам в колонках».

  • Разбиение на фрагменты знаний: эвристика, основанная на единообразной вёрстке; при особой вёрстке возможны небольшие расхождения в объединении/разделении, можно перепроверить через search + kp.

  • Импорт каталога означает пересоздание: ingest <目录> очищает и пересоздаёт базу (id начинаются с 1, воспроизводимы); импорт одного PDF обновляет только эту лекцию.

Available Tools

7 tools
find_by_relationB

按关系类型查知识点,如 relation_type="主将从现"、"时态呼应"。

ParametersJSON Schema
NameRequiredDescriptionDefault
relation_typeYes

Output Schema

ParametersJSON Schema
NameRequiredDescription
resultYes

TDQS

B3.1/5.0
Behavior2/5

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

No annotations are provided, so the description carries the full burden. It indicates a read-like lookup ('查') but does not disclose permissions, side effects, result limits, or other behavioral traits; output schema handles return shape but not operational behavior.

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

Conciseness5/5

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

A single compact sentence that front-loads the action and includes examples. No wasted words.

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?

Output schema exists, so return values need not be described. But for a tool with no annotations and 0% schema coverage on its only parameter, the description leaves gaps: no sibling routing, no relation-type vocabulary, and no behavioral context.

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 0% and there is one required parameter. The description compensates partially by naming 'relation_type' and giving example values ('主将从现', '时态呼应'), but it does not define the valid relation-type set or format.

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?

States a clear verb-resource pair ('查知识点') with the filter ('按关系类型') and example relation values. However, it does not distinguish itself from sibling search_knowledge_points, so it falls short of a 5.

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?

No when-to-use, when-not-to-use, or alternative routing is provided. The relation-type filter is evident, but the agent is not told when this is preferable to search_knowledge_points.

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

get_knowledge_pointA

按 id 获取单个知识点的完整 markdown(含解释、例句、表格、溯源)。

ParametersJSON Schema
NameRequiredDescriptionDefault
kp_idYes

Output Schema

ParametersJSON Schema
NameRequiredDescription
resultYes

TDQS

A3.6/5.0
Behavior3/5

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

No annotations are provided, so the description carries the burden. It usefully discloses the returned payload ('解释、例句、表格、溯源'), which adds value beyond the free-form object, and '获取' implies a read-only operation. It does not state permission requirements, behavior for a missing/invalid id, or failure modes.

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

Conciseness5/5

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

A single front-loaded sentence with no wasted words; the resource and the trigger condition (id) come first.

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

Completeness4/5

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

A one-parameter read tool with an output schema, so return-value shape is already covered by structured data and the description appropriately summarizes payload content. The main gap is the absence of any comparison to the search 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 description coverage is 0% for the single kp_id parameter, which is typed only as an integer. The description partially compensates by indicating the parameter is a knowledge-point id ('按 id 获取单个知识点'), but adds no format, range, or resolution details.

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?

States a specific verb+resource: retrieve a single knowledge point's full markdown by id. The word '单个' (single) implicitly contrasts with the sibling search_knowledge_points, but the description never names that alternative, so sibling differentiation is left to inference.

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

Usage Guidelines3/5

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

The phrase '按 id 获取' implies the prerequisite that a kp_id must already be known, which is useful routing context. However, it gives no explicit when-to-use vs search_knowledge_points or any exclusion condition.

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

get_lecture_markdownB

获取某讲的完整 markdown 讲义(标题/正文/表格已还原为 GFM)。

例如 number=25 返回"第二十五讲 动词时态3"的完整 md。

ParametersJSON Schema
NameRequiredDescriptionDefault
numberYes

Output Schema

ParametersJSON Schema
NameRequiredDescription
resultYes

TDQS

B3.2/5.0
Behavior2/5

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

No annotations are provided, so the description carries the full behavioral burden. It does not state whether this is read-only (though the name implies it), what happens if an invalid number is given, whether output is cached, or how errors are surfaced. The format detail (GFM conversion) is helpful, but overall behavioral disclosure is thin for a tool with zero annotation coverage.

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?

Two short sentences that are front-loaded with the core purpose, followed by a concrete example. No wasted words. It could be slightly more structured (e.g., separating behavior notes), but it is efficient.

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 the description need not explain return values. However, with no annotations and a 0%-coverage parameter schema, the description should compensate more by clarifying read-only nature, error handling, or the relationship to list_lectures. As is, it is minimally complete for a simple read-by-id tool.

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 description coverage is 0% and there is only one parameter ('number'). The description adds meaning by giving a concrete example (number=25 -> lecture 25) and implying the parameter is the lecture number. This is better than nothing but not comprehensive, so a baseline 3 is appropriate for a single-param tool where the schema itself is silent.

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?

States a specific verb (get/获取) and resource (complete markdown lecture notes), with the format detail that tables are converted to GFM. This distinguishes it from list_lectures (which presumably enumerates) and get_knowledge_point (different resource). The purpose is clear, though it doesn't explicitly contrast with siblings.

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

Usage Guidelines3/5

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

The example ('number=25 returns 第二十五讲 动词时态3') implicitly signals when to use it: when you need the full markdown of a specific lecture by number. However, there is no explicit when-to-use vs. alternatives guidance, no mention of prerequisites (e.g., you must first know the lecture number via list_lectures), and no exclusions.

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

list_lecturesA

列出已导入的全部讲次(讲号、标题、分类)。

ParametersJSON Schema
NameRequiredDescriptionDefault

No parameters

Output Schema

ParametersJSON Schema
NameRequiredDescription
resultYes

TDQS

A3.7/5.0
Behavior3/5

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

No annotations are provided, so the description carries the full behavioral burden. It discloses the returned fields and the 'all imported' scope, but does not mention ordering, permissions, pagination, or that the operation is read-only. For a simple zero-parameter list tool, this is minimally adequate.

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

Conciseness5/5

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

The description is a single, compact sentence that front-loads the action and scope. Every element earns its place and there is no wasted text.

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

Completeness4/5

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

The tool is simple, has an output schema covering return values, and zero parameters. The description states what is listed and what fields are included, making it nearly complete. Missing are explicit usage context and any safety/read-only note, but these are minor given the tool's simplicity.

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

Parameters4/5

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

The tool has zero parameters, so the baseline is 4. The description adds no parameter information, which is appropriate given there is nothing to document.

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 uses a specific verb ('列出' / list) and resource ('讲次' / lectures), and states the scope ('已导入的全部' / all imported) plus returned fields (lecture number, title, category). It clearly distinguishes itself from sibling tools by domain, but does not explicitly name or contrast with alternatives.

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

Usage Guidelines3/5

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

Usage is implied by the tool's nature: use it to get a full list of imported lectures. However, there is no explicit guidance on when to prefer this over sibling tools like search_knowledge_points, nor are any exclusions or prerequisites stated.

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

list_markersA

列出标志词/关键词,可溯源到讲次。

默认返回所有时态关键词(category="时态")。 可用 tense 限定具体时态,如 tense="现在完成时"。

ParametersJSON Schema
NameRequiredDescriptionDefault
tenseNo
categoryNo时态

Output Schema

ParametersJSON Schema
NameRequiredDescription
resultYes

TDQS

A3.7/5.0
Behavior3/5

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

No annotations exist, so the description carries the full burden. It adds meaningful behavioral context by declaring the implicit default value of category, and the read-only nature is inferable from '列出'. However, it says nothing about auth needs, result size, or pagination, which remains a gap for an unannotated tool.

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

Conciseness5/5

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

Three short lines, front-loaded with what the tool returns, then the default, then the narrowing option. Zero wasted text.

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

Completeness4/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 both parameters are addressed with defaults and an example. Only the missing enumeration of accepted values and any usage boundaries keep it from being fully complete.

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

Parameters4/5

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

Schema coverage is 0%, so the description must compensate, and it does: it documents the default for category ('默认返回所有时态关键词') and gives a concrete usage example for tense ('tense="现在完成时"'). It still omits the full set of valid tense values, so it is not exhaustive.

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?

States a specific verb + resource ('列出标志词/关键词') plus the traceability angle ('可溯源到讲次'), which clarifies what the listed markers link back to. It is clearly distinct from siblings like get_knowledge_point or list_lectures, though it never names an alternative to differentiate against.

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

Usage Guidelines3/5

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

It discloses the default behavior (returns all tense keywords with category="时态") and how to narrow results via tense, which implies usage. But it never states when to prefer this over search_knowledge_points or find_by_relation, nor any exclusion.

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

search_knowledge_pointsB

按关键词检索语法知识点。

参数: query: 关键词(中文或英文,如 "现在完成时"、"主将从现"、"since")。 category: 可选,限定大类:词法/句法/时态/语态/非谓语/综合复习。 limit: 最多返回条数。 返回:知识点列表(标题、所在讲次、分类、标签)。

ParametersJSON Schema
NameRequiredDescriptionDefault
limitNo
queryYes
categoryNo

Output Schema

ParametersJSON Schema
NameRequiredDescription
resultYes

TDQS

B3.4/5.0
Behavior2/5

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

No annotations are provided, so the description carries the full burden. It does not disclose whether this is a safe read-only operation, whether it requires permissions, whether results are paginated, or how the search behaves (e.g., exact match vs full-text). The bare return format '知识点列表' is thin behavioral context.

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?

The response is front-loaded with the core purpose, followed by a structured parameter list and a brief return summary. It is compact and every sentence serves to clarify invocation. Slightly verbose in enumerating category values, but that is necessary for an agent to pick valid values.

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

Completeness4/5

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

With no annotations and a 0% schema description coverage, the description steps in to cover all three parameters and the return shape, which is adequate. However, it does not describe pagination, ordering, or how to handle an empty result, leaving minor gaps for a search tool. Since an output schema exists, return values need not be fully explained, so the description's summary suffices.

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

Parameters4/5

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

Schema description coverage is 0%, so the description must compensate. It explains each parameter: query is a keyword in Chinese or English with concrete examples ('现在完成时', 'since'), category limits to specific large classes (词法/句法/时态/语态/非谓语/综合复习), and limit controls the maximum number returned. This adds substantial meaning beyond the schema, though limit's type and default are only in the schema.

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 states a clear verb and resource: '按关键词检索语法知识点' (retrieve grammar knowledge points by keyword). It distinguishes from siblings like get_knowledge_point (singular retrieval) and list_lectures (a different resource), though it does not explicitly name them. The purpose is specific enough for an agent to know this is a search operation over knowledge points.

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

Usage Guidelines3/5

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

Usage is implied by '按关键词检索' (search by keyword), but there is no explicit statement of when to use this tool versus alternatives such as get_knowledge_point or find_by_relation. The parameter descriptions hint at refining searches with category, but no exclusion conditions or preferred scenarios are given.

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

statsC

返回知识库统计(讲次/知识点/标志词数量,按类别分布)。

ParametersJSON Schema
NameRequiredDescriptionDefault

No parameters

Output Schema

ParametersJSON Schema
NameRequiredDescription
resultYes

TDQS

C2.9/5.0
Behavior2/5

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

With no annotations, the description must carry the full behavioral burden, yet it says nothing about whether results are cached, whether the operation is read-only, its cost, or how the category distribution is structured. For a zero-parameter aggregation endpoint these omissions matter.

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 tight sentence that front-loads the verb and resource, with the enumerated metrics acting as scope. No filler, though it is terse to the point of under-specification.

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 existence of an output schema relieves the description of explaining return shapes, and there are no parameters to document. However, for a statistics endpoint over a complex knowledge base there is no mention of read-only behavior or when it should be preferred, leaving a gap given the absence of annotations.

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

Parameters4/5

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

Parameter count is zero, so there are no parameter semantics to convey and the baseline is 4; the description correctly does not fabricate parameter discussion.

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

Purpose3/5

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

States a specific action (return statistics) and resource (knowledge base) with enumerated sub-metrics (lecture/knowledge point/marker counts, distribution by category). This is clearer than a bare name but does not explicitly differentiate itself from siblings like list_lectures or list_markers, which also enumerate counts of the same entities.

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?

No guidance on when to use this aggregation tool versus the sibling list_* tools that would return the underlying items. An agent must infer that this is the 'counts-only' option.

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. 7 tool updatesv0.2.0
    • First observedfind_by_relation
    • First observedget_knowledge_point
    • First observedget_lecture_markdown
    • First observedlist_lectures
    • First observedlist_markers
    • First observedsearch_knowledge_points
    • First observedstats

TDQS

A3.6/5.0

Scored across 7 tools

Disambiguation5/5

Each tool has a clearly distinct retrieval purpose: search, get by id, get lecture markdown, list lectures, list markers, find by relation, and stats. Overlap between search_knowledge_points and list_markers is minimal because markers are a specific entity type with their own filters.

Naming Consistency4/5

Most tools follow a consistent verb_noun pattern (search_, get_, list_, find_by_). 'stats' is a minor deviation as a bare noun, but the overall naming remains predictable and readable.

Tool Count5/5

7 tools is well-scoped for a knowledge base retrieval server. Each tool serves a clear function without redundancy, fitting comfortably within the ideal 3-15 range.

Completeness4/5

Core retrieval operations are covered: search, get by id, get lecture, list lectures, list markers, find by relation, and stats. Minor gaps exist, such as no direct way to list all knowledge points without a search term or to filter markers by lecture, but agents can work around these.

Maintenance

ActivityActive
ResponsivenessNo issues

Related MCP Connectors

Related MCP Servers

  • F
    license
    Not graded
    quality
    D
    maintenance
    Enables storage and retrieval of knowledge in a graph database format, allowing users to create, update, search, and delete entities and relationships in a Neo4j-powered knowledge graph through natural language.
    5
    -
  • A
    license
    Not graded
    quality
    D
    maintenance
    Enables intelligent search and question-answering over PDF documents using semantic similarity and keyword search. Supports OCR for scanned PDFs, persistent vector storage with ChromaDB, and maintains source tracking with page numbers.
    7
    MIT
  • F
    license
    C
    quality
    B
    maintenance
    Enables academic literature management through PDF import, hybrid search, knowledge graph construction, and automated literature review generation. Combines full-text search with semantic vector search for comprehensive paper analysis.
    55
    -