suppa-mcp-2 1.26.0 → 1.27.1

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.
@@ -0,0 +1,84 @@
1
+ /**
2
+ * What to DO about a custom-field refusal.
3
+ *
4
+ * The platform's messages are precise about what went wrong and silent about
5
+ * what to do next, and the same four or five of them are hit from two different
6
+ * places: the tools that create and remove custom fields, and the ordinary
7
+ * record write that carries their values. The table lives here so both can use
8
+ * it without either importing the other.
9
+ *
10
+ * Every entry was hit for real against a live tenant while mapping the feature.
11
+ * A message that matches nothing gets no hint — an invented next step is worse
12
+ * than none.
13
+ */
14
+ const ERROR_HINTS = [
15
+ {
16
+ match: /is not available for this record's context/i,
17
+ hint: "That field is not in any set covering this record's context, so NOTHING was written. " +
18
+ "suppa_resolve_custom_fields(entity_name, record_id=...) lists the fields that ARE live " +
19
+ "for this record. A field goes live by being added with that context, or by linking it " +
20
+ "into the set: suppa_create_record('CustomFieldSetFields', {\"set\": {\"id\": S}, \"field\": {\"id\": F}}).",
21
+ },
22
+ {
23
+ match: /is required for this record's context/i,
24
+ hint: "The set marks that field required (CustomFieldSetFields.required), and the platform " +
25
+ "enforces it when the values row is first created. Send a value for it, or drop the " +
26
+ "customFields key entirely — a record created with NO customFields key is accepted.",
27
+ },
28
+ {
29
+ match: /"sets" or "context" is required for custom fields/i,
30
+ hint: "A custom field must land in a set. Pass context_field + context_value (the set is " +
31
+ "created if that context has none yet), or set_ids of sets that already exist.",
32
+ },
33
+ {
34
+ match: /Custom fields are not enabled for entity/i,
35
+ hint: 'Turn the option on first: suppa_update_entity_options(entity_name, options_json=\'{"customFields": true}\'). ' +
36
+ "That creates the {Entity}CustomFields extension table — a schema change, not a preference.",
37
+ },
38
+ {
39
+ match: /Cannot remove system field/i,
40
+ hint: "Only custom fields can be removed here. The platform's own columns on the extension " +
41
+ "table (createdAt, owner, ...) are system fields and stay.",
42
+ },
43
+ {
44
+ match: /Field .* not found in .*CustomFields/i,
45
+ hint: "The name is checked against the EXTENSION entity, not the owner: a core field of the " +
46
+ "owner cannot be reached through customFields. suppa_resolve_custom_fields lists the " +
47
+ "custom names. Note the schema endpoints lag ~1 minute behind add/remove; resolve does not.",
48
+ },
49
+ {
50
+ match: /already exists in entity/i,
51
+ hint: "A custom field with that name is already live on the extension entity. Pick another name, " +
52
+ "or edit the one that is there with suppa_update_field(entity_name='<Entity>CustomFields').",
53
+ },
54
+ {
55
+ // Verified live: the name of a REMOVED field stays taken. The platform says
56
+ // so itself — "that field is DELETED — its column is parked as
57
+ // <name>_<timestamp>, and restoring it would then fail" — so a removal frees
58
+ // the column, never the name.
59
+ match: /is already taken by field|metadata\.invalid_name/i,
60
+ hint: "That name belongs to a custom field that was REMOVED but not purged: the platform keeps it " +
61
+ "reserved so the parked column can still be restored. Either bring the original back with " +
62
+ "suppa_restore_custom_field (its values come with it), or choose a different name.",
63
+ },
64
+ {
65
+ match: /HTTP 409|statusCode":409/,
66
+ hint: "Concurrent write: two writers created the values row for the same record at once (the " +
67
+ "owner column is unique). Nothing was written — re-send the identical call.",
68
+ },
69
+ {
70
+ match: /planner does not support this query yet/i,
71
+ hint: "Filtering across customFields.<field> is supported for positive comparators; a " +
72
+ "value-less form such as 'is not null' is not lowered by the planner (verified). Filter " +
73
+ "with '=' / 'in' on the value you are looking for instead.",
74
+ },
75
+ ];
76
+ /** Attach the next step to a platform message, when one of the known cases matches. */
77
+ export function customFieldsHint(message) {
78
+ for (const { match, hint } of ERROR_HINTS) {
79
+ if (match.test(message)) {
80
+ return hint;
81
+ }
82
+ }
83
+ return null;
84
+ }
package/dist/server.js CHANGED
@@ -8,9 +8,12 @@
8
8
  */
9
9
  import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
10
10
  import { z } from "zod";
11
+ import { config } from "./config.js";
11
12
  import * as tasks from "./tools/tasks.js";
12
13
  import * as docs from "./tools/docs.js";
13
14
  import * as entity from "./tools/entity.js";
15
+ import * as customFields from "./tools/customFields.js";
16
+ import * as customFieldSets from "./tools/customFieldSets.js";
14
17
  import * as entityCode from "./tools/entityCode.js";
15
18
  import { houseRulesDigest } from "./tools/entityCode.js";
16
19
  import * as files from "./tools/files.js";
@@ -159,7 +162,7 @@ const EntityName = z
159
162
  .string()
160
163
  .describe("Exact entity name, e.g. 'Tasks' — discover via suppa_list_entities.");
161
164
  // Entity Options (captures/api-entity-builder-builder.txt:74-90) — the platform's
162
- // 15 per-entity features. The TIP at :91-92 is quoted in full: enabling one is a
165
+ // 15 per-entity features, plus customFields (newer than that capture, verified live). The TIP at :91-92 is quoted in full: enabling one is a
163
166
  // schema change (it creates the backing side table), not a preference toggle.
164
167
  const EntityOptionsJson = z
165
168
  .string()
@@ -169,7 +172,8 @@ const EntityOptionsJson = z
169
172
  '"hierarchy": "multi"}. Keys: comments, reactions, hierarchy ("single"|"multi"), ' +
170
173
  'folders ("single"|"multi"), trackChangeHistory, browsingHistory (boolean or number), ' +
171
174
  "globalSearch, timeTracking, favorites, pinned, approvals, checklists, recurrence, " +
172
- "reminders, notificationMutes — everything but hierarchy, folders and browsingHistory " +
175
+ "reminders, notificationMutes, customFields — everything but hierarchy, folders and " +
176
+ "browsingHistory " +
173
177
  "is a boolean. Unknown keys are refused (the platform would drop them silently). " +
174
178
  "Enabling an option creates the side table that backs it, and recurrence, reminders, " +
175
179
  "notificationMutes, timeTracking and pinned also refresh the corresponding system " +
@@ -251,43 +255,43 @@ const EntityQuery = z
251
255
  // ---------------------------------------------------------------------------
252
256
  /** Read once, from the one file that states the rules (see houseRulesDigest). */
253
257
  const HOUSE_RULES_DIGEST = houseRulesDigest();
254
- const INSTRUCTIONS = `Suppa Platform MCP Server — Tasks, Docs/Pages, Entities, Forms, Automations and file attachments on Suppa tenants.
255
-
256
- AUTHENTICATION — RESOLVE THIS BEFORE ANY OTHER SUPPA WORK
257
- - Sign-in is an interactive Google flow in the browser. There is NO API key for a user to find or paste — NEVER ask for a token, key or password; call suppa_login instead.
258
- - Unsure whether the user is signed in? Call suppa_list_tenants (cheap, read-only): the ACTIVE tenant shows "authenticated": false or "needs_login": true when not.
259
- - When not signed in — or any tool answers "No Suppa credentials" / HTTP 401 / "session could not be refreshed" / ReloginRequired — DO NOT STOP and DO NOT ask for a key:
260
- 1. Call suppa_login (suppa_login(tenant="<alias|host|url>") targets another instance; default is the active tenant). It OPENS A GOOGLE SIGN-IN PAGE in the default browser, served locally at http://localhost:8080.
261
- 2. Tell the user: "I've opened a Google sign-in page in your browser — pick your account to finish signing in." If the browser did not open, the result carries the URL for them to open by hand.
262
- 3. It blocks until they finish and returns {"status":"ok"} — THEN retry the original action. Tokens go to the OS keychain and auto-refresh: one login per tenant, not per session.
263
- - A static SUPPA_API_KEY in the client env (CI / single tenant) means no login is needed; it is optional and most users have none.
264
- - suppa_diagnostics validates the whole setup and reports the login_origin to whitelist. ONE-TIME ORG SETUP: http://localhost:8080 must be in the Google OAuth client's "Authorized JavaScript origins" — a sign-in page that opens but never completes is almost always this; tell the user so an admin can add it.
265
- - suppa_use_tenant switches the active instance for ALL later calls; suppa_list_tenants shows what is known and authenticated.
266
-
267
- DATA BASICS
268
- - IDs are integers, not UUIDs. Dates are ISO-8601; a naive datetime (no offset) is read as UTC, so pass an explicit offset (+03:00) or convert local times yourself. Task deadlines also accept 'today', 'tomorrow', '+3d', '+2h', '+30m', '+1w'.
269
- - Each write tool's description states the shapes it demands — relations and enums as {"id": N}, list fields REPLACED unless merge_json says otherwise — and validates against the live schema before writing. Read it before calling: a bare number where a reference belongs returns 201 and stores null.
270
- - DELETE IS A SOFT DELETE — every delete tool sets deletedAt and leaves the row in place, reversible with suppa_restore_record(entity_name, record_id); never tell the user their data was destroyed. It still needs confirm=true because the row leaves all normal reads; find it again with deleted_scope='deleted'.
271
- - PERMANENT DELETE IS UNAVAILABLE HERE, BY DESIGN — this server performs REVERSIBLE deletes only. The platform's PERMANENT delete (POST /core/data/:entityName/delete — rows leave the table and cannot be restored) is BLOCKED in the HTTP client itself: no tool, flag, confirm=true or direct call reaches it, and an attempt is refused before any request is sent. Do not look for a tool, a parameter or a workaround — there is none. Asked to erase data for good, say so plainly and offer the soft delete (suppa_delete_record → /remove, undone by suppa_restore_record); permanent removal is an admin action in the platform's own UI.
272
- - Reads are compact: relation objects omit deletedAt when null (a live row); schema reads omit nulls, false flags and default options and carry a _legend (full=true returns the raw form).
273
-
274
- SEARCH & FILTERS — suppa_search_records' description carries the comparators, nested AND/OR groups, dotted field paths, "$current-user", paging and the auto-diagnosis of an empty result. Read it before your first search.
275
- - PROJECT ONLY THE FIELDS YOU NEED: fields_json is on suppa_search_records AND on every task/doc read (suppa_get_task, suppa_search_tasks — which also takes task_ids, so several tasks are ONE call, never one suppa_get_task each — suppa_get_doc, suppa_list_pages, …). A 600-character answer instead of a 50 000-character one, re-sent on every later turn.
276
- - Unsure of the schema: suppa_list_entities → suppa_describe_entity → suppa_search_records. One record by id needs no filters: suppa_get_record / suppa_get_task / suppa_get_doc.
277
-
278
- APPROVAL GATES (human-in-the-loop)
279
- - Every update/move/close/delete tool called without confirm=true returns {"status": "confirmation_required"} and performs NOTHING. Show the user what will change, get explicit approval, then re-call the same tool with confirm=true — never set it on the first call without their go-ahead. Create/read tools and comments need no confirmation.
280
- - A value shown as <N chars — exactly as sent / unchanged from this call's arguments> is NOT the stored text: it names the long string you yourself supplied in this same call. Quote it to the user from your own arguments; never report the marker as the record's content.
281
-
282
- ENTITY BUILDER (create + edit fields; removal is UI-only) — suppa_add_field's description carries the real field types, the sub_type matrix and the field options; suppa_update_field's carries what may still be changed on a field that exists. Two things those cannot decide for you:
283
- - OWNED CHILD COLLECTIONS ARE TABULAR PARTS: repeating rows that belong to ONE parent record (a part's BOM items) go through suppa_create_tabular_part(parent_entity, name), which creates the child's 'owner' relation and the parent link. Never model it by hand — suppa_add_field REFUSES field_type='one-to-many'; 'many-to-many' is for a shared lookup referenced by many records.
284
- - An enum value on a RECORD is a reference, {"id": <Enums row id>} (an array of those for multi-enum), never a bare code like "red" — that is refused. Read the ids with suppa_search_records on 'Enums' filtered by name.
285
-
286
- ${HOUSE_RULES_DIGEST}
287
-
288
- ATTACHMENTS — an entity holds files only through a 'file' or 'multi-file' field (add one with suppa_add_field). suppa_attach_file_to_record uploads from local disk and returns the file_ids that are the only handle to the bytes; suppa_list_record_files lists what a record carries; suppa_download_file and suppa_download_files_zip fetch them. Those descriptions carry the rest.
289
-
290
- MIGRATION (Suppa 1.0 → 2.0) — 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.
258
+ const INSTRUCTIONS = `Suppa Platform MCP Server — Tasks, Docs/Pages, Entities, Forms, Automations and file attachments on Suppa tenants.
259
+
260
+ AUTHENTICATION — RESOLVE THIS BEFORE ANY OTHER SUPPA WORK
261
+ - Sign-in is an interactive Google flow in the browser. There is NO API key for a user to find or paste — NEVER ask for a token, key or password; call suppa_login instead.
262
+ - Unsure whether the user is signed in? Call suppa_list_tenants (cheap, read-only): the ACTIVE tenant shows "authenticated": false or "needs_login": true when not.
263
+ - When not signed in — or any tool answers "No credentials" / HTTP 401 / "session could not be refreshed" / ReloginRequired — DO NOT STOP and DO NOT ask for a key:
264
+ 1. Call suppa_login (suppa_login(tenant="<alias|host|url>") targets another instance; default is the active tenant). It OPENS A GOOGLE SIGN-IN PAGE in the default browser, served locally at http://localhost:${config.LOGIN_PORT}.
265
+ 2. Tell the user: "I've opened a Google sign-in page in your browser — pick your account to finish signing in." If the browser did not open, the result carries the URL for them to open by hand.
266
+ 3. It blocks until they finish and returns {"status":"ok"} — THEN retry the original action. Tokens go to the OS keychain and auto-refresh: one login per tenant, not per session.
267
+ - A static SUPPA_API_KEY in the client env (CI / single tenant) means no login is needed; it is optional and most users have none.
268
+ - suppa_diagnostics validates the whole setup and reports the login_origin to whitelist. ONE-TIME ORG SETUP: http://localhost:${config.LOGIN_PORT} must be in the Google OAuth client's "Authorized JavaScript origins" — a sign-in page that opens but never completes is almost always this; tell the user so an admin can add it.
269
+ - suppa_use_tenant switches the active instance for ALL later calls; suppa_list_tenants shows what is known and authenticated.
270
+
271
+ DATA BASICS
272
+ - IDs are integers, not UUIDs. Dates are ISO-8601; a naive datetime (no offset) is read as UTC, so pass an explicit offset (+03:00) or convert local times yourself. Task deadlines also accept 'today', 'tomorrow', '+3d', '+2h', '+30m', '+1w'.
273
+ - Each write tool's description states the shapes it demands — relations and enums as {"id": N}, list fields REPLACED unless merge_json says otherwise — and validates against the live schema before writing. Read it before calling: a bare number where a reference belongs returns 201 and stores null.
274
+ - DELETE IS A SOFT DELETE — every delete tool sets deletedAt and leaves the row in place, reversible with suppa_restore_record(entity_name, record_id); never tell the user their data was destroyed. It still needs confirm=true because the row leaves all normal reads; find it again with deleted_scope='deleted'.
275
+ - PERMANENT DELETE IS UNAVAILABLE HERE, BY DESIGN — this server performs REVERSIBLE deletes only. The platform's PERMANENT delete (POST /core/data/:entityName/delete — rows leave the table and cannot be restored) is BLOCKED in the HTTP client itself: no tool, flag, confirm=true or direct call reaches it, and an attempt is refused before any request is sent. Do not look for a tool, a parameter or a workaround — there is none. Asked to erase data for good, say so plainly and offer the soft delete (suppa_delete_record → /remove, undone by suppa_restore_record); permanent removal is an admin action in the platform's own UI.
276
+ - Reads are compact: relation objects omit deletedAt when null (a live row); schema reads omit nulls, false flags and default options and carry a _legend (full=true returns the raw form).
277
+
278
+ SEARCH & FILTERS — suppa_search_records' description carries the comparators, nested AND/OR groups, dotted field paths, "$current-user", paging and the auto-diagnosis of an empty result. Read it before your first search.
279
+ - PROJECT ONLY THE FIELDS YOU NEED: fields_json is on suppa_search_records AND on every task/doc read (suppa_get_task, suppa_search_tasks — which also takes task_ids, so several tasks are ONE call, never one suppa_get_task each — suppa_get_doc, suppa_list_pages, …). A 600-character answer instead of a 50 000-character one, re-sent on every later turn.
280
+ - Unsure of the schema: suppa_list_entities → suppa_describe_entity → suppa_search_records. One record by id needs no filters: suppa_get_record / suppa_get_task / suppa_get_doc.
281
+
282
+ APPROVAL GATES (human-in-the-loop)
283
+ - Every update/move/close/delete tool called without confirm=true returns {"status": "confirmation_required"} and performs NOTHING. Show the user what will change, get explicit approval, then re-call the same tool with confirm=true — never set it on the first call without their go-ahead. Create/read tools and comments need no confirmation.
284
+ - A value shown as <N chars — …> is NOT the stored text: the marker stands in for a long string you supplied in this same call, and the reason after the dash says which. Quote it to the user from your own arguments; never report the marker as the record's content.
285
+
286
+ ENTITY BUILDER (create + edit fields; core-field removal is UI-only) — suppa_add_field's description carries the real field types, the sub_type matrix and the field options; suppa_update_field's carries what may still be changed on a field that exists. Two things those cannot decide for you:
287
+ - OWNED CHILD COLLECTIONS ARE TABULAR PARTS: repeating rows that belong to ONE parent record (a part's BOM items) go through suppa_create_tabular_part(parent_entity, name), which creates the child's 'owner' relation and the parent link. Never model it by hand — suppa_add_field REFUSES field_type='one-to-many'; 'many-to-many' is for a shared lookup referenced by many records.
288
+ - An enum value on a RECORD is a reference, {"id": <Enums row id>} (an array of those for multi-enum), never a bare code like "red" — that is refused. Read the ids with suppa_search_records on 'Enums' filtered by name.
289
+
290
+ ${HOUSE_RULES_DIGEST}
291
+
292
+ ATTACHMENTS — an entity holds files only through a 'file' or 'multi-file' field (add one with suppa_add_field). suppa_attach_file_to_record uploads from local disk and returns the file_ids that are the only handle to the bytes; suppa_list_record_files lists what a record carries; suppa_download_file and suppa_download_files_zip fetch them. Those descriptions carry the rest.
293
+
294
+ MIGRATION (Suppa 1.0 → 2.0) — 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.
291
295
  `;
292
296
  // ---------------------------------------------------------------------------
293
297
  // Registered tool + prompt names (tests assert the counts).
@@ -992,7 +996,8 @@ export function buildServer() {
992
996
  inputSchema: {
993
997
  name: z
994
998
  .string()
995
- .describe("PascalCase entity name, e.g. 'CustomerOrders'."),
999
+ .describe("PascalCase, and the English MEANING of the title, e.g. 'CustomerOrders' — a title in " +
1000
+ "Latin letters (Zamovlennia for 'Замовлення') is refused."),
996
1001
  title: z.string(),
997
1002
  title_field_name: z
998
1003
  .string()
@@ -1015,8 +1020,9 @@ export function buildServer() {
1015
1020
  " /core/builder/<entity>/update-options) — a narrower alternative to editing the\n" +
1016
1021
  " entity that touches only options. This is the only way to reach comments,\n" +
1017
1022
  " reactions, hierarchy, folders, change history, browsing history, global search,\n" +
1018
- " time tracking, favorites, pinned, approvals, checklists, recurrence, reminders\n" +
1019
- " and notification mutes from here; send only the ones you are changing.\n\n" +
1023
+ " time tracking, favorites, pinned, approvals, checklists, recurrence, reminders,\n" +
1024
+ " notification mutes and customFields (per-context extra columns — see\n" +
1025
+ " suppa_add_custom_field) from here; send only the ones you are changing.\n\n" +
1020
1026
  " NOT A FREE TOGGLE: enabling an option CREATES the side table that backs it, and\n" +
1021
1027
  " recurrence / reminders / notificationMutes / timeTracking / pinned also refresh\n" +
1022
1028
  " the cache of the corresponding system entity. It is a schema change.\n\n" +
@@ -1036,7 +1042,7 @@ export function buildServer() {
1036
1042
  "Keys: comments, reactions, hierarchy (\"single\"|\"multi\"), folders " +
1037
1043
  '("single"|"multi"), trackChangeHistory, browsingHistory (boolean or number), ' +
1038
1044
  "globalSearch, timeTracking, favorites, pinned, approvals, checklists, " +
1039
- "recurrence, reminders, notificationMutes — everything but hierarchy, folders " +
1045
+ "recurrence, reminders, notificationMutes, customFields — everything but hierarchy, folders " +
1040
1046
  "and browsingHistory is a boolean. Unknown keys are refused (the platform would " +
1041
1047
  "drop them silently). Enabling an option creates the side table that backs it, " +
1042
1048
  "and recurrence/reminders/notificationMutes/timeTracking/pinned also refresh the " +
@@ -1120,7 +1126,8 @@ export function buildServer() {
1120
1126
  entity_name: EntityName,
1121
1127
  field_name: z
1122
1128
  .string()
1123
- .describe("camelCase field name, e.g. 'orderDate'."),
1129
+ .describe("camelCase, and the English MEANING of the label — never the label in Latin letters: " +
1130
+ "'Опис причини' is reasonDescription, not opysPrychyny. A transliteration is refused."),
1124
1131
  field_type: z
1125
1132
  .string()
1126
1133
  .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."),
@@ -1241,7 +1248,9 @@ export function buildServer() {
1241
1248
  " cannot be combined with them in one call. Encrypting rewrites the existing rows.\n" +
1242
1249
  " - A SYSTEM field (initiator='system') accepts only title and options.{canGroup,\n" +
1243
1250
  " canSort, showInTable, editFromTable, canFilter, readOnly, searchable}.\n" +
1244
- " Removing a field is still UI-only — this server has no remove-field call.\n\n" +
1251
+ " Removing a CORE field is still UI-only — this server has no remove-field call for\n" +
1252
+ " one. A CUSTOM field is different: suppa_remove_custom_field parks it reversibly.\n" +
1253
+ " This tool edits a custom field too — pass entity_name='<Entity>CustomFields'.\n\n" +
1245
1254
  " APPROVAL GATE: without confirm=true this returns a confirmation request and changes nothing.",
1246
1255
  inputSchema: {
1247
1256
  entity_name: EntityName,
@@ -1348,24 +1357,187 @@ export function buildServer() {
1348
1357
  }));
1349
1358
  });
1350
1359
  reg("suppa_add_enum_values", {
1351
- description: "Add values to an enum (lookup table). enum_name: the enum's global name,\n" +
1352
- " conventionally 'Entity.field' (e.g. 'Receipts.type'). values:\n" +
1353
- " comma-separated 'code' or 'code:Label' — a value with no label is\n" +
1354
- " stored with the code as its label, never blank.\n" +
1355
- " Call this BEFORE creating the enum field, then pass the same\n" +
1356
- " enum_name to suppa_add_field.",
1360
+ description: "Add values to an enum (lookup table). values: comma-separated 'code' or\n" +
1361
+ " 'code:Label' — a value with no label is stored with the code as its label.\n" +
1362
+ " WHICH GROUP THEY JOIN: an enum field's subType IS the name of its group of\n" +
1363
+ " values, and that is the only binding the platform enforces. For a field that\n" +
1364
+ " already exists pass entity_name + field_name and the name is READ from it —\n" +
1365
+ " never rebuild it from 'Entity.field', which is a convention, not a rule.\n" +
1366
+ " Use enum_name alone only for a NEW group, before its field exists; then pass\n" +
1367
+ " the same enum_name to suppa_add_field.",
1357
1368
  inputSchema: {
1358
1369
  enum_name: z
1359
1370
  .string()
1360
- .describe("The enum's global name, conventionally 'Entity.field' (e.g. 'Receipts.type'). " +
1361
- "It need not match the field name — one enum can back several fields."),
1371
+ .nullable()
1372
+ .default(null)
1373
+ .describe("Name of a group that has no field yet. Convention 'Entity.field'. Omit when " +
1374
+ "entity_name + field_name are given."),
1362
1375
  values: z
1363
1376
  .string()
1364
1377
  .describe("Comma-separated 'code' or 'code:Label' (e.g. \"new:New request,done:Done\"). " +
1365
1378
  "The label is what users see in the picker. Existing codes are skipped."),
1379
+ entity_name: z
1380
+ .string()
1381
+ .nullable()
1382
+ .default(null)
1383
+ .describe("Entity of an EXISTING enum field; for a custom field, '<Entity>CustomFields'."),
1384
+ field_name: z
1385
+ .string()
1386
+ .nullable()
1387
+ .default(null)
1388
+ .describe("That field's name — its subType decides which group the values join."),
1389
+ },
1390
+ annotations: _ADD,
1391
+ }, async (a) => text(await entity.addEnumValues(a.enum_name, a.values, a.entity_name, a.field_name)));
1392
+ // =========================================================================
1393
+ // Custom fields — per-context extra columns on an entity
1394
+ // =========================================================================
1395
+ reg("suppa_resolve_custom_fields", {
1396
+ description: "Which custom fields are live for a record (or a context), and what it holds.\n" +
1397
+ " Custom fields are extra columns a tenant adds per CONTEXT — a set keyed on a field\n" +
1398
+ " such as project — so the answer differs from record to record. This is the only\n" +
1399
+ " CURRENT view: /schema lags up to a minute behind add/remove.\n" +
1400
+ " Values live on the OWNER under the reserved 'customFields' key — read them with\n" +
1401
+ " fields_json '{\"customFields\": {\"budget\": true}}', write them with\n" +
1402
+ " suppa_update_record fields_json '{\"customFields\": {\"budget\": 600}}'.",
1403
+ inputSchema: {
1404
+ entity_name: EntityName,
1405
+ record_id: z
1406
+ .number()
1407
+ .int()
1408
+ .nullable()
1409
+ .default(null)
1410
+ .describe("The record to answer for — also returns its current values."),
1411
+ context_field: z
1412
+ .string()
1413
+ .nullable()
1414
+ .default(null)
1415
+ .describe("Instead of a record: the context field, e.g. 'project'."),
1416
+ context_value: z
1417
+ .union([z.string(), z.number()])
1418
+ .nullable()
1419
+ .default(null)
1420
+ .describe("That field's value, e.g. the project id."),
1421
+ },
1422
+ annotations: _READ,
1423
+ }, async (a) => text(await customFields.resolveCustomFields(a.entity_name, a.record_id, a.context_field, a.context_value)));
1424
+ reg("suppa_add_custom_field", {
1425
+ description: "Create a CUSTOM field on an entity, live in ONE context.\n" +
1426
+ " Needs context_field + context_value (the set for that context is created if it has\n" +
1427
+ " none) or set_ids — a custom field belonging to neither is refused. The entity needs\n" +
1428
+ " options.customFields on (suppa_update_entity_options).\n" +
1429
+ " Types, sub_type and options are suppa_add_field's. There is no 'required': this build\n" +
1430
+ " cannot create a notNull custom field. To make one mandatory in a context, set required\n" +
1431
+ " on its CustomFieldSetFields row — an ordinary record.\n" +
1432
+ " Enum values come after: suppa_add_enum_values(entity_name='<Entity>CustomFields',\n" +
1433
+ " field_name='<field>') — both, or it cannot read the group off the field.",
1434
+ inputSchema: {
1435
+ entity_name: EntityName,
1436
+ field_name: z
1437
+ .string()
1438
+ .describe("camelCase, letters/numbers/underscores, 1-50 — and the English MEANING of the title, " +
1439
+ "never the title in Latin letters (opysPrychyny is refused; reasonDescription is the name)."),
1440
+ field_type: z.string().describe("As suppa_add_field (see suppa_list_field_types)."),
1441
+ title: z.string().nullable().default(null).describe("Label users see."),
1442
+ context_field: z
1443
+ .string()
1444
+ .nullable()
1445
+ .default(null)
1446
+ .describe("Field the set keys on, e.g. 'project'."),
1447
+ context_value: z
1448
+ .union([z.string(), z.number()])
1449
+ .nullable()
1450
+ .default(null)
1451
+ .describe("Its value, e.g. the project id."),
1452
+ set_ids: z
1453
+ .array(z.number().int())
1454
+ .nullable()
1455
+ .default(null)
1456
+ .describe("Existing CustomFieldSets ids, instead of a context."),
1457
+ relation_entity: z.string().nullable().default(null),
1458
+ options_json: z.string().nullable().default(null),
1459
+ sub_type: z.string().nullable().default(null),
1460
+ max_length: z.number().int().nullable().default(null),
1461
+ decimal_places: z.number().int().nullable().default(null),
1462
+ default_value: z.string().nullable().default(null),
1366
1463
  },
1367
1464
  annotations: _ADD,
1368
- }, async (a) => text(await entity.addEnumValues(a.enum_name, a.values)));
1465
+ }, async (a) => text(await customFields.addCustomField(a.entity_name, a.field_name, a.field_type, a.title, {
1466
+ contextField: a.context_field,
1467
+ contextValue: a.context_value,
1468
+ setIds: a.set_ids,
1469
+ relationEntity: a.relation_entity,
1470
+ options: a.options_json,
1471
+ subType: a.sub_type,
1472
+ maxLength: a.max_length,
1473
+ decimalPlaces: a.decimal_places,
1474
+ defaultValue: a.default_value,
1475
+ })));
1476
+ reg("suppa_remove_custom_field", {
1477
+ description: "Remove custom fields from an entity — reversibly.\n" +
1478
+ " The metadata is soft-deleted and the column is RENAMED to <name>_<timestamp>, not\n" +
1479
+ " dropped, so the values survive and suppa_restore_custom_field brings both back.\n" +
1480
+ " Only CUSTOM fields — core and platform columns are refused.\n" +
1481
+ " APPROVAL GATE: without confirm=true this returns a confirmation request and removes nothing.",
1482
+ inputSchema: {
1483
+ entity_name: EntityName,
1484
+ field_names: z.array(z.string()).describe("Custom field names to remove."),
1485
+ confirm: Confirm,
1486
+ },
1487
+ annotations: _MUT,
1488
+ }, async (a) => text(await customFields.removeCustomFields(a.entity_name, a.field_names, a.confirm)));
1489
+ reg("suppa_restore_custom_field", {
1490
+ description: "Undo suppa_remove_custom_field: the field and the values behind it come back.\n" +
1491
+ " APPROVAL GATE: without confirm=true this returns a confirmation request and restores nothing.",
1492
+ inputSchema: {
1493
+ entity_name: EntityName,
1494
+ field_names: z.array(z.string()).describe("Custom field names to restore."),
1495
+ confirm: Confirm,
1496
+ },
1497
+ annotations: _UNDO,
1498
+ }, async (a) => text(await customFields.restoreCustomFields(a.entity_name, a.field_names, a.confirm)));
1499
+ reg("suppa_add_custom_fields_batch", {
1500
+ description: "Create MANY custom fields in ONE atomic call - one bad entry creates NOTHING.\n" +
1501
+ " Context rules are suppa_add_custom_field's: context_field + context_value (that set\n" +
1502
+ " must already exist) or set_ids. Every entry passes the same guards as a single add.",
1503
+ inputSchema: {
1504
+ entity_name: EntityName,
1505
+ fields_json: z
1506
+ .string()
1507
+ .describe('JSON array: [{"name","type","title",...}] - the keys suppa_add_custom_field takes. ' +
1508
+ "Each name is the English MEANING of its title, never the title in Latin letters."),
1509
+ context_field: z.string().nullable().default(null).describe("Field the set keys on, e.g. 'project'."),
1510
+ context_value: z.union([z.string(), z.number()]).nullable().default(null).describe("Its value."),
1511
+ set_ids: z.array(z.number().int()).nullable().default(null).describe("Existing set ids instead of a context."),
1512
+ },
1513
+ annotations: _ADD,
1514
+ }, async (a) => text(await customFieldSets.addCustomFieldsBatch(a.entity_name, a.fields_json, {
1515
+ contextField: a.context_field,
1516
+ contextValue: a.context_value,
1517
+ setIds: a.set_ids,
1518
+ })));
1519
+ reg("suppa_link_custom_field", {
1520
+ description: "Put EXISTING custom fields into another context, take them out of one, or set required.\n" +
1521
+ " A field joins a context through a row, so ONE field can be live in several contexts at\n" +
1522
+ " once, keeping one column and one set of values. required is the only per-context flag\n" +
1523
+ " offered: the platform enforces it and enforces neither readOnly nor defaultValue.\n" +
1524
+ " APPROVAL GATE: without confirm=true this returns a confirmation request and changes nothing.",
1525
+ inputSchema: {
1526
+ entity_name: EntityName,
1527
+ field_names: z.array(z.string()).describe("Existing custom field names."),
1528
+ context_field: z.string().nullable().default(null).describe("Field the set keys on, e.g. 'project'."),
1529
+ context_value: z.union([z.string(), z.number()]).nullable().default(null).describe("Its value."),
1530
+ set_ids: z.array(z.number().int()).nullable().default(null).describe("Existing set ids instead of a context."),
1531
+ required: z
1532
+ .boolean()
1533
+ .nullable()
1534
+ .default(null)
1535
+ .describe("Make them required in this context (or not). Omit to leave unchanged."),
1536
+ unlink: z.boolean().default(false).describe("Take the fields OUT of this context instead of putting them in."),
1537
+ confirm: z.boolean().default(false).describe("Required — the change is gated either way."),
1538
+ },
1539
+ annotations: _MUT,
1540
+ }, async (a) => text(await customFieldSets.linkCustomFields(a.entity_name, a.field_names, { contextField: a.context_field, contextValue: a.context_value, setIds: a.set_ids }, { required: a.required, unlink: a.unlink, confirm: a.confirm })));
1369
1541
  reg("suppa_set_title_field", {
1370
1542
  description: "Set an entity's display-title (representative) field; creates it if missing.\n" +
1371
1543
  "\n" +
@@ -1466,8 +1638,9 @@ export function buildServer() {
1466
1638
  " this server does not expose; every delete tool here is the reversible one.\n\n" +
1467
1639
  " Removes a single instance, not the entity/schema. Entities and fields are\n" +
1468
1640
  " created with suppa_create_entity / suppa_add_field and edited with\n" +
1469
- " suppa_update_field (a field's type is never changeable); REMOVING a field is\n" +
1470
- " UI-only — this server has no remove-field call.\n\n" +
1641
+ " suppa_update_field (a field's type is never changeable); REMOVING a core field\n" +
1642
+ " is UI-only. Custom fields have their own reversible pair:\n" +
1643
+ " suppa_remove_custom_field / suppa_restore_custom_field.\n\n" +
1471
1644
  " APPROVAL GATE: without confirm=true this returns a confirmation request and deletes nothing.",
1472
1645
  inputSchema: {
1473
1646
  entity_name: EntityName,
@@ -1498,6 +1671,9 @@ export function buildServer() {
1498
1671
  " deletedAt IS NOT NULL, so calling this on a live record changes nothing and\n" +
1499
1672
  " returns restored=false. A record removed with the platform's PERMANENT\n" +
1500
1673
  " delete cannot be restored — but this server never issues that call.\n\n" +
1674
+ " ALSO WRITES to <Entity>CustomFields: the platform's own restore leaves the\n" +
1675
+ " record's custom-values row deleted, so this restores that too — which is\n" +
1676
+ " why calling it on an ALREADY-ACTIVE record is not a no-op.\n\n" +
1501
1677
  " APPROVAL GATE: without confirm=true this returns a confirmation request and restores nothing.",
1502
1678
  inputSchema: {
1503
1679
  entity_name: EntityName,
@@ -1507,9 +1683,10 @@ export function buildServer() {
1507
1683
  annotations: _UNDO,
1508
1684
  }, async (a) => {
1509
1685
  if (!a.confirm) {
1510
- return text(confirmRequired("restore record", {
1511
- entity: a.entity_name,
1512
- record_id: a.record_id,
1686
+ return text(confirmRequired("restore record", { entity: a.entity_name, record_id: a.record_id }, {
1687
+ also_restores: `${a.entity_name}CustomFields — the record's custom values, which the ` +
1688
+ "platform's own restore leaves deleted. Skipped when this tenant owns an entity of " +
1689
+ "that name.",
1513
1690
  }));
1514
1691
  }
1515
1692
  return text(await entity.restoreRecord(a.entity_name, a.record_id));
@@ -2191,7 +2368,7 @@ export function buildServer() {
2191
2368
  description: "Sign in to a Suppa tenant via Google — call this whenever the user is not\n" +
2192
2369
  " authenticated (no need to ask them for a key; there isn't one).\n\n" +
2193
2370
  " Opens a Google sign-in page in the user's default browser (a local page at\n" +
2194
- " http://localhost:8080) and BLOCKS until they pick an account, then exchanges\n" +
2371
+ ` http://localhost:${config.LOGIN_PORT}) and BLOCKS until they pick an account, then exchanges\n` +
2195
2372
  " the Google identity for Suppa tokens and stores them in the OS keychain\n" +
2196
2373
  " (auto-refreshed afterwards — a one-time step per tenant). Tell the user a\n" +
2197
2374
  " sign-in page has opened and to finish there; if the browser didn't open, the\n" +
@@ -733,6 +733,35 @@ function _isAbstract(e) {
733
733
  * recordCount costs ONE capped id-page per match. Abstract/unqueryable entities
734
734
  * yield recordCount=null + recordCountError instead of failing the whole search.
735
735
  */
736
+ /**
737
+ * The readable text of an entity title, which the platform sends either as a
738
+ * plain string or as a localisation record `{id, key, name, en, uk, …}`.
739
+ * `String(record)` gives "[object Object]" — as a label that is noise, and as a
740
+ * haystack it means a title search can never match.
741
+ */
742
+ export function entityTitleText(title) {
743
+ if (typeof title === "string")
744
+ return title;
745
+ if (!isPlainObject(title))
746
+ return "";
747
+ const BOOKKEEPING = new Set(["id", "key", "name"]);
748
+ const values = Object.entries(title)
749
+ .filter(([k, v]) => !BOOKKEEPING.has(k) && typeof v === "string" && v.trim())
750
+ .map(([, v]) => String(v).trim());
751
+ return values.length > 0 ? values[0] : "";
752
+ }
753
+ /** Every language a title carries, so a search matches whichever one was typed. */
754
+ function entityTitleHaystack(title) {
755
+ if (typeof title === "string")
756
+ return title;
757
+ if (!isPlainObject(title))
758
+ return "";
759
+ const BOOKKEEPING = new Set(["id", "key"]);
760
+ return Object.entries(title)
761
+ .filter(([k, v]) => !BOOKKEEPING.has(k) && typeof v === "string")
762
+ .map(([, v]) => v)
763
+ .join(" ");
764
+ }
736
765
  export async function searchEntities(query, limit = 20) {
737
766
  const schema = await makeRequest("GET", "/api/core/schema");
738
767
  const q = (query || "").toLowerCase().trim();
@@ -744,7 +773,9 @@ export async function searchEntities(query, limit = 20) {
744
773
  continue;
745
774
  }
746
775
  const name = String(e.name ?? "");
747
- const title = String(e.title ?? "");
776
+ // Every language, not String(record): searching for a Ukrainian title used
777
+ // to be matched against the text "[object object]" and never hit.
778
+ const title = entityTitleHaystack(e.title);
748
779
  if (q && !name.toLowerCase().includes(q) && !title.toLowerCase().includes(q)) {
749
780
  continue;
750
781
  }
@@ -757,7 +788,7 @@ export async function searchEntities(query, limit = 20) {
757
788
  const out = [];
758
789
  for (const e of matches) {
759
790
  const name = String(e.name ?? "");
760
- const row = { name: name, label: String(e.title || name) };
791
+ const row = { name: name, label: entityTitleText(e.title) || name };
761
792
  const desc = String(e.description ?? "");
762
793
  if (desc) {
763
794
  row.description = desc;