code-search-mcp
🔍 code-search-mcp
Zero-daemon локальный MCP-сервер семантического поиска по коду на базе LanceDB и встроенных ONNX-эмбеддингов.
Хватит искать точные слова через grep. Дайте вашему ИИ-ассистенту для кода возможность искать по смыслу.
Работает из коробки с Claude Code, Gemini CLI, Antigravity (agy) и Cursor на macOS, Windows и Linux.
☕️ Представьте приложение для кофейни
Представьте, что вы пишете программное обеспечение для небольшой районной кофейни.
В вашем коде есть файл, который обрабатывает ситуацию, когда клиент заказывает дополнительный латте с овсяным молоком и получает утреннюю скидку:
// Apply a 15% promotional deduction if the customer visits before 9 AM
export function calculateEarlyBirdReward(bill: OrderSummary): number {
if (bill.orderHour < 9) {
return bill.subtotal * 0.85;
}
return bill.subtotal;
}Теперь представьте, что вы открываете своего ИИ-ассистента для кода (например, Claude Code, Cursor или Gemini CLI) и спрашиваете:
«Где рассчитывается утренняя скидка на напиток?»
Если ваш инструмент опирается только на традиционный текстовый поиск (например, grep), он ищет точное слово "discount".
Нашёл ли он
calculateEarlyBirdReward? Нет.Почему? Потому что в коде использовались слова
promotional deductionиEarlyBirdReward, но не использовалось точное слово"discount".
Именно здесь семантический поиск меняет всё.
Related MCP server: smart-coding-mcp
🧠 Что такое семантический поиск (человеческим языком)?
Традиционный поиск ищет точные буквы и слова.
Семантический поиск ищет смысл за вашими словами.
Как это работает: карта смыслов
Числа вместо букв: ИИ-модель берёт фрагмент текста (или кода) и превращает его в список чисел, который называется эмбеддинг (или вектор).
Координаты на карте: Представьте эти числа как GPS-координаты на огромной карте человеческих понятий.
"discount"и"promotional deduction"оказываются рядом друг с другом на карте."espresso shot"и"latte"находятся вместе."database migration"находится далеко, на другой стороне карты.
Поиск ближайших соседей: Когда вы задаёте вопрос на естественном языке, поисковый движок превращает ваш вопрос в координаты и просто находит фрагменты кода, расположенные на карте ближе всего к нему.
[ Map of Meaning ]
☕️ "morning drink discount" 📍 (Your Question)
│ (Close match!)
▼
🏷 "calculateEarlyBirdReward" 📍 (Your Code)
─────────────────────────────────────────────
🗄 "sql database migration" 📍 (Far Away - Ignored)🚀 Почему семантический поиск — прорыв для написания кода с ИИ
Когда ИИ-ассистенты работают с большими репозиториями на тысячи файлов, они не могут читать каждый файл на каждый запрос — это слишком медленно и требует слишком много токенов.
Вместо этого ИИ должен мгновенно находить нужные 2–3 файла.
В реальных проектах наши кодовые базы полны этого контекста:
Markdown-документация (
.md): ADR-документы, руководства по API, онбординг-документация.Комментарии в коде: объясняющие, почему существует бизнес-правило (например:
// Списываем зерно из бункера кофемашины).Имена функций и переменных: паттерны имен, которые могут различаться между библиотеками.
Семантический поиск напрямую связывает ваши мысли на естественном языке с этими Markdown-документами, комментариями и фрагментами кода — даже когда вы не помните точных имён функций.
🛠 Что мы создали: code-search-mcp
Многие существующие инструменты семантического поиска для разработчиков требуют сложной настройки:
Установка Python 3, виртуальных окружений и
pip.Запуск внешнего фонового сервера базы данных (например, ChromaDB), слушающего сетевой порт.
Настройка демонов автозапуска (
LaunchAgentsна Mac, Task Scheduler в Windows), которые разряжают батарею при включении.Добавление сложных Git-хуков (
pre-commit), которые могут заблокировать работу, если сервер БД офлайн.
Мы хотели совершенно другое: Ноль настройки. Ноль внешних демонов. Мгновенная работа в любом проекте.
Поэтому мы создали code-search-mcp — автономный кросс-платформенный Model Context Protocol (MCP) сервер для Node.js.
┌─────────────────────────────────────────────────────────────┐
│ AI Client │
│ (Claude Code / Gemini CLI / Antigravity / Cursor) │
└──────────────────────────────┬──────────────────────────────┘
│ MCP Protocol (JSON-RPC over stdio)
┌──────────────────────────────▼──────────────────────────────┐
│ code-search-mcp │
│ │
│ ┌──────────────────┐ ┌──────────────────┐ ┌───────────┐ │
│ │ Scanner & │ │ EmbeddingEngine │ │ Watcher │ │
│ │ Layered Ignores │ │ (all-MiniLM-L6) │ │(chokidar) │ │
│ └────────┬─────────┘ └────────┬─────────┘ └─────┬─────┘ │
│ │ │ │ │
│ └───────────┬─────────┴──────────────────┘ │
│ ▼ │
│ VectorStore (LanceDB) │
│ node_modules/.cache/code-search/ │
└─────────────────────────────────────────────────────────────┘⚙️ Технологии внутри
Компонент | Технология | Почему мы выбрали это |
Среда выполнения | Node.js + TypeScript | Кроссплатформенность (macOS, Windows, Linux) с ноль зависимых транзитивных в рантайме. |
Локальные AI-эмбеддинги |
| Генерирует плотные векторы размерностью 384 в том же процессе через |
Векторное хранилище | Встраиваемая бессерверная векторная БД на базе Apache Arrow. Не требуется внешний серверный процесс. | |
Живой наблюдатель файлов |
| Следит за файлами в реальном времени и обновляет векторы инкрементально за ~200 мс при сохранении. |
Протокол |
| Стандартный протокол MCP, поддерживаемый Claude Code, Gemini CLI, Cursor и Windsurf. |
🔍 Как это работает под капотом
1. Как he know when to start индексирование?
Когда ваш ИИ-ассистент запускается (например, вы запускаете Claude Code, Antigravity или Gemini CLI), he подключается к code-search-mcp через стандартный ввод/вывод (stdio).
MCP-сервер подключается мгновенно, меньше чем за 15 мс.
Фоновый рабочий процесс начинает сканирование файлов проекта, не блокируя вашу чат-сессию.
2. Можно ли искать до завершения индексации? (суперспособность в процессе индексации)
Да! Если вы зададите вопрос через 2 секунды после открытия проекта, code-search-mcp никогда не блокирует и не зависает.
Он ет по всем уже проиндексированным файлам и показывает вающий заголовок прогресса в реальном времени:
⚠️ [Index status: INDEXING (35% complete - 2,100/6,000 files indexed)]
Results from currently indexed files:
### Match 1: src/drinks/espresso.ts (Lines 12-30) [Score: 54.2%]3. Будьте терпеливы при первом запуске — он работает только один раз! ⏳
В огромных репозиториях с более чем 5000 файлов самое первое индексирование занимает несколько минут, потому что локальная ИИ-модель впервые генерирует векторные эмбеддинги для каждого чанка кода на вашей машине.
Хорошие новости:
Вы платите время только один раз: итоговая векторная база данных постоянно хранится в
node_modules/.cache/code-search/lancedb/.Мгновенный запуск при следующем открытии: В каждой последующей сессии или перезапуске редактора сервер подключается менее чем за 15 мс без переиндексации.
Инкрементальные обновления в реальном времени: Когда вы пишете код в течение дня, живой наблюдатель обновляет только одну изменёняющуюся файл при сохранении примерно за ~150 мс.
Ждать не нужно: Вы можете сразу начинать задавать вопросы и искать — ассистент ищет по тому, что уже проиндексировано в фоне.
4. Где хранится индекс?
По умолчанию база данных хранится здесь:
📁 node_modules/.cache/code-search/lancedb/
Почему node_modules/.cache?
node_modulesуже игнорируется Git в 100% проектов.Ноль шума в Git системы: неотслеживаемые папки номехи в Git никогда не появляются в вашем репозитории.
(Если в проекте нет
node_modules, сервер корректно использует.code-search/).
5. Что происходит при переключении Git-веток? 🔀
Когда вы выполняете git checkout, git switch или git pull:
Детекция живым наблюдателем: Git обновляет файлы на диске. Он обнаруживает добавленные, изменённые или удалённые файлы в реальном времени.
Быстрое дифференциальное повторное сканирование: переиндексируются только те файлы, которые изменились между ветками (1–2 секунды вместо минут).
Автоматическая очистка: удалённые файлы и старые фрагменты кода из предыдущей ветки автоматически удаляются из LanceDB.
Ручная синхронизация: если вы хотите принудительно выполнить полную переиндексацию после большого merge'а, просто скажите ассистенту: "Выполни
code_search_reindexс параметром force: true".
⚙️ Как управлять настройками и игнорировать лишние файлы
По умолчанию code-search-mcp автоматически игнорирует бинарные файлы (.png, .mp4, .zip), результаты сборки (dist/, build/), локбоксы и любые файлы объемом более 500 КБ, а также учитывает ваш существующий .gitignore.
Если вы хотите настроить параметры или игнорировать дополнительные файлы для вашего проекта, у вас есть два простых варианта:
Вариант 1: Создайте файл .codesearchignore (быстро и просто)
Создайте в корне проекта файл .codesearchignore и используйте стандартный синтаксис gitignore:
# Ignore mock data and test fixtures
tests/fixtures/**
src/mocks/**
# Ignore auto-generated files
src/models/*.generated.ts
locales/**Вариант 2: Создайте файл .codesearchrc.json (расширенные настройки)
Создайте файл .codesearchrc.json в корне проекта, чтобы управлять поведением индексации, пакетной обработкой и лимитом размера файлов:
{
"maxFileSizeKb": 300,
"batchSize": 50,
"customExcludes": [
"legacy_vendor/**",
"docs/archive/**"
],
"supportedExtensions": [
".ts", ".tsx", ".js", ".vue", ".py", ".md", ".json"
]
}📦 Как установить инструмент
Вы можете установить и запустить инструмент любым из следующих способов:
1 шаг: / choice among installation method
Способ A: Прямо из GitHub через npx (без установки — не нужна публикация в npm!)
Любой ИИ-клиент может запустить его напрямую из вашего GitHub-репозитория в момент необходимости:
npx -y github:your-username/code-search-mcp(Node автоматически скачивает репозиторий, собирает бандл и запускает MCP-сервер).
Способ B: Из npm-реестра (после публикации)
Если вы опубликовали пакет в npm:
npx -y code-search-mcp
# or global install:
npm install -g code-search-mcpСпособ C: Локальная разработка / через npm link (самый быстрый локальный старт)
Если вы запускаете его прямо из локальной папки с сорк-кодом:
cd /path/to/code-search-mcp
npm install
npm run build
npm linkТеперь code-search-mcp зарегистрирован как глобальная команда в вашей системе!
2 шаг: подключите его к ИИ-клиенту
1. Claude Code
# If running via GitHub:
claude mcp add code-search -s user -- npx -y github:your-username/code-search-mcp
# If running locally (linked):
claude mcp add code-search -s user -- code-search-mcp2. Antigravity CLI (agy)
Выполните эту команду в терминале:
mkdir -p ~/.gemini/config/plugins/code-search && cat << 'EOF' > ~/.gemini/config/plugins/code-search/plugin.json
{ "name": "code-search" }
EOF
cat << 'EOF' > ~/.gemini/config/plugins/code-search/mcp_config.json
{
"mcpServers": {
"code-search": {
"command": "npx",
"args": ["-y", "github:your-username/code-search-mcp"]
}
}
}
EOF3. Gemini CLI
Добавьте в ~/.gemini/settings.json:
{
"mcpServers": {
"code-search": {
"command": "npx",
"args": ["-y", "github:your-username/code-search-mcp"],
"trust": true
}
}
}4. Cursor / Claude Desktop
Добавьте в .cursor/mcp.json:
{
"mcpServers": {
"code-search": {
"command": "npx",
"args": ["-y", "github:your-username/code-search-mcp", "--path", "${workspaceFolder}"]
}
}
}🤖 Руководство для ИИ-агента и справочник инструментов
Если вы ИИ-ассистент (Claude Code, Gemini CLI, Cursor, Antigravity или Windsurf), читающий этот репозиторий, вот ваше краткое руководство по использованию инструментов MCP, предоставляемых code-search-mcp:
🛠️ Доступные MCP-инструменты
Инструмент | Параметры (Аргументы) | Описание | Когда использовать |
|
| Выполняет гибридный семантический + лексический поиск по проиндексированным файлам репозитория. Возвращает фрагменты кода с номерами строк и оценками схожести. | ПЕРВЫЙ ВЫЗОВ при поиске концепций, бизнес-логики, рабочих процессов, UI-компонентов или функций, описанных на естественном языке (например, «где обновляется аутентификация пользователя», «калькулятор налога для корзины покупок»). |
| (нет) | Возвращает текущий статус индексации ( | Используйте перед большими поисковыми запросами, если подозреваете, что индексация ещё не завершена. |
|
| Запускает фоновую переиндексацию или полное пересоздание базы данных. | Используйте, когда пользователь явно запросил пересоздание базы данных или после массовых слияний веток. |
| (нет) | Возвращает встроенные рекомендации по использованию агента и лучшие практики. | Используйте для самостоятельного изучения лучших практик при вызове инструмента. |
🧭 Матрица выбора инструмента: когда какой инструмент использовать
┌───────────────────────────────────────────────┐
│ What are you looking for in the codebase? │
└───────────────────────┬───────────────────────┘
│
┌───────────────────────────────────┼───────────────────────────────────┐
▼ ▼ ▼
┌─────────────────────────┐ ┌─────────────────────────┐ ┌─────────────────────────┐
│ Concept / Feature / │ │ Known Symbol / Callers │ │ Exact Literal String / │
│ Business Logic Intent │ │ & Blast Radius Analysis │ │ Error Code / CSS Class │
│ (Natural Language) │ │ (Exact identifier) │ │ (Exact text match) │
└──────────┬──────────────┘ └──────────┬──────────────┘ └──────────┬──────────────┘
▼ ▼ ▼
┌─────────────────────────┐ ┌─────────────────────────┐ ┌─────────────────────────┐
│ 🔍 USE: code_search │ │ 🌳 USE: codegraph │ │ 🔎 USE: grep_search │
│ • "where is payment..." │ │ • codegraph_explore │ │ • "ERR_INVALID_AUTH" │
│ • "tax calculation..." │ │ • callers / callees │ │ • ".btn-primary-blue" │
└─────────────────────────┘ └─────────────────────────┘ └─────────────────────────┘💡 Полезные советы для ИИ-агентов
Используйте
codeOnly: trueдля чистой логики реализации: Если вы хотите найти вычисления и формулы на чистом TypeScript/JavaScript и исключить документацию в Markdown или руководства по навыкам, всегда передавайтеcodeOnly: true.Используйте
pathFilterдля сужения до подсистем: Если пользователь спрашивает «как работает оформление заказа в биллинговом модуле?», передайтеpathFilter: "src/billing".Используйте номера строк для прямого редактирования кода: Фрагменты кода возвращаются с номерами строк, начиная с 1 (
14: export function calculateTotal()). Эти диапазоны можно передать напрямую вreplace_file_contentилиview_file— без угадывания.Устойчивость к опечаткам: Свободно передавайте обычные слова — движок автоматически обрабатывает множественные формы (
стемминг) и опечатки (исправление Левенштейна) за <1мс.
🤝 Идеальная пара для ИИ: почему стоит установить оба инструмента: code-search и codegraph
Современные ИИ-ассистенты для работы с кодом показывают наилучший результат, когда у них есть два взаимосторонних инструмента: семантический поиск (code-search-mcp) и AST-граф кода (codegraph).
┌─────────────────────────────────────────────────────────┐
│ User: "Where is subscription discount handled?" │
└────────────────────────────┬────────────────────────────┘
│
▼
┌─────────────────────────────────────────────────────────┐
│ 1. SEMANTIC SEARCH (code_search) │
│ • Understands intent, concepts, and natural language │
│ • Finds: subscription-billing.engine.ts (via JSDoc) │
└────────────────────────────┬────────────────────────────┘
│
▼
┌─────────────────────────────────────────────────────────┐
│ 2. AST CODE GRAPH (codegraph_explore) │
│ • Understands syntax trees, callers, and blast radius │
│ • Traces: callers into legacy LegacyOrderProcessor.js │
│ • Discovers: unit tests (subscription-billing.spec.ts) │
└─────────────────────────────────────────────────────────┘Почему одного инструмента недостаточно:
Инструмент | Основная задача | Что удаётся лучше всего | Где возникают сложности |
| Поиск концепций и намерений | Находит бизнес-логику, функции, компоненты, архитектурные документы по мнению на естественном языке. | Трудно обходить динамические иерархии вызовов и старые файлы без аннотаций. |
| Структурная навигация и радиус поражения | Прослеживает буквальные определения символа, вызывающие и вызываемые функции и покрывающие unit-тесты в один переход. | Плохо ищет концепции, описаны на естественном языке, если неизвестны имена символов. |
Пример из реальной практики: современный движок против легаси-монолита
В реальной корпоративной кодовой базе:
Современный движок (
subscription-billing.engine.ts) имеет осознанные имена (calculateSubscriptionDiscount) и подробные JSDoc-объяснения.code_searchнаходит её с более 55% совпадением за миллисекунды.Легаси-ядро (
LegacyOrderProcessor.js) — это файл на 2 000 строк, исползующий старые термины (getDiscountedTotal,applyOldDeduction) или опечатки. Только семантический поиск может его занизить.Синергия: когда
code_searchпопадает наsubscription-billing.engine.ts,codegraph_exploreпроментно прослеживает все вызовы вLegacyOrderProcessor.jsи карпографирует радиус поражения по unit-тестам, покрывающим их — без догадок!
Рекомендуемая парная конфигурация
Добавьте оба инструмента в вашу MCP-конфигурацию:
{
"mcpServers": {
"code-search": {
"command": "node",
"args": ["/path/to/code-search-mcp/dist/bin/cli.js"]
},
"codegraph": {
"command": "codegraph",
"args": ["mcp"]
}
}
}📋 Рекомендации по настройке ассистента
Чтобы ваш ИИ-ассистент автоматически выбирал code_search и codegraph, добавьте следующее правило в файл инструкций проекта (CLAUDE.md, GEMINI.md, .github/copilot-instructions.md or .cursorrules):
## Code Navigation & Search
1. **CodeGraph (`codegraph_explore`)**: Call FIRST when exploring known symbols, tracking call paths, finding usages, or analyzing blast radius (callers + covering tests).
2. **Semantic Search (`code_search`)**: Call FIRST when looking for features, domain behaviors, or business logic described in natural language (e.g. "where is discount calculated", "checkout suggestions formatted").🧪 Как проверить, что всё работает
После установки вы можете проверить работу code-search-mcp тремя проверки:
Проверка 1. Спросите своего ИИ-ассистента о статусе
В любом чате с Claude Code, Cursor или Gemini CLI спросите:
«Проверь
code_search_status»
Ожидаемый результат:
Index Status: READY (or INDEXING)
Progress: 100%
Files: 6,070 / 6,070 indexed
Chunks: 8,204 code chunks in LanceDBПроверка 2. Попробуйте семантический поиск по естественному языку
Спросите ИИ-ассистента:
«Используй
code_search, чтобы найти, как обрабатываются правила скидок и бонусов для клиентов»
Ожидаемый результат:
### Match 1: src/rewards/early-bird.ts (Lines 1-18) [Score: 56.4%]Ассистент мгновенно возвращает релевантные фрагменты кода с точными номерами строк и оценками схожести.
Проверка 3. Проверьте отслеживание файлов в живом режиме
Создайте в проекте новый тестовый файл (например,
src/drinks/secret-recipe.ts) с уникальным комментарием:// Caramel macchiato secret syrup blend formula export const caramelBlend = 42;Сохраните файл.
Сразу спросите вашего ИИ-ассистента:
«Найди формулу секретной смеси сиропов через
code_search»Новый файл будет найден и показан менее чем за 1 секунду — никакого ручного пересборки или перезапуском не требуется!
Проверка 4. Запуск автоматических тестов (необязательно)
Если вы разработчик из исходного кода, выполните:
npm testВсе 31 модульный и интеграционный тест будут выполены и пройдены, проверяя рукопожатие MCP-протокола, генерацию векторов ONNX, хранение LanceDB, жизненный цикл watcher, стемминг слов и коррекцию опечаток.
🛠️ Реальные проблемы, с которые мы столкнулись, и как починили (простыми понятиями)
Создание поискового движка, одинаково хорошо работающего для людей и ИИ-агентов, выздоявило несколько практических сложностей. Вот что было найдено, и как решена каждая проблема:
1. 🔤 Ловушка множественного числа и окончаний ("marks" против "Marker")
Проблема: когда человек общается на естественном языке и пишет: "как chart iqа uses marks на графике", он использует множественное число
"marks". При этом в коде класс может называтьсяCIQ.MarkerormarkersSample. Обычный запрос (LIKE '%marks%') полностью упускаетMarkerиз-за лишней «s».Устранение: мы создали лёгкий стеммер. Он автоматически удаляет типичные суффиксы (
-s,-ing,-ed,-ers,tion). При поиске"marks"ищется корень"mark"и мгновенно находятсяCIQ.Marker,markAxis,markersSample— с нулевой производительностью.
2. ✍️ Ловушка опечаток ("calcualte mrgin shortfall")
Проблема: люди живо наберётся в чат и допускают опечатки (например,
mrginвместоmarginилиcalcualteвместоcalculate). Если в слове опечатка, классический keyword search не сработает в 100% случаев.Устранение: создан встроенный словарь в памяти + корректор Левенштейна. Во время индексации движок собирает словарь всех реальных имён переменных, классов и терминов в вашем репозитории. Когда вы приходите с описанкой, движок проверяет словарь и исправляет опечатку за <1 мс перед поиском.
3. 🤖 Дружелюбные для ИИ-агентов блоки кода (с номерами строк)
Проблема: при выводеомы в ходе водики строка (
Lines 10-50), но код внутри блока не имел номеров строк. Когда ИИ-агент (Claude Code, Gemini CLI, Antigravity) хотел отредактировать или процитировать строку, ему приходилось вручную пересчитать или угадывать смещение.Устрашение: теперь каждая строка в фрагменте кода автоматически получает префикс с исходным номером (
10: export class ...). ИИ-агенты могут сразу передавать точные номера строк в инструменты редактирования, без дополнительных чтений.
4. 📚 Шум документации в чистом поиске по коду
Проблема: при поиске общих понятий, например «как форматива валюту», большие markdown-файлы и инженерные гайды часто ранжировались выше реальных
.tsутилитов, потому что док содержат много разговорного английского.Что мы сделали:
Добавлены параметры поиска:
codeOnly: true(игнорирует markdown/doc),pathFilter: "src/...",language.Снижен вес встроенных JSON-словарей, чтобы ключевая логика TypeScript/JavaScript всегда была выше приоритет.
5. 🔁 Переполнение результата (множество чанков из одного большого файла)
Проблема: при поиске общей темы один файл на 3000 строк с нескольким совпадениями занимал все 10 слотов и скрывал совпадения из мелких خوب вспомогательных файлов.
Устранение: введено разнообразие в рамках одного файла: engine возвращает не более 2 чанков с высокими очками срезов для каждого файла, что позволяет получить хорошее разнообразие результатов по всей базе.
6. ⚡ Конфликты блокировки БД при быстрых сохранениях
Проблема: при переключении веток или массового сохранения одного за другим несколько параллельных записей в LanceDB могли вызывать ошибки конфликта версии.
Устранено: добавлена асинхронная очередь записей с попеременно-экспоненциальной задержкой (backoff). Если возникают конфликты добавления, очередь несколько миллисекунд и безопасно повторяет, не роняя сервер.
💡 Итог
Совмещая эмбеддинги ONNX внутри процесса с встроенной LanceDB, интеллектуальной генерацией токенов и протоколом контекста моделей (MCP), мы устраняли трение локального семантического поиска:
✅ Без бэкграунд-демонов на вашем ноутбуке.
✅ Без зависимостей OpenAI/Python и ChromaDB.
✅ Без засорение git (только
node_modules/.cache).✅ Автоматическая обработка опечаток и словоформ в <1 мс.
✅ Мгновенный смысловой поиск, связавание природных вопросов на ваш язык с точным кодом и markdown-документами.
Приятной разработки! ☕️🚀
Available Tools
4 toolscode_searchA
Search the codebase semantically using natural language queries (e.g. "how is payment verified", "calculate discount rate"). Returns relevant code snippets with file paths and line numbers. Supports filtering by directory path, programming language, or codeOnly (to exclude markdown docs).
| Name | Required | Description | Default |
|---|---|---|---|
| limit | No | Maximum number of results to return (default: 10) | |
| query | Yes | The natural language or identifier search query | |
| codeOnly | No | If true, excludes markdown documentation files (.md) to prioritize actual code formulas and logic | |
| language | No | Optional programming language filter (e.g. "typescript", "javascript", "vue") | |
| pathFilter | No | Optional directory or file path substring to restrict search (e.g. "src/auth", "src/billing") |
TDQS
Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?
With no annotations provided, the description carries the full burden of behavioral disclosure. It explicitly states that the tool returns 'relevant code snippets with file paths and line numbers' and describes supported filters, which conveys a read-only, non-destructive behavior. It does not mention any side effects or limitations, but for a search tool this level of detail is adequate.
Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.
Is the description appropriately sized, front-loaded, and free of redundancy?
The description is compact and efficient, consisting of two sentences that front-load the primary action with examples, then cover the return format and filters. There is zero filler, and every sentence contributes to the agent's ability to invoke the tool correctly.
Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.
Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?
Since there is no output schema, the description appropriately explains the return value ('relevant code snippets with file paths and line numbers'). It also covers all parameters implicitly through the filtering descriptions and the query example, making the tool fully usable without needing to inspect the schema or other sources.
Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.
Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?
Schema description coverage is 100%, so the schema already documents every parameter. The description adds minimal extra meaning beyond what the schema provides—it merely echoes the filtering options (directory path, language, codeOnly) without introducing new syntax or details. This is the baseline score for high schema coverage.
Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.
Does the description clearly state what the tool does and how it differs from similar tools?
The description clearly states a specific verb ('search'), a resource ('the codebase'), and a method ('semantically'), with concrete examples of natural language queries. It also differentiates from sibling tools by implying this is the actual search operation, while siblings are status, reindex, and guide tools.
Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.
Does the description explain when to use this tool, when not to, or what alternatives exist?
The description provides clear context for when to use the tool (searching the codebase semantically) and mentions filtering options that shape usage. It does not explicitly name alternatives or state when not to use it, but the sibling tools are so distinct (status, reindex, guide) that exclusion guidance is not strictly necessary.
Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.
code_search_guideA
Get best practices and usage instructions for AI agents on how and when to use code_search.
| Name | Required | Description | Default |
|---|---|---|---|
No parameters | |||
TDQS
Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?
No annotations are provided, so the description must carry the behavioral burden. It clearly implies a read-only retrieval of guidance, but does not disclose output format, size, or any side effects. For a simple guide tool, the lack of explicit behavioral detail is acceptable but not comprehensive.
Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.
Is the description appropriately sized, front-loaded, and free of redundancy?
The description is a single, front-loaded sentence that states the action and the target resource with zero redundancy. Every word contributes to clarity, making it highly efficient.
Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.
Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?
For a parameterless guide with no output schema, the description sufficiently conveys the tool's purpose and content. It could explicitly state that the returned instructions should be followed before using code_search, but the sibling context and the description's phrasing make this largely self-evident, so the gap is minimal.
Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.
Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?
There are zero parameters, and schema coverage is 100% (vacuously). Since the tool takes no inputs, the description need not add parameter-specific meaning; the baseline of 4 for no-parameter tools applies without deduction.
Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.
Does the description clearly state what the tool does and how it differs from similar tools?
The description uses a specific verb ('get') and a clear resource ('best practices and usage instructions for AI agents on code_search'). It distinguishes itself from sibling tools like code_search (which performs the search), code_search_status, and code_search_reindex, making its purpose unambiguous.
Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.
Does the description explain when to use this tool, when not to, or what alternatives exist?
The description explicitly states it provides guidance on how and when to use code_search, which implicitly tells an agent to use this tool when needing to decide on code_search usage. However, it does not explicitly contrast with sibling tools or state 'use this before calling code_search', leaving that inference to the agent.
Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.
code_search_reindexA
Trigger a background re-index of the repository. Can be used to force a full reindex.
| Name | Required | Description | Default |
|---|---|---|---|
| forceFull | No | If true, clears existing vector database and rebuilds index from scratch |
TDQS
Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?
With no annotations provided, the description carries the burden of disclosing behavior. It mentions 'background' indicating asynchronicity and 'force a full reindex' implying destructive potential, but it omits details like whether an incremental reindex is available, idempotency, or cancellation behavior. It provides some useful context but is not comprehensive.
Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.
Is the description appropriately sized, front-loaded, and free of redundancy?
The description is two short, focused sentences with no filler. It front-loads the core action ('Trigger a background re-index') and adds the optional force behavior succinctly. Every word earns its place.
Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.
Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?
For a tool with a single optional parameter and no output schema, the description covers the essentials but leaves gaps: it does not clarify what happens when forceFull is false (e.g., incremental indexing) nor mention the sibling code_search_status for checking reindex progress. These are minor gaps given the simplicity.
Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.
Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?
Schema description coverage is 100%, and the forceFull parameter is fully documented in the schema ('clears existing vector database and rebuilds index from scratch'). The description's mention of 'force a full reindex' adds minimal value beyond the schema. Baseline 3 is appropriate when the schema does the heavy lifting.
Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.
Does the description clearly state what the tool does and how it differs from similar tools?
The description clearly states the action ('Trigger a background re-index of the repository') with a specific verb and resource. It also hints at the forceFull parameter. This distinguishes it from siblings like code_search, code_search_status, and code_search_guide, which serve different purposes.
Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.
Does the description explain when to use this tool, when not to, or what alternatives exist?
The description does not explicitly state when to use this tool versus alternatives. It implies usage through the tool's purpose but lacks explicit context such as 'use after schema changes' or 'when index is stale'. No exclusions or alternative routing are provided.
Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.
code_search_statusA
Get the current indexing status, progress percentage, total files, and indexed chunk count.
| Name | Required | Description | Default |
|---|---|---|---|
No parameters | |||
TDQS
Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?
With no annotations, the description carries the full burden. It correctly implies a read-only operation via 'Get' and enumerates the output fields. It does not mention side effects, authentication, or rate limits, but for a simple status check these are not critical. It does not contradict any annotations (there are none) and gives sufficient behavioral context for expectation setting.
Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.
Is the description appropriately sized, front-loaded, and free of redundancy?
The description is a single sentence that lists the key outputs without any fluff. It is front-loaded with the verb and resource, making it instantly scannable. Every word earns its place.
Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.
Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?
For a tool with no parameters, no annotations, and no output schema, the description is fully sufficient. It states exactly what information will be retrieved. An agent can call it without needing additional context or clarification.
Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.
Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?
The tool has zero parameters, so the schema coverage is trivially 100%. Baseline for 0 parameters is 4. The description adds no parameter-specific details (none needed), and it correctly explains what the tool returns, which is sufficient.
Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.
Does the description clearly state what the tool does and how it differs from similar tools?
The description clearly states the action ('Get') and the resource ('current indexing status'), and lists specific fields (progress percentage, total files, indexed chunk count). The verb and resource differentiate it from siblings like code_search, code_search_reindex, and code_search_guide. It unambiguously describes what the tool does.
Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.
Does the description explain when to use this tool, when not to, or what alternatives exist?
The description implies its use for checking indexing status but provides no explicit guidance on when to choose this over the sibling tools (e.g., 'use this to check, not to trigger reindexing'). No exclusions or alternative references are given. While the purpose is clear, the tool lacks explicit routing compared to the high-standard examples.
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.
4 tool updates
v0.1.0- First observed
code_search - First observed
code_search_guide - First observed
code_search_reindex - First observed
code_search_status
TDQS
Scored across 4 tools
Each tool has a unique, clearly defined purpose: search, status, reindex, and guide. There is no overlap or ambiguity between them, and the descriptions make it obvious which tool to use for each task.
All tool names follow the same convention: 'code_search_' followed by a simple action verb (search, status, reindex, guide). This is perfectly consistent and makes the tool set easy to predict and use.
With 4 tools, the set is tightly scoped and every tool serves a necessary function for a code search server. This is an ideal count—not too thin or over-bloated—for the domain.
The tool surface covers the full lifecycle of a code search server: performing searches, checking index status, triggering reindexes, and providing usage guidance. There are no obvious gaps in functionality.
Maintenance
Related MCP Connectors
Shared memory for coding agents. Stop re-explaining your codebase every session.
Code intelligence for coding agents: semantic, AST, graph, and full-text search. 279+ languages.
Project memory, semantic code search, and grounded agent context.
Code intelligence for LLMs. Analyze, search, and retrieve code from any public git repository.
Related MCP Servers
- AlicenseNot gradedqualityCmaintenanceProvides Claude Code with local semantic search and indexing of your codebase using AST-aware chunking and hybrid search, enabling deep code understanding without sending data to the cloud.46 PyPIMIT
- AlicenseAqualityDmaintenanceEnables AI assistants to perform intelligent semantic code search across codebases using local AI embeddings for meaning-based retrieval.678 npmMIT
- FlicenseNot gradedqualityDmaintenanceEnables semantic code search across codebases using AI embeddings and vector similarity, integrated with Claude Desktop and Cursor.-
- AlicenseAqualityAmaintenanceEnables AI coding assistants to perform local semantic code search using AST parsing and embeddings, finding code by meaning with exact file and line locations, plus AST-based usage lookup.4MIT