suppa-mcp-2 1.2.3 → 1.3.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 CHANGED
@@ -1,7 +1,7 @@
1
1
  /**
2
2
  * Suppa MCP Server — unified gateway to the Suppa platform.
3
3
  *
4
- * Faithful 1:1 port of the Python `suppa_mcp/server.py`. Wires all 79 tools,
4
+ * Faithful 1:1 port of the Python `suppa_mcp/server.py`. Wires all 84 tools,
5
5
  * mirrors the tool-behavior annotations (_READ/_ADD/_MUT), reproduces the
6
6
  * server `instructions` string verbatim, and OWNS all confirm-gating (the tool
7
7
  * modules mutate unconditionally, exactly like the Python tool functions).
@@ -34,6 +34,16 @@ const _MUT = {
34
34
  destructiveHint: true,
35
35
  idempotentHint: true,
36
36
  };
37
+ // An UNDO writes, but it destroys nothing — it puts data BACK. Hosts turn
38
+ // destructiveHint into a "this may destroy data" warning, which is precisely
39
+ // the wrong thing to show in front of a recovery action (a user who hesitates
40
+ // there loses the record they were trying to save). It keeps the confirm gate:
41
+ // restoring still changes what every normal read returns.
42
+ const _UNDO = {
43
+ readOnlyHint: false,
44
+ destructiveHint: false,
45
+ idempotentHint: true,
46
+ };
37
47
  // ---------------------------------------------------------------------------
38
48
  // Shared parameter types: Field descriptions land in the tools' inputSchema, so
39
49
  // the model sees the format guidance at call time — not only in the docstring.
@@ -47,10 +57,52 @@ const ProjectionJson = z
47
57
  .string()
48
58
  .describe('JSON projection of fields to return, e.g. {"id": true, "title": true, ' +
49
59
  '"owner": {"id": true, "fullName": true}}. Enums: {"myEnum": {"value": true}}.');
60
+ // Soft-delete read scoping. Both mirror the platform's own defaults
61
+ // (captures/api-entity-builder-data.txt:75-76) — this server used to force
62
+ // includeDeletedRelations=false, which silently hid soft-deleted relations.
63
+ const DeletedScopeArg = z
64
+ .enum(["active", "deleted", "all"])
65
+ .default("active")
66
+ .describe("Which records to return w.r.t. soft deletion: 'active' (default — hides " +
67
+ "soft-deleted rows), 'deleted' (ONLY soft-deleted rows — use this to find a " +
68
+ "record's id for suppa_restore_record), 'all' (both).");
69
+ const IncludeDeletedRelationsArg = z
70
+ .boolean()
71
+ .default(true)
72
+ .describe("Keep RELATED records that are soft-deleted (platform default true). Set false " +
73
+ "to see only live relations — note that then a deleted relation is " +
74
+ "indistinguishable from one that was never set.");
50
75
  const RecordValuesJson = z
51
76
  .string()
52
77
  .describe('JSON object of field values. Relations/enums as {"id": N}, e.g. ' +
53
78
  '{"title": "X", "customer": {"id": 7}, "status": {"id": 12}}.');
79
+ // create_record only: the same object, or an ARRAY of them for a batch insert
80
+ // (data.txt:323 — insert's `fields` is "Array of records to insert").
81
+ const RecordValuesOrBatchJson = z
82
+ .string()
83
+ .describe('JSON object of field values — or a JSON ARRAY of such objects to create many ' +
84
+ 'in one request. Relations/enums as {"id": N}, e.g. {"title": "X", ' +
85
+ '"customer": {"id": 7}}; batch: [{"title": "A"}, {"title": "B"}].');
86
+ const MergeNamesJson = z
87
+ .string()
88
+ .nullable()
89
+ .describe('JSON array of field NAMES from fields_json to MERGE instead of replace, e.g. ' +
90
+ '["watchers"] — the items you send are ADDED to the stored list and the ' +
91
+ "existing ones are kept (without this the list is REPLACED wholesale). Every " +
92
+ "name must also appear in fields_json with an array value and must not appear " +
93
+ "in unmerge_json. There is no cap on how many items one list may carry: the " +
94
+ "platform reads the current values before writing, so the bound is on RECORDS " +
95
+ 'MATCHED — an update matching more than 500 records fails with "Cannot perform ' +
96
+ "'merge'/'unmerge': update query returned maximum allowed records; limit is " +
97
+ '500." This tool updates ONE record by id, so it cannot reach that bound.');
98
+ const UnmergeNamesJson = z
99
+ .string()
100
+ .nullable()
101
+ .describe('JSON array of field NAMES from fields_json to UNMERGE, e.g. ["watchers"] — the ' +
102
+ "items you send are REMOVED from the stored list and the rest are kept. Same " +
103
+ "rules as merge_json (name must be in fields_json with an array value, not in " +
104
+ "both lists; no item-count cap — the platform's 500 limit bounds the RECORDS an " +
105
+ "update matches, and this tool matches one record by id).");
54
106
  const TenantArg = z
55
107
  .string()
56
108
  .describe("Tenant alias ('testing'), host ('testing.modern.me'), or full URL.");
@@ -66,6 +118,23 @@ const BlocksJson = z
66
118
  const EntityName = z
67
119
  .string()
68
120
  .describe("Exact entity name, e.g. 'Tasks' — discover via suppa_list_entities.");
121
+ // Entity Options (captures/api-entity-builder-builder.txt:74-90) — the platform's
122
+ // 15 per-entity features. The TIP at :91-92 is quoted in full: enabling one is a
123
+ // schema change (it creates the backing side table), not a preference toggle.
124
+ const EntityOptionsJson = z
125
+ .string()
126
+ .nullable()
127
+ .default(null)
128
+ .describe('Entity options as a JSON object, e.g. {"comments": true, "globalSearch": true, ' +
129
+ '"hierarchy": "multi"}. Keys: comments, reactions, hierarchy ("single"|"multi"), ' +
130
+ 'folders ("single"|"multi"), trackChangeHistory, browsingHistory (boolean or number), ' +
131
+ "globalSearch, timeTracking, favorites, pinned, approvals, checklists, recurrence, " +
132
+ "reminders, notificationMutes — everything but hierarchy, folders and browsingHistory " +
133
+ "is a boolean. Unknown keys are refused (the platform would drop them silently). " +
134
+ "Enabling an option creates the side table that backs it, and recurrence, reminders, " +
135
+ "notificationMutes, timeTracking and pinned also refresh the corresponding system " +
136
+ "entity's cache — so this is not a free toggle. Options can also be changed later " +
137
+ "with suppa_update_entity_options.");
69
138
  const TaskSearch = z.string().describe("Free-text search over task titles.");
70
139
  const MyFlag = z
71
140
  .boolean()
@@ -140,53 +209,62 @@ const EntityQuery = z
140
209
  // ---------------------------------------------------------------------------
141
210
  // Server instructions — reproduced VERBATIM from server.py.
142
211
  // ---------------------------------------------------------------------------
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
- - Record writes are validated against the live schema BEFORE writing: an unknown field name or a non-existent entity is REFUSED (the platform silently drops unknown keys → a record missing data). Use only real fields (suppa_describe_entity), or add the field first with suppa_add_field. Don't invent field names.
162
- - READ enum fields back as objects: project {"myEnum": {"value": true}} and read .value, never as a bare string.
163
- - HTML content (descriptions, comments, blocks): plain text is auto-wrapped in <p>…</p>; to pass raw HTML start the string with <.
164
- - A document's LAST page cannot be deleted (platform rule) — delete the doc itself instead.
165
-
166
- SEARCH & FILTERS
167
- - Filters: {"field": "name", "value": "...", "comparator": "="} — comparators: =, !=, <, >, <=, >=, like, in, is null, is not null.
168
- - 'like' requires SQL wildcards: %substring%. 'in' takes a JSON array value.
169
- - Filters combine with AND by default; pass match_any=true (search_records) for OR.
170
- - Dotted field paths work in filters: "stage.status.value", "owner.id".
171
- - Magic value "$current-user" resolves to the authenticated user's ID.
172
- - Project only the fields you need (fields_json) — it keeps responses small and fast.
173
- - 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.
174
- - One record by id: suppa_get_record (any entity) / suppa_get_task / suppa_get_doc — no filters needed.
175
- - Discover schema first when unsure: suppa_list_entities → suppa_describe_entity, then suppa_search_records.
176
-
177
- APPROVAL GATES (human-in-the-loop)
178
- - Every update/move/close/delete tool returns {"status": "confirmation_required"} when called without confirm=true, and performs NOTHING.
179
- - 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.
180
- - Create/read tools (and comments) need no confirmation.
181
-
182
- ENTITY BUILDER (add-only by design)
183
- - Real field types only: text, numeric, integer, serial, boolean, timestamp, json, uuid, multi-language, icon, enum, multi-enum, file, multi-file, many-to-one, 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.
184
- - OWNED CHILD COLLECTIONS ARE TABULAR PARTS. Repeating rows that belong to one parent record (e.g. a part's BOM items) → suppa_create_tabular_part(parent_entity, name), which auto-creates the child's 'owner' relation and the parent link. NEVER model this by hand as parent.one-to-many + child.owner: suppa_add_field REFUSES field_type='one-to-many'. Use 'many-to-many' only for a shared lookup referenced by many records.
185
- - Relations need relation_entity; enums need enum_name (qualified 'Entity.field') with values added via suppa_add_enum_values.
186
- - Removing/altering existing fields is UI-only by design — this server can only add.
187
-
188
- MIGRATION (Suppa 1.0 → 2.0)
189
- - 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.
212
+ const INSTRUCTIONS = `Suppa Platform MCP Server — manage Tasks, Docs/Pages, Entities, Forms, and file attachments on modern.suppa.me.
213
+
214
+ AUTHENTICATION — RESOLVE THIS BEFORE ANY OTHER SUPPA WORK
215
+ - 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.
216
+ - 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.
217
+ - 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:
218
+ 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.
219
+ 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.
220
+ 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.
221
+ - 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.
222
+ - 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.
223
+ - suppa_use_tenant switches the active instance for ALL later calls; suppa_list_tenants shows what's known and authenticated.
224
+
225
+ DATA BASICS
226
+ - IDs are integers (not UUIDs).
227
+ - 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.
228
+ - Task deadlines also accept 'today', 'tomorrow', '+3d', '+2h', '+30m', '+1w'.
229
+ - 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.
230
+ - REPLACE vs MERGE — an update REPLACES a list-valued field. {"watchers": [{"id": 15}]} does NOT add watcher 15; it makes 15 the ONLY watcher and the others are gone. To ADD items pass their field names in suppa_update_record's merge_json (e.g. ["watchers"]); to REMOVE only the items you list, pass them in unmerge_json. Every merged/unmerged name must also be in fields_json with an array value and no name may be in both lists; there is no cap on list length — the platform's 500 bounds the RECORDS one merge/unmerge update matches ("Cannot perform 'merge'/'unmerge': update query returned maximum allowed records; limit is 500"), and suppa_update_record matches a single record by id. suppa_update_task / suppa_update_doc / suppa_update_page / suppa_update_block have NO merge option — every list-valued field they write is replaced wholesale.
231
+ - DELETE IS A SOFT DELETE — every delete tool here sets deletedAt and leaves the row in the database; the delete is reversible with suppa_restore_record(entity_name, record_id). Don't tell the user their data was destroyed. It still needs confirm=true, because the record disappears from all normal reads.
232
+ - PERMANENT DELETE IS UNAVAILABLE HERE, BY DESIGN — this server performs REVERSIBLE deletes only. The platform's PERMANENT delete (POST /core/data/:entityName/delete: the rows leave the table and cannot be restored) is BLOCKED in the HTTP client itself, so no tool, no flag, no confirm=true and no direct call can reach it; an attempt is refused before the request is sent. Don't look for a tool, a parameter or a workaround — there is none. If a user asks to erase data for good, say so plainly and offer the soft delete (suppa_delete_record → /remove, undone by suppa_restore_record); permanent removal has to be done by an admin in the platform's own UI.
233
+ - FINDING A DELETED RECORD — soft-deleted rows are hidden from every normal read. suppa_search_records / suppa_get_record take deleted_scope: 'active' (default), 'deleted' (only removed rows — this is how you get the id for suppa_restore_record), or 'all'. Project deletedAt to see which rows are removed and when.
234
+ - Record writes are validated against the live schema BEFORE writing: an unknown field name or a non-existent entity is REFUSED (the platform silently drops unknown keys → a record missing data). Use only real fields (suppa_describe_entity), or add the field first with suppa_add_field. Don't invent field names.
235
+ - READ enum fields back as objects: project {"myEnum": {"value": true}} and read .value, never as a bare string.
236
+ - HTML content (descriptions, comments, blocks): plain text is auto-wrapped in <p>…</p>; to pass raw HTML start the string with <.
237
+ - A document's LAST page cannot be deleted (platform rule) — delete the doc itself instead.
238
+
239
+ SEARCH & FILTERS
240
+ - Filters: {"field": "name", "value": "...", "comparator": "="} — comparators: =, !=, <, >, <=, >=, like, in, is null, is not null.
241
+ - 'like' requires SQL wildcards: %substring%. 'in' takes a JSON array value.
242
+ - Filters combine with AND by default; pass match_any=true (search_records) for OR.
243
+ - MIXED AND/OR IN ONE CALL — a filters_json entry may be a nested GROUP {"operator": "and"|"or", "filters": [...]} (shorthand: {"or": [...]}), nested to any depth. (status=open AND owner=me) OR priority=high is: [{"or": [{"and": [{"field":"status.value","value":"open","comparator":"="},{"field":"owner.id","value":"$current-user","comparator":"="}]},{"field":"priority.value","value":"high","comparator":"="}]}]. Don't run several searches and merge them yourself.
244
+ - AN EMPTY SEARCH RESULT IS DIAGNOSED FOR YOU — a misspelled field returns no records rather than an error, so suppa_search_records validates the payload (select/validate) whenever it gets zero rows or a 400 and returns a "validation" block naming the reference that does not resolve. Read it before concluding "there is no such data". suppa_validate_select does the same check on demand, without running the query.
245
+ - CREATING MANY RECORDS — pass a JSON ARRAY to suppa_create_record's fields_json; the whole batch goes in ONE request with one schema check. Don't loop the tool per record.
246
+ - Dotted field paths work in filters: "stage.status.value", "owner.id".
247
+ - Magic value "$current-user" resolves to the authenticated user's ID.
248
+ - Project only the fields you need (fields_json) — it keeps responses small and fast.
249
+ - 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.
250
+ - One record by id: suppa_get_record (any entity) / suppa_get_task / suppa_get_doc — no filters needed.
251
+ - Discover schema first when unsure: suppa_list_entities → suppa_describe_entity, then suppa_search_records.
252
+
253
+ APPROVAL GATES (human-in-the-loop)
254
+ - Every update/move/close/delete tool returns {"status": "confirmation_required"} when called without confirm=true, and performs NOTHING.
255
+ - 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.
256
+ - Create/read tools (and comments) need no confirmation.
257
+
258
+ ENTITY BUILDER (create + edit fields; removal is UI-only)
259
+ - Real field types only: text, numeric, integer, serial, boolean, timestamp, json, uuid, multi-language, bytea, tsvector, multi-type, icon, enum, multi-enum, file, multi-file, many-to-one, 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.
260
+ - sub_type matrix: timestamp → 'date' | 'time' | 'timestamp'; text → 'encrypted'; enum/multi-enum → the enum's global name, set by the platform (never pass it); every other type takes none. Anything else is refused before the request.
261
+ - FIELD OPTIONS decide whether a field is usable: searchable, searchPriority (1-4), readOnly, canGroup, canSort, showInTable, editFromTable, canFilter. Pass options_json on suppa_add_field — a field created without them is missing from table views, and suppa_search_records' free-text search only covers fields marked searchable. Turn them on later with suppa_update_field.
262
+ - OWNED CHILD COLLECTIONS ARE TABULAR PARTS. Repeating rows that belong to one parent record (e.g. a part's BOM items) → suppa_create_tabular_part(parent_entity, name), which auto-creates the child's 'owner' relation and the parent link. NEVER model this by hand as parent.one-to-many + child.owner: suppa_add_field REFUSES field_type='one-to-many'. Use 'many-to-many' only for a shared lookup referenced by many records.
263
+ - Relations need relation_entity; enums need enum_name (qualified 'Entity.field') with values added via suppa_add_enum_values.
264
+ - Existing fields CAN be edited with suppa_update_field (name, title, notNull/unique/default, relation target, and the options above), within the platform's own limits: a field's TYPE can never be changed, its SUBTYPE only toggles 'encrypted' on/off (text fields only), and a system field takes just title + the options keys. Removing a field is still UI-only — this server has no remove-field call.
265
+
266
+ MIGRATION (Suppa 1.0 → 2.0)
267
+ - 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.
190
268
  `;
191
269
  // ---------------------------------------------------------------------------
192
270
  // Registered tool + prompt names (tests assert the counts).
@@ -197,11 +275,28 @@ export const PROMPT_NAMES = [];
197
275
  function text(result) {
198
276
  return { content: [{ type: "text", text: result }] };
199
277
  }
278
+ /**
279
+ * Best-effort read of a merge_json/unmerge_json argument for the confirmation
280
+ * preview. Malformed input yields [] here — updateRecord is the authority and
281
+ * rejects it with a proper message once the call is confirmed.
282
+ */
283
+ function nameList(raw) {
284
+ if (!raw) {
285
+ return [];
286
+ }
287
+ try {
288
+ const parsed = typeof raw === "string" ? JSON.parse(raw) : raw;
289
+ return Array.isArray(parsed) ? parsed.filter((n) => typeof n === "string") : [];
290
+ }
291
+ catch {
292
+ return [];
293
+ }
294
+ }
200
295
  export function buildServer() {
201
296
  // Reset so repeated buildServer() calls (e.g. in tests) do not double-count.
202
297
  TOOL_NAMES.length = 0;
203
298
  PROMPT_NAMES.length = 0;
204
- const server = new McpServer({ name: "suppa-2.0", version: "1.1.4" }, { instructions: INSTRUCTIONS });
299
+ const server = new McpServer({ name: "suppa-2.0", version: "1.3.0" }, { instructions: INSTRUCTIONS });
205
300
  const reg = (name, cfg, handler) => {
206
301
  server.registerTool(name, {
207
302
  description: cfg.description,
@@ -275,6 +370,9 @@ export function buildServer() {
275
370
  }, 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)));
276
371
  reg("suppa_update_task", {
277
372
  description: "Update fields on an existing task. Only provided fields are changed.\n\n" +
373
+ " Any list-valued field written here is REPLACED wholesale — this tool has no\n" +
374
+ " merge option. To ADD to / REMOVE from a task's list field, use\n" +
375
+ ' suppa_update_record("Tasks", ...) with merge_json / unmerge_json.\n\n' +
278
376
  " APPROVAL GATE: without confirm=true this returns a confirmation request and\n" +
279
377
  " changes nothing. Get the user's approval, then re-call with confirm=true.",
280
378
  inputSchema: {
@@ -315,6 +413,12 @@ export function buildServer() {
315
413
  });
316
414
  reg("suppa_delete_task", {
317
415
  description: "Soft-delete a task.\n\n" +
416
+ " SOFT DELETE: sets deletedAt — the row remains in the database and the delete\n" +
417
+ " is reversible: suppa_restore_record('Tasks', task_id) brings it back. The task\n" +
418
+ " does drop out of every normal read — find it again with\n" +
419
+ " suppa_search_records('Tasks', deleted_scope='deleted').\n\n" +
420
+ " NOT the platform's permanent delete (a separate endpoint where the rows leave\n" +
421
+ " the table and cannot be restored); that one is deliberately not exposed here.\n\n" +
318
422
  " APPROVAL GATE: without confirm=true this returns a confirmation request and\n" +
319
423
  " deletes nothing. Get the user's approval, then re-call with confirm=true.",
320
424
  inputSchema: { task_id: z.number().int(), confirm: Confirm },
@@ -448,6 +552,8 @@ export function buildServer() {
448
552
  }, async (a) => text(await docs.createDoc(a.title, a.is_public)));
449
553
  reg("suppa_update_doc", {
450
554
  description: "Update a document's title or visibility.\n\n" +
555
+ " Any list-valued field written here is REPLACED wholesale — this tool has no\n" +
556
+ ' merge option; use suppa_update_record("Docs", ...) with merge_json to add.\n\n' +
451
557
  " APPROVAL GATE: without confirm=true this returns a confirmation request and\n" +
452
558
  " changes nothing. Get the user's approval, then re-call with confirm=true.",
453
559
  inputSchema: {
@@ -469,7 +575,13 @@ export function buildServer() {
469
575
  return text(await docs.updateDoc(a.doc_id, a.title, a.is_public));
470
576
  });
471
577
  reg("suppa_delete_doc", {
472
- description: "Delete a document (and its pages).\n\n" +
578
+ description: "Soft-delete a document (and its pages).\n\n" +
579
+ " SOFT DELETE: sets deletedAt — the row remains in the database and the delete\n" +
580
+ " is reversible: suppa_restore_record('Docs', doc_id) brings it back. The doc\n" +
581
+ " does drop out of every normal read — find it again with\n" +
582
+ " suppa_search_records('Docs', deleted_scope='deleted').\n\n" +
583
+ " NOT the platform's permanent delete (a separate endpoint where the rows leave\n" +
584
+ " the table and cannot be restored); that one is deliberately not exposed here.\n\n" +
473
585
  " APPROVAL GATE: without confirm=true this returns a confirmation request and\n" +
474
586
  " deletes nothing. Get the user's approval, then re-call with confirm=true.",
475
587
  inputSchema: { doc_id: z.number().int(), confirm: Confirm },
@@ -515,6 +627,8 @@ export function buildServer() {
515
627
  }, async (a) => text(await docs.createPage(a.doc_id, a.title, a.parent_id, a.description, a.icon)));
516
628
  reg("suppa_update_page", {
517
629
  description: "Update a page's metadata.\n\n" +
630
+ " Any list-valued field written here is REPLACED wholesale — this tool has no\n" +
631
+ ' merge option; use suppa_update_record("Pages", ...) with merge_json to add.\n\n' +
518
632
  " APPROVAL GATE: without confirm=true this returns a confirmation request and\n" +
519
633
  " changes nothing. Get the user's approval, then re-call with confirm=true.",
520
634
  inputSchema: {
@@ -544,8 +658,14 @@ export function buildServer() {
544
658
  return text(await docs.updatePage(a.page_id, a.title, a.description, a.icon, a.is_public));
545
659
  });
546
660
  reg("suppa_delete_page", {
547
- description: "Delete a page. The platform refuses to delete a document's LAST page\n" +
661
+ description: "Soft-delete a page. The platform refuses to delete a document's LAST page\n" +
548
662
  " (HTTP 400) — delete the whole doc instead (suppa_delete_doc).\n\n" +
663
+ " SOFT DELETE: sets deletedAt — the row remains in the database and the delete\n" +
664
+ " is reversible: suppa_restore_record('Pages', page_id) brings it back. The page\n" +
665
+ " does drop out of every normal read — find it again with\n" +
666
+ " suppa_search_records('Pages', deleted_scope='deleted').\n\n" +
667
+ " NOT the platform's permanent delete (a separate endpoint where the rows leave\n" +
668
+ " the table and cannot be restored); that one is deliberately not exposed here.\n\n" +
549
669
  " APPROVAL GATE: without confirm=true this returns a confirmation request and\n" +
550
670
  " deletes nothing. Get the user's approval, then re-call with confirm=true.",
551
671
  inputSchema: { page_id: z.number().int(), confirm: Confirm },
@@ -598,6 +718,9 @@ export function buildServer() {
598
718
  }, async (a) => text(await docs.insertBlock(a.page_id, a.blocks_json, a.after_id, a.before_id)));
599
719
  reg("suppa_update_block", {
600
720
  description: "Update a block's content. Provide title (text/HTML) or full properties_json.\n\n" +
721
+ " properties_json REPLACES the block's properties wholesale (as does any\n" +
722
+ " list-valued field) — this tool has no merge option; read the current\n" +
723
+ " properties with suppa_get_blocks first and re-send them in full.\n\n" +
601
724
  " APPROVAL GATE: without confirm=true this returns a confirmation request and\n" +
602
725
  " changes nothing. Get the user's approval, then re-call with confirm=true.",
603
726
  inputSchema: {
@@ -627,7 +750,13 @@ export function buildServer() {
627
750
  return text(await docs.updateBlock(a.block_id, a.title, a.properties_json));
628
751
  });
629
752
  reg("suppa_delete_block", {
630
- description: "Delete a content block.\n\n" +
753
+ description: "Soft-delete a content block.\n\n" +
754
+ " SOFT DELETE: sets deletedAt — the row remains in the database and the delete\n" +
755
+ " is reversible: suppa_restore_record('PageBlocks', block_id) brings it back. The\n" +
756
+ " block does drop out of every normal read — find it again with\n" +
757
+ " suppa_search_records('PageBlocks', deleted_scope='deleted').\n\n" +
758
+ " NOT the platform's permanent delete (a separate endpoint where the rows leave\n" +
759
+ " the table and cannot be restored); that one is deliberately not exposed here.\n\n" +
631
760
  " APPROVAL GATE: without confirm=true this returns a confirmation request and\n" +
632
761
  " deletes nothing. Get the user's approval, then re-call with confirm=true.",
633
762
  inputSchema: { block_id: z.number().int(), confirm: Confirm },
@@ -657,9 +786,23 @@ export function buildServer() {
657
786
  .nullable()
658
787
  .default(null)
659
788
  .describe("Place the moved blocks before this block id."),
789
+ confirm: Confirm,
660
790
  },
661
791
  annotations: _MUT,
662
- }, async (a) => text(await docs.reorderBlocks(a.page_id, a.block_ids, a.after_id, a.before_id)));
792
+ }, async (a) => {
793
+ // A move rearranges existing content, which is why it is annotated _MUT
794
+ // and why the server instructions promise a confirmation for every
795
+ // "update/move/close/delete" tool. It used to reorder on the first call.
796
+ if (!a.confirm) {
797
+ return text(confirmRequired("reorder blocks", {
798
+ page_id: a.page_id,
799
+ block_ids: a.block_ids,
800
+ after_id: a.after_id,
801
+ before_id: a.before_id,
802
+ }));
803
+ }
804
+ return text(await docs.reorderBlocks(a.page_id, a.block_ids, a.after_id, a.before_id));
805
+ });
663
806
  // =========================================================================
664
807
  // Entity tools
665
808
  // =========================================================================
@@ -691,9 +834,17 @@ export function buildServer() {
691
834
  reg("suppa_search_records", {
692
835
  description: "Search records of any entity. filters_json: [{field, value, comparator}]. fields_json: {field: true}.\n" +
693
836
  " match_any=true combines filters with OR instead of AND.\n" +
694
- " Returns {records, returned, has_more, next_offset} — page with offset until has_more is false.\n\n" +
837
+ ' NESTED GROUPS: a filters_json entry may be {"operator": "and"|"or", "filters": [...]}\n' +
838
+ " (nested to any depth), so (status=open AND owner=me) OR priority=high is ONE call.\n" +
839
+ " An EMPTY result (or a 400) is auto-diagnosed with select/validate: if the query\n" +
840
+ ' references a field that does not exist you get "validation" naming it, not silence.\n' +
841
+ " Returns {records, returned, has_more, next_offset, deleted_scope} — page with offset until has_more is false.\n\n" +
695
842
  " Enum fields read back as objects {value, title, id} — project them as\n" +
696
- ' {"myEnum": {"value": true}} and read .value, not as a bare string.',
843
+ ' {"myEnum": {"value": true}} and read .value, not as a bare string.\n\n' +
844
+ " SOFT-DELETED ROWS: deleted_scope='deleted' returns ONLY records that\n" +
845
+ " suppa_delete_record removed — that is how you find the id to hand to\n" +
846
+ " suppa_restore_record. 'all' returns live and removed together (removed\n" +
847
+ " ones carry a non-null deletedAt; project it to tell them apart).",
697
848
  inputSchema: {
698
849
  entity_name: z
699
850
  .string()
@@ -701,7 +852,8 @@ export function buildServer() {
701
852
  filters_json: z
702
853
  .string()
703
854
  .default("[]")
704
- .describe('JSON array of filters: [{"field": "status.value", "value": "active", "comparator": "="}]. \'like\' needs %wildcards%; dotted paths allowed.'),
855
+ .describe('JSON array of filters: [{"field": "status.value", "value": "active", "comparator": "="}]. \'like\' needs %wildcards%; dotted paths allowed. ' +
856
+ 'An entry may also be a NESTED GROUP {"operator": "and"|"or", "filters": [...]} (shorthand {"or": [...]}), so (a AND b) OR c is one call.'),
705
857
  fields_json: ProjectionJson.default('{"id": true}'),
706
858
  limit: z.number().int().default(20),
707
859
  offset: z.number().int().default(0),
@@ -717,22 +869,57 @@ export function buildServer() {
717
869
  .boolean()
718
870
  .default(false)
719
871
  .describe("true = combine filters with OR instead of AND."),
872
+ deleted_scope: DeletedScopeArg,
873
+ include_deleted_relations: IncludeDeletedRelationsArg,
720
874
  },
721
875
  annotations: _READ,
722
- }, 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)));
876
+ }, 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, a.deleted_scope, a.include_deleted_relations)));
877
+ reg("suppa_validate_select", {
878
+ description: "Check a search/select payload against the entity WITHOUT running it —\n" +
879
+ " POST /core/data/:entity/select/validate. Use it when a search returns\n" +
880
+ " nothing: a typo'd field name gives an EMPTY result, not an error, and this\n" +
881
+ ' turns that into {"valid": false, "invalidFields": [{path, location, kind,\n' +
882
+ " reason}]} naming the reference that does not resolve.\n\n" +
883
+ " suppa_search_records already runs this automatically on an empty result or\n" +
884
+ " a 400 — call it directly to pre-flight an expensive query.",
885
+ inputSchema: {
886
+ entity_name: EntityName,
887
+ filters_json: z
888
+ .string()
889
+ .default("[]")
890
+ .describe("Same filters_json as suppa_search_records — flat filters and/or nested " +
891
+ '{"operator": "and"|"or", "filters": [...]} groups.'),
892
+ fields_json: ProjectionJson.default('{"id": true}'),
893
+ order_by: z
894
+ .string()
895
+ .default("")
896
+ .describe("Optional 'field:asc' / 'field:desc' to validate too."),
897
+ match_any: z
898
+ .boolean()
899
+ .default(false)
900
+ .describe("true = the top-level group is OR instead of AND."),
901
+ },
902
+ annotations: _READ,
903
+ }, async (a) => text(await entity.validateSelectQuery(a.entity_name, a.filters_json, a.fields_json, a.order_by, a.match_any)));
723
904
  reg("suppa_get_record", {
724
905
  description: "Get a single record of any entity by id. fields_json: {field: true} projection —\n" +
725
- ' request only the fields you need (relations as nested objects, e.g. {"owner": {"id": true, "fullName": true}}).',
906
+ ' request only the fields you need (relations as nested objects, e.g. {"owner": {"id": true, "fullName": true}}).\n\n' +
907
+ " A soft-deleted record is NOT returned by default: read it with\n" +
908
+ " deleted_scope='deleted' (or 'all') to inspect it before calling\n" +
909
+ " suppa_restore_record.",
726
910
  inputSchema: {
727
911
  entity_name: EntityName,
728
912
  record_id: z.number().int(),
729
913
  fields_json: ProjectionJson.default('{"id": true}'),
914
+ deleted_scope: DeletedScopeArg,
915
+ include_deleted_relations: IncludeDeletedRelationsArg,
730
916
  },
731
917
  annotations: _READ,
732
- }, async (a) => text(await entity.getRecord(a.entity_name, a.record_id, a.fields_json)));
918
+ }, async (a) => text(await entity.getRecord(a.entity_name, a.record_id, a.fields_json, a.deleted_scope, a.include_deleted_relations)));
733
919
  reg("suppa_create_entity", {
734
920
  description: "Create a new entity (database table). By default also creates the display-title\n" +
735
- " field so records have a label and titleFieldName resolves to a real field.\n\n" +
921
+ " field so records have a label and titleFieldName resolves to a real field, and\n" +
922
+ " sets that field as the entity's representative (what the UI shows for a record).\n\n" +
736
923
  " NOT for repeating child rows that belong to one parent record (invoice\n" +
737
924
  ' line-items, "X by category", per-period breakdowns) — those must be a tabular\n' +
738
925
  " part: use suppa_create_tabular_part instead, or they end up as a stray separate\n" +
@@ -749,14 +936,61 @@ export function buildServer() {
749
936
  auto_title_field: z
750
937
  .boolean()
751
938
  .default(true)
752
- .describe("Also create the title field so records have a label (default true)."),
939
+ .describe("Also create the title field (and make it the representative) so records have a label (default true)."),
753
940
  title_field_type: z
754
941
  .string()
755
942
  .default("multi-language")
756
943
  .describe("Type for the auto-created title field (default 'multi-language')."),
944
+ options_json: EntityOptionsJson,
757
945
  },
758
946
  annotations: _ADD,
759
- }, async (a) => text(await entity.createEntity(a.name, a.title, a.title_field_name, a.auto_title_field, a.title_field_type)));
947
+ }, async (a) => text(await entity.createEntity(a.name, a.title, a.title_field_name, a.auto_title_field, a.title_field_type, a.options_json)));
948
+ reg("suppa_update_entity_options", {
949
+ description: "Turn the platform's per-entity FEATURES on or off (POST\n" +
950
+ " /core/builder/<entity>/update-options) — a narrower alternative to editing the\n" +
951
+ " entity that touches only options. This is the only way to reach comments,\n" +
952
+ " reactions, hierarchy, folders, change history, browsing history, global search,\n" +
953
+ " time tracking, favorites, pinned, approvals, checklists, recurrence, reminders\n" +
954
+ " and notification mutes from here; send only the ones you are changing.\n\n" +
955
+ " NOT A FREE TOGGLE: enabling an option CREATES the side table that backs it, and\n" +
956
+ " recurrence / reminders / notificationMutes / timeTracking / pinned also refresh\n" +
957
+ " the cache of the corresponding system entity. It is a schema change.\n\n" +
958
+ " RESTRICTIONS (builder.txt:250-264): on an entity created by the system\n" +
959
+ " (initiator='system') only options.globalSearch is accepted — the rest is dropped\n" +
960
+ " silently, so this server refuses the call instead. On a system-GENERATED entity\n" +
961
+ " (reserved suffix) enabling comments, timeTracking, pinned, favorites, approvals or\n" +
962
+ " checklists is forbidden; the docs do not list the suffixes, so that one can only\n" +
963
+ " be reported as a warning. The platform answers with the APPLIED options, which\n" +
964
+ " may be a subset of the request — anything missing is called out in the result.\n\n" +
965
+ " APPROVAL GATE: without confirm=true this returns a confirmation request and\n" +
966
+ " changes nothing. Get the user's approval, then re-call with confirm=true.",
967
+ inputSchema: {
968
+ entity_name: EntityName,
969
+ options_json: z
970
+ .string()
971
+ .describe('Entity options as a JSON object, e.g. {"comments": true, "globalSearch": true}. ' +
972
+ "Keys: comments, reactions, hierarchy (\"single\"|\"multi\"), folders " +
973
+ '("single"|"multi"), trackChangeHistory, browsingHistory (boolean or number), ' +
974
+ "globalSearch, timeTracking, favorites, pinned, approvals, checklists, " +
975
+ "recurrence, reminders, notificationMutes — everything but hierarchy, folders " +
976
+ "and browsingHistory is a boolean. Unknown keys are refused (the platform would " +
977
+ "drop them silently). Enabling an option creates the side table that backs it, " +
978
+ "and recurrence/reminders/notificationMutes/timeTracking/pinned also refresh the " +
979
+ "corresponding system entity's cache — so this is not a free toggle."),
980
+ confirm: Confirm,
981
+ },
982
+ annotations: _MUT,
983
+ }, async (a) => {
984
+ if (!a.confirm) {
985
+ return text(confirmRequired("update entity options", { entity: a.entity_name }, {
986
+ options: a.options_json,
987
+ side_effects: "Enabling an option creates the side table that backs it; recurrence, reminders, " +
988
+ "notificationMutes, timeTracking and pinned also refresh the corresponding system " +
989
+ "entity's cache (builder.txt:91-92).",
990
+ }));
991
+ }
992
+ return text(await entity.updateEntityOptions(a.entity_name, a.options_json));
993
+ });
760
994
  reg("suppa_create_tabular_part", {
761
995
  description: 'Create a tabular part (ТЧ / "таблична частина") — an owned child sub-table of\n' +
762
996
  " parent_entity, edited inline in the parent (like 1C invoice line-items).\n\n" +
@@ -780,7 +1014,7 @@ export function buildServer() {
780
1014
  auto_title_field: z
781
1015
  .boolean()
782
1016
  .default(true)
783
- .describe("Also create the title field (default true)."),
1017
+ .describe("Also create the title field and make it the row's representative (default true)."),
784
1018
  title_field_type: z
785
1019
  .string()
786
1020
  .default("multi-language")
@@ -796,13 +1030,22 @@ export function buildServer() {
796
1030
  reg("suppa_add_field", {
797
1031
  description: "Add a field to an entity.\n\n" +
798
1032
  " field_type: a real Suppa 2.0 type — text, numeric, integer, serial, boolean,\n" +
799
- " timestamp, json, uuid, multi-language, icon, enum, multi-enum, file, multi-file,\n" +
800
- " many-to-one, many-to-many, many-to-many-backref. There is NO\n" +
801
- " date/datetime/richtext/email/url/phone type — use timestamp (+sub_type='date'\n" +
802
- " for date-only) and multi-language for localized text. 'relation' is accepted\n" +
803
- " as an alias for many-to-one. Provide relation_entity for relations, enum_name\n" +
804
- " for enums. Constraints: max_length/min_length (text), decimal_places /\n" +
805
- " min_value / max_value / only_positive (numeric).\n" +
1033
+ " timestamp, json, uuid, multi-language, bytea, tsvector, multi-type, icon, enum,\n" +
1034
+ " multi-enum, file, multi-file, many-to-one, many-to-many, many-to-many-backref.\n" +
1035
+ " There is NO date/datetime/richtext/email/url/phone type — use timestamp\n" +
1036
+ " (+sub_type='date' for date-only) and multi-language for localized text.\n" +
1037
+ " 'relation' is accepted as an alias for many-to-one. Provide relation_entity for\n" +
1038
+ " relations, enum_name for enums. Constraints: max_length/min_length (text),\n" +
1039
+ " decimal_places / min_value / max_value / only_positive (numeric).\n" +
1040
+ " options_json decides whether the field is USABLE once created: showInTable,\n" +
1041
+ " canFilter, canSort, canGroup, editFromTable, readOnly, searchable +\n" +
1042
+ " searchPriority (1-4). A field created without them is absent from table views\n" +
1043
+ " and cannot be found by free-text search. They can be changed later with\n" +
1044
+ " suppa_update_field; the field's TYPE never can.\n" +
1045
+ " required=true makes the column NOT NULL and REQUIRES default_value (a SQL\n" +
1046
+ " expression or literal: '0', 'false', \"'draft'\", 'now()'); the call is refused\n" +
1047
+ " before any request if it is missing — no default is ever invented for you.\n" +
1048
+ " many-to-many / multi-enum take no default_value.\n" +
806
1049
  " 'one-to-many' is REFUSED: an owned child collection is a TABULAR PART\n" +
807
1050
  " (suppa_create_tabular_part, which auto-creates the child's 'owner' and the\n" +
808
1051
  " parent link); never hand-build parent.one-to-many + child.owner. Use\n" +
@@ -817,6 +1060,11 @@ export function buildServer() {
817
1060
  .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'. 'one-to-many' is refused — use suppa_create_tabular_part for owned children, 'many-to-many' for shared lookups."),
818
1061
  title: z.string().nullable().default(null),
819
1062
  required: z.boolean().default(false),
1063
+ default_value: z
1064
+ .string()
1065
+ .nullable()
1066
+ .default(null)
1067
+ .describe("Value for rows that leave the field empty — a SQL expression or literal ('0', 'false', \"'draft'\", 'now()'). REQUIRED when required=true (except many-to-many/multi-enum); the platform rejects NOT NULL without it."),
820
1068
  unique: z.boolean().default(false),
821
1069
  relation_entity: z
822
1070
  .string()
@@ -832,7 +1080,24 @@ export function buildServer() {
832
1080
  .string()
833
1081
  .nullable()
834
1082
  .default(null)
835
- .describe("'date' makes a timestamp date-only."),
1083
+ .describe("Refines the type — the documented matrix is exactly: timestamp → 'date' " +
1084
+ "(date-only column), 'time' (time-only) or 'timestamp' (default when omitted); " +
1085
+ "text → 'encrypted' (stored as an AES-GCM envelope, which forces unique, " +
1086
+ "searchable, canFilter, canSort and canGroup off and clears max_length/min_length). " +
1087
+ "On enum / multi-enum the platform sets subType itself to the enum's global name — " +
1088
+ "never pass one there. Every other type takes NO sub_type; an undocumented " +
1089
+ "combination is refused before the request."),
1090
+ options_json: z
1091
+ .string()
1092
+ .nullable()
1093
+ .default(null)
1094
+ .describe('Field options as a JSON object, e.g. {"searchable": true, "searchPriority": 3, ' +
1095
+ '"showInTable": true, "canSort": true}. Keys: searchable, searchPriority (1-4, ' +
1096
+ "higher = stronger weight), readOnly, canGroup, canSort, showInTable, " +
1097
+ "editFromTable, canFilter. WITHOUT these a new field does not appear in table " +
1098
+ "views and free-text search (suppa_search_records search=...) cannot see it — " +
1099
+ "only fields marked searchable participate. Unknown keys are refused here " +
1100
+ "(the platform would silently drop them)."),
836
1101
  max_length: z
837
1102
  .number()
838
1103
  .int()
@@ -869,6 +1134,7 @@ export function buildServer() {
869
1134
  annotations: _ADD,
870
1135
  }, async (a) => text(await entity.addField(a.entity_name, a.field_name, a.field_type, a.title, {
871
1136
  required: a.required,
1137
+ defaultValue: a.default_value,
872
1138
  unique: a.unique,
873
1139
  relationEntity: a.relation_entity,
874
1140
  enumName: a.enum_name,
@@ -879,7 +1145,132 @@ export function buildServer() {
879
1145
  minValue: a.min_value,
880
1146
  maxValue: a.max_value,
881
1147
  onlyPositive: a.only_positive,
1148
+ options: a.options_json,
882
1149
  })));
1150
+ reg("suppa_update_field", {
1151
+ description: "Edit an EXISTING field of an entity (POST /core/builder/<entity>/<field>/update-field).\n" +
1152
+ " Send only what changes — everything is optional.\n\n" +
1153
+ " Use it to fix a label, rename a field, flip required/unique, set a default, or —\n" +
1154
+ " most often — turn on the field OPTIONS a field was created without:\n" +
1155
+ " searchable / searchPriority (1-4) / readOnly / canGroup / canSort / showInTable /\n" +
1156
+ " editFromTable / canFilter. A field with none of them is invisible in table views\n" +
1157
+ " and cannot be found by free-text search.\n\n" +
1158
+ " WHAT THE PLATFORM DOES NOT ALLOW (refused here BEFORE any request, so a rejected\n" +
1159
+ " call changes nothing):\n" +
1160
+ " - The TYPE of a field can never be changed ('Field type cannot be changed.') —\n" +
1161
+ " there is no type parameter. Add a new field and move the data instead.\n" +
1162
+ " - The SUBTYPE cannot be changed either ('Field subType cannot be changed.'). The\n" +
1163
+ " ONE permitted transition is encryption: encrypt=true sets sub_type 'encrypted',\n" +
1164
+ " encrypt=false clears it. A date/time choice is fixed at creation.\n" +
1165
+ " - 'encrypted' is only allowed on a TEXT field, and it forces searchable, canFilter,\n" +
1166
+ " canSort and canGroup off (plus unique, max_length, min_length, mask), so it\n" +
1167
+ " cannot be combined with them in one call. Encrypting rewrites the existing rows.\n" +
1168
+ " - A SYSTEM field (initiator='system') accepts only title and options.{canGroup,\n" +
1169
+ " canSort, showInTable, editFromTable, canFilter, readOnly, searchable}.\n" +
1170
+ " Removing a field is still UI-only — this server has no remove-field call.\n\n" +
1171
+ " APPROVAL GATE: without confirm=true this returns a confirmation request and\n" +
1172
+ " changes nothing. Get the user's approval, then re-call with confirm=true.",
1173
+ inputSchema: {
1174
+ entity_name: EntityName,
1175
+ field_name: z
1176
+ .string()
1177
+ .describe("Existing field name (case-sensitive) — see suppa_describe_entity."),
1178
+ new_name: z
1179
+ .string()
1180
+ .nullable()
1181
+ .default(null)
1182
+ .describe("Rename the field (1-50 chars: letters, numbers, underscores)."),
1183
+ title: z
1184
+ .string()
1185
+ .nullable()
1186
+ .default(null)
1187
+ .describe("New label; written into every platform language."),
1188
+ required: z
1189
+ .boolean()
1190
+ .nullable()
1191
+ .default(null)
1192
+ .describe("Set/clear NOT NULL (wire key notNull). Omit to leave as is."),
1193
+ unique: z
1194
+ .boolean()
1195
+ .nullable()
1196
+ .default(null)
1197
+ .describe("Set/clear the unique constraint. Omit to leave as is."),
1198
+ default_value: z
1199
+ .string()
1200
+ .nullable()
1201
+ .default(null)
1202
+ .describe("New default — a SQL expression or literal ('0', \"'draft'\", 'now()')."),
1203
+ relation_entity: z
1204
+ .string()
1205
+ .nullable()
1206
+ .default(null)
1207
+ .describe("New relation target entity (wire key relationTarget)."),
1208
+ back_reference: z
1209
+ .string()
1210
+ .nullable()
1211
+ .default(null)
1212
+ .describe("Name of the back-reference field on the related entity."),
1213
+ is_primary: z.boolean().nullable().default(null).describe("Set/clear the primary flag."),
1214
+ is_array: z.boolean().nullable().default(null).describe("Set/clear the array flag."),
1215
+ encrypt: z
1216
+ .boolean()
1217
+ .nullable()
1218
+ .default(null)
1219
+ .describe("true encrypts a TEXT field (sub_type='encrypted'), false decrypts it (clears the " +
1220
+ "subtype); null leaves the subtype alone. This is the only subtype change the " +
1221
+ "platform accepts, and it rewrites every existing row."),
1222
+ options_json: z
1223
+ .string()
1224
+ .nullable()
1225
+ .default(null)
1226
+ .describe('Field options as a JSON object, e.g. {"showInTable": true, "canFilter": true, ' +
1227
+ '"searchable": true, "searchPriority": 3}. Keys: searchable, searchPriority ' +
1228
+ "(1-4), readOnly, canGroup, canSort, showInTable, editFromTable, canFilter. " +
1229
+ "Unknown keys are refused (the platform would drop them silently)."),
1230
+ confirm: Confirm,
1231
+ },
1232
+ annotations: _MUT,
1233
+ }, async (a) => {
1234
+ const changes = {};
1235
+ if (a.new_name !== null)
1236
+ changes.new_name = a.new_name;
1237
+ if (a.title !== null)
1238
+ changes.title = a.title;
1239
+ if (a.required !== null)
1240
+ changes.required = a.required;
1241
+ if (a.unique !== null)
1242
+ changes.unique = a.unique;
1243
+ if (a.default_value !== null)
1244
+ changes.default_value = a.default_value;
1245
+ if (a.relation_entity !== null)
1246
+ changes.relation_entity = a.relation_entity;
1247
+ if (a.back_reference !== null)
1248
+ changes.back_reference = a.back_reference;
1249
+ if (a.is_primary !== null)
1250
+ changes.is_primary = a.is_primary;
1251
+ if (a.is_array !== null)
1252
+ changes.is_array = a.is_array;
1253
+ if (a.encrypt !== null)
1254
+ changes.encrypt = a.encrypt;
1255
+ if (a.options_json !== null)
1256
+ changes.options = a.options_json;
1257
+ if (!a.confirm) {
1258
+ return text(confirmRequired("update field", { entity: a.entity_name, field: a.field_name }, changes));
1259
+ }
1260
+ return text(await entity.updateField(a.entity_name, a.field_name, {
1261
+ newName: a.new_name,
1262
+ title: a.title,
1263
+ required: a.required,
1264
+ unique: a.unique,
1265
+ defaultValue: a.default_value,
1266
+ relationEntity: a.relation_entity,
1267
+ backReference: a.back_reference,
1268
+ isPrimary: a.is_primary,
1269
+ isArray: a.is_array,
1270
+ encrypt: a.encrypt,
1271
+ options: a.options_json,
1272
+ }));
1273
+ });
883
1274
  reg("suppa_add_enum_values", {
884
1275
  description: "Add values to an enum (lookup table). enum_name: qualified 'Entity.field'\n" +
885
1276
  " key (e.g. 'Receipts.type'). values: comma-separated list.",
@@ -909,11 +1300,15 @@ export function buildServer() {
909
1300
  }, async () => text(await entity.listFieldTypes()));
910
1301
  reg("suppa_create_record", {
911
1302
  description: "Create a record in any entity. fields_json: JSON object of field values.\n\n" +
1303
+ " BATCH: pass a JSON ARRAY of record objects to create many in ONE request\n" +
1304
+ ' (e.g. [{"title": "A"}, {"title": "B"}]) — do not loop this tool. The batch\n' +
1305
+ " returns {created, requested, entity, records} and is validated as a unit:\n" +
1306
+ " if any record is malformed, nothing is inserted.\n\n" +
912
1307
  ' Write relations as {"id": N} and enum fields as {"id": <enumValueId>} —\n' +
913
1308
  " a bare number/string returns HTTP 201 but silently stores null.",
914
1309
  inputSchema: {
915
1310
  entity_name: EntityName,
916
- fields_json: RecordValuesJson,
1311
+ fields_json: RecordValuesOrBatchJson,
917
1312
  },
918
1313
  annotations: _ADD,
919
1314
  }, async (a) => text(await entity.createRecord(a.entity_name, a.fields_json)));
@@ -921,12 +1316,18 @@ export function buildServer() {
921
1316
  description: "Update a record in any entity. fields_json: JSON object of fields to change.\n\n" +
922
1317
  ' Write relations as {"id": N} and enum fields as {"id": <enumValueId>} —\n' +
923
1318
  " a bare number/string returns HTTP 201 but silently stores null.\n\n" +
1319
+ " LIST FIELDS ARE REPLACED, NOT APPENDED: fields_json={\"watchers\":\n" +
1320
+ ' [{"id": 15}]} makes 15 the ONLY watcher — every other watcher is dropped.\n' +
1321
+ ' To ADD the listed items instead, pass merge_json=["watchers"]; to REMOVE\n' +
1322
+ ' only the listed items, pass unmerge_json=["watchers"].\n\n' +
924
1323
  " APPROVAL GATE: without confirm=true this returns a confirmation request and\n" +
925
1324
  " changes nothing. Get the user's approval, then re-call with confirm=true.",
926
1325
  inputSchema: {
927
1326
  entity_name: EntityName,
928
1327
  record_id: z.number().int(),
929
1328
  fields_json: RecordValuesJson,
1329
+ merge_json: MergeNamesJson.default(null),
1330
+ unmerge_json: UnmergeNamesJson.default(null),
930
1331
  confirm: Confirm,
931
1332
  },
932
1333
  annotations: _MUT,
@@ -939,15 +1340,43 @@ export function buildServer() {
939
1340
  catch {
940
1341
  proposed = a.fields_json;
941
1342
  }
942
- return text(confirmRequired("update record", { entity: a.entity_name, record_id: a.record_id }, proposed));
1343
+ const merge = nameList(a.merge_json);
1344
+ const unmerge = nameList(a.unmerge_json);
1345
+ const preview = { fields: proposed };
1346
+ if (merge.length > 0) {
1347
+ preview.merge_add_to_existing_list = merge;
1348
+ }
1349
+ if (unmerge.length > 0) {
1350
+ preview.unmerge_remove_from_existing_list = unmerge;
1351
+ }
1352
+ // Name the lists this call would wipe, so the human approving sees the
1353
+ // replace BEFORE it happens rather than in the result. Schema-aware: a
1354
+ // json column holding an array is one value being overwritten, not a
1355
+ // list being wiped, and must not be announced as a replacement.
1356
+ const replaced = proposed && typeof proposed === "object" && !Array.isArray(proposed)
1357
+ ? await entity.previewReplacedLists(a.entity_name, proposed, merge, unmerge)
1358
+ : [];
1359
+ if (replaced.length > 0) {
1360
+ preview.replaces_entire_list = replaced;
1361
+ }
1362
+ return text(confirmRequired("update record", { entity: a.entity_name, record_id: a.record_id }, preview));
943
1363
  }
944
- return text(await entity.updateRecord(a.entity_name, a.record_id, a.fields_json));
1364
+ return text(await entity.updateRecord(a.entity_name, a.record_id, a.fields_json, a.merge_json, a.unmerge_json));
945
1365
  });
946
1366
  reg("suppa_delete_record", {
947
- description: "Delete a record (instance) from any entity.\n\n" +
948
- " Removes a single instance, not the entity/schema. Entity definitions and\n" +
949
- " fields are add-only here (create_entity / add_field) — removing or modifying\n" +
950
- " fields is UI-only by design.\n\n" +
1367
+ description: "Soft-delete a record (instance) from any entity.\n\n" +
1368
+ " SOFT DELETE: the platform sets deletedAt — the row remains in the database\n" +
1369
+ " and the delete is reversible with suppa_restore_record. Nothing is purged.\n" +
1370
+ " The record does disappear from every normal read; find it again with\n" +
1371
+ " suppa_search_records(deleted_scope='deleted').\n\n" +
1372
+ " NOT A PERMANENT DELETE: the platform's permanent delete is a different\n" +
1373
+ " endpoint (/core/data/<entity>/delete) where the rows leave the table and\n" +
1374
+ " cannot be restored. This server deliberately does not expose it — every\n" +
1375
+ " delete tool here is the reversible one.\n\n" +
1376
+ " Removes a single instance, not the entity/schema. Entities and fields are\n" +
1377
+ " created with suppa_create_entity / suppa_add_field and edited with\n" +
1378
+ " suppa_update_field (a field's type is never changeable); REMOVING a field is\n" +
1379
+ " UI-only — this server has no remove-field call.\n\n" +
951
1380
  " APPROVAL GATE: without confirm=true this returns a confirmation request and\n" +
952
1381
  " deletes nothing. Get the user's approval, then re-call with confirm=true.",
953
1382
  inputSchema: {
@@ -965,6 +1394,63 @@ export function buildServer() {
965
1394
  }
966
1395
  return text(await entity.deleteRecord(a.entity_name, a.record_id));
967
1396
  });
1397
+ reg("suppa_restore_record", {
1398
+ description: "UNDO a soft delete: bring a removed record of any entity back by clearing\n" +
1399
+ " deletedAt. This is the counterpart of suppa_delete_record (and of every\n" +
1400
+ " other delete tool here — they all only set deletedAt), so a deletion the\n" +
1401
+ " user regrets is recoverable; nothing was purged.\n\n" +
1402
+ " FINDING THE ID: a removed record is invisible to a normal read. List the\n" +
1403
+ " candidates with suppa_search_records(entity_name, deleted_scope='deleted')\n" +
1404
+ ' — project deletedAt (fields_json {"id": true, "deletedAt": true, ...}) to see\n' +
1405
+ " when each was removed — or read one you already know by id with\n" +
1406
+ " suppa_get_record(..., deleted_scope='deleted').\n\n" +
1407
+ " Only soft-deleted rows are touched: the platform scopes the restore to\n" +
1408
+ " deletedAt IS NOT NULL, so calling this on a live record changes nothing and\n" +
1409
+ " returns restored=false. A record removed with the platform's PERMANENT\n" +
1410
+ " delete cannot be restored — but this server never issues that call.\n\n" +
1411
+ " APPROVAL GATE: without confirm=true this returns a confirmation request and\n" +
1412
+ " restores nothing. Get the user's approval, then re-call with confirm=true.",
1413
+ inputSchema: {
1414
+ entity_name: EntityName,
1415
+ record_id: z.number().int(),
1416
+ confirm: Confirm,
1417
+ },
1418
+ annotations: _UNDO,
1419
+ }, async (a) => {
1420
+ if (!a.confirm) {
1421
+ return text(confirmRequired("restore record", {
1422
+ entity: a.entity_name,
1423
+ record_id: a.record_id,
1424
+ }));
1425
+ }
1426
+ return text(await entity.restoreRecord(a.entity_name, a.record_id));
1427
+ });
1428
+ reg("suppa_copy_record", {
1429
+ description: "Duplicate an existing record of any entity, server-side. fields_json holds the\n" +
1430
+ " values that must DIFFER on the copy — they are applied on top of the copied\n" +
1431
+ ' ones (pass {} to copy as-is). Write relations/enums as {"id": N}.\n\n' +
1432
+ " copy_files=true duplicates the source record's ATTACHMENTS onto the copy.\n" +
1433
+ " This is the only way to do that here: suppa_attach_file_to_record uploads\n" +
1434
+ " from a local path, which you do not have for a file that lives on the\n" +
1435
+ " platform.\n\n" +
1436
+ " copy_related_entities=true also copies the records related to this one —\n" +
1437
+ " it multiplies data, so leave it false unless the user asked for a deep copy.\n\n" +
1438
+ " Creates a NEW record and never changes the source, so no approval gate.",
1439
+ inputSchema: {
1440
+ entity_name: EntityName,
1441
+ record_id: z.number().int().describe("Id of the record to copy."),
1442
+ fields_json: RecordValuesJson.default("{}"),
1443
+ copy_files: z
1444
+ .boolean()
1445
+ .default(false)
1446
+ .describe("Duplicate the attached files instead of skipping them."),
1447
+ copy_related_entities: z
1448
+ .boolean()
1449
+ .default(false)
1450
+ .describe("Also copy the records related to this one (deep copy)."),
1451
+ },
1452
+ annotations: _ADD,
1453
+ }, async (a) => text(await entity.copyRecord(a.entity_name, a.record_id, a.fields_json, a.copy_files, a.copy_related_entities)));
968
1454
  reg("suppa_attach_file_to_record", {
969
1455
  description: "Attach a local file to a record (instance) of any entity.\n\n" +
970
1456
  " Auto-detects the entity's file/attachment field from its schema; pass\n" +
@@ -1121,6 +1607,14 @@ export function buildServer() {
1121
1607
  });
1122
1608
  reg("suppa_delete_automation", {
1123
1609
  description: "Soft-delete an automation workflow.\n\n" +
1610
+ " SOFT DELETE: this goes through the same /remove as every other delete here —\n" +
1611
+ " the platform sets deletedAt, the row remains in the database and the delete\n" +
1612
+ " is reversible: suppa_restore_record('AutomationWorkflow', automation_id) brings\n" +
1613
+ " it back. Nothing is purged. The workflow does disappear from every normal read\n" +
1614
+ " and stops running, so treat it as gone for further work; find it again with\n" +
1615
+ " suppa_search_records('AutomationWorkflow', deleted_scope='deleted').\n\n" +
1616
+ " NOT the platform's permanent delete (a separate endpoint where the rows leave\n" +
1617
+ " the table and cannot be restored); that one is deliberately not exposed here.\n\n" +
1124
1618
  " APPROVAL GATE: without confirm=true this returns a confirmation request and\n" +
1125
1619
  " deletes nothing. Get the user's approval, then re-call with confirm=true.",
1126
1620
  inputSchema: { automation_id: AutomationId, confirm: Confirm },
@@ -1546,10 +2040,20 @@ export function buildServer() {
1546
2040
  annotations: _READ,
1547
2041
  }, async () => text(tenants.listTenants()));
1548
2042
  reg("suppa_logout", {
1549
- description: "Remove stored keychain credentials for a tenant (default: the active one).",
1550
- inputSchema: { tenant: TenantArg.default("") },
2043
+ description: "Remove stored keychain credentials for a tenant (default: the active one).\n\n" +
2044
+ " APPROVAL GATE: without confirm=true this returns a confirmation request and\n" +
2045
+ " removes nothing. Signing back in needs suppa_login and a browser.",
2046
+ inputSchema: { tenant: TenantArg.default(""), confirm: Confirm },
1551
2047
  annotations: _MUT,
1552
- }, async (a) => text(tenants.logout(a.tenant)));
2048
+ }, async (a) => {
2049
+ // Erasing the stored credentials is not undoable from here — getting them
2050
+ // back means a human at a browser (suppa_login). Gated like every other
2051
+ // destructive tool, so a host that auto-approves cannot sign the user out.
2052
+ if (!a.confirm) {
2053
+ return text(confirmRequired("log out", { tenant: a.tenant || "<active tenant>" }));
2054
+ }
2055
+ return text(tenants.logout(a.tenant));
2056
+ });
1553
2057
  reg("suppa_diagnostics", {
1554
2058
  description: "Validate the whole multi-tenant setup in one report.\n\n" +
1555
2059
  " Checks environment prerequisites (keychain backend, Google client id, login\n" +
@@ -1619,7 +2123,11 @@ export function buildServer() {
1619
2123
  "then suppa_add_field on the returned entity_name (the `owner` link is created for you).\n" +
1620
2124
  "4. Verify with suppa_describe_entity, and suppa_list_tabular_parts(parent) for any tabular parts.\n" +
1621
2125
  "5. Offer a form: suppa_create_form(generate_from_entity=true, entity_name=...). \n" +
1622
- "Schema is add-only — fields cannot be removed via this server, so get the design right before creating.");
2126
+ "Pass options_json on each field the user should see or search — {\"showInTable\": true, \"canFilter\": true, " +
2127
+ '"canSort": true} and {"searchable": true, "searchPriority": 3} on the ones worth finding by text; without ' +
2128
+ "them the field is absent from table views and from free-text search.\n" +
2129
+ "Fields cannot be REMOVED via this server (UI only) and a field's TYPE can never be changed — so get the types " +
2130
+ "right before creating; names, labels, flags and options can be corrected later with suppa_update_field.");
1623
2131
  regPrompt("migrate_from_v1", {
1624
2132
  description: "Guided Suppa 1.0 → 2.0 schema migration (dry-run, review, execute)",
1625
2133
  argsSchema: {