odant-work 1.0.75 → 1.0.77

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.
@@ -155,9 +155,17 @@ async function mcpRpc(owner, method, params, opts = {}) {
155
155
  if (String(cfg.url || '').trim())
156
156
  return mcpHttpRpc(owner, method, params, opts);
157
157
  const command = String(cfg.command || '').trim();
158
- const args = Array.isArray(cfg.args) ? cfg.args.map(String) : [];
158
+ let args = Array.isArray(cfg.args) ? cfg.args.map(String) : [];
159
159
  if (!command)
160
160
  return { error: 'mcp: нет mcp.command (stdio) или mcp.url (remote) в class.js провайдера' };
161
+ if (command === 'node' && args[0] && /^sources\//.test(args[0])) {
162
+ const pathMod = await import('node:path');
163
+ const fsMod = await import('node:fs');
164
+ const baseDir = globalThis.WORK?.real_dir || process.cwd();
165
+ const abs = pathMod.resolve(baseDir, args[0]);
166
+ if (fsMod.existsSync(abs))
167
+ args = [abs, ...args.slice(1)];
168
+ }
161
169
  const env = await mcpEnv(owner, cfg.env);
162
170
  if (env.error)
163
171
  return env;
@@ -395,22 +403,33 @@ function parseHttpRpc(body) {
395
403
  return null;
396
404
  }
397
405
 
398
- /** Переменные окружения / заголовки: `secret:ФАЙЛ` резолвятся через read_secret владельца. */
406
+ /** Переменные окружения / заголовки: `secret:ФАЙЛ` (строгий) и `secret?:ФАЙЛ` (опциональный) резолвятся через read_secret владельца. */
399
407
  async function mcpEnv(owner, env) {
400
408
  const vars = {};
401
409
  for (const [k, v] of Object.entries(env && typeof env === 'object' ? env : {})) {
402
410
  const s = String(v ?? '');
403
- if (/^secret:/i.test(s)) {
404
- const filename = s.slice(7).trim();
411
+ const secMatch = s.match(/^secret(\?)?:(.*)$/i);
412
+ if (secMatch) {
413
+ const optional = Boolean(secMatch[1]);
414
+ const filename = String(secMatch[2] || '').trim();
405
415
  try {
406
416
  const data = await owner.read_secret({ filename });
407
417
  const value = typeof data === 'string' ? data
408
418
  : data?.value ?? data?.token ?? data?.key ?? data?.apiKey ?? null;
409
- if (value == null || String(value) === '')
419
+ if (value == null || String(value) === '') {
420
+ if (optional) {
421
+ vars[k] = '';
422
+ continue;
423
+ }
410
424
  return { error: 'mcp: секрет ' + filename + ' пуст (нужно поле value/token/key в #secret/' + filename + ')' };
425
+ }
411
426
  vars[k] = String(value);
412
427
  }
413
428
  catch (e) {
429
+ if (optional) {
430
+ vars[k] = '';
431
+ continue;
432
+ }
414
433
  return { error: 'mcp: нет секрета ' + filename + ' (#secret): ' + String(e.message || e) };
415
434
  }
416
435
  }
@@ -0,0 +1,9 @@
1
+ /**
2
+ * Подраздел «Маркетплейсы» (/SERVICES/Marketplaces) — MCP-серверы для российских маркетплейсов.
3
+ */
4
+ export default {
5
+ icon: 'carbon:shopping-cart',
6
+ label: 'Маркетплейсы',
7
+ description: 'MCP-интеграции с российскими маркетплейсами: Ozon, Wildberries и Яндекс Маркет',
8
+ enabled: true,
9
+ };
@@ -0,0 +1,19 @@
1
+ /**
2
+ * Ozon Seller MCP (/SERVICES/Marketplaces/Ozon).
3
+ * Секреты сохраняются в #secret/ozon_client_id и #secret/ozon_api_key.
4
+ */
5
+ export default {
6
+ icon: 'carbon:shopping-bag',
7
+ label: 'Ozon Seller MCP',
8
+ description: 'Товары, цены, остатки, заказы FBS/FBO, аналитика и финансы через Ozon Seller API',
9
+ capabilities: ['marketplace', 'ozon', 'ecommerce'],
10
+ enabled: true,
11
+ mcp: {
12
+ command: 'node',
13
+ args: ['sources/modules/mcp-marketplaces/ozon.js'],
14
+ env: {
15
+ OZON_CLIENT_ID: 'secret?:ozon_client_id',
16
+ OZON_API_KEY: 'secret?:ozon_api_key',
17
+ },
18
+ },
19
+ };
@@ -0,0 +1,18 @@
1
+ /**
2
+ * Wildberries Seller MCP (/SERVICES/Marketplaces/Wildberries).
3
+ * Секрет сохраняется в #secret/wb_api_token.
4
+ */
5
+ export default {
6
+ icon: 'carbon:store',
7
+ label: 'Wildberries Seller MCP',
8
+ description: 'Карточки товаров, цены и скидки, склады, остатки FBS, заказы и статистика продаж Wildberries',
9
+ capabilities: ['marketplace', 'wildberries', 'wb', 'ecommerce'],
10
+ enabled: true,
11
+ mcp: {
12
+ command: 'node',
13
+ args: ['sources/modules/mcp-marketplaces/wildberries.js'],
14
+ env: {
15
+ WB_API_TOKEN: 'secret?:wb_api_token',
16
+ },
17
+ },
18
+ };
@@ -0,0 +1,19 @@
1
+ /**
2
+ * Yandex Market Partner MCP (/SERVICES/Marketplaces/YandexMarket).
3
+ * Секреты сохраняются в #secret/yandex_market_api_key и #secret/yandex_market_campaign_id.
4
+ */
5
+ export default {
6
+ icon: 'carbon:shopping-catalog',
7
+ label: 'Яндекс Маркет MCP',
8
+ description: 'Магазины, товары/офферы, остатки, цены, заказы и отчёты через Yandex Market Partner API',
9
+ capabilities: ['marketplace', 'yandex-market', 'ecommerce'],
10
+ enabled: true,
11
+ mcp: {
12
+ command: 'node',
13
+ args: ['sources/modules/mcp-marketplaces/yandex-market.js'],
14
+ env: {
15
+ YANDEX_MARKET_API_KEY: 'secret?:yandex_market_api_key',
16
+ YANDEX_MARKET_CAMPAIGN_ID: 'secret?:yandex_market_campaign_id',
17
+ },
18
+ },
19
+ };
@@ -23,6 +23,11 @@
23
23
  - **`DuckDuckGo` («DuckDuckGo Веб-поиск»)** — поиск и чтение веб-страниц (`fetch_url`).
24
24
  - **`Weather` («Погода wttr.in»)** — прогноз погоды по городам и координатам России и мира без ключа.
25
25
 
26
+ ### 4. Маркетплейсы (`/SERVICES/Marketplaces`)
27
+ - **`Ozon` («Ozon Seller MCP»)** — товары, цены, остатки FBO/FBS, заказы, аналитика продаж и финансовые транзакции (`#secret/ozon_client_id`, `#secret/ozon_api_key`).
28
+ - **`Wildberries` («Wildberries Seller MCP»)** — карточки товаров, цены и скидки, склады, остатки FBS, заказы и статистика продаж (`#secret/wb_api_token`).
29
+ - **`YandexMarket` («Яндекс Маркет MCP»)** — кампании, товары/офферы, остатки, цены, заказы и отчёты (`#secret/yandex_market_api_key`, `#secret/yandex_market_campaign_id`).
30
+
26
31
  ## Подключение MCP-серверов (`mcp`)
27
32
 
28
33
  Любой класс в `/SERVICES/<Имя>/$service/class.js` с полем `mcp` автоматически работает как MCP-клиент:
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "odant-work",
3
- "version": "1.0.75",
3
+ "version": "1.0.77",
4
4
  "description": "ODANT-WORK — платформа цифровой организации (встроенная система учёта, документооборот, управление процессами и приватный мультимодальный ИИ)",
5
5
  "type": "module",
6
6
  "main": "sources/work.js",
@@ -274,6 +274,8 @@ export class $folder extends $item {
274
274
  || method.startsWith('license_')
275
275
  || method.startsWith('messenger_')
276
276
  || method.startsWith('distro_')
277
+ || method.startsWith('agent_')
278
+ || method === 'security_update'
277
279
  || method === 'export_distro'
278
280
  ))
279
281
  || (method === 'logs' && params.mode && params.mode !== 'folder' && params.mode !== 'files');
@@ -72,14 +72,47 @@ export const MCP_PRESETS = [
72
72
  },
73
73
  },
74
74
  {
75
- id: 'marketplaces-ru',
76
- label: 'Wildberries и Ozon Seller MCP',
77
- description: 'Остатки на складах, карточки товаров, заказы и финансовые отчёты селлера WB / Ozon',
78
- icon: 'carbon:shopping-cart',
79
- transport: 'http',
75
+ id: 'Marketplaces/Ozon',
76
+ label: 'Ozon Seller MCP',
77
+ description: 'Товары, остатки, цены, заказы FBS/FBO, аналитика и финансы Ozon Seller API',
78
+ icon: 'carbon:shopping-bag',
79
+ transport: 'stdio',
80
+ mcp: {
81
+ command: 'node',
82
+ args: ['sources/modules/mcp-marketplaces/ozon.js'],
83
+ env: {
84
+ OZON_CLIENT_ID: 'secret?:ozon_client_id',
85
+ OZON_API_KEY: 'secret?:ozon_api_key',
86
+ },
87
+ },
88
+ },
89
+ {
90
+ id: 'Marketplaces/Wildberries',
91
+ label: 'Wildberries Seller MCP',
92
+ description: 'Карточки товаров, цены, склады, остатки FBS, заказы и статистика продаж Wildberries',
93
+ icon: 'carbon:store',
94
+ transport: 'stdio',
95
+ mcp: {
96
+ command: 'node',
97
+ args: ['sources/modules/mcp-marketplaces/wildberries.js'],
98
+ env: {
99
+ WB_API_TOKEN: 'secret?:wb_api_token',
100
+ },
101
+ },
102
+ },
103
+ {
104
+ id: 'Marketplaces/YandexMarket',
105
+ label: 'Яндекс Маркет MCP',
106
+ description: 'Кампании, товары/офферы, остатки, цены, заказы и отчёты Yandex Market Partner API',
107
+ icon: 'carbon:shopping-catalog',
108
+ transport: 'stdio',
80
109
  mcp: {
81
- url: 'http://localhost:8092/mcp/marketplaces',
82
- headers: { Authorization: 'secret:marketplace_api_key' },
110
+ command: 'node',
111
+ args: ['sources/modules/mcp-marketplaces/yandex-market.js'],
112
+ env: {
113
+ YANDEX_MARKET_API_KEY: 'secret?:yandex_market_api_key',
114
+ YANDEX_MARKET_CAMPAIGN_ID: 'secret?:yandex_market_campaign_id',
115
+ },
83
116
  },
84
117
  },
85
118
  {
@@ -759,13 +792,19 @@ export function formatMentionedAgentsAndToolsBlock(promptText, agentsMap) {
759
792
  // ============================================================================
760
793
 
761
794
  function normalizeMcpServerId(rawId) {
762
- const clean = String(rawId || '')
795
+ const parts = String(rawId || '')
763
796
  .trim()
764
- .replace(/[^a-zA-Z0-9_-]+/g, '-')
765
- .replace(/^-+|-+$/g, '');
766
- if (!clean || !/^[a-zA-Z0-9][a-zA-Z0-9_-]{0,48}$/.test(clean))
767
- throw new Error(`Недопустимое имя MCP-сервера «${rawId}» (используйте латиницу, цифры, дефис или подчёркивание)`);
768
- return clean;
797
+ .replace(/\\/g, '/')
798
+ .split('/')
799
+ .map(seg => seg.trim().replace(/[^a-zA-Z0-9_-]+/g, '-').replace(/^-+|-+$/g, ''))
800
+ .filter(Boolean);
801
+ if (!parts.length || parts.length > 2)
802
+ throw new Error(`Недопустимое имя MCP-сервера «${rawId}» (латиница, цифры, дефис, подчёркивание; допускается 1 подраздел)`);
803
+ for (const seg of parts) {
804
+ if (!/^[a-zA-Z0-9][a-zA-Z0-9_-]{0,48}$/.test(seg))
805
+ throw new Error(`Недопустимое имя MCP-сервера «${rawId}» (используйте латиницу, цифры, дефис или подчёркивание)`);
806
+ }
807
+ return parts.join('/');
769
808
  }
770
809
 
771
810
  /**
@@ -854,83 +893,94 @@ export function parseMcpInstallInput(input = {}) {
854
893
  });
855
894
  }
856
895
 
857
- /** Список всех сервисов и MCP-серверов в /SERVICES + каталог пресетов. */
896
+ /** Список всех сервисов и MCP-серверов в /SERVICES (до 2 уровней вложенности) + каталог пресетов. */
858
897
  export async function listMcpCatalog() {
859
898
  const servicesDir = path.join(process.cwd(), 'SERVICES');
860
899
  const mcpServers = [];
861
900
  const connectors = [];
862
901
 
863
- if (fs.existsSync(servicesDir)) {
864
- const entries = await fsp.readdir(servicesDir, { withFileTypes: true }).catch(() => []);
865
- for (const e of entries.sort((a, b) => a.name.localeCompare(b.name))) {
866
- if (!e.isDirectory() || /^[$.#]/.test(e.name))
867
- continue;
868
- const workPath = '/SERVICES/' + e.name;
869
- let data = null;
870
- try {
871
- const item = await globalThis.WORK?.get_item?.(workPath);
872
- if (item && typeof item.import === 'function')
873
- data = await item.import();
874
- }
875
- catch { /* fallback to reading class.js */ }
902
+ const readServiceData = async (relId) => {
903
+ const workPath = '/SERVICES/' + relId;
904
+ let data = null;
905
+ try {
906
+ const item = await globalThis.WORK?.get_item?.(workPath);
907
+ if (item && typeof item.import === 'function')
908
+ data = await item.import();
909
+ }
910
+ catch { /* fallback to reading class.js */ }
876
911
 
877
- if (!data) {
878
- const clsFile = path.join(servicesDir, e.name, '$service', 'class.js');
879
- if (fs.existsSync(clsFile)) {
912
+ if (!data) {
913
+ const clsFile = path.join(servicesDir, ...relId.split('/'), '$service', 'class.js');
914
+ if (fs.existsSync(clsFile)) {
915
+ try {
916
+ const raw = await fsp.readFile(clsFile, 'utf-8');
917
+ const m = raw.match(/export\s+default\s+(\{[\s\S]*\})\s*;?\s*$/);
918
+ if (m)
919
+ data = JSON.parse(m[1]);
920
+ }
921
+ catch { /* fallback to dynamic import */ }
922
+ if (!data) {
880
923
  try {
881
- const raw = await fsp.readFile(clsFile, 'utf-8');
882
- const m = raw.match(/export\s+default\s+(\{[\s\S]*\})\s*;?\s*$/);
883
- if (m)
884
- data = JSON.parse(m[1]);
885
- }
886
- catch { /* fallback to dynamic import */ }
887
- if (!data) {
888
- try {
889
- const { pathToFileURL } = await import('node:url');
890
- const mod = await import(pathToFileURL(clsFile).href + '?t=' + Date.now());
891
- data = mod?.default || null;
892
- }
893
- catch { /* ignore */ }
924
+ const { pathToFileURL } = await import('node:url');
925
+ const mod = await import(pathToFileURL(clsFile).href + '?t=' + Date.now());
926
+ data = mod?.default || null;
894
927
  }
928
+ catch { /* ignore */ }
895
929
  }
896
930
  }
931
+ }
932
+ return { workPath, data };
933
+ };
897
934
 
898
- if (!data || typeof data !== 'object')
935
+ const scanDir = async (dirPath, prefix = '', level = 1) => {
936
+ const entries = await fsp.readdir(dirPath, { withFileTypes: true }).catch(() => []);
937
+ for (const e of entries.sort((a, b) => a.name.localeCompare(b.name))) {
938
+ if (!e.isDirectory() || /^[$.#]/.test(e.name))
899
939
  continue;
900
-
901
- if (data.mcp && typeof data.mcp === 'object') {
902
- const isHttp = Boolean(data.mcp.url);
903
- mcpServers.push({
904
- id: e.name,
905
- path: workPath,
906
- label: data.label || e.name,
907
- description: data.description || 'MCP-сервер',
908
- icon: data.icon || 'carbon:plug',
909
- enabled: data.enabled !== false,
910
- transport: isHttp ? 'http' : 'stdio',
911
- command: data.mcp.command || '',
912
- args: Array.isArray(data.mcp.args) ? data.mcp.args : [],
913
- url: data.mcp.url || '',
914
- envKeys: data.mcp.env ? Object.keys(data.mcp.env) : [],
915
- headerKeys: data.mcp.headers ? Object.keys(data.mcp.headers) : [],
916
- mcp: data.mcp,
917
- });
918
- }
919
- else {
920
- const schemaTools = data.SCHEMA && typeof data.SCHEMA === 'object' ? Object.keys(data.SCHEMA) : [];
921
- connectors.push({
922
- id: e.name,
923
- path: workPath,
924
- label: data.label || e.name,
925
- description: data.description || '',
926
- icon: data.icon || 'carbon:api',
927
- enabled: data.enabled !== false,
928
- capabilities: Array.isArray(data.capabilities) ? data.capabilities : [],
929
- tools: schemaTools,
930
- });
940
+ const relId = prefix ? `${prefix}/${e.name}` : e.name;
941
+ const { workPath, data } = await readServiceData(relId);
942
+
943
+ if (data && typeof data === 'object') {
944
+ if (data.mcp && typeof data.mcp === 'object') {
945
+ const isHttp = Boolean(data.mcp.url);
946
+ mcpServers.push({
947
+ id: relId,
948
+ path: workPath,
949
+ label: data.label || e.name,
950
+ description: data.description || 'MCP-сервер',
951
+ icon: data.icon || 'carbon:plug',
952
+ enabled: data.enabled !== false,
953
+ transport: isHttp ? 'http' : 'stdio',
954
+ command: data.mcp.command || '',
955
+ args: Array.isArray(data.mcp.args) ? data.mcp.args : [],
956
+ url: data.mcp.url || '',
957
+ envKeys: data.mcp.env ? Object.keys(data.mcp.env) : [],
958
+ headerKeys: data.mcp.headers ? Object.keys(data.mcp.headers) : [],
959
+ mcp: data.mcp,
960
+ });
961
+ }
962
+ else if (data.SCHEMA || level > 1) {
963
+ const schemaTools = data.SCHEMA && typeof data.SCHEMA === 'object' ? Object.keys(data.SCHEMA) : [];
964
+ connectors.push({
965
+ id: relId,
966
+ path: workPath,
967
+ label: data.label || e.name,
968
+ description: data.description || '',
969
+ icon: data.icon || 'carbon:api',
970
+ enabled: data.enabled !== false,
971
+ capabilities: Array.isArray(data.capabilities) ? data.capabilities : [],
972
+ tools: schemaTools,
973
+ });
974
+ }
931
975
  }
976
+
977
+ if (level < 2)
978
+ await scanDir(path.join(dirPath, e.name), relId, level + 1);
932
979
  }
933
- }
980
+ };
981
+
982
+ if (fs.existsSync(servicesDir))
983
+ await scanDir(servicesDir, '', 1);
934
984
 
935
985
  return {
936
986
  mcpServers,
@@ -950,7 +1000,7 @@ export async function installMcpServers(input = {}, ctx = {}) {
950
1000
  const installed = [];
951
1001
 
952
1002
  for (const spec of specs) {
953
- const srvDir = path.join(servicesDir, spec.id, '$service');
1003
+ const srvDir = path.join(servicesDir, ...spec.id.split('/'), '$service');
954
1004
  const secretDir = path.join(srvDir, '#secret');
955
1005
  await fsp.mkdir(srvDir, { recursive: true });
956
1006
 
@@ -997,7 +1047,7 @@ export async function setMcpServerEnabled({ id, enabled }, ctx = {}) {
997
1047
  if (ctx?.session && !(await isAdmin(ctx.session)))
998
1048
  throw new Error('Доступ запрещён: управлять сервисами и MCP может только руководитель (BOSS)');
999
1049
  const cleanId = normalizeMcpServerId(id);
1000
- const clsFile = path.join(process.cwd(), 'SERVICES', cleanId, '$service', 'class.js');
1050
+ const clsFile = path.join(process.cwd(), 'SERVICES', ...cleanId.split('/'), '$service', 'class.js');
1001
1051
  if (!fs.existsSync(clsFile))
1002
1052
  throw new Error(`Сервис /SERVICES/${cleanId} не найден`);
1003
1053
 
@@ -1034,7 +1084,7 @@ export async function removeMcpServer({ id }, ctx = {}) {
1034
1084
  if (ctx?.session && !(await isAdmin(ctx.session)))
1035
1085
  throw new Error('Доступ запрещён: удалять MCP-серверы может только руководитель (BOSS)');
1036
1086
  const cleanId = normalizeMcpServerId(id);
1037
- const targetDir = path.join(process.cwd(), 'SERVICES', cleanId);
1087
+ const targetDir = path.join(process.cwd(), 'SERVICES', ...cleanId.split('/'));
1038
1088
  if (!fs.existsSync(targetDir))
1039
1089
  throw new Error(`MCP-сервер /SERVICES/${cleanId} не найден`);
1040
1090
  await fsp.rm(targetDir, { recursive: true, force: true });
@@ -655,7 +655,10 @@ export async function listNodeStructures(storage, params = {}) {
655
655
  }
656
656
  const items = await Promise.resolve(node.items).catch(() => []) || [];
657
657
  for (const ch of items) {
658
- if (ch && ch.id?.[0] !== '$' && ['$domain', '$base', '$project', '$structure'].includes(ch.type))
658
+ if (!ch || ch.id?.[0] === '$')
659
+ continue;
660
+ await ch.init?.catch?.(() => {});
661
+ if (['$domain', '$base', '$project', '$structure'].includes(ch.type))
659
662
  await visit(ch, depth + 1);
660
663
  }
661
664
  };
@@ -667,6 +670,39 @@ export async function listNodeStructures(storage, params = {}) {
667
670
  return { structures: out };
668
671
  }
669
672
 
673
+ /**
674
+ * Список серверов сети WORK (/NODES/<Узел>) для назначения в роли доступа.
675
+ */
676
+ export async function listNodeNetworkNodes(storage, params = {}) {
677
+ await assertBoss(storage, params);
678
+ const WORK = globalThis.WORK;
679
+ if (!WORK)
680
+ return { nodes: [] };
681
+ const nodesRoot = await WORK.get_item('/NODES').catch(() => null);
682
+ if (!nodesRoot)
683
+ return { nodes: [] };
684
+ const items = await Promise.resolve(nodesRoot.items).catch(() => []) || [];
685
+ const out = [];
686
+ for (const n of items) {
687
+ if (!n || n.id?.[0] === '$' || n.type !== '$node')
688
+ continue;
689
+ await n.init?.catch?.(() => {});
690
+ const principalId = String(n.principalId || n.DATA?.host_id || n.id || '').trim();
691
+ if (!principalId)
692
+ continue;
693
+ out.push({
694
+ id: n.id,
695
+ path: n.path || `/NODES/${n.id}`,
696
+ principalId,
697
+ label: n.DATA?.label || n.label || n.id,
698
+ origin: n.DATA?.origin || '',
699
+ status: n.DATA?.status || '',
700
+ icon: n.DATA?.icon || n.icon || 'icons:dns',
701
+ });
702
+ }
703
+ return { nodes: out };
704
+ }
705
+
670
706
  /**
671
707
  * Последние выполненные задачи `.task` подразделения (для повторения по расписанию).
672
708
  */
@@ -0,0 +1,114 @@
1
+ /**
2
+ * Лёгкий JSON-RPC 2.0 MCP-сервер по stdio (NDJSON) для встроенных коннекторов WORK.
3
+ * Совместим со спецификацией MCP 2025-06-18 и пулом `sources/modules/agent/mcp-pool.js`.
4
+ */
5
+ import readline from 'node:readline';
6
+
7
+ export function startMcpStdioServer({ name, version = '1.0.0', tools = [] }) {
8
+ const toolMap = new Map();
9
+ for (const t of tools) {
10
+ if (t?.name)
11
+ toolMap.set(t.name, t);
12
+ }
13
+
14
+ const send = (obj) => {
15
+ process.stdout.write(JSON.stringify(obj) + '\n');
16
+ };
17
+
18
+ const rl = readline.createInterface({
19
+ input: process.stdin,
20
+ crlfDelay: Infinity,
21
+ });
22
+
23
+ rl.on('line', async (rawLine) => {
24
+ const line = String(rawLine || '').trim();
25
+ if (!line)
26
+ return;
27
+ let msg;
28
+ try {
29
+ msg = JSON.parse(line);
30
+ }
31
+ catch {
32
+ return;
33
+ }
34
+ if (!msg || typeof msg !== 'object')
35
+ return;
36
+ const { id, method, params } = msg;
37
+
38
+ // Уведомления (без id) не требуют ответа
39
+ if (id == null)
40
+ return;
41
+
42
+ try {
43
+ if (method === 'initialize') {
44
+ send({
45
+ jsonrpc: '2.0',
46
+ id,
47
+ result: {
48
+ protocolVersion: params?.protocolVersion || '2025-06-18',
49
+ capabilities: { tools: { listChanged: false } },
50
+ serverInfo: { name, version },
51
+ },
52
+ });
53
+ return;
54
+ }
55
+ if (method === 'ping') {
56
+ send({ jsonrpc: '2.0', id, result: {} });
57
+ return;
58
+ }
59
+ if (method === 'tools/list') {
60
+ send({
61
+ jsonrpc: '2.0',
62
+ id,
63
+ result: {
64
+ tools: tools.map(t => ({
65
+ name: t.name,
66
+ description: t.description || '',
67
+ inputSchema: t.inputSchema || { type: 'object', properties: {} },
68
+ })),
69
+ },
70
+ });
71
+ return;
72
+ }
73
+ if (method === 'tools/call') {
74
+ const toolName = String(params?.name || '').trim();
75
+ const tool = toolMap.get(toolName);
76
+ if (!tool) {
77
+ send({
78
+ jsonrpc: '2.0',
79
+ id,
80
+ error: { code: -32601, message: `Неизвестный инструмент MCP: ${toolName}` },
81
+ });
82
+ return;
83
+ }
84
+ const out = await tool.handler(params?.arguments || {});
85
+ const isError = Boolean(out?.error && !out?.notConfigured);
86
+ const text = typeof out === 'string' ? out : JSON.stringify(out, null, 2);
87
+ send({
88
+ jsonrpc: '2.0',
89
+ id,
90
+ result: {
91
+ content: [{ type: 'text', text }],
92
+ ...(isError ? { isError: true } : {}),
93
+ },
94
+ });
95
+ return;
96
+ }
97
+ send({
98
+ jsonrpc: '2.0',
99
+ id,
100
+ error: { code: -32601, message: `Метод ${method} не поддерживается` },
101
+ });
102
+ }
103
+ catch (err) {
104
+ send({
105
+ jsonrpc: '2.0',
106
+ id,
107
+ result: {
108
+ content: [{ type: 'text', text: JSON.stringify({ error: String(err?.message || err) }, null, 2) }],
109
+ isError: true,
110
+ },
111
+ });
112
+ }
113
+ });
114
+ }