# code-index [Health: Active]

**Category:** 🗄️ Databases  
**Repository:** https://github.com/Regsorm/code-index-mcp  
**GitHub Stars:** 124  
**Views:** 2  
**Installs:** 0  
**Upvotes:** 0  
**Directory Page:** https://allmcps.com/mcp/code-index

## Description
Быстрый индексатор кода для AI-моделей. Rust + tree-sitter + SQLite. Мгновенный поиск по символам.

## Tools
Capabilities this server exposes over MCP:

- **search_function** — Full-text search across functions (name, docstring, body)
- **search_class** — Full-text search across classes
- **get_function** — Get function by exact name (case-insensitive fallback; **(v0.44.0)** on 0 matches returns `did_you_mean` with similar names)
- **get_class** — Get class by exact name (case-insensitive fallback; **(v0.44.0)** on 0 matches returns `did_you_mean` with similar names)
- **get_object_structure** — Structure of a 1C object. **v0.63.0:** object templates are now in the registry — a row `Catalog.X.Template.Y` with the owner, the template kind and a `content_indexed` flag (large templates stay out of the index, yet the template itself is visible and findable by name)
- **get_callers** — Who calls this function? **(v0.35.0)** each row carries the caller's source `path` (distinguishes same-named callers from different files). **v0.62.0:** for 1C configurations, form event handler bindings (`kind: form_binding`) are added to the code callers — such a procedure is run by the platform…
- **get_callees** — What does this function call? **(v0.35.0)** each row carries the source `path
- **find_path** — (v0.23.0)** Shortest path in the call graph between two functions `from`→`to` (iterative cycle-safe BFS over unique `calls` nodes, `max_depth=5`, any language). Returns path edges `[{caller, callee, line}]`. **v0.57.0:** an empty answer carries walk cut-off flags `walk_depth_exhausted` / `walk_node…
- **get_call_tree** — (v0.23.0)** Call tree from a `root` function up to `max_depth` (default 3). `direction`: `callees`/`down` (downstream) or `callers`/`up`. Flat edge list `[{caller, callee, line, depth, path}]` (**(v0.35.0)** `path` = source file of each edge) + nested `{name, children}` tree; `max_nodes` cap
- **find_symbol** — Search everywhere (functions, classes, variables, imports)
- **get_imports** — Imports by module or file
- **get_file_summary** — Complete file map without reading source
- **get_stats** — Index statistics
- **search_text** — Full-text search across text files
- **grep_body** — Substring or regex search in function/class bodies. Returns `match_lines` (first 3 line numbers) and `match_count` (total, if > 3). v0.7.0: optional `path_glob`, `context_lines
- **stat_file** — (v0.7.0)** Metadata of a single file: exists, size, mtime, language, lines_total, content_hash, indexed_at, category (`text`/`code`). **(v0.8.0)** adds `oversize: bool` for code files
- **list_files** — (v0.7.0)** Flat file listing with optional `pattern` (glob like `**/*.py`), `path_prefix`, `language`, `limit`. **v0.49.8:** `limit` defaults to 500; when more files match, the response carries `{truncated, total, shown, limit}` — previously the listing was cut off silently and looked complete
- **read_file** — (v0.7.0)** Read content of a file. Optional `line_start`/`line_end` (1-based, inclusive). Soft-cap 5000 lines or 500 KB, hard-cap 2 MB. **(v0.8.0)** works for **code files** too (`.py`, `.bsl`, `.rs`, `.ts`, etc.) — content stored in `file_contents` table (zstd). Oversize files (default > 5 MB) ret…
- **grep_text** — (v0.7.0)** Regex search over text-file content (REGEXP). Closes the FTS5 special-character gap. Optional `path_glob`, `language`, `context_lines`. Hard-cap 1 MB on response size
- **grep_code** — (v0.8.0)** Regex search over **code-file** content (`.py`, `.bsl`, `.rs`, `.ts`, etc.) via `file_contents` table (zstd-decode in Rust). Same parameters as `grep_text`: `regex`, `path_glob?`, `language?`, `limit?`, `context_lines?`. Since v0.66.0 both tools also accept `pattern` — a literal, case-in…
- **health** — MCP server health and connected repos
- **get_form_handlers** — Managed-form event handlers by `(owner_full_name, form_name)`. Owner accepted in both formats — `Document.X` and export-folder `Documents.X` (v0.31.0). **v0.54.0:** returns `(event, handler, element)` triples — `element` is the form item the handler belongs to (absent for form-level handlers); an o…
- **get_event_subscriptions** — All event subscriptions from `EventSubscriptions/*.xml`. Filters: handler module, event (Russian or English platform enum — `OnWrite`→`ПриЗаписи`), `source` — by source object (`Document.X`/`DocumentObject.X`/short name, v0.31.0). Unknown parameters are rejected with the list of valid filters; defa…
- **find_path_bsl** — Call-chain between two procedures via `proc_call_graph` (recursive CTE, max_depth=3). BSL-specific variant of the universal `find_path` — `proc_call_graph` carries `call_type` and procedure keys. **(v0.35.0)** `from`/`to` and procedure keys are `<rel_path>::<name>` (a bare name is accepted for unre…
- **search_terms** — Meaning-based procedure search (v0.30.0):** terms are filled mechanically at index time — words of the procedure name (CamelCase split), the owner object's name and synonym, the comment above the procedure; no LLM needed. Trigram FTS: word forms and 3+ character substrings work, case and ё/е are ir…
- **get_data_links** — Data-links graph (v0.10.0):** what an object references / what references it, via reference-typed attributes, register dimensions and tabular-section attributes (`data_links` table). `direction=out\
- **find_data_path** — Data-links graph (v0.10.0):** chain of reference links from one object to another (BFS over `data_links`, like `find_path` but for data, not calls). **v0.57.0:** on failure the answer distinguishes «no path» from «not enough hops» — flags `depth_exhausted`, `visited_nodes` and a ready call with a l…
- **get_register_writers** — Register recorders / document movements (v0.16.0):** for a register (`AccumulationRegister.Stock`) returns `writers` — documents writing movements; for a document — `writes_to` (target registers). From the declarative `<RegisterRecords>` set (recorder edges of `data_links`). One call covers both di…
- **get_object_profile** — Object passport in one call (v0.21.0):** the full portrait of an object — structure + forms + modules + data links — instead of a series of `get_object_structure`/`get_form_handlers`/`get_data_links`. The `sections` parameter (`['structure'\
- **find_references** — Impact map (v0.21.0):** everything that references an object, in one call — reverse `data_links` (structural refs from metadata) + `metadata_code_usages` (usages in `.bsl` code) + `role_rights` (roles holding rights on it), broken down by kind with samples (`limit`). **v0.55.0:** `section` (`data_r…
- **bsl_sql** — Arbitrary read-only SQL (v0.21.0):** a `SELECT`/`WITH` query over the repo's `index.db` for the long tail of metadata/graph questions that have no dedicated tool (roles/RLS, joins, aggregations). Guard: `SELECT`/`WITH` only + `Statement::readonly()` + row cap + timeout. Tables: `metadata_objects`,…

## Claude Desktop Quick Installation
Install path detected from listing signals. Uses `npx` (confidence: high):

```json
"mcpServers": {
  "code-index": {
    "command": "npx",
    "args": ["-y","@regsorm/code-index-mcp"]
  }
}
```

## Documentation & README

<a href="https://infostart.ru/1c/tools/2677918/" title="Публикация на Инфостарте">
  <img src="https://infostart.ru/bitrix/templates/sandbox_empty/assets/tpl/abo/img/logo.svg" alt="Infostart" height="32">
</a>

---

# code-index-mcp

[![Релиз](https://img.shields.io/github/v/release/Regsorm/code-index-mcp)](https://github.com/Regsorm/code-index-mcp/releases/latest)
[![npm](https://img.shields.io/npm/v/%40regsorm%2Fcode-index-mcp)](https://www.npmjs.com/package/@regsorm/code-index-mcp)
[![Лицензия](https://img.shields.io/github/license/Regsorm/code-index-mcp)](LICENSE)

**Поиск по коду для ИИ-агентов. Один бинарник, индекс в SQLite, ответ за миллисекунды.
Разбирает выгрузки 1С:Предприятие 8.3 — и из Конфигуратора, и из 1С:EDT.**

[Полное руководство](https://github.com/Regsorm/code-index-mcp/blob/HEAD/README_RU.md) · [English](https://github.com/Regsorm/code-index-mcp/blob/HEAD/README_EN.md) · [Документация](https://github.com/Regsorm/code-index-mcp/blob/HEAD/docs/) · [Журнал изменений](https://github.com/Regsorm/code-index-mcp/blob/HEAD/CHANGELOG.md)

---

## Установка

### Windows — одной командой

```powershell
irm https://raw.githubusercontent.com/Regsorm/code-index-mcp/main/install.ps1 | iex
```

Скачивает последний выпуск в `C:\tools\code-index`, запоминает папку в
переменной окружения, создаёт заготовку файла настроек и печатает готовый блок
для `.mcp.json`.

С параметрами — папка установки, папка с исходниками, автозапуск при входе в
систему:

```powershell
& ([scriptblock]::Create((irm https://raw.githubusercontent.com/Regsorm/code-index-mcp/main/install.ps1))) `
    -InstallDir 'D:\code-index' -Repo 'main=D:\Repo1C' -RegisterAutostart
```

Автозапуск идёт через папку автозагрузки пользователя: прав администратора не
требует, окон не показывает. Остальные параметры — `-Flavor core` для сборки
без 1С, `-Version 1.0.0` для конкретного выпуска, `-Port` и `-DaemonPort`, если
порты по умолчанию заняты. Полный список — `Get-Help .\install.ps1 -Detailed`.

### Windows — вручную, готовый архив из выпуска

Скачивает последний выпуск, распаковывает в `C:\tools\code-index` и запоминает
эту папку в переменной окружения:

```powershell
$dst = 'C:\tools\code-index'
New-Item -ItemType Directory -Force $dst | Out-Null
$url = (Invoke-RestMethod https://api.github.com/repos/Regsorm/code-index-mcp/releases/latest).assets |
       Where-Object name -eq 'bsl-indexer-windows-x64.zip' |
       Select-Object -ExpandProperty browser_download_url
Invoke-WebRequest $url -OutFile "$env:TEMP\code-index.zip"
Expand-Archive "$env:TEMP\code-index.zip" -DestinationPath $dst -Force
setx CODE_INDEX_HOME $dst
```

`bsl-indexer` — сборка с поддержкой 1С (33 инструмента). Нужна работа без 1С —
возьмите `code-index-windows-x64.zip` (20 инструментов). Для Linux и macOS в том
же выпуске лежат `*-linux-x64.tar.gz` и `*-macos-arm64.tar.gz`.

Дальше — файл настроек, запуск, подключение клиента и автозапуск.
Всё это без скриптов, по шагам: [установка вручную](https://github.com/Regsorm/code-index-mcp/blob/HEAD/docs/manual-install.md)
([English](https://github.com/Regsorm/code-index-mcp/blob/HEAD/docs/manual-install_EN.md)).

### npm

```bash
npm install -g @regsorm/code-index-mcp
npx @regsorm/code-index-mcp serve --path /путь/к/репозиторию
```

Шаг `postinstall` скачивает готовый бинарник под вашу платформу — ничего не
компилируется. Пакет есть и в [реестре MCP](https://registry.modelcontextprotocol.io/)
под именем `io.github.Regsorm/code-index`. В обёртке только сборка без 1С.

Сервер `serve` только читает индекс, строит его фоновый индексатор. Поэтому
должны быть запущены `npx @regsorm/code-index-mcp daemon run` и задана
переменная `CODE_INDEX_HOME` — иначе инструменты отвечают `daemon_offline`.
Настройка — в [полном руководстве](https://github.com/Regsorm/code-index-mcp/blob/HEAD/README_RU.md#настройка-фонового-демона-v05).

### Сборка из исходников

```bash
git clone https://github.com/Regsorm/code-index-mcp.git
cd code-index-mcp
cargo build --release -p code-index                          # без 1С
cargo build --release -p bsl-indexer --features enrichment   # с поддержкой 1С
```

Нужен Rust 1.77+.

## Подключение к клиенту

Общий процесс по HTTP — один индекс на все сессии и все проекты. HTTP-сервер
встроен в программу, отдельный веб-сервер не нужен; по умолчанию он слушает
только `127.0.0.1`:

```json
{
  "mcpServers": {
    "code-index": {
      "type": "http",
      "url": "http://127.0.0.1:8011/mcp"
    }
  }
}
```

Отдельный процесс на сессию (`stdio`) — клиент сам запускает сервер при открытии
сессии, порт не нужен. Фоновый индексатор (`daemon run`) при этом тоже должен
работать: сервер только читает индекс, а строит его индексатор. Без него
инструменты отвечают `daemon_offline`:

```json
{
  "mcpServers": {
    "code-index": {
      "command": "npx",
      "args": ["-y", "@regsorm/code-index-mcp", "serve", "--path", "."]
    }
  }
}
```

Работает с Claude Code, Cursor, VS Code, LibreChat — с любым клиентом MCP.
Настройка фонового демона, список репозиториев, тонкие параметры —
[полное руководство](https://github.com/Regsorm/code-index-mcp/blob/HEAD/README_RU.md#настройка-фонового-демона-v05).

### Гард: чтение через индекс (необязательно)

Правило «по индексированным каталогам читай через code-index» модель под
нагрузкой забывает и уходит в обычное чтение файлов, которое в 3–10 раз
дороже по токенам. `code-index-guard` — хук `PreToolUse` для Claude Code и
Codex CLI: отклоняет обычное чтение, поиск и обход каталога только там, где
индекс отдаёт тот же файл, и подсказывает нужный инструмент. Новый, ещё не
проиндексированный или исключённый из индекса файл читается как обычно.
Сборка и установка — [crates/code-index-guard](https://github.com/Regsorm/code-index-mcp/blob/HEAD/crates/code-index-guard/README.md).

## Зачем это нужно

Языковая модель без индекса ищет по коду тем же способом, что и человек без среды
разработки: перебором. Один вопрос «кто вызывает эту процедуру» превращается в
десяток последовательных обходов файлов, каждый из которых читает тысячи файлов и
возвращает в контекст модели куски текста — вместе с оплатой этих кусков.

`code-index` делает работу заранее: разбирает исходники в синтаксическое дерево,
складывает символы, тела, вызовы и метаданные в SQLite и отдаёт агенту готовый
ответ по протоколу MCP. Модель получает три строки вместо трёх файлов.

## Цифры

<picture>
  <source media="(prefers-color-scheme: dark)" srcset="docs/bench-summary-dark.svg">
  <img alt="В среднем в 2,04 раза дешевле по токенам, в 1,78 раза быстрее, 51 % экономии за сеанс"
       src="https://raw.githubusercontent.com/Regsorm/code-index-mcp/HEAD/docs/bench-summary-light.svg" width="880">
</picture>

| Кодовая база | Файлов | Полная индексация | Запуск на готовом индексе |
|---|---:|---:|---:|
| 1С:Управление Торговлей | 57 072 | 2 мин 41 с | **2,3 с** |
| 1С:Бухгалтерия предприятия | 88 284 | 5 мин 51 с | **5,3 с** |
| сайт на PHP | 157 772 | 13 мин 1 с | **8,0 с** |

**Полная индексация** — разбор всего с нуля, делается один раз. У Бухгалтерии эти
5 мин 51 с складываются так: 2 мин 38 с ядро (синтаксические деревья и запись),
1 мин 58 с надстройка 1С (метаданные, формы, права, граф вызовов), 56 с сброс
базы на диск. Дальше правки подхватываются по одной, за миллисекунды.

**Запуск на готовом индексе** сверяет время правки и размер каждого файла — ни
одного чтения содержимого, ни одного хеша.

| | |
|---|---|
| Ответ на запрос | около 10 мс по HTTP, повторный из кэша — доли миллисекунды |
| Размер бинарника | 39 МБ без 1С, 41 МБ с 1С |
| Функций в индексе Управления Торговлей | 261 548 |
| Вызовов в графе там же | 1 962 941 |

Замеры сделаны на одной машине под Windows с обычным жёстким диском, август 2026.

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

Каждый вызов принимает алиас репозитория, так что один сервер обслуживает
несколько кодовых баз сразу — в том числе с других машин.

**Поиск и навигация**

| | |
|---|---|
| `search_function` `search_class` | полнотекстовый поиск по функциям и классам |
| `get_function` `get_class` | точное имя → готовое тело; при промахе подсказывает похожие имена |
| `find_symbol` | символ любого рода: функция, класс, переменная, импорт |
| `get_imports` | импорты модуля или файла |
| `get_file_summary` | карта файла без чтения исходника |

**Граф вызовов**

| | |
|---|---|
| `get_callers` `get_callees` | кто вызывает процедуру и кого вызывает она |
| `find_path` | кратчайшая цепочка вызовов между двумя функциями |
| `get_call_tree` | дерево вызовов вниз или вверх на заданную глубину |

**Содержимое файлов**

| | |
|---|---|
| `read_file` | чтение с диапазоном строк; содержимое кода лежит в индексе, сжатое zstd |
| `list_files` `stat_file` | список файлов по маске и метаданные одного файла |
| `grep_body` | подстрока или регулярное выражение в телах функций и классов |
| `grep_code` `grep_text` | то же по всему тексту файлов кода и текстовых файлов |
| `search_text` | полнотекстовый поиск по текстовым форматам |
| `get_stats` `health` | состояние индекса и сервера |

**Для конфигураций 1С** (сборка `bsl-indexer`, появляются сами при наличии
репозитория с выгрузкой)

| | |
|---|---|
| `get_object_structure` | реквизиты с типами и синонимами, табличные части, измерения и ресурсы, предопределённые элементы, свойства проведения |
| `get_object_profile` | паспорт объекта одним вызовом: структура, формы, модули, связи |
| `get_form_handlers` | обработчики событий управляемой формы, с привязкой к элементу |
| `get_event_subscriptions` | подписки на события с фильтрами по источнику и событию |
| `get_data_links` `find_data_path` | граф связей данных: кто на кого ссылается и цепочка между двумя объектами |
| `find_references` | карта влияния: ссылки из метаданных, обращения в коде, права ролей |
| `get_register_writers` | регистраторы регистра и движения документа |
| `find_path_bsl` | цепочка вызовов процедур по графу выгрузки |
| `search_terms` | смысловой поиск процедур по именам, синонимам и комментариям |
| `get_role_rights` | права ролей на объект и права одной роли |
| `bsl_sql` | произвольный запрос на чтение к таблицам метаданных и графов |

## Что даёт поддержка 1С

- Разбираются обе формы выгрузки: XML из Конфигуратора и `.mdo` из 1С:EDT.
- Граф связей данных строится по ссылочным типам реквизитов, измерений и
  табличных частей: для Бухгалтерии предприятия это 65 421 ребро.
- Из модулей извлекаются директивы компиляции (`&НаСервере`, `&НаКлиенте`) и
  аннотации расширений (`&Вместо`, `&После`, `&Перед`) вместе с именем
  переопределяемой процедуры.
- Понимаются оба синтаксиса BSL — русский и английский.
- Регистр имени объекта не важен: кириллические имена приводятся к записи из
  конфигурации, в ответе имя показывается канонически.

Подробности — [docs/bsl-indexer.md](https://github.com/Regsorm/code-index-mcp/blob/HEAD/docs/bsl-indexer.md).

## Языки

Полный разбор синтаксиса: Python, JavaScript, TypeScript, Java, Rust, Go, PHP, C,
C++, C#, Ruby, Swift, 1С (BSL), HTML. Метаданные 1С — XML Конфигуратора и `.mdo`
из EDT. Плюс полнотекстовая индексация 50+ текстовых форматов (`.md`, `.json`,
`.yaml`, `.toml`, `.sql` и других).

## Дальше

- [Полное руководство на русском](https://github.com/Regsorm/code-index-mcp/blob/HEAD/README_RU.md) — демон, конфигурация, CLI, архитектура
- [docs/operations.md](https://github.com/Regsorm/code-index-mcp/blob/HEAD/docs/operations.md) — эксплуатация: перезапуск, добавление репозиториев, диагностика
- [docs/bsl-indexer.md](https://github.com/Regsorm/code-index-mcp/blob/HEAD/docs/bsl-indexer.md) — сборка для 1С
- [CHANGELOG.md](https://github.com/Regsorm/code-index-mcp/blob/HEAD/CHANGELOG.md) — журнал изменений

## Участие

Ошибки и предложения — в [issues](https://github.com/Regsorm/code-index-mcp/issues),
вопросы и обсуждения — в [Discussions](https://github.com/Regsorm/code-index-mcp/discussions).
Как прислать правку — [CONTRIBUTING.md](https://github.com/Regsorm/code-index-mcp/blob/HEAD/CONTRIBUTING.md), об уязвимостях —
[SECURITY.md](https://github.com/Regsorm/code-index-mcp/blob/HEAD/SECURITY.md).

## Лицензия

MIT, см. [LICENSE](https://github.com/Regsorm/code-index-mcp/blob/HEAD/LICENSE).

Проект стоит на [tree-sitter](https://tree-sitter.github.io/),
[грамматике BSL от сообщества 1c-syntax](https://github.com/1c-syntax/tree-sitter-bsl),
[rusqlite](https://github.com/rusqlite/rusqlite), [rayon](https://github.com/rayon-rs/rayon)
и [Rust SDK для MCP](https://github.com/modelcontextprotocol/rust-sdk).

