odant-work 1.0.76 → 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.
@@ -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 });
@@ -670,6 +670,39 @@ export async function listNodeStructures(storage, params = {}) {
670
670
  return { structures: out };
671
671
  }
672
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
+
673
706
  /**
674
707
  * Последние выполненные задачи `.task` подразделения (для повторения по расписанию).
675
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
+ }