@x0333/bitrix24-mcp-server 2.2.1 → 2.3.1

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.
@@ -0,0 +1,50 @@
1
+ name: Publish to npm
2
+
3
+ on:
4
+ push:
5
+ branches: [main, master]
6
+ paths:
7
+ - "package.json"
8
+ workflow_dispatch:
9
+
10
+ concurrency:
11
+ group: npm-publish-${{ github.repository }}
12
+ cancel-in-progress: false
13
+
14
+ jobs:
15
+ publish:
16
+ runs-on: ubuntu-latest
17
+ permissions:
18
+ contents: read
19
+ steps:
20
+ - uses: actions/checkout@v4
21
+
22
+ - uses: actions/setup-node@v4
23
+ with:
24
+ node-version: "20"
25
+ registry-url: "https://registry.npmjs.org"
26
+
27
+ - name: Compare local version with npm latest
28
+ id: version
29
+ run: |
30
+ set -euo pipefail
31
+ LOCAL=$(node -p "require('./package.json').version")
32
+ NAME=$(node -p "require('./package.json').name")
33
+ NPM_VER=$(npm view "$NAME" version 2>/dev/null || echo "0.0.0")
34
+ echo "Package: $NAME"
35
+ echo "Local version: $LOCAL"
36
+ echo "npm latest: $NPM_VER"
37
+ MATCH=$(npx -y semver@7 -r ">$NPM_VER" "$LOCAL" 2>/dev/null || true)
38
+ if [ "$MATCH" = "$LOCAL" ]; then
39
+ echo "should_publish=true" >> "$GITHUB_OUTPUT"
40
+ echo "Will publish: $LOCAL is newer than $NPM_VER"
41
+ else
42
+ echo "should_publish=false" >> "$GITHUB_OUTPUT"
43
+ echo "Skip publish: $LOCAL is not newer than $NPM_VER"
44
+ fi
45
+
46
+ - name: npm publish
47
+ if: steps.version.outputs.should_publish == 'true'
48
+ run: npm publish --access public
49
+ env:
50
+ NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
package/README.md CHANGED
@@ -19,6 +19,12 @@ MCP-сервер для работы с Bitrix24 через входящий в
19
19
  - **search_groups** — рабочие группы и проекты по подстроке имени (`sonet_group.get.json`, фильтр `%NAME`).
20
20
  - **get_group** — данные группы или проекта по ID (`sonet_group.get.json`, фильтр `ID`).
21
21
  - **get_kanban_stages_by_group** — стадии канбана задач для группы по её ID (`task.stages.get`, в теле запроса `entityId` = ID группы).
22
+ - **get_task_comments** — «комментарии» задачи в **новой карточке задач** (чат задачи): цепочка `tasks.task.get` → `im.dialog.messages.get`. Сначала **самые свежие** сообщения, если не передавать курсоры пагинации.
23
+ - Параметры: **`task_id`** (обязательно), **`limit`** (1–50, по умолчанию 20), опционально **`first_id`** (Bitrix `FIRST_ID`, следующая страница **старее**) или **`last_id`** (`LAST_ID`, сообщения **новее** id) — оба курсора одновременно нельзя.
24
+ - В ответе урезанные массивы: **`messages`** — только `id`, `author_id`, `text`, `date`; **`users`** — только `id`, `name`, `work_position`, `email`. Есть **`agent_instructions`** для модели и **`pagination`** с подсказками `suggested_next_first_id` / `suggested_next_last_id`.
25
+ - **`author_id === 0`** — системные сообщения чата (смена стадии, учёт времени и т.п.), это **не** пользовательский комментарий; в **`users`** для них строки обычно нет. Для **`author_id > 0`** сопоставляй с **`users[].id`**.
26
+
27
+ Если в `tasks.task.get` на обычном URL `.../rest/USER/WEBHOOK/` нет **`chatId`**, сервер **сам** повторит запрос к `.../rest/api/USER/WEBHOOK/` (тот же вебхук, другой префикс пути).
22
28
 
23
29
  Все вызовы к Bitrix24 идут как `POST` на `{B24_BASE}/{метод}` с JSON-телом, как в документации REST.
24
30
 
@@ -65,7 +71,8 @@ B24_BASE="https://your-domain.bitrix24.ru/rest/USER_ID/WEBHOOK_CODE/" npx -y @x0
65
71
  4. Выдайте вебхуку нужные права (минимум для текущих инструментов):
66
72
  - задачи (в т.ч. стадии канбана групповых задач);
67
73
  - рабочие группы / проекты;
68
- - пользователи (для профиля).
74
+ - пользователи (для профиля);
75
+ - **чаты и мессенджер (im)** — для **`get_task_comments`** (`im.dialog.messages.get`).
69
76
  5. Скопируйте **URL для вызова REST API**.
70
77
 
71
78
  Обычно он выглядит примерно так:
package/index.js CHANGED
@@ -24,23 +24,51 @@ if (!B24_BASE) {
24
24
  process.exit(1);
25
25
  }
26
26
 
27
+ function bitrixPortalUrlFromBase(base) {
28
+ try {
29
+ const u = new URL(String(base).trim());
30
+ if (!u.host) return null;
31
+ return `${u.protocol}//${u.host}`;
32
+ } catch {
33
+ return null;
34
+ }
35
+ }
36
+
37
+ const B24_PORTAL_URL = bitrixPortalUrlFromBase(B24_BASE);
38
+ const mcpInstructions = B24_PORTAL_URL
39
+ ? `Bitrix24 address: ${B24_PORTAL_URL}`
40
+ : "Bitrix24 address: take scheme and host from B24_BASE (the part before /rest/ in the webhook URL).";
41
+
27
42
  const server = new Server(
28
43
  {
29
44
  name: "bitrix24-mcp-server",
30
- version: "2.2.0",
45
+ version: "2.3.0",
31
46
  },
32
47
  {
33
48
  capabilities: {
34
49
  tools: {},
35
50
  },
51
+ instructions: mcpInstructions,
36
52
  }
37
53
  );
38
54
 
55
+ /**
56
+ * If B24_BASE is legacy .../rest/{user}/{webhook}/ (without /api/), new task fields
57
+ * like chatId are returned from .../rest/api/{user}/{webhook}/ only.
58
+ */
59
+ function bitrixRestApiBaseFromLegacy() {
60
+ const b = B24_BASE.replace(/\/$/, "");
61
+ if (/\/rest\/api\//.test(b)) return null;
62
+ if (/\/rest\/\d+\//.test(b)) return b.replace("/rest/", "/rest/api/");
63
+ return null;
64
+ }
65
+
39
66
  /**
40
67
  * Helper to call Bitrix24 REST API
68
+ * @param {string} [baseUrl] — override base (e.g. rest/api for tasks.task.get)
41
69
  */
42
- async function callBitrix(method, body) {
43
- const url = `${B24_BASE.replace(/\/$/, "")}/${method}`;
70
+ async function callBitrix(method, body, baseUrl) {
71
+ const url = `${(baseUrl || B24_BASE).replace(/\/$/, "")}/${method}`;
44
72
  try {
45
73
  const response = await axios.post(url, body, {
46
74
  headers: { "Content-Type": "application/json" },
@@ -54,6 +82,48 @@ async function callBitrix(method, body) {
54
82
  }
55
83
  }
56
84
 
85
+ const IM_MESSAGES_LIMIT_MAX = 50;
86
+
87
+ function pickTaskItem(taskGetResult) {
88
+ const r = taskGetResult?.result;
89
+ if (!r) return null;
90
+ return r.item ?? r.task ?? null;
91
+ }
92
+
93
+ function resolveTaskChatId(item) {
94
+ if (!item || typeof item !== "object") return null;
95
+ const cid = item.chatId ?? item.CHAT_ID ?? item.chat?.id ?? item.chat?.ID;
96
+ return cid != null && cid !== "" ? Number(cid) : null;
97
+ }
98
+
99
+ function slimTaskChatMessages(messages) {
100
+ const list = Array.isArray(messages) ? messages : [];
101
+ return list.map((m) => ({
102
+ id: m.id,
103
+ author_id: m.author_id,
104
+ text: m.text,
105
+ date: m.date,
106
+ }));
107
+ }
108
+
109
+ function slimImUsers(users) {
110
+ const list = Array.isArray(users) ? users : [];
111
+ return list.map((u) => ({
112
+ id: u.id,
113
+ name: u.name,
114
+ work_position: u.work_position ?? null,
115
+ email: u.email ?? null,
116
+ }));
117
+ }
118
+
119
+ function throwIfBitrixError(data, context) {
120
+ if (!data || typeof data !== "object") return;
121
+ if (!Object.prototype.hasOwnProperty.call(data, "error") || data.error == null) return;
122
+ const code = typeof data.error === "object" ? JSON.stringify(data.error) : String(data.error);
123
+ const desc = data.error_description != null ? String(data.error_description) : "";
124
+ throw new Error(`${context}: ${code}${desc ? ` — ${desc}` : ""}`);
125
+ }
126
+
57
127
  /**
58
128
  * Define available tools
59
129
  */
@@ -136,6 +206,37 @@ server.setRequestHandler(ListToolsRequestSchema, async () => {
136
206
  required: ["id"],
137
207
  },
138
208
  },
209
+ {
210
+ name: "get_task_comments",
211
+ description:
212
+ "Comments for a task on the new task card (module tasks 25.700.0+): messages come from the task chat via im.dialog.messages.get, newest first when no cursors are passed. " +
213
+ "Arrays are trimmed: messages only id, author_id, text, date; users only id, name, work_position, email. " +
214
+ "author_id 0 means system/service chat messages (stage changes, time tracking, joins, etc.) — not a user comment; do not expect a matching row in users. " +
215
+ "For author_id > 0, match message.author_id to users[].id to resolve author name. " +
216
+ "ИИ: author_id 0 = системные сообщения чата (не комментарий человека), в users не сопоставлять; для author_id > 0 сопоставляй с users[].id. В теле ответа см. agent_instructions. " +
217
+ "Pagination: limit 1–50 (default 20). first_id = Bitrix FIRST_ID (next page of older messages). last_id = Bitrix LAST_ID (messages newer than id). Do not send both first_id and last_id.",
218
+ inputSchema: {
219
+ type: "object",
220
+ properties: {
221
+ task_id: { type: "number", description: "Task ID" },
222
+ limit: {
223
+ type: "number",
224
+ description: `Page size (1–${IM_MESSAGES_LIMIT_MAX}, default 20). Bitrix im.dialog.messages.get LIMIT`,
225
+ },
226
+ first_id: {
227
+ type: "number",
228
+ description:
229
+ "Optional. Bitrix FIRST_ID: load messages older than this id (next page toward history). Typically set to the smallest message id from the previous response.",
230
+ },
231
+ last_id: {
232
+ type: "number",
233
+ description:
234
+ "Optional. Bitrix LAST_ID: load messages newer than this id. Do not combine with first_id.",
235
+ },
236
+ },
237
+ required: ["task_id"],
238
+ },
239
+ },
139
240
  ],
140
241
  };
141
242
  });
@@ -203,6 +304,85 @@ server.setRequestHandler(CallToolRequestSchema, async (request) => {
203
304
  return { content: [{ type: "text", text: JSON.stringify(data, null, 2) }] };
204
305
  }
205
306
 
307
+ case "get_task_comments": {
308
+ const taskId = Number(args.task_id);
309
+ if (!Number.isFinite(taskId) || taskId <= 0) {
310
+ throw new Error("get_task_comments: task_id must be a positive number");
311
+ }
312
+ const hasFirst = args.first_id !== undefined && args.first_id !== null;
313
+ const hasLast = args.last_id !== undefined && args.last_id !== null;
314
+ if (hasFirst && hasLast) {
315
+ throw new Error("get_task_comments: pass only one of first_id or last_id, not both");
316
+ }
317
+ let limit = args.limit === undefined || args.limit === null ? 20 : Number(args.limit);
318
+ if (!Number.isFinite(limit)) limit = 20;
319
+ limit = Math.min(IM_MESSAGES_LIMIT_MAX, Math.max(1, Math.floor(limit)));
320
+
321
+ const taskSelect = ["id", "chatId", "chat.id"];
322
+ let taskRaw = await callBitrix("tasks.task.get", {
323
+ id: taskId,
324
+ select: taskSelect,
325
+ });
326
+ throwIfBitrixError(taskRaw, "tasks.task.get");
327
+ let item = pickTaskItem(taskRaw);
328
+ let chatId = resolveTaskChatId(item);
329
+ const apiBase = bitrixRestApiBaseFromLegacy();
330
+ if (!chatId && apiBase) {
331
+ taskRaw = await callBitrix(
332
+ "tasks.task.get",
333
+ { id: taskId, select: taskSelect },
334
+ apiBase
335
+ );
336
+ throwIfBitrixError(taskRaw, "tasks.task.get (rest/api)");
337
+ item = pickTaskItem(taskRaw);
338
+ chatId = resolveTaskChatId(item);
339
+ }
340
+ if (!chatId) {
341
+ throw new Error(
342
+ "get_task_comments: task has no chatId (new-card comments unavailable, no access, or set B24_BASE to .../rest/api/...)"
343
+ );
344
+ }
345
+
346
+ const imBody = {
347
+ DIALOG_ID: `chat${chatId}`,
348
+ LIMIT: limit,
349
+ };
350
+ if (hasFirst) imBody.FIRST_ID = Number(args.first_id);
351
+ if (hasLast) imBody.LAST_ID = Number(args.last_id);
352
+
353
+ const imRaw = await callBitrix("im.dialog.messages.get", imBody);
354
+ throwIfBitrixError(imRaw, "im.dialog.messages.get");
355
+ const imResult = imRaw.result || {};
356
+ const rawMessages = Array.isArray(imResult.messages) ? imResult.messages : [];
357
+ const slimMessages = slimTaskChatMessages(rawMessages);
358
+ const ids = slimMessages.map((m) => m.id).filter((id) => typeof id === "number");
359
+ const minId = ids.length ? Math.min(...ids) : null;
360
+ const maxId = ids.length ? Math.max(...ids) : null;
361
+
362
+ const payload = {
363
+ task_id: taskId,
364
+ chat_id: imResult.chat_id ?? chatId,
365
+ messages: slimMessages,
366
+ users: slimImUsers(imResult.users),
367
+ pagination: {
368
+ limit,
369
+ first_id_sent: hasFirst ? Number(args.first_id) : null,
370
+ last_id_sent: hasLast ? Number(args.last_id) : null,
371
+ suggested_next_first_id:
372
+ !hasLast && slimMessages.length > 0 ? minId : null,
373
+ suggested_next_last_id:
374
+ !hasFirst && slimMessages.length > 0 ? maxId : null,
375
+ note:
376
+ "If suggested_next_first_id is set and you need older messages, call again with first_id equal to that value. If suggested_next_last_id is set and you need newer messages, call again with last_id equal to that value. Empty page or short page means no more in that direction (heuristic).",
377
+ },
378
+ agent_instructions:
379
+ "author_id 0 — это системные сообщения чата Битрикс24 (смена стадии, учёт времени, приглашения и т.п.), а не пользовательский комментарий; не ищи для них запись в users. " +
380
+ "Для author_id > 0 сопоставь author_id с users[].id и бери имя/должность из найденного user. Текст сообщения в messages[].text.",
381
+ };
382
+
383
+ return { content: [{ type: "text", text: JSON.stringify(payload, null, 2) }] };
384
+ }
385
+
206
386
  default:
207
387
  throw new Error(`Unknown tool: ${name}`);
208
388
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@x0333/bitrix24-mcp-server",
3
- "version": "2.2.1",
3
+ "version": "2.3.1",
4
4
  "description": "Bitrix24 MCP Server for AI Agent Integration.",
5
5
  "main": "index.js",
6
6
  "bin": {