integram-mcp 0.1.0

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 +148 -0
  2. package/index.js +1791 -0
  3. package/package.json +24 -0
package/index.js ADDED
@@ -0,0 +1,1791 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * Integram MCP Server — exposes Integram AI tools via MCP protocol.
4
+ *
5
+ * Env vars:
6
+ * INTEGRAM_URL — base URL (default: http://localhost:8081)
7
+ * INTEGRAM_EMAIL — login email
8
+ * INTEGRAM_PASSWORD — login password
9
+ * INTEGRAM_WORKSPACE — workspace slug (e.g. "my")
10
+ * INTEGRAM_SKIP_HITL — set to "true" to auto-confirm all HITL prompts (for automation)
11
+ */
12
+
13
+ // ─── SOCKS/HTTP proxy for MCP calls (reads HTTPS_PROXY env) ─────────────────
14
+ import { EnvHttpProxyAgent, setGlobalDispatcher } from 'undici';
15
+ if (process.env.HTTPS_PROXY || process.env.HTTP_PROXY) {
16
+ setGlobalDispatcher(new EnvHttpProxyAgent());
17
+ }
18
+
19
+ import { Server } from '@modelcontextprotocol/sdk/server/index.js';
20
+ import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
21
+ import {
22
+ ListToolsRequestSchema,
23
+ CallToolRequestSchema,
24
+ } from '@modelcontextprotocol/sdk/types.js';
25
+
26
+ const BASE_URL = (process.env.INTEGRAM_URL || 'http://localhost:8081').replace(/\/$/, '');
27
+ const EMAIL = process.env.INTEGRAM_EMAIL;
28
+ const PASSWORD = process.env.INTEGRAM_PASSWORD;
29
+ let workspace = process.env.INTEGRAM_WORKSPACE || '';
30
+ const SKIP_HITL = process.env.INTEGRAM_SKIP_HITL === 'true';
31
+
32
+ // ─── Auth state ──────────────────────────────────────────────────────────────
33
+
34
+ let accessToken = null;
35
+ let refreshToken = null;
36
+ let tokenExp = 0; // epoch seconds
37
+ let _authPromise = null;
38
+
39
+ async function apiFetch(path, opts = {}, _retried = false) {
40
+ const url = `${BASE_URL}${path}`;
41
+ const headers = { 'Content-Type': 'application/json', ...opts.headers };
42
+ if (accessToken) headers['Authorization'] = `Bearer ${accessToken}`;
43
+ const res = await fetch(url, { ...opts, headers });
44
+ if (!res.ok) {
45
+ // Retry once on 401 — token may have expired between ensureAuth and fetch
46
+ if (res.status === 401 && !_retried) {
47
+ tokenExp = 0; // force re-auth
48
+ await ensureAuth();
49
+ return apiFetch(path, opts, true);
50
+ }
51
+ const text = await res.text().catch(() => '');
52
+ throw new Error(`API ${opts.method || 'GET'} ${path} → ${res.status}: ${text}`);
53
+ }
54
+ const text = await res.text();
55
+ try {
56
+ return JSON.parse(text);
57
+ } catch {
58
+ throw new Error(`API ${opts.method || 'GET'} ${path} → invalid JSON response (${text.length} chars)`);
59
+ }
60
+ }
61
+
62
+ async function login() {
63
+ if (!EMAIL || !PASSWORD) throw new Error('INTEGRAM_EMAIL and INTEGRAM_PASSWORD are required');
64
+ const data = await apiFetch('/api/v2/iam/login', {
65
+ method: 'POST',
66
+ body: JSON.stringify({ email: EMAIL, password: PASSWORD }),
67
+ });
68
+ if (!data.ok) throw new Error(`Login failed: ${JSON.stringify(data.error)}`);
69
+ accessToken = data.accessToken || data.data?.accessToken || data.data?.token;
70
+ refreshToken = data.refreshToken || data.data?.refreshToken;
71
+ tokenExp = decodeExp(accessToken);
72
+ log(`Logged in as ${EMAIL}, token expires ${new Date(tokenExp * 1000).toISOString()}`);
73
+ }
74
+
75
+ async function ensureAuth() {
76
+ const now = Math.floor(Date.now() / 1000);
77
+ if (tokenExp - now >= 60) return;
78
+
79
+ // Coalesce concurrent auth attempts into a single request
80
+ if (_authPromise) return _authPromise;
81
+ _authPromise = (async () => {
82
+ if (refreshToken) {
83
+ try {
84
+ const data = await apiFetch('/api/v2/iam/refresh', {
85
+ method: 'POST',
86
+ body: JSON.stringify({ refreshToken }),
87
+ });
88
+ if (data.ok) {
89
+ accessToken = data.accessToken || data.data?.accessToken || data.data?.token;
90
+ refreshToken = data.refreshToken || data.data?.refreshToken || refreshToken;
91
+ tokenExp = decodeExp(accessToken);
92
+ log('Token refreshed');
93
+ return;
94
+ }
95
+ } catch { /* fall through to re-login */ }
96
+ }
97
+ await login();
98
+ })().finally(() => { _authPromise = null; });
99
+ return _authPromise;
100
+ }
101
+
102
+ function decodeExp(jwt) {
103
+ try {
104
+ if (!jwt || typeof jwt !== 'string') return 0;
105
+ const parts = jwt.split('.');
106
+ if (parts.length < 3) return 0;
107
+ const payload = JSON.parse(Buffer.from(parts[1], 'base64url').toString());
108
+ return payload.exp || 0;
109
+ } catch { return 0; }
110
+ }
111
+
112
+ function log(msg) {
113
+ process.stderr.write(`[integram-mcp] ${msg}\n`);
114
+ }
115
+
116
+ // ─── Tool definitions cache ──────────────────────────────────────────────────
117
+
118
+ let allTools = []; // full list from backend
119
+ const activeTools = new Map(); // name → tool def (currently exposed via MCP)
120
+
121
+ // Built-in MCP tools handled locally — never load from backend to avoid duplicates
122
+ const BUILT_IN_NAMES = new Set([
123
+ 'list_workspaces', 'switch_workspace', 'create_workspace',
124
+ 'delete_workspace', 'clone_workspace', 'search_tools', 'confirm_action',
125
+ ]);
126
+
127
+ // Pending HITL state — stores the threadId for the last pending_confirmation
128
+ const pendingHitlQueue = []; // [{ threadId, action, description, createdAt }, ...]
129
+ const HITL_QUEUE_MAX_SIZE = 50;
130
+ const HITL_QUEUE_TTL_MS = 10 * 60 * 1000; // 10 minutes
131
+
132
+ async function fetchTools() {
133
+ const data = await apiFetch(`/api/v2/${workspace}/ai/tools`);
134
+ if (!data.ok) throw new Error(`Failed to fetch tools: ${JSON.stringify(data.error)}`);
135
+ allTools = data.data;
136
+ return allTools;
137
+ }
138
+
139
+ // ─── MCP Server (low-level — we pass raw JSON Schema, not Zod) ──────────────
140
+
141
+ const INSTRUCTIONS = `Integram — workspace-based platform: tables, documents, reports, automations, permissions, forms, webhooks, files, knowledge graph.
142
+ Server: ${BASE_URL}
143
+
144
+ ## Getting started
145
+ 1. list_workspaces → switch_workspace (required before anything else). Or create_workspace to start fresh.
146
+ 2. Explore: list_tables, list_documents, list_objects for data; semantic_search for fuzzy lookup.
147
+ 3. Workspace management: clone_workspace to duplicate an existing workspace; delete_workspace to permanently remove one.
148
+
149
+ ## Tool discovery
150
+ Only core tools (~15: CRUD, search, graph, comments, bulk, history) are loaded by default. Use search_tools to activate more:
151
+ - "schema" — create/modify tables and columns, AI/HTTP/script buttons, computed columns (LOOKUP/ROLLUP/FORMULA), validation rules, AI formula generation (~27 tools)
152
+ - "reports" — create, run, export reports with aggregation, joins and filters (~15 tools)
153
+ - "docs" — documents, blocks, folders, tags, sharing, versions, templates, PDF generation (~38 tools)
154
+ - "workspace" — files, import/export, connectors, members, backups, dashboards, view/record sharing, audit log, normalizer, automations, webhooks, forms (~80 tools)
155
+ - "portal" — portal config, catalog, carts, orders, tickets, KB articles, metrics, customer profiles, Telegram bots (~42 tools)
156
+ - "telegram" — Telegram bot management, messaging, moderation, payments, stories, business API (subset of portal group)
157
+ - "grants" — roles, grants, row-level rules, member access (admin only) (~11 tools)
158
+ - "codespace" — git repositories: branches, commits, files, pull requests (~21 tools)
159
+ - "teamchat" — rooms, topics, messages, decisions, agent metrics, W-matrix (ONA) (~35 tools)
160
+ - "graph" — get_related, graph_query, neighborhood, shortest path, health, memory agents (~9 tools)
161
+ - "meta-kb" — debate-based knowledge curation: start debates, parallel experts, LLM synthesis (~6 tools)
162
+ - "kag" — knowledge-augmented generation: search, traverse, ask (~3 tools)
163
+ - "memory" — agent long-term memory, recall, procedures, contradictions (~7 tools)
164
+ - "timeseries" — record, query, and list time-series data sources (~3 tools)
165
+ - "advisor" — ask platform expert for advice on schema design, best practices (~2 tools)
166
+ - "ai" — text-to-speech synthesis (TTS): speak text, list voices (~2 tools)
167
+ - "agents" — list and delegate to external AI agents (~2 tools)
168
+ - "orgs" — organizations: create, list, manage multi-workspace orgs and members (~8 tools)
169
+ - "bulk" — bulk_create, bulk_update, bulk_delete, autofill_batch (~4 tools)
170
+ - "comments" — comments, reactions on records (~6 tools)
171
+ - "history" — object change history, rollback (~2 tools)
172
+ - "objects" — move, reorder, duplicate records (~4 tools)
173
+ - "lookups" — get lookup options, ref options (~2 tools)
174
+ - "automations" — get automation details, webhook delivery log (~3 tools)
175
+
176
+ ---
177
+
178
+ ## Column types (colTypeName for add_column / type for plan_schema)
179
+
180
+ | colTypeName | UI | Use when |
181
+ |---|---|---|
182
+ | text, string | single-line input | free-form unique values: name, title, URL, address, article code |
183
+ | phone | phone input | phone number with click-to-call: mobile, tel, телефон |
184
+ | email | email input | email address with mailto link: email, mail, почта |
185
+ | memo, multiline | textarea | long text: description, notes, comment, bio, summary |
186
+ | number | numeric input | price, cost, amount, qty, score, rating, age, salary, budget |
187
+ | date | date picker | birthday, deadline, start date, hire date |
188
+ | datetime | date+time picker | event time, created_at, timestamp, log entry |
189
+ | bool, checkbox | toggle | flag: active, paid, approved, done, published, verified |
190
+ | file | file upload | attachment, photo, image, document, avatar |
191
+ | pwd, password | masked input | password, secret, API key (stored hashed) |
192
+ | uuid | auto-generated | unique identifier |
193
+ | url | URL input | website, link, external resource |
194
+ | duration | duration input | time duration: hours, minutes (e.g. task effort) |
195
+ | currency | currency input | monetary values with currency symbol |
196
+ | percent | percentage input | percentage values (0–100) |
197
+ | rating | star rating | ratings, scores (1–5 stars) |
198
+ | status | status badge | workflow status with color coding |
199
+ | choice | choice/select | single choice from predefined options |
200
+ | http_button | clickable button | HTTP request per row (see HTTP Buttons section) |
201
+ | script_button | clickable button | JavaScript per row (see Script Buttons section) |
202
+ | ai_button | clickable button | AI prompt per row (see AI Buttons section) |
203
+ | ai | clickable button | alias for ai_button |
204
+
205
+ **IMPORTANT — semantic type inference:**
206
+ Choose type by the MEANING of the field, not just the word:
207
+ - "Phone", "Mobile", "Tel" → phone (type 30, renders with call icon)
208
+ - "Email", "Mail" → email (type 41, renders as mailto: link)
209
+ - "Website", "URL" → text (NOT number, NOT special type)
210
+ - "Price", "Salary", "Budget", "Score", "Age", "Rating" → number
211
+ - "Birthday", "Deadline", "Start date" → date
212
+ - "Description", "Notes", "Comment", "Bio" → memo
213
+ - "Active", "Done", "Published", "Verified" → bool
214
+ - "Status", "Priority", "Category", "City", "Department", "Stage", "Type", "Tags" → **NOT text!** → ref to a lookup table (see below)
215
+
216
+ ## Data modeling — the DECISION TREE
217
+
218
+ For every field, ask: "Where do the values come from?"
219
+
220
+ 1. **User types any value, each entry unique** (name, address, phone, email)
221
+ → **text** (or **memo** for long text)
222
+
223
+ 2. **User picks ONE value from a fixed set** (status, priority, category, city, stage, department, type)
224
+ → **ref** to a lookup table (single select dropdown)
225
+ How: create a lookup table with options → add ref column pointing to it
226
+
227
+ 3. **User picks MULTIPLE values from a fixed set** (tags, skills, features, categories)
228
+ → **ref + multi=true** to a lookup table (multiselect checkboxes/chips)
229
+ How: create a lookup table with options → add ref column with multi=true
230
+
231
+ 4. **User picks a record from another entity** (client on a deal, assignee on a task)
232
+ → **ref** to that entity's table (dropdown showing records from the target table)
233
+ How: add ref column with refTypeId = target table ID
234
+
235
+ 5. **Data is a sub-list owned by a parent** (order items, task steps, contact persons, comments)
236
+ → **child table** with parentTableName (in plan_schema) or parentTypeId (in create_table)
237
+ Child records are created with parentId and shown as nested tabs inside parent record
238
+
239
+ 6. **Numeric value** (price, qty, score) → **number**
240
+ 7. **Date** (deadline, birthday) → **date**; with time → **datetime**
241
+ 8. **Yes/No flag** (active, done) → **bool**
242
+ 9. **File upload** (photo, document) → **file**
243
+
244
+ ## Lookup tables (справочники) — dropdowns & multiselects
245
+
246
+ A lookup table = regular table where each record is one option. Other tables reference it via ref columns → user sees a dropdown.
247
+
248
+ **Key rules:**
249
+ - Lookup table itself has NO columns — only a name per record (seedRecords in plan_schema)
250
+ - The ref column goes in the TABLE THAT USES the dropdown, NOT in the lookup table
251
+ - One lookup can serve multiple ref columns across different tables (e.g., "Priorities" used by both "Tasks" and "Deals")
252
+ - For multiselect: ref + multi=true. Multiselect WITHOUT a lookup is IMPOSSIBLE.
253
+ - When setting ref values in create_object/update_object: pass either the record ID (number) OR the exact record name — the backend resolves names → ids via _v2_objects lookup. For multi: comma-separated ids or names. Ambiguous names (multiple matches) throw an error — pass id to disambiguate.
254
+
255
+ **Common lookups to create:**
256
+ - Statuses: "New", "In Progress", "Done", "Cancelled"
257
+ - Priorities: "Low", "Medium", "High", "Critical"
258
+ - Categories/Types: domain-specific classification
259
+ - Stages: workflow steps ("Lead", "Negotiation", "Contract", "Closed")
260
+ - Tags: multi-select labels
261
+
262
+ ## Table relationships — ref vs child vs lookup
263
+
264
+ | Pattern | Example | How | UI |
265
+ |---|---|---|---|
266
+ | **Lookup** (fixed options) | Task → Status | lookup table + ref column | dropdown |
267
+ | **Lookup multi** (multiple options) | Task → Tags | lookup table + ref + multi=true | checkboxes/chips |
268
+ | **Reference** (link to entity) | Deal → Client | ref column pointing to entity table | dropdown with entity records |
269
+ | **Child table** (owned sub-records) | Order → Order Items | child table with parentTableName | nested tabs inside parent record |
270
+
271
+ **When to use ref vs child table:**
272
+ - **ref** = link between INDEPENDENT entities. Both exist on their own. Deleting one doesn't delete the other. Example: Deal references Client — Client exists without Deal.
273
+ - **child table** = OWNED sub-records. Children don't exist without parent. Shown as tabs inside parent record, NOT in sidebar. Example: Order has Order Items — items don't exist outside the order.
274
+
275
+ **Child table rules:**
276
+ - In plan_schema: set parentTableName = name of parent table
277
+ - In create_table: set parentTypeId = ID of parent table
278
+ - When creating child records: pass parentId = ID of the parent record
279
+ - Child tables appear as nested tabs when viewing the parent record
280
+ - Child tables do NOT appear in the sidebar navigation
281
+ - A child table can have its own columns, refs, and even its own child tables (nested hierarchy)
282
+
283
+ ## plan_schema — create entire schema in one shot
284
+
285
+ **ALWAYS use plan_schema when creating 2+ tables.** Activate via search_tools("schema").
286
+
287
+ plan_schema({ tables: [...] }) creates all tables, columns, refs, and seed records with ONE confirmation.
288
+
289
+ **Table properties:**
290
+ - name (required) — table name
291
+ - icon — emoji icon
292
+ - valueColumnName — display name for the virtual _value column (record name). Default = table name in singular form (table "Clients" → column "Client"). Use valueColumnName only if you want a different header (e.g. "Full Name" instead of "Client", "Order #" instead of "Order").
293
+ - isLookup — true for dropdown/lookup tables (only has seedRecords, no columns)
294
+ - seedRecords — array of option names for lookup tables: ["New", "Active", "Closed"]
295
+ - parentTableName — name of parent table (for child tables). Must match another table's name in the plan.
296
+ - columns — array of column definitions (see below). Do NOT include a "Name"/"Title" column — it duplicates _value.
297
+
298
+ **Column properties:**
299
+ - alias (required) — display name
300
+ - type — data type: text/memo/number/date/datetime/bool/file/pwd/uuid/url/duration/currency/percent/rating/status/choice/phone/email/http_button/script_button/ai_button (NOT needed if refTable is set)
301
+ - refTable — name of another table in the plan for ref/dropdown column
302
+ - multi — true for multiselect (REQUIRES refTable)
303
+ - required — true for mandatory field
304
+ - unique — true for unique constraint (article codes, SKU, email if must be unique)
305
+ - size — length limit: "100" (max chars) or "10,2" (precision,scale for numbers e.g. price with 2 decimals)
306
+
307
+ **Smart header grouping — column merging under parent headers:**
308
+ Use dot "." in alias to group columns: "Group.Column" → columns with same prefix merge under a shared header.
309
+ Example: { "alias": "Contacts.Phone" }, { "alias": "Contacts.Email" }, { "alias": "Contacts.Telegram" } → all three appear under "CONTACTS" parent header.
310
+ Rules: at least 2 consecutive columns with same prefix; columns without dot remain standalone.
311
+ Use for tables with many related columns (contacts, address, financials, specs). Skip for tables with ≤4 columns.
312
+
313
+ **CRITICAL — _value virtual column (record name):**
314
+ Every table automatically has a virtual _value column — the record's display name (first column in UI, clickable link).
315
+ - _value is filled via the "name" field in create_object / bulk_create.
316
+ - Do NOT create a separate "Name"/"Title"/"Название" column — it duplicates _value and causes UI confusion.
317
+ - Default _value header = table name in singular form ("Products" → "Product"). Use valueColumnName only to override (e.g. "Full Name" instead of "Client").
318
+
319
+ **CRITICAL rules:**
320
+ - Ref columns go in the TABLE THAT REFERENCES, NOT in the lookup. "Status" column → in "Clients", NOT in "Statuses".
321
+ - Lookup tables (isLookup=true) have ONLY seedRecords, NO columns array.
322
+ - Tables are auto-sorted: lookups first, then parents, then children. No need to order manually.
323
+ - refTable must match the exact name of another table in the same plan.
324
+ - After plan_schema completes — ALL tables, columns, refs, and seed records are ALREADY created. Do NOT call create_table, add_column, create_object, or plan_schema after it — everything is done. Just tell the user what was created.
325
+
326
+ **Example — Project Management:**
327
+ \`\`\`json
328
+ {
329
+ "tables": [
330
+ { "name": "Statuses", "isLookup": true, "seedRecords": ["Backlog", "In Progress", "Review", "Done"] },
331
+ { "name": "Priorities", "isLookup": true, "seedRecords": ["Low", "Medium", "High", "Critical"] },
332
+ { "name": "Tags", "isLookup": true, "seedRecords": ["Bug", "Feature", "Improvement", "Urgent"] },
333
+ { "name": "Projects", "icon": "📁", "columns": [
334
+ { "alias": "Description", "type": "memo" },
335
+ { "alias": "Status", "refTable": "Statuses" },
336
+ { "alias": "Start Date", "type": "date" },
337
+ { "alias": "Budget", "type": "number" }
338
+ ]},
339
+ { "name": "Tasks", "icon": "✅", "columns": [
340
+ { "alias": "Description", "type": "memo" },
341
+ { "alias": "Project", "refTable": "Projects" },
342
+ { "alias": "Status", "refTable": "Statuses" },
343
+ { "alias": "Priority", "refTable": "Priorities" },
344
+ { "alias": "Tags", "refTable": "Tags", "multi": true },
345
+ { "alias": "Deadline", "type": "date" },
346
+ { "alias": "Completed", "type": "bool" }
347
+ ]},
348
+ { "name": "Subtasks", "parentTableName": "Tasks", "icon": "📋", "columns": [
349
+ { "alias": "Done", "type": "bool" }
350
+ ]},
351
+ { "name": "Comments", "parentTableName": "Tasks", "columns": [
352
+ { "alias": "Text", "type": "memo", "required": true },
353
+ { "alias": "Date", "type": "datetime" }
354
+ ]}
355
+ ]
356
+ }
357
+ \`\`\`
358
+
359
+ This creates: 3 lookups (dropdown sources), 2 main tables (Projects, Tasks) linked by refs, 2 child tables (Subtasks, Comments nested inside Tasks). Tasks has single-select Status/Priority, multiselect Tags, and a ref to Projects. Note: NO "Name"/"Title" columns — record names are set via _value (the "name" field in create_object).
360
+
361
+ **Example — Manufacturing (from production template):**
362
+
363
+ Lookups: Shops, Equipment Statuses ["Working","Maintenance","Broken","Decommissioned"], Maintenance Types ["Planned","Unplanned","Emergency","Diagnostic"], Severity Levels, Units, Positions
364
+ Main tables: Equipment (→Shop ref, →Status ref, Model text, Serial text, Commissioned date, Description memo), Spare Parts (SKU text unique, →Unit ref, →Supplier ref, Qty number, MinQty number)
365
+ Child tables: Maintenance → child of Equipment (→Type ref, →Executor ref, Planned date, Actual date, Cost number), Incidents → child of Equipment (→Severity ref, Description memo, Downtime number, Resolution memo)
366
+ Independent: Suppliers (Contact text, Email text, Phone text), Staff (→Position ref, →Shop ref)
367
+
368
+ **Example — E-commerce (from production template):**
369
+
370
+ Lookups: Categories, Product Statuses ["Active","Draft","Discontinued"], Order Statuses ["New","Processing","Shipped","Delivered","Cancelled"], Payment Statuses ["Pending","Paid","Refund"], Ticket Statuses, Document Types ["Invoice","Waybill","Act","Return"]
371
+ Main tables: Products (→Category ref, →Status ref, SKU text unique, Price number, Cost number, Description memo, Photo file, InStock bool), Clients (Email text, Phone text, Address memo, Comment memo), Orders (→Client ref, →Status ref, →Payment Status ref, →Warehouse ref, Total number, Tracking text, Date datetime)
372
+ Child tables: Order Items → child of Orders (→Product ref, Qty number, Price number, Sum number)
373
+ Independent: Warehouses (Address text, Phone text), Stock (→Product ref, →Warehouse ref, Qty number), Support Tickets (→Client ref, →Order ref, →Status ref, Subject text, Description memo)
374
+
375
+ **Example — Farm Shop (from production template):**
376
+
377
+ Lookups: Client Sources ["UDS","VK","Instagram","Telegram","Referral","Repeat"], Order Statuses, Payment Statuses, Product Categories, Messengers, Delivery Methods ["CDEK","Russian Post"], Loyalty Levels
378
+ Main tables: Clients (valueColumnName="Full Name", Phone text, Email text, →Messenger ref, →Source ref, →Loyalty ref, Points number, Total number), Products (→Category ref, SKU text, Price number, Photo file, Description memo, Weight number, InStock bool), Orders (→Client ref, →Status ref, →Payment ref, →Delivery ref, →Messenger ref, Number text, Total number, Ship date, Tracking text)
379
+ Child tables: Addresses → child of Clients (City text, Address memo, Zip text, Primary bool), Order Items → child of Orders (→Product ref, Qty number, Price number), Reorders → child of Orders (Sum number, Comment memo, →Payment ref), Comments → child of Orders (Text memo)
380
+
381
+ **Advanced patterns (from production systems):**
382
+ 1. **Shared lookup across tables** — one "Statuses" lookup can be used in Orders, Tasks, Tickets etc. One isLookup table, multiple ref columns in different tables pointing to it. Don't create "Order Statuses" + "Task Statuses" if values are the same.
383
+ 2. **Multiple refs to same table** — a Contract can reference Contractor THREE times: "Customer", "Executor", "Agent". Each is a separate ref column with different alias but same refTable.
384
+ 3. **Lookups with extra columns** — if a lookup needs its own data fields (e.g. Bank with BIC, Role with Template), use isLookup=false with both columns AND seedRecords.
385
+
386
+ **Patterns from production templates:**
387
+ - Status, Category, Type, Priority, Payment Method, Source, Messenger, Role, City → ALWAYS lookup table (isLookup + seedRecords), never text
388
+ - Order items, Maintenance, Incidents, Addresses, Reorders, Details, Statistics → CHILD tables (parentTableName), not standalone
389
+ - Phone, Email, Address, SKU, Tracking, TIN, URL → text
390
+ - Price, Qty, Cost, Downtime, Points, Reach, Subscribers → number
391
+ - Description, Notes, Resolution, Comment, Details (long) → memo
392
+
393
+ **Common mistakes to avoid:**
394
+ 1. Missing lookup table — if a ref column points to "OrderStatuses", a table "OrderStatuses" with isLookup=true MUST exist in the plan
395
+ 2. Not using child tables — order items, maintenance records, addresses, contacts, details, statistics MUST be child (parentTableName), not standalone root tables
396
+ 3. Using text for statuses/categories — these are ALWAYS lookups
397
+ 4. Creating duplicate lookups — if "Statuses" is shared across Orders and Tasks, create ONE lookup, not two separate "Order Statuses" and "Task Statuses" tables
398
+ 5. Forgetting multiple refs — when an entity has multiple roles (buyer/seller/agent), create separate ref columns with unique aliases pointing to the same refTable
399
+
400
+ **Manual schema creation (for single table or adding to existing):**
401
+ When not using plan_schema — plan ALL tables first. Ref columns need the target table to exist. Steps:
402
+ 1. Create ALL lookup tables first (statuses, categories, tags)
403
+ 2. Fill lookup tables with option records (create_object)
404
+ 3. Create main tables with ref columns pointing to lookups (add_column with refTypeId)
405
+ 4. Create data — for ref fields, use record IDs from lookup tables
406
+
407
+ ---
408
+
409
+ ## Records (objects)
410
+
411
+ Records are created with create_object({ typeId, fields, parentId }). Fields is an object { columnAlias: value }.
412
+ - For text/number/date/bool: pass the value directly: { "Название": "iPhone 15", "Цена": 999, "В наличии": true }
413
+ - For single ref: pass either the record ID as a number OR the exact record name as a string — the backend resolves both: { "Статус": 42 } or { "Статус": "Новый" }. ID is preferred when names may be ambiguous.
414
+ - For multiselect: comma-separated ids or names: { "Теги": "urgent, important" } or { "Теги": "12, 13" }
415
+ - For child records: include parentId = ID of the parent record
416
+
417
+ list_objects returns records with column aliases as keys. Use search for free-text search across all fields; filters for exact match on known aliases.
418
+
419
+ ## Computed columns (LOOKUP, ROLLUP, FORMULA)
420
+
421
+ Computed columns auto-calculate values based on other data. Activate via search_tools("schema").
422
+
423
+ - **LOOKUP** — pull a value from a related record through a reference column. Like VLOOKUP in Excel.
424
+ Example: Order has ref to Product → LOOKUP pulls Product's price into Order table.
425
+ Config: { sourceReqId: refColumnId, targetColId: targetColumnId }
426
+
427
+ - **ROLLUP** — aggregate values from child records or linked records. Like SUMIF in Excel.
428
+ Example: Order has child table OrderItems → ROLLUP sums all item prices.
429
+ Config: { linkReqId: columnIdInChildTable, targetColId: childColumnId, fn: "SUM"|"AVG"|"COUNT"|"MIN"|"MAX" }
430
+ Note: linkReqId is the column in the CHILD table that references this (parent) table, NOT a column in this table.
431
+
432
+ - **FORMULA** — calculate a value using an expression with other columns.
433
+ Example: "Сумма" = [Цена] * [Количество]
434
+ Config: { expr: "[Цена] * [Количество]", vars: { "varName": reqId } }
435
+ Use generate_formula(typeId, description) to auto-generate formula from natural language.
436
+ Formula functions: if, switch, coalesce, isnull, abs, round, floor, ceil, sqrt, power, mod, log, sign, int, sum, average, min, max, concat, upper, lower, trim, len, left, right, substr, contains, starts_with, ends_with, find, replace, today, now, year, month, day, hour, minute, weekday, date_diff, date_add, number, text, bool, and, or, not, xor
437
+
438
+ Workflow: list_computed → create_computed(kind, typeId, alias, config) → update_computed / delete_computed.
439
+ Backlinks: get_schema_backlinks(typeId) — show which columns from OTHER tables reference this table. Useful when creating ROLLUP to discover available linkReqId values.
440
+
441
+ ## Validation rules
442
+
443
+ Set constraints on column values. Activate via search_tools("schema").
444
+ - get_validation_rules(reqId) — see current rules for a column
445
+ - set_validation_rules(reqId, rules) — set rules: { minLength, maxLength, minValue, maxValue, regex, unique }
446
+ Example: require email format → set_validation_rules(reqId, { regex: "^[\\\\w.-]+@[\\\\w.-]+\\\\.[a-z]{2,}$" })
447
+
448
+ ## AI Buttons
449
+
450
+ AI Button is a column that shows a clickable button per row. When clicked, it runs an LLM prompt using data from that row and optionally writes the result to another column.
451
+
452
+ Setup: 1) add_column(typeId, alias, colTypeName="ai") → 2) configure_ai_button(typeId, reqId, prompt, ...)
453
+ - In prompt, use [ColumnName] to inject column values: "Summarize: [Description]"
454
+ - [ID] = record id, [VAL] = record display name
455
+ - outputReqId = column ID where AI result is auto-written (optional)
456
+ - temperature: "low" (0.2 — factual), "medium" (0.7 — balanced), "high" (1.2 — creative)
457
+ - agentMode: true — run full agent with all tools (web_search, tables, docs, etc.) instead of simple LLM chat
458
+ Run per row: run_ai_button(typeId, reqId, objectId). Get config: get_ai_button_config(typeId, reqId).
459
+
460
+ ## HTTP Buttons
461
+
462
+ HTTP Button (type 1016) is a column that makes a direct HTTP request on button click using row data as placeholders — no LLM involved.
463
+
464
+ Setup: 1) add_column(typeId, alias, colTypeName="http_button") → 2) configure_http_button(typeId, reqId, url, method?, headers?, bodyTemplate?, responsePath?, outputReqId?)
465
+ - url and bodyTemplate support [ColumnName] placeholders (replaced with row values)
466
+ - responsePath — dot-notation path to extract value from JSON response (e.g. "data.price")
467
+ - outputReqId = column ID where extracted value is auto-written (optional)
468
+ Run per row: run_http_button(typeId, reqId, objectId). Get config: get_http_button_config(typeId, reqId).
469
+
470
+ ## Script Buttons
471
+
472
+ Script Button (type 1020) is a column that runs user-written JavaScript on button click. Scripts execute exclusively in the browser (Web Worker) — server-side execution is disabled for security.
473
+
474
+ Setup: 1) add_column(typeId, alias, colTypeName="script_button") → 2) configure_script_button(typeId, reqId, script, outputReqId?)
475
+ - Script globals: \`row\` (field name → value map, includes row.ID), \`fetch\` (HTTP requests via server proxy), \`ai(prompt, model?)\` (LLM call, default model: "fast"), \`output(value)\` (write result), \`setField(reqId, value)\` (write to any column)
476
+ - outputReqId = column ID where result is auto-written (optional)
477
+ - Timeout: 60s total (allows time for fetch + ai calls)
478
+ - Scripts can only be run by clicking the button in the UI. There is no server-side run tool.
479
+ Get config: get_script_button_config(typeId, reqId).
480
+
481
+ Example scripts:
482
+ - \`output(row['Price'] * 1.2)\` — apply markup
483
+ - \`const r = await fetch('https://api.example.com?q=' + encodeURIComponent(row['Name'])); const d = await r.json(); output(d.price)\` — fetch from external API
484
+ - \`const summary = await ai('Classify this product: ' + row['Name']); output(summary)\` — LLM classification
485
+
486
+ ---
487
+
488
+ ## run_script Tool
489
+
490
+ Execute JavaScript in an isolated sandbox (isolated-vm, V8 isolate). Requires confirmation (TIER_HIGH).
491
+
492
+ run_script(script, typeId, objectId?, timeoutMs?)
493
+ - script: JavaScript code to execute
494
+ - typeId: table ID (for column definitions and row context)
495
+ - objectId: record ID (loads row data). If omitted, row = {}
496
+ - timeoutMs: execution timeout (max 60000, default 60000)
497
+
498
+ Script globals: row (record fields object, empty {} if no objectId), fetch(url, opts) → {status, body, ok}, ai(prompt, model?) → string, output(value), setField(reqId, value) (requires objectId — skipped without it), query(typeId, opts) → [{id, value, parentId, typeId}] (metadata only — use getRecord for full fields), getRecord(id), createRecord(typeId, {name, fields}), updateRecord(id, {fields}), deleteRecord(id), console.log(), JSON, Math, Date.
499
+ - browse(query, source?) — search marketplace prices. Returns [{name, price, url, source}]. Calls browser service internally.
500
+
501
+ Returns: { value, fields, logs }
502
+ - value: string from output() call
503
+ - fields: { reqId: value } from setField() calls (written to DB only if objectId was provided)
504
+ - logs: array of console.log() messages
505
+
506
+ Limits: 128MB RAM, 60s timeout, rate limits per execution (30 queries, 50 mutations, 50 fetch, 10 ai).
507
+ SSRF protection: requests to localhost, private IPs, .local, .internal are blocked.
508
+
509
+ ---
510
+
511
+ ## search_prices Tool
512
+
513
+ Search marketplace prices for a product by name. Returns array of results with name, price, URL, source.
514
+
515
+ search_prices(query, source?, limit?)
516
+ - query: product name to search
517
+ - source: marketplace source (default: "komus"). Supported: komus, wildberries, samson.
518
+ - limit: max results (default: 10)
519
+ - Returns: { items: [{name, price, url, source}], query, total }
520
+ - TIER_LOW — no confirmation required.
521
+ - Requires browser service running on port 3099.
522
+
523
+ ---
524
+
525
+ ## Reports
526
+
527
+ Reports aggregate and filter data from tables. Activate via search_tools("reports").
528
+
529
+ **Creating a report:**
530
+ 1. create_report(name, parentTypeId) — parentTypeId = source table ID. Returns reportId.
531
+ 2. add_report_column(reportId, reqTypeId or columnAlias) — add columns. Returns colId.
532
+ **IMPORTANT:** Do NOT add the record name (_value) column — it is included automatically as the first column of every report. Passing valueColumnName (e.g. "Наименование") or the table name as columnAlias creates a broken column with reqTypeId=0 that shows "NaN" in the report.
533
+ 3. Optionally set func (SUM/AVG/COUNT/MIN/MAX/GROUP_CONCAT), totalFunc (footer totals), storedFrom/storedTo (default filters).
534
+ 4. update_report(reportId, where) to add WHERE filter.
535
+
536
+ **WHERE filter syntax:**
537
+ - Column alias in WHERE = "c" + colId (from add_report_column response, NOT the original reqTypeId)
538
+ - Tokens: [USER] = current username, [USER_ID] = current user id, [TODAY] = today's date, [NOW] = current datetime
539
+ - {{DB}} = workspace EAV table name (for subqueries, auto-resolved at execution time)
540
+ - Example: \`AND c35768.val = '[USER]'\` — filter to current user's records
541
+ - Subquery example: \`AND EXISTS (SELECT 1 FROM {{DB}} _st WHERE _st.up = a.up AND _st.val = '378' AND _st.t = 393)\` — filter child records by parent's ref field (a.up = parent record ID)
542
+
543
+ **Aggregation in reports:**
544
+ - func on a column: SUM, AVG, COUNT, MIN, MAX, GROUP_CONCAT
545
+ - totalFunc: shows a total in the report footer
546
+ - havingFrom/havingTo: HAVING filters for aggregated columns (e.g., "show only groups with COUNT > 5")
547
+ - storedFrom/storedTo: default filter range (pre-applied when user opens the report). Supports [TODAY], [NOW]. For ref columns, use the record ID (not name).
548
+
549
+ **Cross-table reports (JOIN):**
550
+ - create_report_join(reportId, typeId, alias) — add JOIN to another table. For child table reports, JOIN to parent table is auto-detected (uses a.up).
551
+ - add_report_column with joinAlias=alias — column from the joined table. Works with ref columns (inverted EAV handled automatically).
552
+ - storedFrom/storedTo on joined columns — filter by joined table's field values.
553
+ - Example workflow: report on "Order Items" (child) + JOIN to "Orders" (parent, alias="order") + column "Order Status" (joinAlias="order", storedFrom=statusId, storedTo=statusId) → filters child records by parent's status.
554
+ - delete_report_join(reportId, joinId) — remove JOIN (requires confirmation).
555
+
556
+ **Permissions report:** create_report with parentTypeId=9001 (virtual). Columns: 9011=User, 9012=Role, 9013=Object Type, 9014=Access Level, 9015=Export flag, 9016=Delete flag.
557
+
558
+ Run: get_report(reportId, limit, filters). Structure: describe_report(reportId). History: get_report_history(reportId).
559
+ Export: export_report(reportId, filters?, order?, limit?) — export report data to CSV string. Returns { csv, filename, rowCount }.
560
+ Bulk update: report_bulk_update(reportId, filters?) — mass-update records using SET expressions defined in report columns (requires confirmation). Only works if report has SET columns configured.
561
+
562
+ ## Documents
563
+
564
+ Block-based documents (like Notion). Activate via search_tools("documents").
565
+
566
+ - list_documents(search, folderId) — browse documents
567
+ - get_document(docId) / get_document_blocks(docId) — read content and block structure
568
+ - create_document(title, parentId) — create new doc (parentId for nesting)
569
+ - append_block(docId, text, type) — add block at end. Types: text, heading, code, quote, list, todo.
570
+ - update_block(docId, blockId, text) — modify existing block
571
+ - delete_block(docId, blockId) — remove block
572
+ - update_document_title(docId, title)
573
+ - delete_document(docId) — move document to trash (requires confirmation)
574
+ - reorder_blocks(docId, order) — reorder blocks in a document. order = array of block IDs in target order.
575
+ - create_document_from_template(templateId, title?, folderId?) — create document from a template (doc with is_template=true)
576
+ - generate_pdf(objectId, templateId, format?, landscape?) — generate PDF from template document for a specific record. Returns { filename, size, base64 }.
577
+
578
+ **Trash:**
579
+ - list_doc_trash(limit?, offset?) — list deleted documents
580
+ - restore_document(docId) — restore document from trash
581
+
582
+ **Organization:**
583
+ - Folders: list_doc_folders, create_doc_folder, update_doc_folder, delete_doc_folder
584
+ - Tags: list_doc_tags, create_doc_tag, delete_doc_tag, add_tag_to_doc, remove_tag_from_doc
585
+ - Versions: list_doc_versions, get_doc_version(docId, versionId), restore_doc_version
586
+ - Block history: get_block_history(docId, blockId, limit?, offset?)
587
+ - Purge: purge_document(docId) — permanently delete trashed doc (requires confirmation)
588
+ - Sharing: list_doc_sharing, grant_doc_access(docId, userId, level), revoke_doc_access
589
+
590
+ ## Automations
591
+
592
+ Event-driven rules: when X happens → check condition → do Y. Activate via search_tools("automations").
593
+
594
+ create_automation({ name, trigger: { type, typeId }, condition, actions: [{ type, config }] })
595
+ - Trigger types: on_create, on_update, on_delete, on_deadline, on_webhook, on_form_submit, schedule, manual, ai_analysis, on_metric_threshold, on_metric_silence, on_document, on_telegram_command, on_telegram_message, on_telegram_pre_checkout, on_telegram_shipping, on_telegram_payment, on_telegram_inline, on_telegram_join_request, on_telegram_business_connection, on_telegram_business_message, on_bot_chat_member
596
+ - Actions: send_notification, send_notification_to_group, update_field, create_object, delete_object, fire_webhook, run_ai_agent, run_script, send_telegram, run_connector, send_email, update_related_records, set_requisite, update_related, http_request, if_else, switch, transform, wait_delay, request_approval, delegate_to_agent, invoke_agent, send_invoice, telegram_forward, answer_inline_query, telegram_ban, telegram_unban, telegram_restrict, telegram_promote, telegram_approve_join, telegram_decline_join, telegram_pin, telegram_unpin, telegram_get_chat, telegram_post_story, answer_shipping, telegram_business_reply
597
+ update_related_records: { childTypeId, matchRefReqId, targetTypeId, targetMatchReqId, targetFieldReqId, sourceFieldReqId, operation: 'add'|'subtract'|'set' } — declarative cross-table update (e.g. inventory deduction: order items → match product ref → subtract from stock)
598
+ send_notification_to_group: { typeId, usernameReqId, title, body, filter?: { reqId, val } } — notifies all members of a table whose usernameReqId field is a valid Integram username; optional filter restricts to members where reqId==val (e.g. role filter)
599
+ - list_automations, get_automation (single), update_automation, delete_automation, trigger_automation (manual run), get_automation_runs (execution log)
600
+
601
+ ## Permissions (admin only)
602
+
603
+ Role-based access control. Activate via search_tools("permissions").
604
+
605
+ - list_members — all workspace users with roles
606
+ - list_roles — all roles and their access levels per table
607
+ - get_user_permissions(username or userId) — what a specific user can access
608
+ - set_grant(roleId or username, targetTypeId, level) — level: NONE/READ/WRITE/ADMIN. targetTypeId=0 = all tables.
609
+ Optional: canExport (allow CSV export), canDelete (allow record deletion)
610
+ - remove_grant — revoke access
611
+
612
+ ## Graph (PostgreSQL)
613
+
614
+ Knowledge graph of relationships between records stored in PostgreSQL. Activate via search_tools("graph").
615
+
616
+ - get_related(objId, relType, depth) — find connected records up to depth 1-3
617
+ - get_graph_node(objId) — get a single graph node: type, name, edges
618
+ - get_graph_neighborhood(objId, direction, limit) — get neighbors (1-hop): edges and connected nodes
619
+ - list_graph_nodes(typeId, withEdges, limit, skip) — list graph nodes by table type
620
+ - get_shortest_path(fromObjId, toObjId, maxHops) — shortest path between two objects
621
+ - graph_query(cypher) — read-only SQL query against graph_objects/graph_edges tables. Only SELECT/WITH. Use $1 for workspace db.
622
+ - graph_health() — check graph subsystem health: node count, edge count, connection status
623
+ - list_memory_agents() — list agents that store data in graph memory
624
+ - browse_graph_memory(agentId) — browse an agent's memory graph: nodes, edges, keys
625
+
626
+ ## Lookups
627
+
628
+ Dropdown/reference value discovery. Activate via search_tools("lookups").
629
+ - get_lookup(typeId, search?, limit?) — get all values from a lookup table (dropdown source). Returns records with id and display name.
630
+ - get_ref_options(refId, search?, limit?) — get valid options for a specific reference column by reqId. Use before creating/updating objects to discover allowed values for ref fields.
631
+
632
+ ## Webhooks
633
+
634
+ HTTP callbacks on events. Activate via search_tools("webhooks").
635
+ create_webhook(typeId, events: ["create","update","delete"], url, secret)
636
+ - get_webhook_deliveries(webhookId, limit) — delivery history (status, response code, errors)
637
+ - retry_webhook_delivery(deliveryId) — retry a failed delivery
638
+
639
+ ## Forms
640
+
641
+ Public data collection forms linked to a table. Activate via search_tools("forms").
642
+ create_form(typeId, config, expiresAt) — generates a public URL for external users to submit records.
643
+
644
+ ## Bulk operations
645
+
646
+ Activate via search_tools("bulk").
647
+ - bulk_create(typeId, records) — create many records at once
648
+ - bulk_update(updates: [{ objId, fields }]) — update many records
649
+ - bulk_delete(objIds) — delete many records (requires confirmation)
650
+ - autofill_batch(typeId, reqId, objectIds) — run AI autofill on multiple rows
651
+
652
+ ## Import / Export
653
+
654
+ Activate via search_tools("workspace").
655
+ - import_data(typeId, csv, mapping) — import CSV string into table. Auto-maps columns by header names. mapping override: { columnIndex: "colId" | "__val__" | "__skip__" }
656
+ - export_data(typeId, limit, filters) — export table to CSV format
657
+ - download_file(fileName, subdir?) — download a file from workspace storage. Returns base64 content (max 10 MB).
658
+
659
+ ## Dashboards
660
+
661
+ Visual dashboards with widgets. Activate via search_tools("workspace").
662
+ - list_dashboards, get_dashboard(id), create_dashboard(name, widgets), update_dashboard, delete_dashboard
663
+
664
+ ## Workspace invitations
665
+
666
+ Activate via search_tools("workspace").
667
+ - list_workspace_invitations — pending invitations (email, role, status)
668
+ - cancel_workspace_invitation(invitationId) — cancel an invitation (requires confirmation)
669
+
670
+ ## Sharing
671
+
672
+ Public links for views and records. Activate via search_tools("workspace").
673
+ - share_view(viewId, typeId, expiresInDays, password) → returns share token/URL
674
+ - share_record(objId, typeId, expiresInDays) → returns share token/URL
675
+ - revoke_view_share, revoke_record_share — disable public links
676
+
677
+ ## Connectors
678
+
679
+ External data integrations. Activate via search_tools("workspace").
680
+ - list_connectors, get_connector, create_connector, update_connector, delete_connector, run_connector, reconcile_cdek
681
+ - list_connector_presets — available presets (1C, SAP, SCADA, REST templates)
682
+ - AI-assisted connector setup workflow:
683
+ 1. fetch_api_docs(url) — load API docs (OpenAPI/Swagger/HTML)
684
+ 2. generate_connector_config(apiStructure, description) — LLM generates connector config
685
+ 3. test_connector_draft(config, params) — test real HTTP request (requires confirmation)
686
+ 4. generate_connector_schema(config, sampleResponse) — generate table schema from response (requires confirmation)
687
+ 5. create_connector(...) — save the connector
688
+
689
+ ## Comments & reactions
690
+
691
+ Activate via search_tools("comments").
692
+ - list_comments(objId), create_comment(objId, text), update_comment, delete_comment
693
+ - add_reaction(commentId, emoji), remove_reaction
694
+
695
+ ## History & rollback
696
+
697
+ Activate via search_tools("history").
698
+ - get_object_history(objId) — full change log for a record
699
+ - rollback_object(objId, auditId) — restore record to state before a specific audit entry (requires confirmation)
700
+ - get_object_backlinks(objectId, limit, offset) — find all records that reference this object via ref columns or mentions
701
+
702
+ ## Audit log (admin)
703
+
704
+ query_audit(type, typeId, userId, from, to, limit) — unified audit log across objects, schema, and reports.
705
+
706
+ ## Notifications
707
+
708
+ - list_notifications, mark_read(notifId), send_notification(targetUsername, title, body), delete_notification(notifId)
709
+ - get_notification_count() — number of unread notifications for current user
710
+ - notification_action(notifId, actionKey) — execute action on a notification (e.g. approve/reject a suspended automation). Requires confirmation.
711
+
712
+ ## Workspace admin
713
+
714
+ Read-only workspace metadata available without search_tools activation.
715
+ - get_workspace() — current workspace: name, slug, plan, settings (admin only)
716
+ - get_template(templateId) — template details: slug, name, description, schema
717
+
718
+ ## Trash
719
+
720
+ - list_trash(typeId) — see deleted records for a specific table
721
+ - restore_from_trash(objId) — restore a deleted record
722
+
723
+ ## Memory (agent long-term memory)
724
+
725
+ Activate via search_tools("memory").
726
+ - remember(key, value, tags) — save a fact for future conversations
727
+ - recall(question) — retrieve relevant memories
728
+ - forget(key) — delete a memory
729
+ - share_insight(key, value) — share with other agents in shared namespace
730
+ - find_procedure(query) — find step-by-step recipes from memory
731
+ - list_contradictions / resolve_contradiction — manage conflicting facts
732
+
733
+ ## Portal (admin)
734
+
735
+ Client-facing portal management. Activate via search_tools("portal").
736
+
737
+ **Configuration:**
738
+ - get_portal_config() — current portal config (branding, pages, modules, auth, chat, SEO)
739
+ - set_portal_config(config, active, custom_domain, merge?) — create/replace full config. With `merge: true` — deep-merge partial config into existing (no need to send entire config; only changed fields). **Requires confirmation.**
740
+ - update_portal_module(slug, config, moduleIndex) — update one module without overwriting others
741
+ - portal_preview() — get preview URL
742
+ - portal_publish(active) — publish (true) or unpublish (false). **Requires confirmation.**
743
+
744
+ **Data (admin read access, no client filter):**
745
+ - get_portal_catalog(category, limit, offset) — products: price, photo, category, stock status
746
+ - get_portal_carts(limit, offset) — active client carts: item count, total
747
+ - get_portal_orders(status, limit, offset) — orders with status filter
748
+ - get_portal_tickets(status, limit, offset) — support tickets with status filter
749
+ - get_portal_kb_articles(category, limit, offset) — KB articles: category, date, excerpt
750
+ - get_portal_metrics() — order counts by status + total revenue
751
+ - get_portal_documents(limit, offset) — client documents
752
+
753
+ **Clients:**
754
+ - get_portal_profile(email, phone, customerId) — find customer by email/phone/ID
755
+ - get_portal_client_role(customerId) — role, grants, allowed pages
756
+
757
+ **Custom Code:**
758
+ - commit_portal_component(repo, file, code, message?, branch?) — commit Vue SFC to codespace repo for custom_code module. Repo is auto-created if it doesn't exist.
759
+
760
+ **Telegram Bots:**
761
+ - list_telegram_bots() — list all Telegram bots for the workspace
762
+ - create_telegram_bot(name, username, token, config?) — create bot + auto-register webhook. **Requires confirmation.**
763
+ - update_telegram_bot(id, ...) — update bot (name, username, token, enabled, config). Token change re-registers webhook. **Requires confirmation.**
764
+ - delete_telegram_bot(id) — permanently delete bot. **Requires HITL confirmation.**
765
+ - sync_telegram_bot(id) — sync config → Telegram API (commands menu, description, short description, menu button). **Requires confirmation.**
766
+ - get_telegram_bot_status(id) — get bot info (getMe) + webhook status (getWebhookInfo). Read-only.
767
+ - test_telegram_bot(id, chatId, text) — send test message from bot to a chat. **Requires confirmation.**
768
+
769
+ **Telegram Messaging:**
770
+ - telegram_forward_message(botId, fromChatId, toChatId, messageId, copy?) — forward or copy a message. copy=true removes "Forwarded from". **Requires confirmation.**
771
+
772
+ **Telegram Payments:**
773
+ - telegram_send_invoice(botId, chatId, title, description, payload?, currency?, prices?, providerToken?, photoUrl?) — send payment invoice. currency "XTR" for Telegram Stars. **Requires confirmation.**
774
+ - telegram_create_invoice_link(botId, title, description, payload?, currency?, prices?, providerToken?) — create payment URL (no chat needed). Returns { url }.
775
+
776
+ **Telegram Chat Admin:**
777
+ - telegram_ban_member(botId, chatId, userId, untilDate?, revokeMessages?) — ban user. **Requires confirmation.**
778
+ - telegram_unban_member(botId, chatId, userId) — unban user. **Requires confirmation.**
779
+ - telegram_restrict_member(botId, chatId, userId, permissions?, untilDate?) — restrict user permissions. **Requires confirmation.**
780
+ - telegram_promote_member(botId, chatId, userId, canManageChat?, canDeleteMessages?, ...) — promote/demote to admin. **Requires confirmation.**
781
+ - telegram_approve_join(botId, chatId, userId) — approve pending join request. **Requires confirmation.**
782
+ - telegram_decline_join(botId, chatId, userId) — decline pending join request. **Requires confirmation.**
783
+ - telegram_pin_message(botId, chatId, messageId, disableNotification?) — pin a message. **Requires confirmation.**
784
+ - telegram_unpin_message(botId, chatId, messageId?) — unpin one or all messages. **Requires confirmation.**
785
+ - telegram_get_chat(botId, chatId) — get chat info (title, type, members). Read-only.
786
+ - telegram_get_chat_member_count(botId, chatId) — get member count. Read-only.
787
+ - telegram_create_invite_link(botId, chatId, name?, expireDate?, memberLimit?, createsJoinRequest?) — create invite link.
788
+
789
+ **Telegram Stories:**
790
+ - telegram_post_story(botId, chatId, content, caption?, activePeriod?) — publish story. content: {type:"photo"|"video", photo/video: "URL"}. **Requires confirmation.**
791
+ - telegram_edit_story(botId, chatId, storyId, content?, caption?) — edit story. **Requires confirmation.**
792
+ - telegram_delete_story(botId, chatId, storyId) — delete story. **Requires confirmation.**
793
+
794
+ **Telegram Business API:**
795
+ - telegram_get_business_connection(botId, businessConnectionId) — get business connection info. Read-only.
796
+ - telegram_set_business_bio(botId, businessConnectionId, bio) — set bio (0-140 chars). **Requires confirmation.**
797
+ - telegram_set_business_name(botId, businessConnectionId, firstName, lastName?) — set account name. **Requires confirmation.**
798
+
799
+ Bot config schema: { description?: "...", shortDescription?: "...", welcomeMessage?: "...", menuButton?: {type: "commands"|"web_app"|"default"}, employeeTable?: {typeId, chatIdReqId, roleReqId} }.
800
+ Bot reactions (commands + keywords) are stored as **automations** with trigger.botId — use create_automation with:
801
+ - Command: trigger: { type: "on_telegram_command", command: "status", botId: N }
802
+ - Keyword: trigger: { type: "on_telegram_message", pattern: "привет,hello", matchMode: "contains", botId: N }
803
+ - Payment: trigger: { type: "on_telegram_payment", botId: N } — fires on successful payment
804
+ - Pre-checkout: trigger: { type: "on_telegram_pre_checkout", botId: N } — validate before charging
805
+ - Shipping: trigger: { type: "on_telegram_shipping", botId: N } — provide shipping options
806
+ - Inline query: trigger: { type: "on_telegram_inline", botId: N } — respond to @bot queries
807
+ - Join request: trigger: { type: "on_telegram_join_request", botId: N, chatId? } — auto-approve/decline
808
+ - Business connection: trigger: { type: "on_telegram_business_connection", botId: N }
809
+ - Business message: trigger: { type: "on_telegram_business_message", botId: N }
810
+ Actions use send_telegram with chatId: "{{_tgChatId}}" to reply to sender.
811
+ Template vars: {{_tgCommand}}, {{_tgArgs}}, {{_tgChatId}}, {{_tgFromUsername}}, {{_tgFromFirstName}}, {{_tgMessage}}.
812
+ Payment vars: {{_tgPaymentCurrency}}, {{_tgPaymentAmount}}, {{_tgPaymentPayload}}, {{_tgPaymentChargeId}}.
813
+ Inline vars: {{_tgInlineQuery}}, {{_tgInlineQueryId}}, {{_tgInlineOffset}}.
814
+ Join vars: {{_tgJoinUserId}}, {{_tgJoinUsername}}, {{_tgJoinFirstName}}, {{_tgJoinBio}}.
815
+ Business vars: {{_tgBusinessConnectionId}}, {{_tgBusinessUserId}}, {{_tgBusinessChatId}}, {{_tgBusinessCanReply}}.
816
+ Filter automations by bot: list_automations with filter by trigger.botId (GET /automations?botId=N).
817
+
818
+ **Multi-screen keyboards (screens):** send_telegram supports hierarchical navigation via \`screens\`:
819
+ \`\`\`
820
+ { screens: {
821
+ main: { text: "Menu", buttons: [{ text: "Orders", go: "orders" }] },
822
+ orders: {
823
+ text: "Orders (page {{_page}})",
824
+ listSource: { queryMode: "table", typeId: 311, pageSize: 6, filterReqId: 378 },
825
+ listButton: { text: "Order #{{name}}", go: "detail" },
826
+ buttons: [
827
+ { text: "New", go: "orders", goFilter: "391" },
828
+ { text: "All", go: "orders" },
829
+ { text: "Back", go: "_back" }
830
+ ]
831
+ },
832
+ detail: {
833
+ text: "Order #{{val}}\\nStatus: {{req_378}}\\nSum: {{req_340}}",
834
+ buttons: [{ text: "Back", go: "_back" }]
835
+ }
836
+ }}
837
+ \`\`\`
838
+ - go: "screenId" — navigate forward; go: "_back" — linear back (preserves page+filter); goBackTo: "screenId" — named back (jumps to specific screen, clears stack above)
839
+ - goFilter: "value" — apply filter to listSource (e.g., status ID)
840
+ - listSource: dynamic paginated list. queryMode: "table" (root records) | "children". pageSize (default 8). filterReqId — EAV field for goFilter.
841
+ - listButton.go — detail screen on item click. Detail screen gets {{id}}, {{val}}, {{req_NNN}} from the object's EAV data.
842
+ - {{_breadcrumb}} — breadcrumb trail built from nav stack: «Меню > Заказы > №6278886»
843
+ - Navigation stack in Redis (1h TTL) stores {automationId, screenId, page, filterValue}. _back restores full context.
844
+ - botId (preferred over botToken) — resolves token from _v2_tg_bots table.
845
+
846
+ Portal data comes from workspace EAV tables. Portal config maps page types to EAV typeId/reqId references.
847
+
848
+ ## Codespace (git repositories)
849
+
850
+ Git repository hosting per workspace. Activate via search_tools("codespace").
851
+
852
+ **Repositories:**
853
+ - list_repos() — list all git repos in workspace
854
+ - get_repo(slug) — repo info (branches, size, last commit)
855
+
856
+ **Branches:**
857
+ - list_branches(slug) — list branches
858
+ - create_branch(slug, name, fromRef?) — create branch from ref/HEAD
859
+ - delete_branch(slug, name) — delete branch (cannot delete default branch). **TIER_HIGH**
860
+
861
+ **Commits & files:**
862
+ - list_commits(slug, ref?, limit?, offset?) — list commits on a branch
863
+ - get_commit_diff(slug, sha) — unified diff for a single commit (works for initial commit)
864
+ - get_file_tree(slug, ref?, path?) — list files/dirs in a repo. Returns { items: [{ name, type, size, path }], ref, path }
865
+ - read_blob(slug, path, ref?) — read file content. Returns text (up to 200K chars, supports offset/limit for pagination) for text files, metadata only for binary. Use for reading custom_code components.
866
+ - commit_file(slug, branch, filePath, content, message?) — create/update file in one commit
867
+ - commit_multi_files(slug, branch, files, message) — commit multiple files atomically; files = [{filePath, content}] (up to 100 files)
868
+ - delete_repo_file(slug, branch, filePath, message?) — delete file via git rm + commit. **TIER_HIGH**
869
+
870
+ **Pull Requests:**
871
+ - list_prs(slug, status?, limit?, offset?) — list PRs (status: open|closed|merged|draft)
872
+ - get_pr(slug, number) — PR details
873
+ - create_pr(slug, title, sourceBranch, targetBranch, description?, mergeStrategy?) — create PR
874
+ - update_pr(slug, number, title?, description?, status?, mergeStrategy?) — update PR; pass status="open" to reopen
875
+ - merge_pr(slug, number, strategy?) — merge PR into target branch. **TIER_HIGH**
876
+ - list_pr_comments(slug, number) — list PR comments
877
+ - add_pr_comment(slug, number, body) — add comment to PR
878
+
879
+ **GitHub Sync:**
880
+ - get_github_sync(slug) — get GitHub Sync config (remoteUrl, direction, lastSync, lastError)
881
+ - configure_github_sync(slug, remoteUrl, token, direction, autoSync?) — set up sync; direction: push_only | pull_only | both. **TIER_HIGH**
882
+ - push_to_github(slug) — manually push all branches to GitHub
883
+ - pull_from_github(slug) — manually pull all branches from GitHub
884
+
885
+ ## Advisor (platform expert)
886
+
887
+ Platform expert for guidance and help. Activate via search_tools("advisor").
888
+
889
+ - ask_advisor(question, topic?) — ask about schema design, best practices, troubleshooting, feature usage. Returns detailed advice based on current workspace schema. topic: schema/reports/automations/portal/documents/permissions/import/dashboards/integrations/general
890
+ - list_platform_capabilities() — full list of Integram features by category (data, columns, analytics, automations, documents, integrations, security, portal, AI, graph)
891
+
892
+ Use advisor when user asks "help", "how to", "what can you do", "best practice", or needs guidance on platform features.
893
+
894
+ ## Teamchat (internal messaging)
895
+
896
+ Internal messaging with rooms, topics, and decisions. Activate via search_tools("teamchat").
897
+
898
+ **Rooms:**
899
+ - list_rooms() — list chat rooms the user has access to
900
+ - create_room(name, description?, isPublic?) — create a new room
901
+ - get_room(roomId) — room details
902
+ - update_room(roomId, name?, description?) — update room info
903
+ - delete_room(roomId) — delete room. **Requires confirmation.**
904
+ - join_room(roomId) — join a public room
905
+
906
+ **Room members:**
907
+ - list_room_members(roomId) — list members
908
+ - add_room_member(roomId, userId) — add a member
909
+ - remove_room_member(roomId, userId) — remove a member
910
+
911
+ **Topics:**
912
+ - list_topics(roomId?, search?) — list topics across rooms or in a specific room
913
+ - list_recent_topics(limit?) — recently active topics
914
+ - create_topic(roomId, title, description?) — create a topic in a room
915
+ - update_topic(topicId, title?, description?, status?) — update topic
916
+ - delete_topic(topicId) — delete topic. **Requires confirmation.**
917
+ - summarize_topic(topicId) — AI-generated summary of topic discussion
918
+ - mark_topic_read(topicId) — mark topic as read
919
+ - export_topic_to_document(topicId) — export topic content to a document
920
+
921
+ **Messages:**
922
+ - list_messages(topicId, limit?, before?) — list messages in a topic
923
+ - create_message(topicId, text) — post a message
924
+ - send_teamchat_message(topicId, text, cards?) — post a message with optional code_cell cards for executable code
925
+ - update_message(msgId, text) — edit a message
926
+ - delete_message(msgId) — delete a message. **Requires confirmation.**
927
+ - move_message(msgId, targetTopicId) — move a message to another topic
928
+ - search_teamchat(query, roomId?, limit?) — full-text search across messages
929
+
930
+ **Decisions:**
931
+ - create_decision(title, description?, domain?) — create an architectural decision record
932
+ - get_decision(decisionId) — get decision details
933
+ - update_decision(decisionId, title?, description?, status?) — update a decision
934
+ - delete_decision(decisionId) — delete a decision. **Requires confirmation.**
935
+ - search_similar_decisions(query, domain?, limit?) — semantic search for similar decisions
936
+ - analyze_decision_conflicts(decisionId) — find conflicts with other decisions
937
+ - list_decision_links(decisionId) — list links to/from a decision
938
+ - create_decision_link(fromId, toId, type) — link two decisions (type: supersedes|depends_on|relates_to|conflicts_with)
939
+ - delete_decision_link(linkId) — remove a link
940
+
941
+ **Analytics:**
942
+ - get_agent_metrics(agentId?) — AI agent usage metrics
943
+ - get_wmatrix(room_id?, days?) — W-matrix (Organizational Network Analysis) for collaboration patterns
944
+
945
+ ## Organizations
946
+
947
+ Multi-workspace organizations. Activate via search_tools("orgs").
948
+
949
+ - list_orgs() — list organizations the user belongs to
950
+ - get_org(orgId) — organization details
951
+ - create_org(name, slug) — create a new organization. **Requires confirmation.**
952
+ - update_org(orgId, name?) — update organization. **Requires confirmation.**
953
+ - delete_org(orgId) — delete organization. **Requires confirmation.**
954
+ - list_org_members(orgId) — list members of an organization
955
+ - add_org_member(orgId, userId, role?) — add member. **Requires confirmation.**
956
+ - remove_org_member(orgId, userId) — remove member. **Requires confirmation.**
957
+
958
+ ## Timeseries
959
+
960
+ Time-series data ingestion and aggregated queries. Activate via search_tools("timeseries").
961
+
962
+ - record_timeseries(source, metric, value, timestamp?, tags?) — record a data point
963
+ - query_timeseries(source, metric, from?, to?, aggregation?, interval?) — query aggregated data. aggregation: avg|sum|min|max|count. interval: 1h|1d|1w|1M
964
+ - list_timeseries_sources() — list available data sources and their metrics
965
+
966
+ ## KAG (Knowledge-Augmented Generation)
967
+
968
+ Knowledge graph search and question answering. Activate via search_tools("kag").
969
+
970
+ - kag_search(query, limit?) — search entities in the knowledge graph by text
971
+ - kag_traverse(entityId, depth?, relType?) — traverse graph from an entity, discover related nodes
972
+ - kag_ask(question) — answer a natural language question using knowledge graph context. Auto-searches relevant entities and synthesizes an answer.
973
+
974
+ ## Objects (advanced operations)
975
+
976
+ Move, reorder, and duplicate records. Activate via search_tools("objects").
977
+
978
+ - move_object(objectId, parentId) — move a record to a different parent (change parentId)
979
+ - reorder_object(objectId, order, afterId?) — change record position (ord) within its parent
980
+ - duplicate_object(objectId) — create a copy of a record with all its field values
981
+
982
+ ## AI (Text-to-Speech)
983
+
984
+ Text-to-speech synthesis. Activate via search_tools("ai").
985
+
986
+ - speak_text(text, voice?, speed?) — synthesize speech from text. Returns audio file URL.
987
+ - list_tts_voices() — list available TTS voices with language and gender info
988
+ - get_tts_status() — check TTS service availability
989
+
990
+ ## Excel export
991
+
992
+ Create Excel files from raw data. Available via search_tools("workspace").
993
+
994
+ - create_excel(title?, sheets) — create an XLSX file from raw data. sheets: [{ name, headers: ["Col1","Col2"], rows: [["val1","val2"]] }]. File is saved to workspace storage. Returns download link.
995
+
996
+ ## External agents
997
+
998
+ Delegate tasks to registered external agents. Activate via search_tools("agents").
999
+ - list_agents — discover available external agents and their capabilities
1000
+ - delegate_to_agent(agentSlug, task, context) — send a task to an external agent and get the result
1001
+
1002
+ ## Meta KB mode
1003
+
1004
+ POST /ai/agent-chat accepts optional agentSlug and topicId params:
1005
+ - agentSlug: 'teamchat-agent' — bypasses orchestrator, calls teamchat-agent directly
1006
+ - topicId: number — for multi-turn conversation in teamchat topic
1007
+ When agentSlug is set, Q&A is saved to teamchat room 'meta-kb' instead of _v2_ai_conversations.
1008
+
1009
+ ---
1010
+
1011
+ ## Anti-hallucination rules
1012
+ - NEVER state record counts, specific values, or data without calling a tool first.
1013
+ - Any question like "how many records", "what's in the table", "show records" MUST call list_objects.
1014
+ - If unsure about data — always call a tool, never guess.
1015
+
1016
+ ## Confirmation flow
1017
+ Destructive and schema operations return "REQUIRES CONFIRMATION". Ask the user to confirm, then call confirm_action(approved=true/false). Never auto-confirm without explicit user approval.
1018
+ `;
1019
+
1020
+ const server = new Server(
1021
+ { name: 'integram', version: '1.0.0' },
1022
+ { capabilities: { tools: { listChanged: true }, elicitation: {} }, instructions: INSTRUCTIONS },
1023
+ );
1024
+
1025
+ // ─── Built-in tool definitions (always present) ─────────────────────────────
1026
+
1027
+ const LIST_WORKSPACES_DEF = {
1028
+ name: 'list_workspaces',
1029
+ description: 'Use to see all available workspaces and which one is currently active. Call this FIRST before any other operation. Response includes server URL so you know which environment (local/prod) you are connected to. Returns: { items:[{id,slug,name}], total }.',
1030
+ inputSchema: { type: 'object', properties: {} },
1031
+ annotations: { readOnlyHint: true },
1032
+ };
1033
+
1034
+ const SWITCH_WORKSPACE_DEF = {
1035
+ name: 'switch_workspace',
1036
+ description: 'Use to select a workspace by slug or name (fuzzy match). Reloads all available tools for the new workspace. Call list_workspaces first to see available options. Returns: { message }.',
1037
+ inputSchema: {
1038
+ type: 'object',
1039
+ properties: {
1040
+ slug: { type: 'string', description: 'Workspace slug or part of workspace name to match' },
1041
+ },
1042
+ required: ['slug'],
1043
+ },
1044
+ };
1045
+
1046
+ const CREATE_WORKSPACE_DEF = {
1047
+ name: 'create_workspace',
1048
+ description: 'Create a new workspace. Requires name and slug. Slug must be lowercase, 3-64 chars, start with a letter, only a-z 0-9 _ -. Optionally apply a template. After creation, automatically switches to the new workspace. Returns: { id, type:"workspace", slug, message }.',
1049
+ inputSchema: {
1050
+ type: 'object',
1051
+ properties: {
1052
+ name: { type: 'string', description: 'Display name for the workspace (1-255 chars)' },
1053
+ slug: { type: 'string', description: 'URL slug: lowercase, 3-64 chars, a-z start, only a-z0-9_- (e.g. "my-project")' },
1054
+ template: { type: 'string', description: 'DEPRECATED: use templateId instead. Optional template db_name string.' },
1055
+ templateId: { type: 'number', description: 'Optional template ID (from list_templates) to create workspace with predefined schema structure' },
1056
+ },
1057
+ required: ['name', 'slug'],
1058
+ },
1059
+ };
1060
+
1061
+ const SEARCH_TOOLS_DEF = {
1062
+ name: 'search_tools',
1063
+ description: 'Use to discover and activate additional tools by keyword. Core tools (CRUD, search) are loaded by default. Use this for: schema changes ("create table", "add column"), reports, permissions, documents, automations, webhooks, forms, import/export. Activated tools appear in your tool list immediately. Returns: { items:[{name,description}], total }.',
1064
+ inputSchema: {
1065
+ type: 'object',
1066
+ properties: {
1067
+ query: { type: 'string', description: 'Capability you need — e.g. "create table", "manage permissions", "work with documents", "reports"' },
1068
+ },
1069
+ required: ['query'],
1070
+ },
1071
+ annotations: { readOnlyHint: true },
1072
+ };
1073
+
1074
+ const CONFIRM_ACTION_DEF = {
1075
+ name: 'confirm_action',
1076
+ description: 'Use to confirm or reject a pending action after "REQUIRES CONFIRMATION" response. ALWAYS ask the user first before calling this. Never auto-confirm without explicit user approval. Returns: depends on confirmed action.',
1077
+ inputSchema: {
1078
+ type: 'object',
1079
+ properties: {
1080
+ approved: { type: 'boolean', description: 'true = user confirmed, false = user rejected' },
1081
+ },
1082
+ required: ['approved'],
1083
+ },
1084
+ };
1085
+
1086
+ const DELETE_WORKSPACE_DEF = {
1087
+ name: 'delete_workspace',
1088
+ description: 'Permanently delete a workspace and ALL its data (tables, records, documents, files, etc.). This action is irreversible. Requires the workspace slug. Returns: { message }.',
1089
+ inputSchema: {
1090
+ type: 'object',
1091
+ properties: {
1092
+ slug: { type: 'string', description: 'Slug of the workspace to delete' },
1093
+ },
1094
+ required: ['slug'],
1095
+ },
1096
+ annotations: { destructiveHint: true },
1097
+ };
1098
+
1099
+ const CLONE_WORKSPACE_DEF = {
1100
+ name: 'clone_workspace',
1101
+ description: 'Clone an existing workspace into a new one. Copies schema (tables, columns, views) and optionally documents and members. After cloning, automatically switches to the new workspace. Returns: { id, type:"workspace", slug, message }.',
1102
+ inputSchema: {
1103
+ type: 'object',
1104
+ properties: {
1105
+ sourceSlug: { type: 'string', description: 'Slug of the workspace to clone from' },
1106
+ name: { type: 'string', description: 'Display name for the new workspace' },
1107
+ slug: { type: 'string', description: 'URL slug for the new workspace: lowercase, 3-64 chars, a-z start, only a-z0-9_-' },
1108
+ includeDocuments: { type: 'boolean', description: 'Copy documents from the source workspace (default: false)' },
1109
+ includeMembers: { type: 'boolean', description: 'Copy member list and roles from the source workspace (default: false)' },
1110
+ },
1111
+ required: ['sourceSlug', 'name', 'slug'],
1112
+ },
1113
+ };
1114
+
1115
+ // Tools that only read data
1116
+ const READ_ONLY_TOOLS = new Set([
1117
+ 'list_tables', 'list_objects', 'list_views', 'get_view', 'get_object', 'get_related', 'graph_query',
1118
+ 'list_documents', 'get_object_history', 'list_comments', 'semantic_search',
1119
+ 'get_table_schema', 'list_reports', 'get_report', 'describe_report',
1120
+ 'list_members', 'list_roles', 'get_user_permissions', 'list_grants',
1121
+ 'search_documents', 'get_document', 'get_document_blocks',
1122
+ 'list_doc_versions', 'list_doc_sharing', 'list_doc_folders', 'list_doc_tags', 'preview_document',
1123
+ 'get_block_history', 'get_doc_version',
1124
+ 'recall', 'find_procedure', 'list_contradictions',
1125
+ 'get_schema_history', 'get_schema_snapshot', 'get_report_history', 'get_columns_batch',
1126
+ 'list_templates', 'list_workspace_templates',
1127
+ // new
1128
+ 'get_automation', 'get_webhook_deliveries',
1129
+ 'list_workspace_invitations', 'get_object_backlinks',
1130
+ 'fetch_api_docs',
1131
+ 'get_lookup', 'get_ref_options',
1132
+ 'get_graph_node', 'get_graph_neighborhood', 'list_graph_nodes', 'get_shortest_path',
1133
+ 'graph_health', 'list_memory_agents', 'browse_graph_memory',
1134
+ 'download_file', 'get_file_meta', 'get_notification_count', 'get_workspace', 'get_template',
1135
+ 'count_objects', 'import_preview', 'get_trash_item',
1136
+ // teamchat & decisions
1137
+ 'search_teamchat', 'search_similar_decisions', 'analyze_decision_conflicts', 'get_agent_metrics',
1138
+ 'get_wmatrix', 'list_recent_topics', 'list_topics', 'summarize_topic',
1139
+ 'list_decisions', 'get_decision_history', 'get_decision_iterations',
1140
+ // meta-kb
1141
+ 'mk_welcome', 'mk_list_rules', 'mk_gift_matrix', 'mk_gift_closed',
1142
+ 'mk_list_iterations', 'mk_get_debate',
1143
+ 'export_type', 'list_qa_results', 'list_test_sessions', 'get_test_session',
1144
+ 'get_batch_status',
1145
+ // resolution
1146
+ 'get_resolution_config', 'verify_client', 'get_client_lineage',
1147
+ // reports
1148
+ 'export_report',
1149
+ ]);
1150
+
1151
+ // Tools that delete or destroy data
1152
+ const DESTRUCTIVE_TOOLS = new Set([
1153
+ 'delete_object', 'bulk_delete', 'delete_table', 'delete_column',
1154
+ 'delete_report', 'delete_report_column', 'delete_comment',
1155
+ 'remove_grant', 'delete_document', 'delete_block',
1156
+ 'delete_doc_folder', 'delete_doc_tag', 'remove_tag_from_doc', 'purge_doc_versions', 'purge_document',
1157
+ 'revoke_doc_access', 'forget',
1158
+ 'restore_doc_version', 'rollback_object', 'delete_workspace',
1159
+ // new
1160
+ 'cancel_workspace_invitation', 'delete_report_join', 'delete_notification',
1161
+ 'test_connector_draft', 'generate_connector_schema', 'delete_resolution_config',
1162
+ 'invite_member', 'update_member_role',
1163
+ 'start_normalization', 'cancel_normalization',
1164
+ 'delete_topic',
1165
+ 'change_object_id',
1166
+ 'delete_test_session',
1167
+ 'mk_delete_rule',
1168
+ 'delete_agent',
1169
+ 'report_bulk_update',
1170
+ ]);
1171
+
1172
+ // English descriptions for MCP — backend TOOL_DEFS are in Russian for the in-app agent.
1173
+ // Add entries here when introducing new tools so MCP clients see English descriptions.
1174
+ const EN_DESCRIPTIONS = {
1175
+ // Lookups
1176
+ get_lookup: 'Get dropdown values for a lookup table by ID. Returns an array of records with id and display name.',
1177
+ get_ref_options: 'Get available options for a reference column by reqId. Use before creating/updating objects to discover valid values for ref fields.',
1178
+ // Graph
1179
+ get_graph_node: 'Get a graph node by object ID. Returns type, name, and edges.',
1180
+ get_graph_neighborhood: 'Get neighbors of a graph node (1-hop). Returns edges and connected nodes.',
1181
+ list_graph_nodes: 'List graph nodes by table type ID. Optionally includes edges.',
1182
+ get_shortest_path: 'Find the shortest path between two objects in the graph.',
1183
+ graph_health: 'Check graph subsystem health: node count, edge count, status.',
1184
+ list_memory_agents: 'List agents that store data in graph memory.',
1185
+ browse_graph_memory: 'Browse an agent memory graph — nodes, edges, keys. Optional agentId filter.',
1186
+ // Files
1187
+ download_file: 'Download a file from workspace storage by name. Returns base64 content, size, filename (max 10 MB).',
1188
+ get_file_meta: 'Get file metadata: processing status, extracted text, classification, extracted fields.',
1189
+ confirm_extracted_fields: 'Confirm extracted fields from a file and create an object from them.',
1190
+ reprocess_file: 'Re-trigger file processing (OCR, text extraction, classification).',
1191
+ mark_file_imported: 'Mark a file as imported and link it to a created object.',
1192
+ // Codespace
1193
+ get_file_tree: 'List files and directories in a codespace repository at a given path and ref (branch/commit). Returns: { items: [{ name, type, size, path }], ref, path }.',
1194
+ read_blob: 'Read file content from a codespace repository. Returns text for text files (up to 200K chars, supports offset/limit for pagination), metadata only for binary files. Returns: { content, path, ref, binary, size, truncated }. Use after get_file_tree to read specific files.',
1195
+ // Notifications
1196
+ get_notification_count: 'Get the number of unread notifications for the current user. Returns: { count }.',
1197
+ // Workspace
1198
+ get_workspace: 'Get current workspace details: name, slug, plan, settings (admin only).',
1199
+ get_template: 'Get details of a workspace template by ID (schema, description). Returns: { id, slug, name, description, icon, category, schema }.',
1200
+ list_workspace_templates: 'List available templates for creating new workspaces.',
1201
+ create_workspace_from_template: 'Create a new workspace from a template. Provide templateId, name, and slug.',
1202
+ // Decisions
1203
+ create_decision: 'Create a new team decision with optional linked chat room. Returns decision ID and metadata.',
1204
+ search_teamchat: 'Search teamchat messages by topic, room, or keyword. Returns matching messages with metadata.',
1205
+ search_similar_decisions: 'Find decisions semantically similar to a query or decision ID. Returns ranked results with similarity scores.',
1206
+ get_agent_metrics: 'Get performance metrics for AI agents. If agentId is provided, returns metrics for that agent only; otherwise all agents. Returns { data: [{ agentId, totalMessages, messages24h, topicsInvolved, trustScore }] }.',
1207
+ analyze_decision_conflicts: 'Analyze a decision for conflicts, contradictions, and overlaps with other decisions. Returns analysis with conflict descriptions.',
1208
+ list_decisions: 'List all architectural decisions with optional search and filters.',
1209
+ get_decision_history: 'Get change history for a decision — who changed what and when.',
1210
+ get_decision_iterations: 'Get reasoning iterations for a decision — evolution of thinking.',
1211
+ get_wmatrix: 'W-matrix (ONA graph): collaboration graph between team members. Shows hubs, bridges, isolated members. Edges: reply (answers) and co-topic (co-participation). Params: room_id (optional filter), days (1-365, default 30).',
1212
+ list_recent_topics: 'List recent active topics across all rooms the user belongs to. Filters: all, participated, unread, resolved, assigned_to_me, overdue, pinned.',
1213
+ summarize_topic: 'Generate an AI summary of a teamchat topic discussion. Extracts key conclusions, decisions made, and open questions.',
1214
+ list_topics: 'Search topics by name across all rooms the user belongs to. Returns matching topics with their IDs, names, and linked room names.',
1215
+ delete_topic: 'Permanently delete a teamchat topic and all its messages. Requires room admin rights. This action is IRREVERSIBLE.',
1216
+ // Meta-KB
1217
+ mk_revoke_entity: 'Revoke all knowledge base entities derived from a specified decision. Use when a decision was found to be incorrect. Returns { revoked: number, message: string }.',
1218
+ mk_list_debates: 'List recent expert debates in the workspace. Returns { debates: Array, total: number }. Each debate has id, question, consensus, verdict, created_by, created_at.',
1219
+ mk_start_debate: 'Start an expert debate on a question. Internal workspace agents evaluate the question in parallel, then cross-examine, then synthesize a consensus. Returns { opinions, crossTurns, consensus }.',
1220
+ mk_analytics: 'Get knowledge base analytics: entity/relation/class counts, orphan nodes, breakdown by source/type/status.',
1221
+ mk_research: 'Research a concept in the knowledge graph: find matching entities, graph neighbors, and knowledge gaps.',
1222
+ mk_propose_change: 'Propose a knowledge base change (add/update/delete entity). Creates a change request for human review. Returns { id, status: "pending" }.',
1223
+ mk_list_snapshots: 'List knowledge base snapshots. Shows date, label, and stats for each snapshot.',
1224
+ mk_create_snapshot: 'Create a snapshot of the current knowledge base state. Captures current state for later comparison.',
1225
+ mk_diff_snapshots: 'Compare two knowledge base snapshots. Shows added/removed entities and stat changes.',
1226
+ mk_review_change: 'Approve or reject a proposed knowledge base change.',
1227
+ mk_export_debate: 'Export a debate to Markdown format.',
1228
+ mk_list_topics: 'List topics in the meta-knowledge-base (meta-kb room).',
1229
+ mk_appropriate_decision: 'Run Socratic appropriation gate for a debate: generate consensus questions or evaluate answers. Step 1: without answers — returns questions. Step 2: with answers — evaluates and, on success, records a covenant act.',
1230
+ mk_welcome: 'Get Meta-KB welcome summary: stats, recent debates, recommendations.',
1231
+ mk_list_rules: 'List Meta-KB validation rules.',
1232
+ // Admin — export/import/QA
1233
+ export_type: 'Export a table definition (schema + data) by typeId.',
1234
+ bki_import: 'Import BKI format (tables + data from previous export). Provide content as JSON string.',
1235
+ list_qa_results: 'List QA test sessions and their results.',
1236
+ list_test_sessions: 'List QA test sessions with aggregate stats (total, passed, failed, skipped).',
1237
+ create_test_session: 'Create a new QA test session. Optional notes parameter.',
1238
+ get_test_session: 'Get a QA test session with all test results.',
1239
+ delete_test_session: 'Delete a QA test session.',
1240
+ upsert_test_result: 'Record a test result (passed/failed/skipped) in a QA session.',
1241
+ mk_run_rules: 'Run validation rules on specified entity IDs. Returns violations.',
1242
+ mk_gift_matrix: 'Get gift/contribution matrix of debate participants.',
1243
+ mk_gift_closed: 'Get participants with balanced contribution ratios over a period.',
1244
+ // Resolution
1245
+ get_resolution_config: 'Get entity resolution config for a table type — matching rules, merge strategy, field weights.',
1246
+ set_resolution_config: 'Create or update entity resolution config for a table type.',
1247
+ delete_resolution_config: 'Delete entity resolution config. Destructive — HITL required.',
1248
+ recompute_client: 'Recompute a client golden record from source records. Triggers re-merge.',
1249
+ verify_client: 'Verify client record — check data quality, shipping validity, duplicate risk.',
1250
+ get_client_lineage: 'Get lineage for a client — source records, merge history, field provenance.',
1251
+ mk_create_rule: 'Create a Meta-KB validation rule. Condition and action are JSON objects.',
1252
+ mk_delete_rule: 'Delete a Meta-KB validation rule by ID (requires confirmation).',
1253
+ mk_list_iterations: 'List Meta-KB iterations with optional status filter (in_progress, proposed, accepted, rejected, ignored).',
1254
+ mk_get_debate: 'Get a full debate by ID: question, opinions, consensus, verdict.',
1255
+ // Objects — new tools
1256
+ count_objects: 'Fast count of objects in a table without loading data. Supports parentId, text search (q), and requisite filters. Returns: { count }.',
1257
+ change_object_id: 'Change an object ID to a new value (requires confirmation). Atomic operation — updates id, references (up), types (t). Returns: { oldId, newId }.',
1258
+ import_preview: 'Preview CSV data before import. Parses CSV text and returns headers + first rows for mapping. Returns: { format, headers, preview, totalRows }.',
1259
+ import_create_table: 'Import CSV data as a new table — auto-creates type, columns from headers, and records. Returns: { typeId, typeName, columnsCreated, created, ids, errors }.',
1260
+ get_trash_item: 'Get a deleted object from trash by ID — with saved requisites. Returns: { id, typeId, parentId, val, ord, reqs, deletedAt, deletedBy }.',
1261
+ // Schema batch & maintenance
1262
+ get_columns_batch: 'Get column definitions for multiple tables in one request. Pass array of typeIds.',
1263
+ rebuild_flat_views: 'Rebuild all flat views (admin). Use after migrations or schema corruption.',
1264
+ set_type_visibility: 'Show or hide a table in navigation. Set hidden=true to hide, false to show.',
1265
+ // Documents — new tools
1266
+ import_document: 'Import an external file (DOCX, HTML, MD) as a document.',
1267
+ create_from_system_template: 'Create a document from a built-in system template by templateId.',
1268
+ purge_doc_versions: 'Permanently delete document versions. HITL required. Destructive.',
1269
+ preview_document: 'Generate a preview/PDF render of a document.',
1270
+ get_block_history: 'Get version history for a specific document block. Read-only.',
1271
+ get_doc_version: 'Get a specific version snapshot of a document. Read-only.',
1272
+ purge_document: 'Permanently delete a trashed document. HITL required. Destructive and irreversible.',
1273
+ // Automations — seed & batch
1274
+ seed_system_automations: 'Restore/seed system automations — creates standard rules if missing.',
1275
+ get_batch_status: 'Get status of an automation batch run — progress, errors, completion.',
1276
+ // Agent registry
1277
+ register_agent: 'Register a new external AI agent with endpoint URL, capabilities, and authentication.',
1278
+ update_agent: 'Update an external agent configuration — endpoint, capabilities, description.',
1279
+ delete_agent: 'Delete a registered external agent. Destructive — HITL required.',
1280
+ };
1281
+
1282
+ /** Convert backend tool def → MCP tool listing entry */
1283
+ function toMcpTool(t) {
1284
+ const entry = {
1285
+ name: t.name,
1286
+ description: EN_DESCRIPTIONS[t.name] || t.description || t.name,
1287
+ inputSchema: t.parameters || { type: 'object', properties: {} },
1288
+ };
1289
+ // Add behavioral annotations
1290
+ const annotations = {};
1291
+ if (READ_ONLY_TOOLS.has(t.name)) annotations.readOnlyHint = true;
1292
+ if (DESTRUCTIVE_TOOLS.has(t.name)) annotations.destructiveHint = true;
1293
+ if (Object.keys(annotations).length) entry.annotations = annotations;
1294
+ return entry;
1295
+ }
1296
+
1297
+ // Handler: list tools
1298
+ server.setRequestHandler(ListToolsRequestSchema, async () => {
1299
+ const tools = [LIST_WORKSPACES_DEF, SWITCH_WORKSPACE_DEF, CREATE_WORKSPACE_DEF, DELETE_WORKSPACE_DEF, CLONE_WORKSPACE_DEF, SEARCH_TOOLS_DEF, CONFIRM_ACTION_DEF];
1300
+ for (const [, t] of activeTools) {
1301
+ tools.push(toMcpTool(t));
1302
+ }
1303
+ return { tools };
1304
+ });
1305
+
1306
+ // Handler: call tool
1307
+ server.setRequestHandler(CallToolRequestSchema, async (request) => {
1308
+ const { name, arguments: args } = request.params;
1309
+
1310
+ // Built-in tools
1311
+ if (name === 'list_workspaces') return handleListWorkspaces();
1312
+ if (name === 'switch_workspace') return handleSwitchWorkspace(args?.slug || '');
1313
+ if (name === 'create_workspace') return handleCreateWorkspace(args || {});
1314
+ if (name === 'delete_workspace') return handleDeleteWorkspace(args?.slug || '');
1315
+ if (name === 'clone_workspace') return handleCloneWorkspace(args || {});
1316
+ if (name === 'search_tools') return handleSearchTools(args?.query || '');
1317
+ if (name === 'confirm_action') return handleConfirmAction(args?.approved ?? false);
1318
+
1319
+ // Check workspace is set
1320
+ if (!workspace) {
1321
+ return { content: [{ type: 'text', text: 'No workspace selected. Use list_workspaces to see available workspaces, then switch_workspace to select one.' }], isError: true };
1322
+ }
1323
+
1324
+ // Regular tool call → proxy to backend
1325
+ if (!activeTools.has(name)) {
1326
+ return { content: [{ type: 'text', text: `Error: Tool "${name}" is not active. Use search_tools to discover and activate it first.` }], isError: true };
1327
+ }
1328
+
1329
+ try {
1330
+ await ensureAuth();
1331
+ const callId = crypto.randomUUID();
1332
+ const data = await apiFetch(`/api/v2/${workspace}/ai/tool`, {
1333
+ method: 'POST',
1334
+ body: JSON.stringify({ name, args: args || {}, skipHitl: SKIP_HITL, callId }),
1335
+ });
1336
+ const result = data.ok ? data.data : data;
1337
+
1338
+ // Check if this is a HITL confirmation request
1339
+ if (result?.status === 'pending_confirmation') {
1340
+ // Evict expired entries
1341
+ const now = Date.now();
1342
+ while (pendingHitlQueue.length && pendingHitlQueue[0].createdAt < now - HITL_QUEUE_TTL_MS) {
1343
+ pendingHitlQueue.shift();
1344
+ }
1345
+ // Cap queue size
1346
+ if (pendingHitlQueue.length >= HITL_QUEUE_MAX_SIZE) {
1347
+ pendingHitlQueue.shift();
1348
+ }
1349
+ pendingHitlQueue.push({
1350
+ threadId: result.threadId,
1351
+ action: name,
1352
+ description: result.message || `Pending: ${name}`,
1353
+ createdAt: now,
1354
+ });
1355
+ const queueNote = pendingHitlQueue.length > 1 ? ` (${pendingHitlQueue.length} actions queued)` : '';
1356
+ return {
1357
+ content: [{ type: 'text', text: `⚠️ REQUIRES CONFIRMATION: ${result.message}${queueNote}\n\nAsk the user to confirm or reject, then call confirm_action(approved=true/false).` }],
1358
+ };
1359
+ }
1360
+
1361
+ // Handle elicitation sentinel — ask the MCP client for structured input
1362
+ if (data?.data?.__elicit) {
1363
+ try {
1364
+ const elicitResult = await server.elicit(
1365
+ data.data.prompt,
1366
+ { schema: data.data.schema }
1367
+ );
1368
+ if (elicitResult.action === 'cancel') {
1369
+ return { content: [{ type: 'text', text: 'Elicitation cancelled by user.' }] };
1370
+ }
1371
+ // Re-call the tool with the elicited answer injected into args
1372
+ const originalArgs = args || {};
1373
+ const resumeData = await apiFetch(`/api/v2/${workspace}/ai/tool`, {
1374
+ method: 'POST',
1375
+ body: JSON.stringify({
1376
+ name,
1377
+ args: { ...originalArgs, elicitedAnswer: elicitResult.content },
1378
+ threadId: data?.data?.threadId,
1379
+ schemaCtx: null,
1380
+ }),
1381
+ headers: { 'Content-Type': 'application/json' },
1382
+ });
1383
+ return {
1384
+ content: [{ type: 'text', text: typeof resumeData.data === 'string' ? resumeData.data : JSON.stringify(resumeData.data) }],
1385
+ };
1386
+ } catch (e) {
1387
+ log(`Elicitation not supported by client or failed: ${e.message}`);
1388
+ return {
1389
+ content: [{ type: 'text', text: `Требуется ввод: ${data.data.prompt}. Передайте ответ в аргументах инструмента.` }],
1390
+ };
1391
+ }
1392
+ }
1393
+
1394
+ // Detect tool-level errors returned as structured JSON from backend
1395
+ if (result?.error === true && result?.message) {
1396
+ return { content: [{ type: 'text', text: `Error: ${result.message}` }], isError: true };
1397
+ }
1398
+
1399
+ return {
1400
+ content: [{ type: 'text', text: typeof result === 'string' ? result : JSON.stringify(result, null, 2) }],
1401
+ };
1402
+ } catch (err) {
1403
+ return { content: [{ type: 'text', text: `Error: ${err.message}` }], isError: true };
1404
+ }
1405
+ });
1406
+
1407
+ // ─── confirm_action handler ──────────────────────────────────────────────────
1408
+
1409
+ async function handleConfirmAction(approved) {
1410
+ if (pendingHitlQueue.length === 0) {
1411
+ return { content: [{ type: 'text', text: 'No pending action to confirm.' }], isError: true };
1412
+ }
1413
+
1414
+ const pending = pendingHitlQueue.shift();
1415
+ try {
1416
+ let msg;
1417
+ if (pending.onApprove) {
1418
+ // Local HITL (e.g. delete_workspace) — execute callback directly
1419
+ if (approved) {
1420
+ msg = await pending.onApprove();
1421
+ } else {
1422
+ if (pending.onReject) pending.onReject();
1423
+ msg = 'Action rejected.';
1424
+ }
1425
+ } else {
1426
+ // Backend HITL — proxy to /mcp-resume
1427
+ await ensureAuth();
1428
+ const data = await apiFetch(`/api/v2/${workspace}/ai/mcp-resume`, {
1429
+ method: 'POST',
1430
+ body: JSON.stringify({ threadId: pending.threadId, approved }),
1431
+ });
1432
+ msg = data.data?.message || (approved ? 'Action confirmed and executed.' : 'Action rejected.');
1433
+ }
1434
+
1435
+ const remaining = pendingHitlQueue.length > 0 ? ` (${pendingHitlQueue.length} more pending — call confirm_action again)` : '';
1436
+ return { content: [{ type: 'text', text: msg + remaining }] };
1437
+ } catch (err) {
1438
+ return { content: [{ type: 'text', text: `Error confirming action: ${err.message}` }], isError: true };
1439
+ }
1440
+ }
1441
+
1442
+ // ─── create_workspace handler ─────────────────────────────────────────────────
1443
+
1444
+ async function handleCreateWorkspace({ name, slug, template, templateId }) {
1445
+ if (!name || !slug) {
1446
+ return { content: [{ type: 'text', text: 'Error: name and slug are required' }], isError: true };
1447
+ }
1448
+ if (!/^[a-z][a-z0-9_-]{1,62}[a-z0-9]$/.test(slug)) {
1449
+ return { content: [{ type: 'text', text: 'Error: slug must be 3-64 chars, start with a letter, only a-z 0-9 _ -' }], isError: true };
1450
+ }
1451
+ try {
1452
+ await ensureAuth();
1453
+ const body = { name, slug };
1454
+ if (templateId) body.templateId = templateId;
1455
+ else if (template) body.template = template;
1456
+ const data = await apiFetch('/api/v2/workspaces', {
1457
+ method: 'POST',
1458
+ body: JSON.stringify(body),
1459
+ });
1460
+ if (!data.ok) throw new Error(JSON.stringify(data.error || data));
1461
+
1462
+ const ws = data.data;
1463
+ log(`Created workspace "${ws.slug}" (id=${ws.id}, db=${ws.dbName})`);
1464
+
1465
+ // Auto-switch to the new workspace
1466
+ workspace = ws.slug;
1467
+ const tools = await fetchTools();
1468
+ activeTools.clear();
1469
+ for (const t of tools) {
1470
+ if (t.group === 'core' && !BUILT_IN_NAMES.has(t.name)) activeTools.set(t.name, t);
1471
+ }
1472
+ await server.sendToolListChanged();
1473
+
1474
+ return {
1475
+ content: [{ type: 'text', text: `Workspace "${ws.name}" created (slug: ${ws.slug}). Automatically switched to it. ${activeTools.size} core tools loaded.` }],
1476
+ };
1477
+ } catch (err) {
1478
+ return { content: [{ type: 'text', text: `Error creating workspace: ${err.message}` }], isError: true };
1479
+ }
1480
+ }
1481
+
1482
+ // ─── delete_workspace handler ─────────────────────────────────────────────────
1483
+
1484
+ let _pendingDeleteSlug = null;
1485
+
1486
+ async function handleDeleteWorkspace(slug) {
1487
+ if (!slug) {
1488
+ return { content: [{ type: 'text', text: 'Error: slug is required' }], isError: true };
1489
+ }
1490
+
1491
+ // Require explicit confirmation via confirm_action before deleting
1492
+ if (_pendingDeleteSlug !== slug) {
1493
+ _pendingDeleteSlug = slug;
1494
+ const now = Date.now();
1495
+ while (pendingHitlQueue.length && pendingHitlQueue[0].createdAt < now - HITL_QUEUE_TTL_MS) {
1496
+ pendingHitlQueue.shift();
1497
+ }
1498
+ if (pendingHitlQueue.length >= HITL_QUEUE_MAX_SIZE) {
1499
+ pendingHitlQueue.shift();
1500
+ }
1501
+ pendingHitlQueue.push({
1502
+ threadId: `delete-ws-${slug}`,
1503
+ action: 'delete_workspace',
1504
+ description: `Permanently delete workspace "${slug}" and ALL its data`,
1505
+ createdAt: now,
1506
+ onApprove: async () => {
1507
+ await ensureAuth();
1508
+ const data = await apiFetch(`/api/v2/workspaces/${slug}`, { method: 'DELETE' });
1509
+ if (!data.ok) throw new Error(JSON.stringify(data.error || data));
1510
+ log(`Deleted workspace "${slug}"`);
1511
+ if (workspace === slug) {
1512
+ workspace = '';
1513
+ activeTools.clear();
1514
+ await server.sendToolListChanged();
1515
+ }
1516
+ _pendingDeleteSlug = null;
1517
+ return `Workspace "${slug}" and all its data have been permanently deleted.`;
1518
+ },
1519
+ onReject: () => { _pendingDeleteSlug = null; },
1520
+ });
1521
+ return {
1522
+ content: [{ type: 'text', text: `⚠️ REQUIRES CONFIRMATION: Permanently delete workspace "${slug}" and ALL its data. This action is irreversible.\n\nAsk the user to confirm or reject, then call confirm_action(approved=true/false).` }],
1523
+ };
1524
+ }
1525
+
1526
+ // If already pending for same slug, remind
1527
+ return {
1528
+ content: [{ type: 'text', text: `Deletion of workspace "${slug}" is already pending confirmation. Call confirm_action(approved=true/false).` }],
1529
+ };
1530
+ }
1531
+
1532
+ // ─── clone_workspace handler ──────────────────────────────────────────────────
1533
+
1534
+ async function handleCloneWorkspace({ sourceSlug, name, slug, includeDocuments, includeMembers }) {
1535
+ if (!sourceSlug || !name || !slug) {
1536
+ return { content: [{ type: 'text', text: 'Error: sourceSlug, name, and slug are required' }], isError: true };
1537
+ }
1538
+ try {
1539
+ await ensureAuth();
1540
+ const body = { name, slug };
1541
+ if (includeDocuments !== undefined) body.includeDocuments = includeDocuments;
1542
+ if (includeMembers !== undefined) body.includeMembers = includeMembers;
1543
+ const data = await apiFetch(`/api/v2/workspaces/${sourceSlug}/clone`, {
1544
+ method: 'POST',
1545
+ body: JSON.stringify(body),
1546
+ });
1547
+ if (!data.ok) throw new Error(JSON.stringify(data.error || data));
1548
+
1549
+ const ws = data.data;
1550
+ log(`Cloned workspace "${sourceSlug}" → "${ws.slug}" (id=${ws.id})`);
1551
+
1552
+ // Auto-switch to the new workspace
1553
+ workspace = ws.slug;
1554
+ const tools = await fetchTools();
1555
+ activeTools.clear();
1556
+ for (const t of tools) {
1557
+ if (t.group === 'core' && !BUILT_IN_NAMES.has(t.name)) activeTools.set(t.name, t);
1558
+ }
1559
+ await server.sendToolListChanged();
1560
+
1561
+ return {
1562
+ content: [{ type: 'text', text: `Workspace "${sourceSlug}" cloned into "${ws.name}" (slug: ${ws.slug}). Automatically switched to it. ${activeTools.size} core tools loaded.` }],
1563
+ };
1564
+ } catch (err) {
1565
+ return { content: [{ type: 'text', text: `Error cloning workspace: ${err.message}` }], isError: true };
1566
+ }
1567
+ }
1568
+
1569
+ // ─── search_tools handler ────────────────────────────────────────────────────
1570
+
1571
+ // Built-in tool descriptors for search — always available, no activation needed
1572
+ const BUILT_IN_TOOL_DEFS = [
1573
+ LIST_WORKSPACES_DEF,
1574
+ SWITCH_WORKSPACE_DEF,
1575
+ CREATE_WORKSPACE_DEF,
1576
+ DELETE_WORKSPACE_DEF,
1577
+ CLONE_WORKSPACE_DEF,
1578
+ SEARCH_TOOLS_DEF,
1579
+ CONFIRM_ACTION_DEF,
1580
+ ];
1581
+
1582
+ // Group alias map — maps Russian/English synonyms to TOOL_DEFS group names
1583
+ const GROUP_ALIASES = {
1584
+ документ: 'docs', документы: 'docs', docs: 'docs', doc: 'docs',
1585
+ отчёт: 'reports', отчеты: 'reports', отчёты: 'reports', report: 'reports', reports: 'reports',
1586
+ схема: 'schema', таблица: 'schema', колонк: 'schema', schema: 'schema',
1587
+ права: 'grants', роли: 'grants', доступ: 'grants', grants: 'grants',
1588
+ автоматизац: 'workspace', вебхук: 'workspace', коннектор: 'workspace', форм: 'workspace',
1589
+ файл: 'workspace', файлы: 'workspace',
1590
+ портал: 'portal', телеграм: 'portal', telegram: 'portal', portal: 'portal',
1591
+ граф: 'graph', связи: 'graph', graph: 'graph',
1592
+ память: 'memory', memory: 'memory', запомни: 'memory',
1593
+ комментар: 'comments', comments: 'comments',
1594
+ git: 'codespace', github: 'codespace', репозитор: 'codespace', codespace: 'codespace',
1595
+ teamchat: 'teamchat', решени: 'teamchat', дискусс: 'teamchat',
1596
+ timeseries: 'timeseries', метрик: 'timeseries',
1597
+ объект: 'objects', запис: 'objects', bulk: 'bulk', массов: 'bulk',
1598
+ kag: 'kag', знани: 'kag',
1599
+ tts: 'ai', озвучк: 'ai', голос: 'ai', speak: 'ai',
1600
+ advisor: 'advisor', совет: 'advisor', консультант: 'advisor',
1601
+ agents: 'agents', агент: 'agents', делегир: 'agents',
1602
+ orgs: 'orgs', организаци: 'orgs', org: 'orgs',
1603
+ automations: 'automations', automation: 'automations',
1604
+ history: 'history', истори: 'history',
1605
+ lookups: 'lookups', lookup: 'lookups', справочник: 'lookups',
1606
+ 'meta-kb': 'meta-kb', metakb: 'meta-kb', дебат: 'meta-kb', дискусси: 'meta-kb',
1607
+ };
1608
+
1609
+ async function handleSearchTools(query) {
1610
+ try {
1611
+ const q = query.toLowerCase();
1612
+ const words = q.split(/\s+/).filter(Boolean);
1613
+
1614
+ // Phase 1: group-based match — if any query word maps to a group, return all tools from that group
1615
+ const matchedGroups = new Set();
1616
+ for (const w of words) {
1617
+ for (const [alias, group] of Object.entries(GROUP_ALIASES)) {
1618
+ if (alias.startsWith(w) || w.startsWith(alias)) matchedGroups.add(group);
1619
+ }
1620
+ }
1621
+
1622
+ let matched;
1623
+ if (matchedGroups.size > 0) {
1624
+ matched = allTools.filter(t => {
1625
+ if (activeTools.has(t.name)) return false;
1626
+ if (BUILT_IN_NAMES.has(t.name)) return false;
1627
+ return matchedGroups.has(t.group);
1628
+ });
1629
+ // Also include tools from other groups where ALL words match
1630
+ const groupSet = new Set(matched.map(t => t.name));
1631
+ const extra = allTools.filter(t => {
1632
+ if (groupSet.has(t.name) || activeTools.has(t.name) || BUILT_IN_NAMES.has(t.name)) return false;
1633
+ const text = `${t.name} ${t.description || ''} ${t.group || ''}`.toLowerCase();
1634
+ return words.every(w => text.includes(w));
1635
+ });
1636
+ matched = matched.concat(extra);
1637
+ } else {
1638
+ // Fallback: multi-word AND — all words must appear in name+description+group
1639
+ matched = allTools.filter(t => {
1640
+ if (activeTools.has(t.name)) return false;
1641
+ if (BUILT_IN_NAMES.has(t.name)) return false;
1642
+ const text = `${t.name} ${t.description || ''} ${t.group || ''}`.toLowerCase();
1643
+ return words.every(w => text.includes(w));
1644
+ });
1645
+ }
1646
+
1647
+ // Cap at 30
1648
+ matched = matched.slice(0, 30);
1649
+
1650
+ // Search built-in tools (always available, just inform)
1651
+ const matchedBuiltins = BUILT_IN_TOOL_DEFS.filter(t => {
1652
+ const text = `${t.name} ${t.description || ''}`.toLowerCase();
1653
+ return words.some(w => text.includes(w));
1654
+ });
1655
+
1656
+ // Activate found backend tools
1657
+ for (const t of matched) {
1658
+ activeTools.set(t.name, t);
1659
+ }
1660
+
1661
+ if (matched.length) {
1662
+ await server.sendToolListChanged();
1663
+ }
1664
+
1665
+ const parts = [];
1666
+ if (matched.length) parts.push(`Activated ${matched.length} tools: ${matched.map(t => t.name).join(', ')}.`);
1667
+ if (matchedBuiltins.length) parts.push(`Already available (built-in): ${matchedBuiltins.map(t => t.name).join(', ')}.`);
1668
+
1669
+ if (!parts.length) {
1670
+ return {
1671
+ content: [{ type: 'text', text: `No tools found matching "${query}". Available groups: schema, reports, docs, workspace, portal, telegram, grants, codespace, teamchat, graph, meta-kb, kag, memory, timeseries, advisor, agents, bulk, comments, history, objects, lookups, automations, ai, orgs` }],
1672
+ };
1673
+ }
1674
+
1675
+ return { content: [{ type: 'text', text: parts.join(' ') }] };
1676
+ } catch (err) {
1677
+ return { content: [{ type: 'text', text: `Error: ${err.message}` }], isError: true };
1678
+ }
1679
+ }
1680
+
1681
+ // ─── list_workspaces / switch_workspace handlers ─────────────────────────────
1682
+
1683
+ async function handleListWorkspaces() {
1684
+ try {
1685
+ await ensureAuth();
1686
+ const data = await apiFetch('/api/v2/workspaces');
1687
+ const list = (data.data || data).map(w => ({ slug: w.slug, name: w.name, role: w.role }));
1688
+ const current = workspace || '(none)';
1689
+ return {
1690
+ content: [{ type: 'text', text: `Server: ${BASE_URL}\nCurrent workspace: ${current}\n\n${list.map(w => `• ${w.slug} — ${w.name} (${w.role})`).join('\n')}` }],
1691
+ };
1692
+ } catch (err) {
1693
+ return { content: [{ type: 'text', text: `Error: ${err.message}` }], isError: true };
1694
+ }
1695
+ }
1696
+
1697
+ async function handleSwitchWorkspace(input) {
1698
+ if (!input) return { content: [{ type: 'text', text: 'Error: slug is required' }], isError: true };
1699
+ try {
1700
+ await ensureAuth();
1701
+
1702
+ // Resolve input — try slug first, then fuzzy match by name
1703
+ const data = await apiFetch('/api/v2/workspaces');
1704
+ const list = data.data || data;
1705
+ const q = input.toLowerCase();
1706
+ let match = list.find(w => w.slug === q);
1707
+ if (!match) match = list.find(w => w.name.toLowerCase() === q);
1708
+ if (!match) match = list.find(w => w.name.toLowerCase().includes(q) || w.slug.includes(q));
1709
+ if (!match) {
1710
+ return { content: [{ type: 'text', text: `Workspace "${input}" not found. Available: ${list.map(w => `${w.slug} (${w.name})`).join(', ')}` }], isError: true };
1711
+ }
1712
+
1713
+ const slug = match.slug;
1714
+ workspace = slug;
1715
+
1716
+ // Reload tools for the new workspace
1717
+ const tools = await fetchTools();
1718
+ activeTools.clear();
1719
+ for (const t of tools) {
1720
+ if (t.group === 'core' && !BUILT_IN_NAMES.has(t.name)) activeTools.set(t.name, t);
1721
+ }
1722
+
1723
+ await server.sendToolListChanged();
1724
+ log(`Switched to workspace "${slug}", ${activeTools.size} core tools loaded`);
1725
+
1726
+ return {
1727
+ content: [{ type: 'text', text: `Switched to workspace "${slug}". Loaded ${tools.length} tools (${activeTools.size} core active). Use search_tools to activate more.` }],
1728
+ };
1729
+ } catch (err) {
1730
+ return { content: [{ type: 'text', text: `Error switching workspace: ${err.message}` }], isError: true };
1731
+ }
1732
+ }
1733
+
1734
+ // ─── Bootstrap ───────────────────────────────────────────────────────────────
1735
+
1736
+ // ─── Auto-update from git ────────────────────────────────────────────────────
1737
+
1738
+ import { execSync } from 'child_process';
1739
+ import { dirname } from 'path';
1740
+ import { fileURLToPath } from 'url';
1741
+
1742
+ const __dirname = dirname(fileURLToPath(import.meta.url));
1743
+ const AUTO_UPDATE_INTERVAL = 60 * 60 * 1000; // check every hour
1744
+
1745
+ function tryAutoUpdate() {
1746
+ try {
1747
+ execSync('git rev-parse --git-dir', { cwd: __dirname, stdio: 'ignore' });
1748
+ const before = execSync('git rev-parse HEAD', { cwd: __dirname, encoding: 'utf8' }).trim();
1749
+ execSync('git pull --ff-only', { cwd: __dirname, stdio: 'ignore', timeout: 15000 });
1750
+ const after = execSync('git rev-parse HEAD', { cwd: __dirname, encoding: 'utf8' }).trim();
1751
+ if (before !== after) {
1752
+ log(`Updated ${before.slice(0, 7)} → ${after.slice(0, 7)}, restarting...`);
1753
+ try { execSync('npm install --omit=dev', { cwd: __dirname, stdio: 'ignore', timeout: 30000 }); } catch {}
1754
+ // Allow pending responses to drain before exit
1755
+ log('Shutting down gracefully...');
1756
+ setTimeout(() => process.exit(0), 2000);
1757
+ }
1758
+ } catch { /* not a git repo or offline — skip */ }
1759
+ }
1760
+
1761
+ async function main() {
1762
+ tryAutoUpdate();
1763
+ setInterval(tryAutoUpdate, AUTO_UPDATE_INTERVAL);
1764
+
1765
+ log(`Connecting to ${BASE_URL}, workspace "${workspace || '(not set)'}"`);
1766
+
1767
+ // 1. Login
1768
+ await login();
1769
+
1770
+ // 2. Fetch tool definitions (if workspace is set)
1771
+ if (workspace) {
1772
+ const tools = await fetchTools();
1773
+ log(`Fetched ${tools.length} tool definitions`);
1774
+ for (const t of tools) {
1775
+ if (t.group === 'core' && !BUILT_IN_NAMES.has(t.name)) activeTools.set(t.name, t);
1776
+ }
1777
+ log(`Activated ${activeTools.size} core tools + built-in tools`);
1778
+ } else {
1779
+ log('No workspace set — use list_workspaces and switch_workspace to select one');
1780
+ }
1781
+
1782
+ // 4. Start stdio transport
1783
+ const transport = new StdioServerTransport();
1784
+ await server.connect(transport);
1785
+ log('MCP server running on stdio');
1786
+ }
1787
+
1788
+ main().catch(err => {
1789
+ process.stderr.write(`[integram-mcp] Fatal: ${err.message}\n`);
1790
+ process.exit(1);
1791
+ });