integram-mcp 0.7.11 → 0.7.13

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/README.md +32 -25
  2. package/index.js +176 -39
  3. package/package.json +1 -1
package/README.md CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  [![npm](https://img.shields.io/npm/v/integram-mcp)](https://www.npmjs.com/package/integram-mcp)
4
4
 
5
- MCP-сервер для Integram — даёт доступ к 311 инструментам (таблицы, документы, отчёты, автоматизации, портал, Telegram-боты, граф знаний и т.д.) из Claude Code, Claude Desktop и Cursor.
5
+ MCP-сервер для Integram — даёт доступ к 609 инструментам (таблицы, документы, отчёты, автоматизации, портал, Telegram-боты, граф знаний и т.д.) из Claude Code, Claude Desktop и Cursor.
6
6
 
7
7
  Работает с облачным Integram на **ai2o.online** или с локальным сервером.
8
8
 
@@ -15,7 +15,7 @@ claude mcp add integram \
15
15
  -e INTEGRAM_URL=https://ai2o.online \
16
16
  -e INTEGRAM_EMAIL=you@example.com \
17
17
  -e INTEGRAM_PASSWORD=secret \
18
- -- npx -y integram-mcp@0.7.11
18
+ -- npx -y integram-mcp@0.7.13
19
19
  ```
20
20
 
21
21
  Ставить ничего не нужно: `npx` скачает пакет сам.
@@ -43,7 +43,7 @@ claude mcp add integram \
43
43
  -e INTEGRAM_URL=http://localhost:8081 \
44
44
  -e INTEGRAM_EMAIL=you@example.com \
45
45
  -e INTEGRAM_PASSWORD=secret \
46
- -- npx -y integram-mcp@0.7.11
46
+ -- npx -y integram-mcp@0.7.13
47
47
  ```
48
48
 
49
49
  Удалить: `claude mcp remove integram`
@@ -57,7 +57,7 @@ claude mcp add integram \
57
57
  "mcpServers": {
58
58
  "integram": {
59
59
  "command": "npx",
60
- "args": ["-y", "integram-mcp@0.7.11"],
60
+ "args": ["-y", "integram-mcp@0.7.13"],
61
61
  "env": {
62
62
  "INTEGRAM_URL": "https://ai2o.online",
63
63
  "INTEGRAM_EMAIL": "you@example.com",
@@ -77,7 +77,7 @@ claude mcp add integram \
77
77
  "mcpServers": {
78
78
  "integram": {
79
79
  "command": "npx",
80
- "args": ["-y", "integram-mcp@0.7.11"],
80
+ "args": ["-y", "integram-mcp@0.7.13"],
81
81
  "env": {
82
82
  "INTEGRAM_URL": "https://ai2o.online",
83
83
  "INTEGRAM_EMAIL": "you@example.com",
@@ -157,30 +157,37 @@ claude mcp add integram -e INTEGRAM_URL=... -e INTEGRAM_EMAIL=... -e INTEGRAM_PA
157
157
 
158
158
  ## Группы инструментов
159
159
 
160
+ <!-- BEGIN:tool-groups — генерируется backend/scripts/sync-tool-counts.mjs, руками не править -->
160
161
  | Группа | Что делает | Кол-во |
161
162
  |---|---|---|
162
- | **core** | CRUD объектов, поиск, граф, комментарии, bulk-операции | 15 |
163
- | **workspace** | Файлы, коннекторы, участники, бэкапы, дашборды, вью, аудит, нормализатор, автоматизации, вебхуки, формы | 80 |
164
- | **portal** | Портал: конфиг, каталог, корзины, заказы, тикеты, KB, метрики, Telegram-боты | 42 |
165
- | **docs** | Документы, блоки, версии, шаринг, папки, теги, шаблоны, PDF | 38 |
166
- | **schema** | Таблицы, колонки, кнопки (AI/HTTP/script), вычисляемые колонки, валидация | 27 |
167
- | **codespace** | Git-репозитории: ветки, коммиты, файлы, точечная правка (`patch_file`), pull requests; запись с `baseCommit` сливается с чужими изменениями вместо перезаписи | 22 |
168
- | **reports** | Отчёты: CRUD, колонки, JOIN, фильтры, экспорт | 15 |
169
- | **grants** | Роли, гранты, row-level правила (только admin) | 11 |
170
- | **teamchat** | Сообщения, решения, метрики агентов, W-матрица, топики | 10 |
171
- | **memory** | Память агента, инсайты, процедуры, противоречия | 7 |
172
- | **meta-kb** | Дебаты: параллельные эксперты, LLM-синтез, курирование знаний | 6 |
173
- | **graph** | Граф данных: запросы, окрестности, кратчайший путь | 6 |
163
+ | **workspace** | Файлы, коннекторы, участники, бэкапы, дашборды, вью, аудит, нормализатор, автоматизации, вебхуки, формы | 121 |
164
+ | **pm** | Управление проектами: задачи, спринты, доски, бэклог, диаграммы | 53 |
165
+ | **docs** | Документы, блоки, версии, шаринг, папки, теги, шаблоны, PDF | 50 |
166
+ | **portal** | Портал: конфиг, каталог, корзины, заказы, тикеты, KB, метрики, Telegram-боты | 46 |
167
+ | **nightcall** | Нормативная спецификация и проверяемая генерация: требования, обязательства, свидетельства, базовые линии | 42 |
168
+ | **teamchat** | Сообщения, решения, метрики агентов, W-матрица, топики | 42 |
169
+ | **codespace** | Git-репозитории: ветки, коммиты, файлы, точечная правка (`patch_file`), pull requests; запись с `baseCommit` сливается с чужими изменениями вместо перезаписи | 30 |
170
+ | **schema** | Таблицы, колонки, кнопки (AI/HTTP/script), вычисляемые колонки, валидация | 30 |
171
+ | **memory** | Память агента, инсайты, процедуры, противоречия | 22 |
172
+ | **meta-kb** | Дебаты: параллельные эксперты, LLM-синтез, курирование знаний | 22 |
173
+ | **objects** | Перемещение, дублирование, переупорядочивание записей, корзина, обратные ссылки | 17 |
174
+ | **core** | CRUD объектов, поиск, граф, комментарии, bulk-операции | 16 |
175
+ | **reports** | Отчёты: CRUD, колонки, JOIN, фильтры, экспорт | 16 |
176
+ | **grants** | Роли, гранты, row-level правила (только admin) | 13 |
177
+ | **graph** | Граф данных: запросы, окрестности, кратчайший путь | 13 |
178
+ | **orgs** | Организации: участники, области, приглашения | 13 |
179
+ | **kag** | Граф знаний: поиск, обход, вопрос-ответ, ввоз сущностей и связей | 12 |
180
+ | **agents** | Реестр внешних AI-агентов, делегирование | 11 |
181
+ | **advisor** | Советы эксперта, возможности платформы | 6 |
174
182
  | **comments** | Комментарии и реакции к записям | 6 |
175
- | **objects** | Перемещение, дублирование, переупорядочивание записей | 4 |
183
+ | **automations** | Детали автоматизации, лог доставки вебхуков | 5 |
184
+ | **workspace-tools** | Инструменты уровня области: регистрация, правка, ввоз наборов | 5 |
176
185
  | **bulk** | Массовые операции: создание, обновление, удаление, AI-batch | 4 |
177
- | **kag** | Граф знаний: поиск, обход, вопрос-ответ | 3 |
186
+ | **ai** | Синтез речи (TTS): озвучка текста, список голосов | 3 |
187
+ | **normalizer** | Разбор документов: запуск, состояние, подтверждение сопоставления | 3 |
178
188
  | **timeseries** | Временные ряды: запись, запрос, список источников | 3 |
179
- | **automations** | Детали автоматизации, лог доставки вебхуков | 3 |
180
- | **advisor** | Советы эксперта, возможности платформы | 2 |
181
- | **ai** | Синтез речи (TTS): озвучка текста, список голосов | 2 |
182
- | **agents** | Реестр внешних AI-агентов, делегирование | 2 |
183
- | **lookups** | Справочники: варианты для dropdown/ref | 2 |
184
189
  | **history** | История изменений объектов, откат | 2 |
190
+ | **lookups** | Справочники: варианты для dropdown/ref | 2 |
191
+ <!-- END:tool-groups -->
185
192
 
186
- Core активна сразу (~15 tools). Остальные — через `search_tools`.
193
+ Core активна сразу (16 tools). Остальные — через `search_tools`.
package/index.js CHANGED
@@ -234,7 +234,7 @@ async function fetchTools() {
234
234
 
235
235
  // ─── MCP Server (low-level — we pass raw JSON Schema, not Zod) ──────────────
236
236
 
237
- const INSTRUCTIONS = `Integram — workspace-based platform: tables, documents, reports, automations, permissions, forms, webhooks, files, knowledge graph.
237
+ export const INSTRUCTIONS = `Integram — workspace-based platform: tables, documents, reports, automations, permissions, forms, webhooks, files, knowledge graph.
238
238
  Server: ${BASE_URL}
239
239
 
240
240
  ## Getting started
@@ -683,7 +683,7 @@ Block-based documents (like Notion). Activate via search_tools("documents").
683
683
  - Versions: list_doc_versions, get_doc_version(docId, versionId), restore_doc_version
684
684
  - Block history: get_block_history(docId, blockId, limit?, offset?)
685
685
  - Purge: purge_document(docId) — permanently delete trashed doc (requires confirmation)
686
- - Sharing: list_doc_sharing, grant_doc_access(docId, userId, level), revoke_doc_access
686
+ - Sharing: list_doc_sharing, grant_doc_access(docId, targetUserId, role: viewer|editor|admin), revoke_doc_access
687
687
 
688
688
  ## Automations
689
689
 
@@ -744,7 +744,7 @@ create_form(typeId, config, expiresAt) — generates a public URL for external u
744
744
  ## Bulk operations
745
745
 
746
746
  Activate via search_tools("bulk").
747
- - bulk_create(typeId, records) — create many records at once
747
+ - bulk_create(typeId, rows, parentId?) — create many records at once
748
748
  - bulk_update(updates: [{ objId, fields }]) — update many records
749
749
  - bulk_delete(objIds) — delete many records (requires confirmation)
750
750
  - autofill_batch(typeId, reqId, objectIds) — run AI autofill on multiple rows
@@ -759,7 +759,7 @@ Activate via search_tools("workspace").
759
759
  ## Dashboards
760
760
 
761
761
  Visual dashboards with widgets. Activate via search_tools("workspace").
762
- - list_dashboards, get_dashboard(id), create_dashboard(name, widgets), update_dashboard, delete_dashboard
762
+ - list_dashboards, get_dashboard(id), create_dashboard(title, widgets, layouts?), update_dashboard, delete_dashboard
763
763
 
764
764
  ## Workspace invitations
765
765
 
@@ -789,7 +789,7 @@ External data integrations. Activate via search_tools("workspace").
789
789
  ## Comments & reactions
790
790
 
791
791
  Activate via search_tools("comments").
792
- - list_comments(objId), create_comment(objId, text), update_comment, delete_comment
792
+ - list_comments(objId), create_comment(objId, body, parentCommentId?), update_comment, delete_comment
793
793
  - add_reaction(commentId, emoji), remove_reaction
794
794
 
795
795
  ## History & rollback
@@ -1827,13 +1827,28 @@ const BUILT_IN_TOOL_DEFS = [
1827
1827
  // Group alias map — maps Russian/English SYNONYMS to TOOL_DEFS group names.
1828
1828
  // Exact group names are matched dynamically against the live catalog (allTools),
1829
1829
  // so a new backend group is picked up automatically — add here only synonyms.
1830
+ //
1831
+ // A value may be an ARRAY when one word honestly names two groups. That is not a
1832
+ // convenience: `automations` is the name of a 5-tool group (run details, webhook
1833
+ // delivery log) AND the everyday word for editing automations, which lives in
1834
+ // `workspace`. Sending the word to one group only silently hid the other half —
1835
+ // the prompt said `search_tools("automations")` and then named `create_automation`,
1836
+ // which the query could never activate. Same shape for connectors and forms.
1830
1837
  const GROUP_ALIASES = {
1831
1838
  документ: 'docs', документы: 'docs', docs: 'docs', doc: 'docs',
1832
1839
  отчёт: 'reports', отчеты: 'reports', отчёты: 'reports', report: 'reports', reports: 'reports',
1833
1840
  схема: 'schema', таблица: 'schema', колонк: 'schema', schema: 'schema',
1834
1841
  права: 'grants', роли: 'grants', доступ: 'grants', grants: 'grants',
1835
- автоматизац: 'workspace', вебхук: 'workspace', коннектор: 'workspace', форм: 'workspace',
1836
- файл: 'workspace', файлы: 'workspace',
1842
+ permissions: 'grants', permission: 'grants', acl: 'grants', role: 'grants', member: 'grants',
1843
+ автоматизац: ['workspace', 'automations'], коннектор: 'workspace', форм: 'workspace',
1844
+ // Вебхук заведён в `workspace`, а журнал его доставки (`get_webhook_deliveries`,
1845
+ // `retry_webhook_delivery`) — в `automations`. Раздел подсказки называет и то и другое.
1846
+ вебхук: ['workspace', 'automations'],
1847
+ webhook: ['workspace', 'automations'], webhooks: ['workspace', 'automations'],
1848
+ form: 'workspace', forms: 'workspace',
1849
+ connector: 'workspace', connectors: 'workspace', dashboard: 'workspace', dashboards: 'workspace',
1850
+ invitation: 'workspace', invitations: 'workspace', backup: 'workspace', audit: 'workspace',
1851
+ файл: 'workspace', файлы: 'workspace', file: 'workspace', files: 'workspace',
1837
1852
  портал: 'portal', телеграм: 'portal', telegram: 'portal', portal: 'portal',
1838
1853
  граф: 'graph', связи: 'graph', graph: 'graph',
1839
1854
  память: 'memory', memory: 'memory', запомни: 'memory',
@@ -1847,8 +1862,9 @@ const GROUP_ALIASES = {
1847
1862
  advisor: 'advisor', совет: 'advisor', консультант: 'advisor',
1848
1863
  agents: 'agents', агент: 'agents', делегир: 'agents',
1849
1864
  orgs: 'orgs', организаци: 'orgs', org: 'orgs',
1850
- automations: 'automations', automation: 'automations',
1851
- history: 'history', истори: 'history',
1865
+ automations: ['automations', 'workspace'], automation: ['automations', 'workspace'],
1866
+ // Раздел «History & rollback» называет и `get_object_backlinks`, а оно в `objects`.
1867
+ history: ['history', 'objects'], истори: ['history', 'objects'],
1852
1868
  lookups: 'lookups', lookup: 'lookups', справочник: 'lookups',
1853
1869
  'meta-kb': 'meta-kb', metakb: 'meta-kb', дебат: 'meta-kb', дискусси: 'meta-kb',
1854
1870
  pm: 'pm', проект: 'pm', задач: 'pm', спринт: 'pm', канбан: 'pm', бэклог: 'pm', issue: 'pm', sprint: 'pm', backlog: 'pm', board: 'pm',
@@ -1856,15 +1872,24 @@ const GROUP_ALIASES = {
1856
1872
  формализ: 'nightcall', formaliz: 'nightcall', governance: 'nightcall', evidence: 'nightcall',
1857
1873
  };
1858
1874
 
1859
- async function handleSearchTools(query) {
1860
- try {
1861
- const q = query.toLowerCase();
1862
- const words = q.split(/\s+/).filter(Boolean);
1863
- // Live group catalog — single source of truth, new backend groups appear automatically
1864
- const knownGroups = [...new Set(allTools.map(t => t.group).filter(g => g && g !== 'core'))];
1865
-
1866
- const available = t => !activeTools.has(t.name) && !BUILT_IN_NAMES.has(t.name);
1867
- const toolText = t => `${t.name} ${t.description || ''} ${t.group || ''}`.toLowerCase();
1875
+ /**
1876
+ * Pure selection step of search_tools — exported so the guard test can run the REAL
1877
+ * matcher over the REAL catalog instead of a copy of it. A copied matcher is how the
1878
+ * prompt drifted away from what activation actually returns in the first place.
1879
+ *
1880
+ * @param {string} query
1881
+ * @param {Array<{name:string,description?:string,group?:string}>} catalog
1882
+ * @param {(t:object)=>boolean} available
1883
+ * @returns {{matched:Array<object>, groupExact:number, total:number, droppedByGroup:Object<string,number>}}
1884
+ */
1885
+ export function selectTools(query, catalog, available = () => true) {
1886
+ const q = String(query).toLowerCase();
1887
+ const words = q.split(/\s+/).filter(Boolean);
1888
+ // Live group catalog — single source of truth, new backend groups appear automatically
1889
+ const knownGroups = [...new Set(catalog.map(t => t.group).filter(g => g && g !== 'core'))];
1890
+ const toolText = t => `${t.name} ${t.description || ''} ${t.group || ''}`.toLowerCase();
1891
+ const allTools = catalog;
1892
+ {
1868
1893
 
1869
1894
  // Phase 1: group-based match — if any query word names a group (exact, or prefix
1870
1895
  // when at least 4 chars to avoid short-name false hits) or hits a synonym alias,
@@ -1876,13 +1901,22 @@ async function handleSearchTools(query) {
1876
1901
  if (w === g || (minLen >= 4 && (g.startsWith(w) || w.startsWith(g)))) matchedGroups.add(g);
1877
1902
  }
1878
1903
  for (const [alias, group] of Object.entries(GROUP_ALIASES)) {
1879
- if (alias.startsWith(w) || w.startsWith(alias)) matchedGroups.add(group);
1904
+ if (alias.startsWith(w) || w.startsWith(alias)) {
1905
+ for (const g of Array.isArray(group) ? group : [group]) matchedGroups.add(g);
1906
+ }
1880
1907
  }
1881
1908
  }
1882
1909
 
1883
1910
  let matched;
1911
+ // Tools that came in because the query NAMED their group. These are exempt from
1912
+ // the result cap below: asking for a group and getting an unannounced 30-tool
1913
+ // prefix of it makes activation-by-name meaningless — `workspace` is 121 tools,
1914
+ // and the prompt names tools that sit past position 30 in every one of them.
1915
+ // A vague query is still capped; an explicit group request is honoured in full.
1916
+ let groupExact = 0;
1884
1917
  if (matchedGroups.size > 0) {
1885
1918
  matched = allTools.filter(t => available(t) && matchedGroups.has(t.group));
1919
+ groupExact = matched.length;
1886
1920
  // Also include tools from other groups where ALL words match
1887
1921
  const groupSet = new Set(matched.map(t => t.name));
1888
1922
  const extra = allTools.filter(t =>
@@ -1922,8 +1956,85 @@ async function handleSearchTools(query) {
1922
1956
  }
1923
1957
  }
1924
1958
 
1925
- // Cap at 30
1926
- matched = matched.slice(0, 30);
1959
+ // Cap at 30 — but SAY SO. Six groups are larger than the cap (`workspace` is
1960
+ // 121 tools), so activating one by name used to answer "Activated 30 tools: …"
1961
+ // and drop the rest without a word. The model read that as the whole group and
1962
+ // called a tool it had never been given. A cap is right — dumping 121 defs into
1963
+ // the tool list is worse — but a silent one turns absence into a lie.
1964
+ const RESULT_CAP = 30;
1965
+ const keep = Math.max(RESULT_CAP, groupExact);
1966
+ const totalMatched = matched.length;
1967
+ const droppedByGroup = {};
1968
+ if (totalMatched > keep) {
1969
+ for (const t of matched.slice(keep)) {
1970
+ const g = t.group || '(no group)';
1971
+ droppedByGroup[g] = (droppedByGroup[g] || 0) + 1;
1972
+ }
1973
+ }
1974
+ matched = matched.slice(0, keep);
1975
+
1976
+ return { matched, groupExact, total: totalMatched, droppedByGroup, knownGroups, words, RESULT_CAP };
1977
+ }
1978
+ }
1979
+
1980
+ /**
1981
+ * Текст ответа `search_tools` — отдельно от побочных действий, чтобы его можно было
1982
+ * проверить, не поднимая сервер.
1983
+ *
1984
+ * Пустой ответ бывает ДВУХ родов, и раньше они звучали одинаково: «ничего не совпало» и
1985
+ * «всё совпавшее уже активно». Второе — не отказ, а сообщение об успехе, сказанное
1986
+ * словами отказа: модель читала «not found», переставала верить имени группы и начинала
1987
+ * подбирать синонимы, имея все её инструменты на руках. Замер 23.08.2026: третий подряд
1988
+ * `search_tools("pm")` отвечал `No tools found matching "pm"` и в той же строке
1989
+ * перечислял `pm` среди доступных групп.
1990
+ *
1991
+ * @param {object} p
1992
+ * @param {string} p.query исходный запрос
1993
+ * @param {string[]} p.activatedNames что активировано этим вызовом
1994
+ * @param {number} p.totalMatched сколько совпало ДО потолка (с учётом предиката)
1995
+ * @param {Object<string,number>} p.droppedByGroup срезано потолком, по группам
1996
+ * @param {number} p.resultCap сам потолок
1997
+ * @param {string[]} p.builtinNames совпавшие встроенные — они и так доступны
1998
+ * @param {string[]} p.alreadyActiveNames совпавшие, но активированные РАНЬШЕ
1999
+ * @param {string[]} p.knownGroups живой перечень групп каталога
2000
+ * @returns {string}
2001
+ */
2002
+ export function buildSearchToolsText(p) {
2003
+ const parts = [];
2004
+ if (p.activatedNames.length) {
2005
+ parts.push(`Activated ${p.activatedNames.length} tools: ${p.activatedNames.join(', ')}.`);
2006
+ }
2007
+ if (p.totalMatched > p.activatedNames.length) {
2008
+ const rest = Object.entries(p.droppedByGroup)
2009
+ .sort((a, b) => b[1] - a[1])
2010
+ .map(([g, n]) => `${g} +${n}`)
2011
+ .join(', ');
2012
+ parts.push(
2013
+ `NOT activated: ${p.totalMatched - p.activatedNames.length} more matched but were cut at the ${p.resultCap}-tool limit (${rest}). ` +
2014
+ `They are NOT available — narrow the query to reach them, e.g. search_tools("${p.query} <what you need>").`
2015
+ );
2016
+ }
2017
+ if (p.builtinNames.length) {
2018
+ parts.push(`Already available (built-in): ${p.builtinNames.join(', ')}.`);
2019
+ }
2020
+ if (parts.length) return parts.join(' ');
2021
+
2022
+ // Ничего не активировано. Разбираем, почему именно.
2023
+ if (p.alreadyActiveNames.length) {
2024
+ return `Nothing new: all ${p.alreadyActiveNames.length} tools matching "${p.query}" are already active ` +
2025
+ `(${p.alreadyActiveNames.join(', ')}). Use them directly — no further search_tools call is needed.`;
2026
+ }
2027
+ const groupsMsg = p.knownGroups.length
2028
+ ? p.knownGroups.slice().sort().join(', ')
2029
+ : '(no tools loaded — select a workspace first)';
2030
+ return `No tools found matching "${p.query}". Available groups: ${groupsMsg}`;
2031
+ }
2032
+
2033
+ async function handleSearchTools(query) {
2034
+ try {
2035
+ const available = t => !activeTools.has(t.name) && !BUILT_IN_NAMES.has(t.name);
2036
+ const { matched, total: totalMatched, droppedByGroup, knownGroups, words, RESULT_CAP } =
2037
+ selectTools(query, allTools, available);
1927
2038
 
1928
2039
  // Search built-in tools (always available, just inform)
1929
2040
  const matchedBuiltins = BUILT_IN_TOOL_DEFS.filter(t => {
@@ -1940,20 +2051,29 @@ async function handleSearchTools(query) {
1940
2051
  await server.sendToolListChanged();
1941
2052
  }
1942
2053
 
1943
- const parts = [];
1944
- if (matched.length) parts.push(`Activated ${matched.length} tools: ${matched.map(t => t.name).join(', ')}.`);
1945
- if (matchedBuiltins.length) parts.push(`Already available (built-in): ${matchedBuiltins.map(t => t.name).join(', ')}.`);
1946
-
1947
- if (!parts.length) {
1948
- const groupsMsg = knownGroups.length
1949
- ? knownGroups.sort().join(', ')
1950
- : '(no tools loaded — select a workspace first)';
1951
- return {
1952
- content: [{ type: 'text', text: `No tools found matching "${query}". Available groups: ${groupsMsg}` }],
1953
- };
1954
- }
1955
-
1956
- return { content: [{ type: 'text', text: parts.join(' ') }] };
2054
+ // Совпавшие, но активированные РАНЬШЕ. Второй прогон отбора без предиката
2055
+ // доступности — единственный способ это узнать: предикат уходит внутрь отбора и
2056
+ // делает «нет совпадений» неотличимым от «всё уже активно». Прогон чистый и идёт
2057
+ // по памяти, так что второй раз он стоит дёшево, и делается только когда
2058
+ // активировать оказалось нечего.
2059
+ const alreadyActiveNames = matched.length
2060
+ ? []
2061
+ : selectTools(query, allTools)
2062
+ .matched
2063
+ .filter(t => activeTools.has(t.name))
2064
+ .map(t => t.name);
2065
+
2066
+ const text = buildSearchToolsText({
2067
+ query,
2068
+ activatedNames: matched.map(t => t.name),
2069
+ totalMatched,
2070
+ droppedByGroup,
2071
+ resultCap: RESULT_CAP,
2072
+ builtinNames: matchedBuiltins.map(t => t.name),
2073
+ alreadyActiveNames,
2074
+ knownGroups,
2075
+ });
2076
+ return { content: [{ type: 'text', text }] };
1957
2077
  } catch (err) {
1958
2078
  return { content: [{ type: 'text', text: `Error: ${err.message}` }], isError: true };
1959
2079
  }
@@ -2017,6 +2137,7 @@ async function handleSwitchWorkspace(input) {
2017
2137
  // ─── Auto-update from git ────────────────────────────────────────────────────
2018
2138
 
2019
2139
  import { execSync } from 'child_process';
2140
+ import { realpathSync } from 'fs';
2020
2141
  import { dirname } from 'path';
2021
2142
  import { fileURLToPath } from 'url';
2022
2143
 
@@ -2071,7 +2192,23 @@ async function main() {
2071
2192
  log('MCP server running on stdio');
2072
2193
  }
2073
2194
 
2074
- main().catch(err => {
2075
- process.stderr.write(`[integram-mcp] Fatal: ${err.message}\n`);
2076
- process.exit(1);
2077
- });
2195
+ // Run only when executed as a program, not when imported. The guard test imports
2196
+ // `selectTools` from this file; without this check the import would log in, open a
2197
+ // stdio transport and hang the run. realpathSync is required, not decoration: npm
2198
+ // installs the bin as a SYMLINK, so process.argv[1] is the link path while
2199
+ // import.meta.url is the real one, and a naive comparison would make `npx
2200
+ // integram-mcp` start nothing at all.
2201
+ const isProgram = (() => {
2202
+ try {
2203
+ return process.argv[1] && realpathSync(process.argv[1]) === fileURLToPath(import.meta.url);
2204
+ } catch {
2205
+ return false;
2206
+ }
2207
+ })();
2208
+
2209
+ if (isProgram) {
2210
+ main().catch(err => {
2211
+ process.stderr.write(`[integram-mcp] Fatal: ${err.message}\n`);
2212
+ process.exit(1);
2213
+ });
2214
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "integram-mcp",
3
- "version": "0.7.11",
3
+ "version": "0.7.13",
4
4
  "type": "module",
5
5
  "description": "MCP server for Integram — connect AI assistants to your workspace via Model Context Protocol",
6
6
  "mcpName": "io.github.judas-priest/integram",