suppa-mcp-2 1.0.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.
package/dist/server.js ADDED
@@ -0,0 +1,1533 @@
1
+ /**
2
+ * Suppa MCP Server — unified gateway to the Suppa platform.
3
+ *
4
+ * Faithful 1:1 port of the Python `suppa_mcp/server.py`. Wires all 74 tools,
5
+ * mirrors the tool-behavior annotations (_READ/_ADD/_MUT), reproduces the
6
+ * server `instructions` string verbatim, and OWNS all confirm-gating (the tool
7
+ * modules mutate unconditionally, exactly like the Python tool functions).
8
+ */
9
+ import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
10
+ import { z } from "zod";
11
+ import * as tasks from "./tools/tasks.js";
12
+ import * as docs from "./tools/docs.js";
13
+ import * as entity from "./tools/entity.js";
14
+ import * as forms from "./tools/forms.js";
15
+ import * as migrate from "./tools/migrate.js";
16
+ import * as workspace from "./tools/workspace.js";
17
+ import * as automation from "./tools/automation.js";
18
+ import * as auth from "./auth.js";
19
+ import * as tenants from "./tenants.js";
20
+ import { confirmRequired, jsonResponse } from "./utils.js";
21
+ // ---------------------------------------------------------------------------
22
+ // Tool-behavior hints (MCP spec): clients use these for auto-approval policies.
23
+ // _READ touches nothing; _ADD only creates new data; _MUT changes or removes
24
+ // existing data (and is additionally approval-gated via confirm=true).
25
+ // ---------------------------------------------------------------------------
26
+ const _READ = { readOnlyHint: true };
27
+ const _ADD = {
28
+ readOnlyHint: false,
29
+ destructiveHint: false,
30
+ idempotentHint: false,
31
+ };
32
+ const _MUT = {
33
+ readOnlyHint: false,
34
+ destructiveHint: true,
35
+ idempotentHint: true,
36
+ };
37
+ // ---------------------------------------------------------------------------
38
+ // Shared parameter types: Field descriptions land in the tools' inputSchema, so
39
+ // the model sees the format guidance at call time — not only in the docstring.
40
+ // ---------------------------------------------------------------------------
41
+ const Confirm = z
42
+ .boolean()
43
+ .default(false)
44
+ .describe("Set true ONLY after the user explicitly approved this exact change. " +
45
+ "First call without it to get a confirmation preview.");
46
+ const ProjectionJson = z
47
+ .string()
48
+ .describe('JSON projection of fields to return, e.g. {"id": true, "title": true, ' +
49
+ '"owner": {"id": true, "fullName": true}}. Enums: {"myEnum": {"value": true}}.');
50
+ const RecordValuesJson = z
51
+ .string()
52
+ .describe('JSON object of field values. Relations/enums as {"id": N}, e.g. ' +
53
+ '{"title": "X", "customer": {"id": 7}, "status": {"id": 12}}.');
54
+ const TenantArg = z
55
+ .string()
56
+ .describe("Tenant alias ('testing'), host ('testing.modern.me'), or full URL.");
57
+ const DeadlineArg = z
58
+ .string()
59
+ .nullable()
60
+ .describe("'today', 'tomorrow', '+3d', '+2h', '+30m', '+1w', or ISO datetime " +
61
+ "(naive = UTC; prefer an explicit offset like +03:00).");
62
+ const BlocksJson = z
63
+ .string()
64
+ .describe('JSON array of blocks: [{"type": "head1|text|bulletList|numberedList|' +
65
+ 'checkList|quote|callout|divider|code|table|toggle", "title": "text or HTML"}].');
66
+ const EntityName = z
67
+ .string()
68
+ .describe("Exact entity name, e.g. 'Tasks' — discover via suppa_list_entities.");
69
+ const TaskSearch = z.string().describe("Free-text search over task titles.");
70
+ const MyFlag = z
71
+ .boolean()
72
+ .describe("Only tasks assigned to the authenticated user.");
73
+ const ActiveFlag = z
74
+ .boolean()
75
+ .describe("Only tasks whose stage status is active/in-progress.");
76
+ const OverdueFlag = z
77
+ .boolean()
78
+ .describe("Only active tasks whose deadline has passed.");
79
+ const DueTodayFlag = z
80
+ .boolean()
81
+ .describe("Only tasks with a deadline today (UTC).");
82
+ const ProjectId = z.number().int().nullable().describe("Project id to scope to.");
83
+ const WorkflowId = z
84
+ .number()
85
+ .int()
86
+ .nullable()
87
+ .describe("Workflow id — see suppa_list_workflows.");
88
+ const StageIdOpt = z
89
+ .number()
90
+ .int()
91
+ .nullable()
92
+ .describe("Stage id — see suppa_list_stages.");
93
+ const AssigneeId = z
94
+ .number()
95
+ .int()
96
+ .nullable()
97
+ .describe("Assignee user id — find via suppa_search_users.");
98
+ const TypeId = z
99
+ .number()
100
+ .int()
101
+ .nullable()
102
+ .describe("Task type id — see suppa_list_task_types.");
103
+ const PriorityId = z.number().int().nullable().describe("Priority id.");
104
+ const TaskDescriptionNew = z
105
+ .string()
106
+ .describe("Task description; HTML or plain text (plain is wrapped in <p>).");
107
+ const TaskDescriptionUpd = z
108
+ .string()
109
+ .nullable()
110
+ .describe("New description; HTML or plain text (plain is wrapped in <p>).");
111
+ const FormColumns = z
112
+ .number()
113
+ .int()
114
+ .describe("Grid column count for the form layout.");
115
+ const GenFields = z
116
+ .string()
117
+ .nullable()
118
+ .describe("Comma-separated entity field names to include/order; default: all client-created fields.");
119
+ const AutomationId = z
120
+ .number()
121
+ .int()
122
+ .describe("AutomationWorkflow id — see suppa_list_automations.");
123
+ const AutomationSearch = z
124
+ .string()
125
+ .describe("Substring match on the automation's name.");
126
+ const IsActiveOpt = z
127
+ .boolean()
128
+ .nullable()
129
+ .describe("Filter by isActive (true/false); omit for all.");
130
+ const RunStatusOpt = z
131
+ .string()
132
+ .nullable()
133
+ .describe("Filter runs by status, e.g. 'success', 'error', 'running'.");
134
+ const NodeTypeArg = z
135
+ .string()
136
+ .describe("Node type identifier — see suppa_list_automation_node_types.");
137
+ const EntityQuery = z
138
+ .string()
139
+ .describe("Substring of an entity name or title to find the canonical entity name.");
140
+ // ---------------------------------------------------------------------------
141
+ // Server instructions — reproduced VERBATIM from server.py.
142
+ // ---------------------------------------------------------------------------
143
+ const INSTRUCTIONS = `Suppa Platform MCP Server — manage Tasks, Docs/Pages, Entities, Forms, and file attachments on modern.suppa.me.
144
+
145
+ AUTHENTICATION — RESOLVE THIS BEFORE ANY OTHER SUPPA WORK
146
+ - Auth is an interactive Google browser sign-in. There is NO API key for an end user to find or paste — so NEVER ask the user for a token, key, or password. If you're tempted to ask for credentials, call suppa_login instead.
147
+ - At the start of Suppa work, if you don't already know the user is signed in, call suppa_list_tenants (cheap, read-only). Look at the ACTIVE tenant: if "authenticated": false or "needs_login": true, the user is not signed in.
148
+ - Whenever the user is not signed in — OR any tool returns "No Suppa credentials" / HTTP 401 / "session could not be refreshed" / a ReloginRequired error — DO NOT STOP and DO NOT ask for a key. Authenticate yourself:
149
+ 1. Call suppa_login (or suppa_login(tenant="<alias|host|url>") to target a specific instance; default is the active tenant). This OPENS A GOOGLE SIGN-IN PAGE in the user's default browser — a local page served at http://localhost:8080.
150
+ 2. Tell the user in plain words: "I've opened a Google sign-in page in your browser — pick your account to finish signing in." If the browser didn't open, the tool result carries the URL; give it to them to open manually.
151
+ 3. suppa_login blocks until they finish and returns {"status":"ok"}. THEN retry the original action. Tokens are stored in the OS keychain and auto-refresh, so this is a one-time step per tenant — you won't need to repeat it next session.
152
+ - A static SUPPA_API_KEY in the client env is supported (CI / single-tenant) and, when present, means no login is needed — but it is optional and most users won't have one.
153
+ - Use suppa_diagnostics to validate the whole setup; it reports the login_origin that must be whitelisted. ONE-TIME ORG SETUP: the loopback origin (http://localhost:8080) must be added to the Google OAuth client's "Authorized JavaScript origins". If the sign-in page opens but never completes, that missing whitelist entry is almost always why — surface this to the user so an admin can add it.
154
+ - suppa_use_tenant switches the active instance for ALL later calls; suppa_list_tenants shows what's known and authenticated.
155
+
156
+ DATA BASICS
157
+ - IDs are integers (not UUIDs).
158
+ - Dates are ISO-8601 strings. A naive datetime (no offset) is treated as UTC — include an explicit offset (e.g. +03:00) or pre-convert local times to UTC to avoid a silent shift.
159
+ - Task deadlines also accept 'today', 'tomorrow', '+3d', '+2h', '+30m', '+1w'.
160
+ - WRITE relations as {"id": N} and enum fields as {"id": <enumValueId>} — a bare number/string would return 201 but silently store null; suppa_create_record/suppa_update_record therefore REFUSE malformed shapes with guidance.
161
+ - READ enum fields back as objects: project {"myEnum": {"value": true}} and read .value, never as a bare string.
162
+ - HTML content (descriptions, comments, blocks): plain text is auto-wrapped in <p>…</p>; to pass raw HTML start the string with <.
163
+ - A document's LAST page cannot be deleted (platform rule) — delete the doc itself instead.
164
+
165
+ SEARCH & FILTERS
166
+ - Filters: {"field": "name", "value": "...", "comparator": "="} — comparators: =, !=, <, >, <=, >=, like, in, is null, is not null.
167
+ - 'like' requires SQL wildcards: %substring%. 'in' takes a JSON array value.
168
+ - Filters combine with AND by default; pass match_any=true (search_records) for OR.
169
+ - Dotted field paths work in filters: "stage.status.value", "owner.id".
170
+ - Magic value "$current-user" resolves to the authenticated user's ID.
171
+ - Project only the fields you need (fields_json) — it keeps responses small and fast.
172
+ - suppa_search_tasks / suppa_search_records return {…, "has_more", "next_offset"}: when has_more is true, re-call with offset=next_offset to page; never assume the first page is everything.
173
+ - One record by id: suppa_get_record (any entity) / suppa_get_task / suppa_get_doc — no filters needed.
174
+ - Discover schema first when unsure: suppa_list_entities → suppa_describe_entity, then suppa_search_records.
175
+
176
+ APPROVAL GATES (human-in-the-loop)
177
+ - Every update/move/close/delete tool returns {"status": "confirmation_required"} when called without confirm=true, and performs NOTHING.
178
+ - On that response: show the user what will change, get explicit approval, then re-call the same tool with confirm=true. Never set confirm=true on the first call without the user's go-ahead.
179
+ - Create/read tools (and comments) need no confirmation.
180
+
181
+ ENTITY BUILDER (add-only by design)
182
+ - Real field types only: text, numeric, integer, serial, boolean, timestamp, json, uuid, multi-language, icon, enum, multi-enum, file, multi-file, many-to-one, one-to-many, many-to-many, many-to-many-backref. There is NO date/datetime/richtext/email/url/phone type — use timestamp (+sub_type='date') or multi-language.
183
+ - Relations need relation_entity; enums need enum_name (qualified 'Entity.field') with values added via suppa_add_enum_values.
184
+ - Removing/altering existing fields is UI-only by design — this server can only add.
185
+
186
+ MIGRATION (Suppa 1.0 → 2.0)
187
+ - Always dry-run first: suppa_migrate_entities_from_v1(dry_run=true, output_file="plan.json"), review/edit the plan, then execute with plan_file="plan.json", dry_run=false.
188
+ `;
189
+ // ---------------------------------------------------------------------------
190
+ // Registered tool + prompt names (tests assert the counts).
191
+ // ---------------------------------------------------------------------------
192
+ export const TOOL_NAMES = [];
193
+ export const PROMPT_NAMES = [];
194
+ /** Wrap a tool-module call result (a JSON string) into an MCP text content. */
195
+ function text(result) {
196
+ return { content: [{ type: "text", text: result }] };
197
+ }
198
+ export function buildServer() {
199
+ // Reset so repeated buildServer() calls (e.g. in tests) do not double-count.
200
+ TOOL_NAMES.length = 0;
201
+ PROMPT_NAMES.length = 0;
202
+ const server = new McpServer({ name: "suppa-2.0", version: "1.0.0" }, { instructions: INSTRUCTIONS });
203
+ const reg = (name, cfg, handler) => {
204
+ server.registerTool(name, {
205
+ description: cfg.description,
206
+ inputSchema: (cfg.inputSchema ?? {}),
207
+ annotations: cfg.annotations,
208
+ }, handler);
209
+ TOOL_NAMES.push(name);
210
+ };
211
+ // =========================================================================
212
+ // Tasks tools
213
+ // =========================================================================
214
+ reg("suppa_get_me", {
215
+ description: "Get the current authenticated user's profile (name, position, roles).",
216
+ annotations: _READ,
217
+ }, async () => text(await tasks.getMe()));
218
+ reg("suppa_search_tasks", {
219
+ description: "Search tasks. Use my=true for your tasks, active=true for open tasks, or search by title substring.",
220
+ inputSchema: {
221
+ search: TaskSearch.default(""),
222
+ my: MyFlag.default(false),
223
+ active: ActiveFlag.default(false),
224
+ overdue: OverdueFlag.default(false),
225
+ due_today: DueTodayFlag.default(false),
226
+ project_id: ProjectId.default(null),
227
+ workflow_id: WorkflowId.default(null),
228
+ stage_id: StageIdOpt.default(null),
229
+ assigned_to_id: AssigneeId.default(null),
230
+ limit: z.number().int().default(20),
231
+ offset: z.number().int().default(0),
232
+ },
233
+ annotations: _READ,
234
+ }, async (a) => text(await tasks.searchTasks(a.search, a.my, a.active, a.overdue, a.due_today, a.project_id, a.workflow_id, a.stage_id, a.assigned_to_id, a.limit, a.offset)));
235
+ reg("suppa_count_tasks", {
236
+ description: "Count tasks matching filters without returning full data.",
237
+ inputSchema: {
238
+ my: MyFlag.default(false),
239
+ active: ActiveFlag.default(false),
240
+ project_id: ProjectId.default(null),
241
+ workflow_id: WorkflowId.default(null),
242
+ search: TaskSearch.default(""),
243
+ overdue: OverdueFlag.default(false),
244
+ due_today: DueTodayFlag.default(false),
245
+ },
246
+ annotations: _READ,
247
+ }, async (a) => text(await tasks.countTasks(a.my, a.active, a.project_id, a.workflow_id, a.search, a.overdue, a.due_today)));
248
+ reg("suppa_get_task", {
249
+ description: "Get full details of a task by its ID.",
250
+ inputSchema: { task_id: z.number().int() },
251
+ annotations: _READ,
252
+ }, async (a) => text(await tasks.getTask(a.task_id)));
253
+ reg("suppa_create_task", {
254
+ description: "Create a new task. Deadline accepts: 'today', 'tomorrow', '+3d', '+2h', '+30m', '+1w', or ISO datetime.",
255
+ inputSchema: {
256
+ title: z.string(),
257
+ description: TaskDescriptionNew.default(""),
258
+ assigned_to_id: AssigneeId.default(null),
259
+ project_id: ProjectId.default(null),
260
+ workflow_id: WorkflowId.default(null),
261
+ stage_id: StageIdOpt.default(null),
262
+ type_id: TypeId.default(null),
263
+ priority_id: PriorityId.default(null),
264
+ deadline: DeadlineArg.default(null),
265
+ parent_id: z
266
+ .number()
267
+ .int()
268
+ .nullable()
269
+ .default(null)
270
+ .describe("Parent task id — makes this a subtask."),
271
+ },
272
+ annotations: _ADD,
273
+ }, async (a) => text(await tasks.createTask(a.title, a.description, a.assigned_to_id, a.project_id, a.workflow_id, a.stage_id, a.type_id, a.priority_id, a.deadline, a.parent_id)));
274
+ reg("suppa_update_task", {
275
+ description: "Update fields on an existing task. Only provided fields are changed.\n\n" +
276
+ " APPROVAL GATE: without confirm=true this returns a confirmation request and\n" +
277
+ " changes nothing. Get the user's approval, then re-call with confirm=true.",
278
+ inputSchema: {
279
+ task_id: z.number().int(),
280
+ title: z.string().nullable().default(null),
281
+ description: TaskDescriptionUpd.default(null),
282
+ assigned_to_id: AssigneeId.default(null),
283
+ project_id: ProjectId.default(null),
284
+ workflow_id: WorkflowId.default(null),
285
+ stage_id: StageIdOpt.default(null),
286
+ type_id: TypeId.default(null),
287
+ priority_id: PriorityId.default(null),
288
+ deadline: DeadlineArg.default(null),
289
+ confirm: Confirm,
290
+ },
291
+ annotations: _MUT,
292
+ }, async (a) => {
293
+ if (!a.confirm) {
294
+ const entries = [
295
+ ["title", a.title],
296
+ ["description", a.description],
297
+ ["assigned_to_id", a.assigned_to_id],
298
+ ["project_id", a.project_id],
299
+ ["workflow_id", a.workflow_id],
300
+ ["stage_id", a.stage_id],
301
+ ["type_id", a.type_id],
302
+ ["priority_id", a.priority_id],
303
+ ["deadline", a.deadline],
304
+ ];
305
+ const changes = {};
306
+ for (const [k, v] of entries) {
307
+ if (v !== null && v !== undefined)
308
+ changes[k] = v;
309
+ }
310
+ return text(confirmRequired("update task", { task_id: a.task_id }, changes));
311
+ }
312
+ return text(await tasks.updateTask(a.task_id, a.title, a.description, a.assigned_to_id, a.project_id, a.workflow_id, a.stage_id, a.type_id, a.priority_id, a.deadline));
313
+ });
314
+ reg("suppa_delete_task", {
315
+ description: "Soft-delete a task.\n\n" +
316
+ " APPROVAL GATE: without confirm=true this returns a confirmation request and\n" +
317
+ " deletes nothing. Get the user's approval, then re-call with confirm=true.",
318
+ inputSchema: { task_id: z.number().int(), confirm: Confirm },
319
+ annotations: _MUT,
320
+ }, async (a) => {
321
+ if (!a.confirm) {
322
+ return text(confirmRequired("delete task", { task_id: a.task_id }));
323
+ }
324
+ return text(await tasks.deleteTask(a.task_id));
325
+ });
326
+ reg("suppa_move_task", {
327
+ description: "Move a task to a different workflow stage.\n\n" +
328
+ " APPROVAL GATE: without confirm=true this returns a confirmation request and\n" +
329
+ " changes nothing. Get the user's approval, then re-call with confirm=true.",
330
+ inputSchema: {
331
+ task_id: z.number().int(),
332
+ stage_id: z
333
+ .number()
334
+ .int()
335
+ .describe("Target stage id; must belong to the task's workflow (suppa_list_stages)."),
336
+ confirm: Confirm,
337
+ },
338
+ annotations: _MUT,
339
+ }, async (a) => {
340
+ if (!a.confirm) {
341
+ return text(confirmRequired("move task", { task_id: a.task_id }, { stage_id: a.stage_id }));
342
+ }
343
+ return text(await tasks.moveTask(a.task_id, a.stage_id));
344
+ });
345
+ reg("suppa_close_task", {
346
+ description: "Close a task by moving it to the workflow's completed stage.\n\n" +
347
+ " APPROVAL GATE: without confirm=true this returns a confirmation request and\n" +
348
+ " changes nothing. Get the user's approval, then re-call with confirm=true.",
349
+ inputSchema: { task_id: z.number().int(), confirm: Confirm },
350
+ annotations: _MUT,
351
+ }, async (a) => {
352
+ if (!a.confirm) {
353
+ return text(confirmRequired("close task", { task_id: a.task_id }));
354
+ }
355
+ return text(await tasks.closeTask(a.task_id));
356
+ });
357
+ reg("suppa_add_comment", {
358
+ description: "Add a comment to a task. Supports HTML. mention_ids: comma-separated 'userId:Name' pairs for @mentions.",
359
+ inputSchema: {
360
+ task_id: z.number().int(),
361
+ content: z
362
+ .string()
363
+ .describe("Comment text; plain text is wrapped in <p>, raw HTML passes through."),
364
+ mention_ids: z
365
+ .string()
366
+ .nullable()
367
+ .default(null)
368
+ .describe("@mentions as comma-separated 'userId:Name' pairs, e.g. '15:Ivan Petrenko'."),
369
+ },
370
+ annotations: _ADD,
371
+ }, async (a) => text(await tasks.addComment(a.task_id, a.content, a.mention_ids)));
372
+ reg("suppa_get_comments", {
373
+ description: "Get the latest N comments on a task, in chronological (oldest-first) order.",
374
+ inputSchema: {
375
+ task_id: z.number().int(),
376
+ limit: z.number().int().default(30),
377
+ },
378
+ annotations: _READ,
379
+ }, async (a) => text(await tasks.getComments(a.task_id, a.limit)));
380
+ reg("suppa_attach_file", {
381
+ description: "Upload a local file and attach it to a task.",
382
+ inputSchema: {
383
+ task_id: z.number().int(),
384
+ file_path: z
385
+ .string()
386
+ .describe("Absolute local path of the file to upload (max 100 MiB)."),
387
+ },
388
+ annotations: _ADD,
389
+ }, async (a) => text(await tasks.attachFile(a.task_id, a.file_path)));
390
+ reg("suppa_list_workflows", {
391
+ description: "List all workflows. Optionally filter by name.",
392
+ inputSchema: { name: z.string().nullable().default(null) },
393
+ annotations: _READ,
394
+ }, async (a) => text(await tasks.listWorkflows(a.name)));
395
+ reg("suppa_list_stages", {
396
+ description: "List all stages in a specific workflow.",
397
+ inputSchema: {
398
+ workflow_id: z
399
+ .number()
400
+ .int()
401
+ .describe("Workflow id — see suppa_list_workflows."),
402
+ },
403
+ annotations: _READ,
404
+ }, async (a) => text(await tasks.listStages(a.workflow_id)));
405
+ reg("suppa_list_task_types", {
406
+ description: "List all available task types.",
407
+ annotations: _READ,
408
+ }, async () => text(await tasks.listTaskTypes()));
409
+ reg("suppa_search_users", {
410
+ description: "Search users by name.",
411
+ inputSchema: {
412
+ name: z
413
+ .string()
414
+ .default("")
415
+ .describe("Substring of the full name; returned ids feed assigned_to_id and mentions."),
416
+ limit: z.number().int().default(20),
417
+ },
418
+ annotations: _READ,
419
+ }, async (a) => text(await tasks.searchUsers(a.name, a.limit)));
420
+ // =========================================================================
421
+ // Docs tools
422
+ // =========================================================================
423
+ reg("suppa_list_docs", {
424
+ description: "List documents, optionally filtering by title.",
425
+ inputSchema: {
426
+ search: z
427
+ .string()
428
+ .default("")
429
+ .describe("Case-insensitive substring of the doc title."),
430
+ limit: z.number().int().default(20),
431
+ },
432
+ annotations: _READ,
433
+ }, async (a) => text(await docs.listDocs(a.search, a.limit)));
434
+ reg("suppa_get_doc", {
435
+ description: "Get a document by ID including its page tree.",
436
+ inputSchema: { doc_id: z.number().int() },
437
+ annotations: _READ,
438
+ }, async (a) => text(await docs.getDoc(a.doc_id)));
439
+ reg("suppa_create_doc", {
440
+ description: "Create a new document.",
441
+ inputSchema: {
442
+ title: z.string(),
443
+ is_public: z.boolean().default(false),
444
+ },
445
+ annotations: _ADD,
446
+ }, async (a) => text(await docs.createDoc(a.title, a.is_public)));
447
+ reg("suppa_update_doc", {
448
+ description: "Update a document's title or visibility.\n\n" +
449
+ " APPROVAL GATE: without confirm=true this returns a confirmation request and\n" +
450
+ " changes nothing. Get the user's approval, then re-call with confirm=true.",
451
+ inputSchema: {
452
+ doc_id: z.number().int(),
453
+ title: z.string().nullable().default(null),
454
+ is_public: z.boolean().nullable().default(null),
455
+ confirm: Confirm,
456
+ },
457
+ annotations: _MUT,
458
+ }, async (a) => {
459
+ if (!a.confirm) {
460
+ const changes = {};
461
+ if (a.title !== null && a.title !== undefined)
462
+ changes.title = a.title;
463
+ if (a.is_public !== null && a.is_public !== undefined)
464
+ changes.is_public = a.is_public;
465
+ return text(confirmRequired("update doc", { doc_id: a.doc_id }, changes));
466
+ }
467
+ return text(await docs.updateDoc(a.doc_id, a.title, a.is_public));
468
+ });
469
+ reg("suppa_delete_doc", {
470
+ description: "Delete a document (and its pages).\n\n" +
471
+ " APPROVAL GATE: without confirm=true this returns a confirmation request and\n" +
472
+ " deletes nothing. Get the user's approval, then re-call with confirm=true.",
473
+ inputSchema: { doc_id: z.number().int(), confirm: Confirm },
474
+ annotations: _MUT,
475
+ }, async (a) => {
476
+ if (!a.confirm) {
477
+ return text(confirmRequired("delete doc", { doc_id: a.doc_id }));
478
+ }
479
+ return text(await docs.deleteDoc(a.doc_id));
480
+ });
481
+ reg("suppa_list_pages", {
482
+ description: "List all pages in a document.",
483
+ inputSchema: {
484
+ doc_id: z.number().int(),
485
+ limit: z.number().int().default(50),
486
+ },
487
+ annotations: _READ,
488
+ }, async (a) => text(await docs.listPages(a.doc_id, a.limit)));
489
+ reg("suppa_get_page", {
490
+ description: "Get a page's metadata.",
491
+ inputSchema: { page_id: z.number().int() },
492
+ annotations: _READ,
493
+ }, async (a) => text(await docs.getPage(a.page_id)));
494
+ reg("suppa_create_page", {
495
+ description: "Create a new page in a document.",
496
+ inputSchema: {
497
+ doc_id: z.number().int(),
498
+ title: z.string(),
499
+ parent_id: z
500
+ .number()
501
+ .int()
502
+ .nullable()
503
+ .default(null)
504
+ .describe("Parent page id — nests this page under it."),
505
+ description: z
506
+ .string()
507
+ .nullable()
508
+ .default(null)
509
+ .describe("Short subtitle shown under the page title."),
510
+ icon: z.string().nullable().default(null),
511
+ },
512
+ annotations: _ADD,
513
+ }, async (a) => text(await docs.createPage(a.doc_id, a.title, a.parent_id, a.description, a.icon)));
514
+ reg("suppa_update_page", {
515
+ description: "Update a page's metadata.\n\n" +
516
+ " APPROVAL GATE: without confirm=true this returns a confirmation request and\n" +
517
+ " changes nothing. Get the user's approval, then re-call with confirm=true.",
518
+ inputSchema: {
519
+ page_id: z.number().int(),
520
+ title: z.string().nullable().default(null),
521
+ description: z.string().nullable().default(null),
522
+ icon: z.string().nullable().default(null),
523
+ is_public: z.boolean().nullable().default(null),
524
+ confirm: Confirm,
525
+ },
526
+ annotations: _MUT,
527
+ }, async (a) => {
528
+ if (!a.confirm) {
529
+ const entries = [
530
+ ["title", a.title],
531
+ ["description", a.description],
532
+ ["icon", a.icon],
533
+ ["is_public", a.is_public],
534
+ ];
535
+ const changes = {};
536
+ for (const [k, v] of entries) {
537
+ if (v !== null && v !== undefined)
538
+ changes[k] = v;
539
+ }
540
+ return text(confirmRequired("update page", { page_id: a.page_id }, changes));
541
+ }
542
+ return text(await docs.updatePage(a.page_id, a.title, a.description, a.icon, a.is_public));
543
+ });
544
+ reg("suppa_delete_page", {
545
+ description: "Delete a page. The platform refuses to delete a document's LAST page\n" +
546
+ " (HTTP 400) — delete the whole doc instead (suppa_delete_doc).\n\n" +
547
+ " APPROVAL GATE: without confirm=true this returns a confirmation request and\n" +
548
+ " deletes nothing. Get the user's approval, then re-call with confirm=true.",
549
+ inputSchema: { page_id: z.number().int(), confirm: Confirm },
550
+ annotations: _MUT,
551
+ }, async (a) => {
552
+ if (!a.confirm) {
553
+ return text(confirmRequired("delete page", { page_id: a.page_id }));
554
+ }
555
+ return text(await docs.deletePage(a.page_id));
556
+ });
557
+ reg("suppa_get_blocks", {
558
+ description: "Get all content blocks on a page in order (raw JSON with IDs and properties).",
559
+ inputSchema: { page_id: z.number().int() },
560
+ annotations: _READ,
561
+ }, async (a) => text(await docs.getBlocks(a.page_id)));
562
+ reg("suppa_read_page", {
563
+ description: "Read a page as human-readable markdown-like text.",
564
+ inputSchema: { page_id: z.number().int() },
565
+ annotations: _READ,
566
+ }, async (a) => text(await docs.readPage(a.page_id)));
567
+ reg("suppa_create_blocks", {
568
+ description: "Create content blocks on a page (appended at end). blocks_json: JSON array of {type, title} objects.\n" +
569
+ " Types: text, head1, head2, head3, bulletList, numberedList, checkList, quote, callout, divider, code, table, toggle.",
570
+ inputSchema: {
571
+ page_id: z.number().int(),
572
+ blocks_json: BlocksJson,
573
+ },
574
+ annotations: _ADD,
575
+ }, async (a) => text(await docs.createBlocks(a.page_id, a.blocks_json)));
576
+ reg("suppa_insert_block", {
577
+ description: "Insert block(s) at a specific position. Provide after_id OR before_id as anchor.\n" +
578
+ " blocks_json: JSON array of {type, title} objects.",
579
+ inputSchema: {
580
+ page_id: z.number().int(),
581
+ blocks_json: BlocksJson,
582
+ after_id: z
583
+ .number()
584
+ .int()
585
+ .nullable()
586
+ .default(null)
587
+ .describe("Insert after this block id (use suppa_get_blocks for ids)."),
588
+ before_id: z
589
+ .number()
590
+ .int()
591
+ .nullable()
592
+ .default(null)
593
+ .describe("Insert before this block id (alternative to after_id)."),
594
+ },
595
+ annotations: _ADD,
596
+ }, async (a) => text(await docs.insertBlock(a.page_id, a.blocks_json, a.after_id, a.before_id)));
597
+ reg("suppa_update_block", {
598
+ description: "Update a block's content. Provide title (text/HTML) or full properties_json.\n\n" +
599
+ " APPROVAL GATE: without confirm=true this returns a confirmation request and\n" +
600
+ " changes nothing. Get the user's approval, then re-call with confirm=true.",
601
+ inputSchema: {
602
+ block_id: z.number().int(),
603
+ title: z
604
+ .string()
605
+ .nullable()
606
+ .default(null)
607
+ .describe("New text/HTML content (simple case)."),
608
+ properties_json: z
609
+ .string()
610
+ .nullable()
611
+ .default(null)
612
+ .describe('Full properties JSON object (advanced; overrides title), e.g. {"title": "<p>x</p>", "checked": true}.'),
613
+ confirm: Confirm,
614
+ },
615
+ annotations: _MUT,
616
+ }, async (a) => {
617
+ if (!a.confirm) {
618
+ const changes = {};
619
+ if (a.title !== null && a.title !== undefined)
620
+ changes.title = a.title;
621
+ if (a.properties_json !== null && a.properties_json !== undefined)
622
+ changes.properties_json = a.properties_json;
623
+ return text(confirmRequired("update block", { block_id: a.block_id }, changes));
624
+ }
625
+ return text(await docs.updateBlock(a.block_id, a.title, a.properties_json));
626
+ });
627
+ reg("suppa_delete_block", {
628
+ description: "Delete a content block.\n\n" +
629
+ " APPROVAL GATE: without confirm=true this returns a confirmation request and\n" +
630
+ " deletes nothing. Get the user's approval, then re-call with confirm=true.",
631
+ inputSchema: { block_id: z.number().int(), confirm: Confirm },
632
+ annotations: _MUT,
633
+ }, async (a) => {
634
+ if (!a.confirm) {
635
+ return text(confirmRequired("delete block", { block_id: a.block_id }));
636
+ }
637
+ return text(await docs.deleteBlock(a.block_id));
638
+ });
639
+ reg("suppa_reorder_blocks", {
640
+ description: "Reorder blocks on a page. block_ids: comma-separated IDs to move. Provide after_id or before_id as anchor.",
641
+ inputSchema: {
642
+ page_id: z.number().int(),
643
+ block_ids: z
644
+ .string()
645
+ .describe("Comma-separated block ids to move, in the order they should appear."),
646
+ after_id: z
647
+ .number()
648
+ .int()
649
+ .nullable()
650
+ .default(null)
651
+ .describe("Place the moved blocks after this block id."),
652
+ before_id: z
653
+ .number()
654
+ .int()
655
+ .nullable()
656
+ .default(null)
657
+ .describe("Place the moved blocks before this block id."),
658
+ },
659
+ annotations: _MUT,
660
+ }, async (a) => text(await docs.reorderBlocks(a.page_id, a.block_ids, a.after_id, a.before_id)));
661
+ // =========================================================================
662
+ // Entity tools
663
+ // =========================================================================
664
+ reg("suppa_list_entities", {
665
+ description: "List all entities (database tables) on the platform. Optionally filter by name.",
666
+ inputSchema: {
667
+ search: z
668
+ .string()
669
+ .default("")
670
+ .describe("Case-insensitive substring of the entity name/title."),
671
+ full: z
672
+ .boolean()
673
+ .default(false)
674
+ .describe("true = raw schema rows; default returns a slim summary per entity."),
675
+ },
676
+ annotations: _READ,
677
+ }, async (a) => text(await entity.listEntities(a.search, a.full)));
678
+ reg("suppa_describe_entity", {
679
+ description: "Get the full schema of an entity — all fields, types, relations, and constraints.",
680
+ inputSchema: { entity_name: EntityName },
681
+ annotations: _READ,
682
+ }, async (a) => text(await entity.describeEntity(a.entity_name)));
683
+ reg("suppa_list_tabular_parts", {
684
+ description: 'List an entity\'s tabular parts (owned child sub-tables / "таблична частина").\n' +
685
+ " Each result has type='tabular-part' and a relationEntity pointing back to the parent.",
686
+ inputSchema: { entity_name: EntityName },
687
+ annotations: _READ,
688
+ }, async (a) => text(await entity.listTabularParts(a.entity_name)));
689
+ reg("suppa_search_records", {
690
+ description: "Search records of any entity. filters_json: [{field, value, comparator}]. fields_json: {field: true}.\n" +
691
+ " match_any=true combines filters with OR instead of AND.\n" +
692
+ " Returns {records, returned, has_more, next_offset} — page with offset until has_more is false.\n\n" +
693
+ " Enum fields read back as objects {value, title, id} — project them as\n" +
694
+ ' {"myEnum": {"value": true}} and read .value, not as a bare string.',
695
+ inputSchema: {
696
+ entity_name: z
697
+ .string()
698
+ .describe("Exact entity name, e.g. 'Tasks', 'Users' — see suppa_list_entities."),
699
+ filters_json: z
700
+ .string()
701
+ .default("[]")
702
+ .describe('JSON array of filters: [{"field": "status.value", "value": "active", "comparator": "="}]. \'like\' needs %wildcards%; dotted paths allowed.'),
703
+ fields_json: ProjectionJson.default('{"id": true}'),
704
+ limit: z.number().int().default(20),
705
+ offset: z.number().int().default(0),
706
+ search: z
707
+ .string()
708
+ .default("")
709
+ .describe("Free-text search across the entity's searchable fields."),
710
+ order_by: z
711
+ .string()
712
+ .default("createdAt:desc")
713
+ .describe("'field:asc' or 'field:desc', e.g. 'createdAt:desc'."),
714
+ match_any: z
715
+ .boolean()
716
+ .default(false)
717
+ .describe("true = combine filters with OR instead of AND."),
718
+ },
719
+ annotations: _READ,
720
+ }, async (a) => text(await entity.searchRecords(a.entity_name, a.filters_json, a.fields_json, a.limit, a.offset, a.search, a.order_by, a.match_any)));
721
+ reg("suppa_get_record", {
722
+ description: "Get a single record of any entity by id. fields_json: {field: true} projection —\n" +
723
+ ' request only the fields you need (relations as nested objects, e.g. {"owner": {"id": true, "fullName": true}}).',
724
+ inputSchema: {
725
+ entity_name: EntityName,
726
+ record_id: z.number().int(),
727
+ fields_json: ProjectionJson.default('{"id": true}'),
728
+ },
729
+ annotations: _READ,
730
+ }, async (a) => text(await entity.getRecord(a.entity_name, a.record_id, a.fields_json)));
731
+ reg("suppa_create_entity", {
732
+ description: "Create a new entity (database table). By default also creates the display-title\n" +
733
+ " field so records have a label and titleFieldName resolves to a real field.\n\n" +
734
+ " NOT for repeating child rows that belong to one parent record (invoice\n" +
735
+ ' line-items, "X by category", per-period breakdowns) — those must be a tabular\n' +
736
+ " part: use suppa_create_tabular_part instead, or they end up as a stray separate\n" +
737
+ " entity.",
738
+ inputSchema: {
739
+ name: z
740
+ .string()
741
+ .describe("PascalCase entity name, e.g. 'CustomerOrders'."),
742
+ title: z.string(),
743
+ title_field_name: z
744
+ .string()
745
+ .default("title")
746
+ .describe("Field shown as each record's display title (default 'title')."),
747
+ auto_title_field: z
748
+ .boolean()
749
+ .default(true)
750
+ .describe("Also create the title field so records have a label (default true)."),
751
+ title_field_type: z
752
+ .string()
753
+ .default("multi-language")
754
+ .describe("Type for the auto-created title field (default 'multi-language')."),
755
+ },
756
+ annotations: _ADD,
757
+ }, async (a) => text(await entity.createEntity(a.name, a.title, a.title_field_name, a.auto_title_field, a.title_field_type)));
758
+ reg("suppa_create_tabular_part", {
759
+ description: 'Create a tabular part (ТЧ / "таблична частина") — an owned child sub-table of\n' +
760
+ " parent_entity, edited inline in the parent (like 1C invoice line-items).\n\n" +
761
+ " Use this — NOT suppa_create_entity — whenever a child holds repeating rows that\n" +
762
+ " belong to ONE parent record. The platform marks it type='tabular-part', auto-adds\n" +
763
+ " a system `owner` (many-to-one → parent) field, and nests it under the parent.\n" +
764
+ " Add data fields afterwards with suppa_add_field, then verify with\n" +
765
+ " suppa_list_tabular_parts(parent_entity).",
766
+ inputSchema: {
767
+ parent_entity: z
768
+ .string()
769
+ .describe("Existing parent entity that owns the rows, e.g. 'PartnerDiscounts'."),
770
+ name: z
771
+ .string()
772
+ .describe("Child name/suffix, e.g. 'ByCategory'. Stored name becomes parent_entity+name unless it already starts with the parent name."),
773
+ title: z.string(),
774
+ title_field_name: z
775
+ .string()
776
+ .default("title")
777
+ .describe("Field shown as each row's display title (default 'title')."),
778
+ auto_title_field: z
779
+ .boolean()
780
+ .default(true)
781
+ .describe("Also create the title field (default true)."),
782
+ title_field_type: z
783
+ .string()
784
+ .default("multi-language")
785
+ .describe("Type for the auto-created title field (default 'multi-language')."),
786
+ full_name: z
787
+ .string()
788
+ .nullable()
789
+ .default(null)
790
+ .describe("Override the exact stored entity name instead of parent_entity+name."),
791
+ },
792
+ annotations: _ADD,
793
+ }, async (a) => text(await entity.createTabularPart(a.parent_entity, a.name, a.title, a.title_field_name, a.auto_title_field, a.title_field_type, a.full_name)));
794
+ reg("suppa_add_field", {
795
+ description: "Add a field to an entity.\n\n" +
796
+ " field_type: a real Suppa 2.0 type — text, numeric, integer, serial, boolean,\n" +
797
+ " timestamp, json, uuid, multi-language, icon, enum, multi-enum, file, multi-file,\n" +
798
+ " one-to-many, many-to-one, many-to-many, many-to-many-backref. There is NO\n" +
799
+ " date/datetime/richtext/email/url/phone type — use timestamp (+sub_type='date'\n" +
800
+ " for date-only) and multi-language for localized text. 'relation' is accepted\n" +
801
+ " as an alias for many-to-one. Provide relation_entity for relations, enum_name\n" +
802
+ " for enums. Constraints: max_length/min_length (text), decimal_places /\n" +
803
+ " min_value / max_value / only_positive (numeric).",
804
+ inputSchema: {
805
+ entity_name: EntityName,
806
+ field_name: z
807
+ .string()
808
+ .describe("camelCase field name, e.g. 'orderDate'."),
809
+ field_type: z
810
+ .string()
811
+ .describe("A real Suppa 2.0 type (see suppa_list_field_types). NO date/richtext/email type exists — use 'timestamp' (+sub_type='date') or 'multi-language'."),
812
+ title: z.string().nullable().default(null),
813
+ required: z.boolean().default(false),
814
+ unique: z.boolean().default(false),
815
+ relation_entity: z
816
+ .string()
817
+ .nullable()
818
+ .default(null)
819
+ .describe("Target entity name — REQUIRED for relation types (many-to-one etc.)."),
820
+ enum_name: z
821
+ .string()
822
+ .nullable()
823
+ .default(null)
824
+ .describe("Qualified enum key 'Entity.field' — REQUIRED for enum/multi-enum."),
825
+ sub_type: z
826
+ .string()
827
+ .nullable()
828
+ .default(null)
829
+ .describe("'date' makes a timestamp date-only."),
830
+ max_length: z
831
+ .number()
832
+ .int()
833
+ .nullable()
834
+ .default(null)
835
+ .describe("Max text length (text type); omit for unlimited."),
836
+ min_length: z
837
+ .number()
838
+ .int()
839
+ .nullable()
840
+ .default(null)
841
+ .describe("Min text length (text type)."),
842
+ decimal_places: z
843
+ .number()
844
+ .int()
845
+ .nullable()
846
+ .default(null)
847
+ .describe("Decimal places (numeric type)."),
848
+ min_value: z
849
+ .number()
850
+ .nullable()
851
+ .default(null)
852
+ .describe("Lower bound (numeric type)."),
853
+ max_value: z
854
+ .number()
855
+ .nullable()
856
+ .default(null)
857
+ .describe("Upper bound (numeric type)."),
858
+ only_positive: z
859
+ .boolean()
860
+ .default(false)
861
+ .describe("Restrict numeric to positive values."),
862
+ },
863
+ annotations: _ADD,
864
+ }, async (a) => text(await entity.addField(a.entity_name, a.field_name, a.field_type, a.title, {
865
+ required: a.required,
866
+ unique: a.unique,
867
+ relationEntity: a.relation_entity,
868
+ enumName: a.enum_name,
869
+ subType: a.sub_type,
870
+ maxLength: a.max_length,
871
+ minLength: a.min_length,
872
+ decimalPlaces: a.decimal_places,
873
+ minValue: a.min_value,
874
+ maxValue: a.max_value,
875
+ onlyPositive: a.only_positive,
876
+ })));
877
+ reg("suppa_add_enum_values", {
878
+ description: "Add values to an enum (lookup table). enum_name: qualified 'Entity.field'\n" +
879
+ " key (e.g. 'Receipts.type'). values: comma-separated list.",
880
+ inputSchema: {
881
+ enum_name: z
882
+ .string()
883
+ .describe("Qualified 'Entity.field' enum key, e.g. 'Receipts.type'."),
884
+ values: z
885
+ .string()
886
+ .describe("Comma-separated values to add; existing ones are skipped."),
887
+ },
888
+ annotations: _ADD,
889
+ }, async (a) => text(await entity.addEnumValues(a.enum_name, a.values)));
890
+ reg("suppa_set_title_field", {
891
+ description: "Set an entity's display-title (representative) field; creates it if missing.",
892
+ inputSchema: {
893
+ entity_name: EntityName,
894
+ field_name: z
895
+ .string()
896
+ .describe("Field to use as the record display title; created (multi-language) if missing."),
897
+ },
898
+ annotations: _ADD,
899
+ }, async (a) => text(await entity.setTitleField(a.entity_name, a.field_name)));
900
+ reg("suppa_list_field_types", {
901
+ description: "List all available field types for entity/form creation.",
902
+ annotations: _READ,
903
+ }, async () => text(await entity.listFieldTypes()));
904
+ reg("suppa_create_record", {
905
+ description: "Create a record in any entity. fields_json: JSON object of field values.\n\n" +
906
+ ' Write relations as {"id": N} and enum fields as {"id": <enumValueId>} —\n' +
907
+ " a bare number/string returns HTTP 201 but silently stores null.",
908
+ inputSchema: {
909
+ entity_name: EntityName,
910
+ fields_json: RecordValuesJson,
911
+ },
912
+ annotations: _ADD,
913
+ }, async (a) => text(await entity.createRecord(a.entity_name, a.fields_json)));
914
+ reg("suppa_update_record", {
915
+ description: "Update a record in any entity. fields_json: JSON object of fields to change.\n\n" +
916
+ ' Write relations as {"id": N} and enum fields as {"id": <enumValueId>} —\n' +
917
+ " a bare number/string returns HTTP 201 but silently stores null.\n\n" +
918
+ " APPROVAL GATE: without confirm=true this returns a confirmation request and\n" +
919
+ " changes nothing. Get the user's approval, then re-call with confirm=true.",
920
+ inputSchema: {
921
+ entity_name: EntityName,
922
+ record_id: z.number().int(),
923
+ fields_json: RecordValuesJson,
924
+ confirm: Confirm,
925
+ },
926
+ annotations: _MUT,
927
+ }, async (a) => {
928
+ if (!a.confirm) {
929
+ let proposed;
930
+ try {
931
+ proposed = JSON.parse(a.fields_json);
932
+ }
933
+ catch {
934
+ proposed = a.fields_json;
935
+ }
936
+ return text(confirmRequired("update record", { entity: a.entity_name, record_id: a.record_id }, proposed));
937
+ }
938
+ return text(await entity.updateRecord(a.entity_name, a.record_id, a.fields_json));
939
+ });
940
+ reg("suppa_delete_record", {
941
+ description: "Delete a record (instance) from any entity.\n\n" +
942
+ " Removes a single instance, not the entity/schema. Entity definitions and\n" +
943
+ " fields are add-only here (create_entity / add_field) — removing or modifying\n" +
944
+ " fields is UI-only by design.\n\n" +
945
+ " APPROVAL GATE: without confirm=true this returns a confirmation request and\n" +
946
+ " deletes nothing. Get the user's approval, then re-call with confirm=true.",
947
+ inputSchema: {
948
+ entity_name: EntityName,
949
+ record_id: z.number().int(),
950
+ confirm: Confirm,
951
+ },
952
+ annotations: _MUT,
953
+ }, async (a) => {
954
+ if (!a.confirm) {
955
+ return text(confirmRequired("delete record", {
956
+ entity: a.entity_name,
957
+ record_id: a.record_id,
958
+ }));
959
+ }
960
+ return text(await entity.deleteRecord(a.entity_name, a.record_id));
961
+ });
962
+ reg("suppa_attach_file_to_record", {
963
+ description: "Attach a local file to a record (instance) of any entity.\n\n" +
964
+ " Auto-detects the entity's file/attachment field from its schema; pass\n" +
965
+ " field_name only when the entity has more than one file field. Provide the\n" +
966
+ " absolute file_path.",
967
+ inputSchema: {
968
+ entity_name: EntityName,
969
+ record_id: z.number().int(),
970
+ file_path: z
971
+ .string()
972
+ .describe("Absolute local path of the file to upload (max 100 MiB)."),
973
+ field_name: z
974
+ .string()
975
+ .nullable()
976
+ .default(null)
977
+ .describe("Target file field; only needed when the entity has more than one file field."),
978
+ },
979
+ annotations: _ADD,
980
+ }, async (a) => text(await entity.attachFileToRecord(a.entity_name, a.record_id, a.file_path, a.field_name)));
981
+ // =========================================================================
982
+ // Automation (workflow) tools — READ-ONLY
983
+ // =========================================================================
984
+ reg("suppa_list_automations", {
985
+ description: "List automation workflows (AutomationWorkflow). NOTE: these are platform\n" +
986
+ " automations, distinct from Task workflows (suppa_list_workflows).",
987
+ inputSchema: {
988
+ search: AutomationSearch.default(""),
989
+ is_active: IsActiveOpt.default(null),
990
+ limit: z.number().int().default(20),
991
+ offset: z.number().int().default(0),
992
+ },
993
+ annotations: _READ,
994
+ }, async (a) => text(await automation.listAutomations(a.search, a.is_active, a.limit, a.offset)));
995
+ reg("suppa_get_automation", {
996
+ description: "Get one automation workflow as a normalized graph: nodes + edges, settings,\n" +
997
+ " and the published snapshot. nodes [{id,type,name,config,position}], edges\n" +
998
+ ' [{from,fromHandle,to,toIndex}], under "published". Distinct from Task workflows.',
999
+ inputSchema: { automation_id: AutomationId },
1000
+ annotations: _READ,
1001
+ }, async (a) => text(await automation.getAutomation(a.automation_id)));
1002
+ reg("suppa_list_automation_runs", {
1003
+ description: "List runs (executions) of one automation, newest first.",
1004
+ inputSchema: {
1005
+ automation_id: AutomationId,
1006
+ status: RunStatusOpt.default(null),
1007
+ limit: z.number().int().default(20),
1008
+ offset: z.number().int().default(0),
1009
+ },
1010
+ annotations: _READ,
1011
+ }, async (a) => text(await automation.listAutomationRuns(a.automation_id, a.status, a.limit, a.offset)));
1012
+ reg("suppa_get_automation_run", {
1013
+ description: "Get one automation run with its per-node `steps` (nodeId/status/timing/\n" +
1014
+ " output/error) and `triggerPayload` (the run input).",
1015
+ inputSchema: { run_id: z.number().int() },
1016
+ annotations: _READ,
1017
+ }, async (a) => text(await automation.getAutomationRun(a.run_id)));
1018
+ reg("suppa_list_automation_node_types", {
1019
+ description: "List automation node types from the authoritative catalog endpoint\n" +
1020
+ " ({type, label, category, description, requiredParams, paramCount, usedCount});\n" +
1021
+ " falls back to deriving the catalog from live graphs on builds without it.",
1022
+ inputSchema: { search: AutomationSearch.default("") },
1023
+ annotations: _READ,
1024
+ }, async (a) => text(await automation.listAutomationNodeTypes(a.search)));
1025
+ reg("suppa_get_automation_node_schema", {
1026
+ description: "Schema for one automation node type from the authoritative catalog\n" +
1027
+ " (params name/type/required/description + credentials), enriched with sample\n" +
1028
+ " values and input/output handles from live graphs; falls back to a graph-\n" +
1029
+ " derived schema on builds without the endpoint or for an unknown type.",
1030
+ inputSchema: { node_type: NodeTypeArg },
1031
+ annotations: _READ,
1032
+ }, async (a) => text(await automation.getAutomationNodeSchema(a.node_type)));
1033
+ reg("suppa_search_entities", {
1034
+ description: "Fuzzy-search the entity registry by name/title and return each match's\n" +
1035
+ " canonical name, label, description, and recordCount. recordCount costs one\n" +
1036
+ " capped id-page per match — keep `query` specific. Abstract/unqueryable\n" +
1037
+ " entities (e.g. BaseEntity) return recordCount=null + recordCountError rather\n" +
1038
+ " than failing the search.",
1039
+ inputSchema: {
1040
+ query: EntityQuery,
1041
+ limit: z.number().int().default(20),
1042
+ },
1043
+ annotations: _READ,
1044
+ }, async (a) => text(await automation.searchEntities(a.query, a.limit)));
1045
+ // =========================================================================
1046
+ // Migration connector (Suppa 1.0 -> Suppa 2.0)
1047
+ // =========================================================================
1048
+ reg("suppa_migrate_entities_from_v1", {
1049
+ description: "Migrate entity schemas (tables + fields + enums) from a Suppa 1.0 backend into this Suppa 2.0 platform.\n\n" +
1050
+ " Reads entities and their fields from Suppa 1.0 (configured via SUPPA_V1_API_KEY / SUPPA_V1_ACCESS_TOKEN\n" +
1051
+ " and SUPPA_V1_BASE_URL) and recreates them here. Relations are created in a second pass.\n\n" +
1052
+ " Recommended workflow:\n" +
1053
+ ' 1. Dry run + export: dry_run=true, output_file="migration_plan.json" → review/edit the file.\n' +
1054
+ ' 2. Execute the file: dry_run=false, plan_file="migration_plan.json".\n\n' +
1055
+ " dry_run: when True (default), returns the migration plan without writing anything to 2.0.\n" +
1056
+ " entity_names: comma-separated 1.0 entity names/aliases to migrate (empty = all).\n" +
1057
+ " include_builtin: include builtin/system entities (default: custom only).\n" +
1058
+ " skip_relations: skip relation/foreign-key fields.\n" +
1059
+ " output_file: write the plan as JSON to this path (for review/editing).\n" +
1060
+ " plan_file: load the plan from this JSON file instead of reading from Suppa 1.0.\n ",
1061
+ inputSchema: {
1062
+ dry_run: z
1063
+ .boolean()
1064
+ .default(true)
1065
+ .describe("true (default) = only build/return the plan, write nothing to 2.0."),
1066
+ entity_names: z
1067
+ .string()
1068
+ .default("")
1069
+ .describe("Comma-separated 1.0 entity names/aliases to migrate; empty = all custom entities."),
1070
+ include_builtin: z
1071
+ .boolean()
1072
+ .default(false)
1073
+ .describe("Include builtin/system 1.0 entities (default: custom only)."),
1074
+ skip_relations: z
1075
+ .boolean()
1076
+ .default(false)
1077
+ .describe("Skip relation/foreign-key fields entirely."),
1078
+ output_file: z
1079
+ .string()
1080
+ .default("")
1081
+ .describe("Write the plan JSON here for review/editing before execution."),
1082
+ plan_file: z
1083
+ .string()
1084
+ .default("")
1085
+ .describe("Execute this (possibly hand-edited) plan JSON instead of re-reading 1.0."),
1086
+ mode: z
1087
+ .string()
1088
+ .default("create")
1089
+ .describe("'create'/'gap-fill' (idempotent: skip existing) or 'reconcile' (read-only diff vs live 2.0, writes nothing)."),
1090
+ },
1091
+ annotations: _ADD,
1092
+ }, async (a) => text(await migrate.migrateEntities(a.dry_run, a.entity_names, a.include_builtin, a.skip_relations, a.output_file, a.plan_file, a.mode)));
1093
+ reg("suppa_read_v1_entities", {
1094
+ description: "List entities on the configured Suppa 1.0 backend (read-only).",
1095
+ inputSchema: {
1096
+ search: z
1097
+ .string()
1098
+ .default("")
1099
+ .describe("Case-insensitive substring of the 1.0 entity name/alias."),
1100
+ },
1101
+ annotations: _READ,
1102
+ }, async (a) => text(await migrate.readV1Entities(a.search)));
1103
+ reg("suppa_read_v1_entity_props", {
1104
+ description: "List the fields (properties) of one Suppa 1.0 entity (read-only).",
1105
+ inputSchema: {
1106
+ entity: z.string().describe("Suppa 1.0 entity name or alias."),
1107
+ },
1108
+ annotations: _READ,
1109
+ }, async (a) => text(await migrate.readV1EntityProps(a.entity)));
1110
+ reg("suppa_read_v1_enum", {
1111
+ description: "Read a Suppa 1.0 custom-enum's values (read-only).",
1112
+ inputSchema: {
1113
+ enum: z
1114
+ .string()
1115
+ .describe("Enum_id (a UUID, or legacy numeric id) or enum name on Suppa 1.0."),
1116
+ },
1117
+ annotations: _READ,
1118
+ }, async (a) => text(await migrate.readV1Enum(a.enum)));
1119
+ // =========================================================================
1120
+ // Workspace & navigation menu tools
1121
+ // =========================================================================
1122
+ reg("suppa_create_workspace", {
1123
+ description: "Create a Workspace (and, by default, a NavigationMenu item linking to it).\n\n" +
1124
+ " Build the sidebar menuPanel form with suppa_create_form first, then pass its\n" +
1125
+ " id as sidebar_form_id. Relations are written as {id} for you.",
1126
+ inputSchema: {
1127
+ name: z.string(),
1128
+ alias: z
1129
+ .string()
1130
+ .nullable()
1131
+ .default(null)
1132
+ .describe("snake_case alias / route segment; defaults to a slug of name."),
1133
+ default_route: z
1134
+ .string()
1135
+ .nullable()
1136
+ .default(null)
1137
+ .describe("Workspace route; defaults to '/workspace/<alias>'."),
1138
+ sidebar_form_id: z
1139
+ .number()
1140
+ .int()
1141
+ .nullable()
1142
+ .default(null)
1143
+ .describe("Id of an existing Form to use as the sidebar (menuPanel)."),
1144
+ filter_form_id: z
1145
+ .number()
1146
+ .int()
1147
+ .nullable()
1148
+ .default(null)
1149
+ .describe("Id of an existing Form to use as the workspace filter."),
1150
+ add_nav_item: z
1151
+ .boolean()
1152
+ .default(true)
1153
+ .describe("Also create a NavigationMenu item linking to the workspace (default true)."),
1154
+ parent_menu_id: z
1155
+ .number()
1156
+ .int()
1157
+ .nullable()
1158
+ .default(null)
1159
+ .describe("Nest the nav item under this NavigationMenu id."),
1160
+ order: z
1161
+ .number()
1162
+ .nullable()
1163
+ .default(null)
1164
+ .describe("Sort order for the nav item."),
1165
+ },
1166
+ annotations: _ADD,
1167
+ }, async (a) => text(await workspace.createWorkspace(a.name, a.alias ?? undefined, a.default_route ?? undefined, a.sidebar_form_id ?? undefined, a.filter_form_id ?? undefined, a.add_nav_item, a.parent_menu_id ?? undefined, a.order ?? undefined)));
1168
+ reg("suppa_add_menu_item", {
1169
+ description: "Create a NavigationMenu item (sidebar/menu entry). Provide href or entity.",
1170
+ inputSchema: {
1171
+ name: z.string(),
1172
+ href: z
1173
+ .string()
1174
+ .nullable()
1175
+ .default(null)
1176
+ .describe("Route the item links to, e.g. '/workspace/sales'."),
1177
+ entity: z
1178
+ .string()
1179
+ .nullable()
1180
+ .default(null)
1181
+ .describe("Entity to link to (sets href='/entity/<Entity>' if href omitted)."),
1182
+ icon: z.string().nullable().default(null).describe("Icon reference."),
1183
+ order: z
1184
+ .number()
1185
+ .nullable()
1186
+ .default(null)
1187
+ .describe("Sort order among siblings."),
1188
+ parent_id: z
1189
+ .number()
1190
+ .int()
1191
+ .nullable()
1192
+ .default(null)
1193
+ .describe("Parent NavigationMenu id to nest under."),
1194
+ menu_type: z
1195
+ .string()
1196
+ .nullable()
1197
+ .default(null)
1198
+ .describe("Optional NavigationMenu 'type' value."),
1199
+ form_id: z
1200
+ .number()
1201
+ .int()
1202
+ .nullable()
1203
+ .default(null)
1204
+ .describe("Bind a Form to this item by id."),
1205
+ is_active: z.boolean().default(true),
1206
+ },
1207
+ annotations: _ADD,
1208
+ }, async (a) => text(await workspace.addMenuItem(a.name, a.href ?? undefined, a.entity ?? undefined, a.icon ?? undefined, a.order ?? undefined, a.parent_id ?? undefined, a.menu_type ?? undefined, a.form_id ?? undefined, a.is_active)));
1209
+ // =========================================================================
1210
+ // Forms tools
1211
+ // =========================================================================
1212
+ reg("suppa_list_forms", {
1213
+ description: "List forms. Optionally filter by entity name or form type (e.g. 'elementForm').",
1214
+ inputSchema: {
1215
+ entity_name: z
1216
+ .string()
1217
+ .nullable()
1218
+ .default(null)
1219
+ .describe("Only forms bound to this entity."),
1220
+ form_type: z
1221
+ .string()
1222
+ .nullable()
1223
+ .default(null)
1224
+ .describe("e.g. 'elementForm'."),
1225
+ limit: z.number().int().default(50),
1226
+ },
1227
+ annotations: _READ,
1228
+ }, async (a) => text(await forms.listForms(a.entity_name, a.form_type, a.limit)));
1229
+ reg("suppa_get_form", {
1230
+ description: "Get a form by ID with full schema (data.formShema) and settings.",
1231
+ inputSchema: { form_id: z.number().int() },
1232
+ annotations: _READ,
1233
+ }, async (a) => text(await forms.getForm(a.form_id)));
1234
+ reg("suppa_create_form", {
1235
+ description: "Create a new form. Provide schema_json (array of fields or {formShema}), or set\n" +
1236
+ " generate_from_entity=True with entity_name to auto-build fields from the entity.\n" +
1237
+ " Form names are UNIQUE platform-wide — a duplicate name fails; pick a distinct one.",
1238
+ inputSchema: {
1239
+ name: z.string(),
1240
+ form_type: z
1241
+ .string()
1242
+ .default("elementForm")
1243
+ .describe("Platform form type; 'elementForm' (default) is the standard record form."),
1244
+ entity_name: z
1245
+ .string()
1246
+ .nullable()
1247
+ .default(null)
1248
+ .describe("Entity to bind the form to."),
1249
+ alias: z.string().nullable().default(null),
1250
+ is_public: z.boolean().default(false),
1251
+ schema_json: z
1252
+ .string()
1253
+ .nullable()
1254
+ .default(null)
1255
+ .describe("JSON array of field objects, or {formShema, formSettings} (platform spelling 'formShema' is intentional)."),
1256
+ settings_json: z
1257
+ .string()
1258
+ .nullable()
1259
+ .default(null)
1260
+ .describe("JSON object of formSettings overrides; wins over the columns/form_type args."),
1261
+ generate_from_entity: z
1262
+ .boolean()
1263
+ .default(false)
1264
+ .describe("true = auto-build the fields from entity_name's schema."),
1265
+ fields: GenFields.default(null),
1266
+ columns: FormColumns.default(1),
1267
+ module_code: z
1268
+ .string()
1269
+ .nullable()
1270
+ .default(null)
1271
+ .describe("Optional JS module (data.formModul)."),
1272
+ },
1273
+ annotations: _ADD,
1274
+ }, async (a) => text(await forms.createForm(a.name, a.form_type, a.entity_name, a.alias, a.is_public, a.schema_json, a.settings_json, a.generate_from_entity, a.fields, a.columns, a.module_code)));
1275
+ reg("suppa_update_form", {
1276
+ description: "Update a form's name, schema (data.formShema), settings, or module code.\n" +
1277
+ " Form names are UNIQUE platform-wide — renaming to an existing name fails.\n\n" +
1278
+ " APPROVAL GATE: without confirm=true this returns a confirmation request and\n" +
1279
+ " changes nothing. Get the user's approval, then re-call with confirm=true.",
1280
+ inputSchema: {
1281
+ form_id: z.number().int(),
1282
+ name: z.string().nullable().default(null),
1283
+ schema_json: z
1284
+ .string()
1285
+ .nullable()
1286
+ .default(null)
1287
+ .describe("JSON array of field objects, or {formShema, formSettings} — replaces data.formShema (platform spelling intentional)."),
1288
+ settings_json: z
1289
+ .string()
1290
+ .nullable()
1291
+ .default(null)
1292
+ .describe("JSON object merged into formSettings."),
1293
+ module_code: z
1294
+ .string()
1295
+ .nullable()
1296
+ .default(null)
1297
+ .describe("JS module (data.formModul); replaces the existing one."),
1298
+ confirm: Confirm,
1299
+ },
1300
+ annotations: _MUT,
1301
+ }, async (a) => {
1302
+ if (!a.confirm) {
1303
+ const entries = [
1304
+ ["name", a.name],
1305
+ ["schema_json", a.schema_json],
1306
+ ["settings_json", a.settings_json],
1307
+ ["module_code", a.module_code],
1308
+ ];
1309
+ const changes = {};
1310
+ for (const [k, v] of entries) {
1311
+ if (v !== null && v !== undefined)
1312
+ changes[k] = v;
1313
+ }
1314
+ return text(confirmRequired("update form", { form_id: a.form_id }, changes));
1315
+ }
1316
+ return text(await forms.updateForm(a.form_id, a.name, a.schema_json, a.settings_json, a.module_code));
1317
+ });
1318
+ reg("suppa_generate_form_schema", {
1319
+ description: "Auto-generate a form schema (formShema + formSettings) from an entity's fields.\n" +
1320
+ " Returns JSON usable as create_form's schema_json. 'fields' limits/orders included fields.",
1321
+ inputSchema: {
1322
+ entity_name: EntityName,
1323
+ columns: FormColumns.default(1),
1324
+ fields: GenFields.default(null),
1325
+ },
1326
+ annotations: _READ,
1327
+ }, async (a) => text(await forms.generateFormSchema(a.entity_name, a.columns, a.fields)));
1328
+ reg("suppa_add_field_to_form", {
1329
+ description: "Append a field to a form's schema. Types: text, textarea, richtext, date, select, userSelect, files, toogle, etc.\n\n" +
1330
+ " This modifies an existing form (data.formShema). APPROVAL GATE: without\n" +
1331
+ " confirm=true this returns a confirmation request and changes nothing. Get\n" +
1332
+ " the user's approval, then re-call with confirm=true.",
1333
+ inputSchema: {
1334
+ form_id: z.number().int(),
1335
+ field_name: z
1336
+ .string()
1337
+ .describe("Field key in the submitted form data."),
1338
+ field_type: z
1339
+ .string()
1340
+ .default("text")
1341
+ .describe("Form field type (see suppa_list_form_field_types); note 'toogle' is the platform's spelling."),
1342
+ label: z.string().nullable().default(null),
1343
+ required: z.boolean().default(false),
1344
+ extra_json: z
1345
+ .string()
1346
+ .nullable()
1347
+ .default(null)
1348
+ .describe('JSON object of extra field props merged in, e.g. {"inputType": "number", "rules": ["numeric"]}.'),
1349
+ confirm: Confirm,
1350
+ },
1351
+ annotations: _ADD,
1352
+ }, async (a) => {
1353
+ if (!a.confirm) {
1354
+ const entries = [
1355
+ ["field_name", a.field_name],
1356
+ ["field_type", a.field_type],
1357
+ ["label", a.label],
1358
+ ["required", a.required || null],
1359
+ ["extra_json", a.extra_json],
1360
+ ];
1361
+ const changes = {};
1362
+ for (const [k, v] of entries) {
1363
+ if (v !== null && v !== undefined)
1364
+ changes[k] = v;
1365
+ }
1366
+ return text(confirmRequired("add field to form", { form_id: a.form_id }, changes));
1367
+ }
1368
+ return text(await forms.addFieldToForm(a.form_id, a.field_name, a.field_type, a.label, a.required, a.extra_json));
1369
+ });
1370
+ reg("suppa_list_form_field_types", {
1371
+ description: "List the available form field types.",
1372
+ annotations: _READ,
1373
+ }, async () => text(await forms.listFormFieldTypes()));
1374
+ // =========================================================================
1375
+ // Multi-tenant — switch between Suppa instances
1376
+ // =========================================================================
1377
+ reg("suppa_login", {
1378
+ description: "Sign in to a Suppa tenant via Google — call this whenever the user is not\n" +
1379
+ " authenticated (no need to ask them for a key; there isn't one).\n\n" +
1380
+ " Opens a Google sign-in page in the user's default browser (a local page at\n" +
1381
+ " http://localhost:8080) and BLOCKS until they pick an account, then exchanges\n" +
1382
+ " the Google identity for Suppa tokens and stores them in the OS keychain\n" +
1383
+ " (auto-refreshed afterwards — a one-time step per tenant). Tell the user a\n" +
1384
+ " sign-in page has opened and to finish there; if the browser didn't open, the\n" +
1385
+ ' returned JSON includes a URL to open manually. Returns {"status":"ok", ...}\n' +
1386
+ ' on success, or {"error": ...} (e.g. the localhost origin isn\'t whitelisted in\n' +
1387
+ " the Google OAuth client, or the account isn't a member of that tenant).\n" +
1388
+ " After a successful login, retry whatever the user originally asked for.\n\n" +
1389
+ " tenant: alias / host / URL (default: the active tenant).",
1390
+ inputSchema: { tenant: TenantArg.default("") },
1391
+ annotations: _ADD,
1392
+ }, async (a) => text(await auth.login(a.tenant)));
1393
+ reg("suppa_use_tenant", {
1394
+ description: "Switch the active Suppa tenant for this session. Accepts a known alias\n" +
1395
+ " ('testing'), a host ('testing.modern.me'), or a full URL. New tenants are\n" +
1396
+ " remembered. Subsequent tool calls hit the selected tenant.",
1397
+ inputSchema: { tenant: TenantArg },
1398
+ annotations: _ADD,
1399
+ }, async (a) => text(tenants.useTenant(a.tenant)));
1400
+ reg("suppa_list_tenants", {
1401
+ description: "List known Suppa tenants — which one is active and whether each is authenticated.",
1402
+ annotations: _READ,
1403
+ }, async () => text(tenants.listTenants()));
1404
+ reg("suppa_logout", {
1405
+ description: "Remove stored keychain credentials for a tenant (default: the active one).",
1406
+ inputSchema: { tenant: TenantArg.default("") },
1407
+ annotations: _MUT,
1408
+ }, async (a) => text(tenants.logout(a.tenant)));
1409
+ reg("suppa_diagnostics", {
1410
+ description: "Validate the whole multi-tenant setup in one report.\n\n" +
1411
+ " Checks environment prerequisites (keychain backend, Google client id, login\n" +
1412
+ " origin to whitelist, registry) and, per known tenant, its registration,\n" +
1413
+ " stored credentials, expiry and — when deep=true — a live authenticated call\n" +
1414
+ " that also exercises token refresh. Use this to confirm tenants are\n" +
1415
+ " configured correctly. Returns JSON with a status, per-tenant rows, and warnings.",
1416
+ inputSchema: {
1417
+ deep: z
1418
+ .boolean()
1419
+ .default(true)
1420
+ .describe("true = also make a live authenticated call per tenant (exercises token refresh)."),
1421
+ },
1422
+ annotations: _READ,
1423
+ }, async (a) => text(await tenants.diagnostics(a.deep)));
1424
+ reg("suppa_health_check", {
1425
+ description: "Health check for stdio clients.\n\n" +
1426
+ " - deep=false: configuration-only (token present)\n" +
1427
+ " - deep=true: configuration + upstream connectivity check\n ",
1428
+ inputSchema: {
1429
+ deep: z
1430
+ .boolean()
1431
+ .default(true)
1432
+ .describe("true = also check upstream connectivity."),
1433
+ },
1434
+ annotations: _READ,
1435
+ }, async (a) => text(await healthCheck(a.deep)));
1436
+ // =========================================================================
1437
+ // Prompts — guided workflows clients can expose as slash commands.
1438
+ // Faithful 1:1 port of server.py's @mcp.prompt functions.
1439
+ // =========================================================================
1440
+ const regPrompt = (name, cfg, build) => {
1441
+ server.registerPrompt(name, {
1442
+ description: cfg.description,
1443
+ argsSchema: (cfg.argsSchema ?? {}),
1444
+ }, ((args) => ({
1445
+ messages: [
1446
+ { role: "user", content: { type: "text", text: build(args ?? {}) } },
1447
+ ],
1448
+ })));
1449
+ PROMPT_NAMES.push(name);
1450
+ };
1451
+ regPrompt("plan_my_day", { description: "Triage my Suppa tasks into a prioritized day plan" }, () => "Build my day plan from Suppa:\n" +
1452
+ "1. suppa_get_me for who I am; suppa_count_tasks(my=true, active=true) for scale.\n" +
1453
+ "2. suppa_search_tasks(my=true, overdue=true) and suppa_search_tasks(my=true, due_today=true) — page with next_offset if has_more.\n" +
1454
+ "3. Also fetch suppa_search_tasks(my=true, active=true, limit=20) for context.\n" +
1455
+ "4. Produce a prioritized plan: overdue first (oldest deadline first), then due today, then notable active items. " +
1456
+ "For each: title, project, deadline, stage, and a one-line suggested next action.\n" +
1457
+ "5. Don't change anything — read-only. Offer to move/close/comment on specific tasks afterwards.");
1458
+ regPrompt("build_entity", {
1459
+ description: "Guided: design and create a new entity with fields, enums, and an auto-generated form",
1460
+ argsSchema: {
1461
+ entity_purpose: z
1462
+ .string()
1463
+ .describe("What the new entity is for — its purpose / the data it should hold."),
1464
+ },
1465
+ }, (a) => `Help me create a new Suppa entity for: ${a.entity_purpose}\n\n` +
1466
+ "Follow this workflow:\n" +
1467
+ "1. Check suppa_list_entities for an existing entity covering this — never duplicate.\n" +
1468
+ "2. Propose a design: PascalCase entity name, camelCase fields with real 2.0 types " +
1469
+ "(suppa_list_field_types; remember: timestamp+sub_type='date' for dates, multi-language for localized text, " +
1470
+ "many-to-one + relation_entity for references, enum + enum_name for fixed choices). Show the design and wait for my approval.\n" +
1471
+ " If any part is a set of repeating rows owned by one record (line-items, 'X by category', " +
1472
+ "per-period breakdowns), model it as a TABULAR PART of the parent — not a separate entity.\n" +
1473
+ "3. Create it: suppa_create_entity, then suppa_add_field per field; for enums add values first via suppa_add_enum_values " +
1474
+ "(qualified 'Entity.field' key). For each tabular part: suppa_create_tabular_part(parent_entity, name, ...) " +
1475
+ "then suppa_add_field on the returned entity_name (the `owner` link is created for you).\n" +
1476
+ "4. Verify with suppa_describe_entity, and suppa_list_tabular_parts(parent) for any tabular parts.\n" +
1477
+ "5. Offer a form: suppa_create_form(generate_from_entity=true, entity_name=...). \n" +
1478
+ "Schema is add-only — fields cannot be removed via this server, so get the design right before creating.");
1479
+ regPrompt("migrate_from_v1", {
1480
+ description: "Guided Suppa 1.0 → 2.0 schema migration (dry-run, review, execute)",
1481
+ argsSchema: {
1482
+ entity_names: z
1483
+ .string()
1484
+ .default("")
1485
+ .describe("Comma-separated 1.0 entity names/aliases to migrate; empty = all custom 1.0 entities."),
1486
+ },
1487
+ }, (a) => {
1488
+ const entityNames = a.entity_names ?? "";
1489
+ const scope = entityNames
1490
+ ? `only these 1.0 entities: ${entityNames}`
1491
+ : "all custom 1.0 entities";
1492
+ return (`Migrate ${scope} from Suppa 1.0 into the active 2.0 tenant, safely:\n` +
1493
+ "1. Confirm the target: suppa_list_tenants — make sure the active tenant is the intended one.\n" +
1494
+ `2. Dry run: suppa_migrate_entities_from_v1(dry_run=true, entity_names="${entityNames}", ` +
1495
+ 'output_file="migration_plan.json").\n' +
1496
+ "3. Walk me through the plan: entity/field renames, type mappings, enum values, relation targets, and every warning. " +
1497
+ "Apply any corrections I ask for by editing migration_plan.json.\n" +
1498
+ '4. Only after my explicit approval: suppa_migrate_entities_from_v1(dry_run=false, plan_file="migration_plan.json").\n' +
1499
+ "5. Verify: suppa_describe_entity for each migrated entity; report failures from the execution report.");
1500
+ });
1501
+ return server;
1502
+ }
1503
+ /**
1504
+ * Health check for stdio clients — faithful port of server.py's suppa_health_check.
1505
+ */
1506
+ async function healthCheck(deep = true) {
1507
+ const ctx = tenants.current();
1508
+ const token = ctx.getToken();
1509
+ const body = {
1510
+ service: "suppa-mcp",
1511
+ tenant: ctx.host,
1512
+ base_url: ctx.baseUrl,
1513
+ token_configured: Boolean(token),
1514
+ };
1515
+ if (!token) {
1516
+ body.status = "unconfigured";
1517
+ body.error =
1518
+ "No credentials for this tenant — set SUPPA_API_KEY or run suppa_login";
1519
+ return jsonResponse(body);
1520
+ }
1521
+ body.status = "ok";
1522
+ if (deep) {
1523
+ try {
1524
+ const res = JSON.parse(await entity.listEntities(""));
1525
+ body.entities_visible = Array.isArray(res) ? res.length : null;
1526
+ }
1527
+ catch (ex) {
1528
+ body.status = "degraded";
1529
+ body.error = ex instanceof Error ? ex.message : String(ex);
1530
+ }
1531
+ }
1532
+ return jsonResponse(body);
1533
+ }