suppa-mcp-2 1.1.3 → 1.2.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.
@@ -13,6 +13,8 @@
13
13
  */
14
14
  import { existsSync, statSync } from "node:fs";
15
15
  import { basename } from "node:path";
16
+ import { config } from "../config.js";
17
+ import * as tenants from "../tenants.js";
16
18
  import { makeRequest, makeRequestRawBytes, searchEntity, selectEntity, insertEntity, updateEntity, removeEntity, } from "../httpClient.js";
17
19
  import { buildFileUpload, makeFilter, jsonResponse, parseJsonParam } from "../utils.js";
18
20
  // Builder field types that accept file uploads.
@@ -43,6 +45,102 @@ export const VALID_FIELD_TYPES = [
43
45
  ...RELATION_FIELD_TYPES,
44
46
  ];
45
47
  // ---------------------------------------------------------------------------
48
+ // Multi-language titles
49
+ // ---------------------------------------------------------------------------
50
+ //
51
+ // The platform stores entity/field titles (labels) and multi-language field
52
+ // values as localized objects keyed by language code ({en, uk, ...}). Writing
53
+ // only {en: ...} leaves the label blank in every OTHER language's UI, so we
54
+ // expand every title into all of the tenant's languages before sending it.
55
+ let _langCacheKey = null;
56
+ let _langCache = null;
57
+ /** TEST HOOK: forget the cached platform language set. */
58
+ export function _resetLanguageCache() {
59
+ _langCacheKey = null;
60
+ _langCache = null;
61
+ }
62
+ /**
63
+ * The tenant's configured language codes for multi-language fields.
64
+ *
65
+ * Resolution order: SUPPA_LANGS env override → the platform itself (the union
66
+ * of keys across existing entity `title` objects returned by /api/core/schema)
67
+ * → ['en', 'uk'] fallback. Cached per active tenant; never throws — a read
68
+ * error falls back rather than blocking a write.
69
+ */
70
+ export async function resolvePlatformLanguages() {
71
+ const envLangs = (process.env.SUPPA_LANGS || "")
72
+ .split(",")
73
+ .map((s) => s.trim())
74
+ .filter(Boolean);
75
+ if (envLangs.length > 0) {
76
+ return envLangs;
77
+ }
78
+ const key = tenants.current().baseUrl;
79
+ if (_langCache && _langCacheKey === key) {
80
+ return _langCache;
81
+ }
82
+ const langs = [];
83
+ const seen = new Set();
84
+ try {
85
+ const schema = await makeRequest("GET", "/api/core/schema");
86
+ if (Array.isArray(schema)) {
87
+ for (const e of schema) {
88
+ if (isPlainObject(e) && isPlainObject(e.title)) {
89
+ for (const k of Object.keys(e.title)) {
90
+ if (k && !seen.has(k)) {
91
+ seen.add(k);
92
+ langs.push(k);
93
+ }
94
+ }
95
+ }
96
+ }
97
+ }
98
+ }
99
+ catch {
100
+ // fall through to the default set
101
+ }
102
+ const resolved = langs.length > 0 ? langs : ["en", "uk"];
103
+ _langCache = resolved;
104
+ _langCacheKey = key;
105
+ return resolved;
106
+ }
107
+ /**
108
+ * Expand a title into a localized object covering every `languages` code.
109
+ *
110
+ * - object in → map each language to its own value; a language the source
111
+ * lacks falls back to the source's default (config.LANG, else the first
112
+ * non-empty value) so no slot is left blank.
113
+ * - string in → duplicate it into every language slot.
114
+ */
115
+ export function toMultiLang(title, languages) {
116
+ const langs = languages.length > 0 ? languages : ["en", "uk"];
117
+ const out = {};
118
+ if (isPlainObject(title)) {
119
+ const src = title;
120
+ const nonEmpty = Object.values(src).find((v) => typeof v === "string" && v.trim() !== "");
121
+ const preferred = src[config.LANG];
122
+ const fallback = typeof preferred === "string" && preferred.trim() !== ""
123
+ ? preferred
124
+ : nonEmpty ?? "";
125
+ for (const lang of langs) {
126
+ const v = src[lang];
127
+ out[lang] = typeof v === "string" && v.trim() !== "" ? v : fallback;
128
+ }
129
+ return out;
130
+ }
131
+ const s = typeof title === "string" ? title : "";
132
+ for (const lang of langs) {
133
+ out[lang] = s;
134
+ }
135
+ return out;
136
+ }
137
+ /** Resolve the tenant languages and expand `title` (falling back to `fallbackName`). */
138
+ async function _expandTitle(title, fallbackName) {
139
+ const langs = await resolvePlatformLanguages();
140
+ const base = isPlainObject(title) ? title : (title || fallbackName);
141
+ return toMultiLang(base, langs);
142
+ }
143
+ // ---------------------------------------------------------------------------
46
144
  // Tools
47
145
  // ---------------------------------------------------------------------------
48
146
  // Keys kept per entity in the default (slim) list_entities output. The raw
@@ -175,16 +273,17 @@ export async function getRecord(entityName, recordId, fieldsJson = '{"id": true}
175
273
  * to avoid a type clash with a field of the same name added later.
176
274
  */
177
275
  export async function createEntity(name, title, titleFieldName = "title", autoTitleField = true, titleFieldType = "multi-language") {
276
+ const titleObj = await _expandTitle(title, name);
178
277
  const body = {
179
278
  name,
180
- title: isPlainObject(title) ? title : { en: title },
279
+ title: titleObj,
181
280
  titleFieldName,
182
281
  fields: [],
183
282
  };
184
283
  const result = await makeRequest("POST", "/api/core/builder/create-entity", body);
185
284
  let titleFieldResult = null;
186
285
  if (autoTitleField && titleFieldName) {
187
- titleFieldResult = _parseMaybe(await addField(name, titleFieldName, titleFieldType, title));
286
+ titleFieldResult = _parseMaybe(await addField(name, titleFieldName, titleFieldType, titleObj));
188
287
  }
189
288
  // NOTE: we deliberately do NOT auto-set the representative field here. The only
190
289
  // builder endpoint that accepts it (POST /builder/{entity}/update with
@@ -223,9 +322,10 @@ export async function createTabularPart(parentEntity, name, title, titleFieldNam
223
322
  else {
224
323
  entityName = parentEntity + name;
225
324
  }
325
+ const titleObj = await _expandTitle(title, name);
226
326
  const body = {
227
327
  name: entityName,
228
- title: isPlainObject(title) ? title : { en: title },
328
+ title: titleObj,
229
329
  titleFieldName,
230
330
  type: "tabular-part",
231
331
  relationEntityName: parentEntity,
@@ -234,7 +334,7 @@ export async function createTabularPart(parentEntity, name, title, titleFieldNam
234
334
  const result = await makeRequest("POST", "/api/core/builder/create-entity", body);
235
335
  let titleFieldResult = null;
236
336
  if (autoTitleField && titleFieldName) {
237
- titleFieldResult = _parseMaybe(await addField(entityName, titleFieldName, titleFieldType, title));
337
+ titleFieldResult = _parseMaybe(await addField(entityName, titleFieldName, titleFieldType, titleObj));
238
338
  }
239
339
  return jsonResponse({
240
340
  tabular_part: result,
@@ -363,15 +463,90 @@ export async function setTitleField(entityName, fieldName) {
363
463
  note,
364
464
  });
365
465
  }
466
+ /**
467
+ * Pre-flight a relation field against the LIVE schema so we never create a
468
+ * broken or duplicate relation — either of which corrupts the entity:
469
+ * 1. the target entity must exist (a relation to a missing target is dangling);
470
+ * 2. the field must not already exist (re-adding e.g. a second `owner` on a
471
+ * tabular part conflicts with the platform-managed one).
472
+ *
473
+ * Case-only target mismatches (entity names are case-sensitive) are corrected to
474
+ * the real name rather than refused. Best-effort: a schema-read failure SKIPS
475
+ * the corresponding check rather than blocking a legitimate write (mirrors
476
+ * `_refShapeProblems`). Returns a refusal JSON string, or the resolved target.
477
+ */
478
+ async function _relationPreflight(entityName, fieldName, relationType, relationEntity) {
479
+ // 1. Target existence (+ case correction).
480
+ let listing;
481
+ try {
482
+ listing = await makeRequest("GET", "/api/core/schema");
483
+ }
484
+ catch {
485
+ return { relationEntity }; // can't verify → proceed (never block on a transient read)
486
+ }
487
+ if (Array.isArray(listing)) {
488
+ const names = listing
489
+ .filter((e) => isPlainObject(e))
490
+ .map((e) => String(e.name ?? ""))
491
+ .filter(Boolean);
492
+ if (names.length > 0 && !names.includes(relationEntity)) {
493
+ const ci = names.find((n) => n.toLowerCase() === relationEntity.toLowerCase());
494
+ if (ci) {
495
+ relationEntity = ci; // case-only mismatch → use the real (case-sensitive) name
496
+ }
497
+ else {
498
+ const rl = relationEntity.toLowerCase();
499
+ const near = names
500
+ .filter((n) => n.toLowerCase().includes(rl) || rl.includes(n.toLowerCase()))
501
+ .slice(0, 8);
502
+ return {
503
+ relationEntity,
504
+ error: jsonResponse({
505
+ error: `Refused: relation target '${relationEntity}' does not exist on this tenant. ` +
506
+ `Creating this ${relationType} field would leave a broken relation. Create the ` +
507
+ "target first (suppa_create_entity / suppa_create_tabular_part) or fix the name. " +
508
+ "If you just created it, retry in a moment (the schema list is briefly eventually-consistent).",
509
+ did_you_mean: near,
510
+ }),
511
+ };
512
+ }
513
+ }
514
+ }
515
+ // 2. The field must not already exist on this entity.
516
+ let schema;
517
+ try {
518
+ schema = await makeRequest("GET", `/api/core/schema/${entityName}`);
519
+ }
520
+ catch {
521
+ return { relationEntity }; // can't verify duplicate → proceed
522
+ }
523
+ const existing = _extractFields(schema)
524
+ .map((f) => f.name)
525
+ .filter((n) => Boolean(n));
526
+ if (existing.includes(fieldName)) {
527
+ return {
528
+ relationEntity,
529
+ error: jsonResponse({
530
+ error: `Refused: field '${fieldName}' already exists on '${entityName}'. This server is ` +
531
+ "add-only; re-adding a relation can duplicate or conflict with the existing field " +
532
+ "(e.g. a second 'owner' on a tabular part). If it is wrong, remove it in the UI first.",
533
+ }),
534
+ };
535
+ }
536
+ return { relationEntity };
537
+ }
366
538
  /**
367
539
  * Add a field to an existing entity.
368
540
  *
369
541
  * field_type: a real Suppa 2.0 type — text, numeric, integer, serial, boolean,
370
542
  * timestamp, json, uuid, multi-language, icon, enum, multi-enum, file, multi-file,
371
- * one-to-many, many-to-one, many-to-many, many-to-many-backref.
543
+ * many-to-one, many-to-many, many-to-many-backref.
372
544
  * There is NO date/datetime/richtext/email/url/phone/string type:
373
545
  * - date-only → field_type='timestamp' with sub_type='date'
374
546
  * - localized → field_type='multi-language'
547
+ * 'one-to-many' is REFUSED here: an owned child collection is a tabular part
548
+ * (suppa_create_tabular_part); the one-to-many side is auto-managed. Use
549
+ * 'many-to-many' for a shared lookup.
375
550
  * The legacy alias 'relation' is accepted and mapped to 'many-to-one'.
376
551
  * For relation fields, provide relation_entity. For enum fields, provide enum_name.
377
552
  * Constraints: max_length/min_length (text), decimal_places (numeric),
@@ -385,6 +560,25 @@ export async function addField(entityName, fieldName, fieldType, title, opts = {
385
560
  if (relationEntity && !RELATION_FIELD_TYPES.includes(resolvedType)) {
386
561
  resolvedType = "many-to-one";
387
562
  }
563
+ // GUARDRAIL: never create a one-to-many field manually. An owned child
564
+ // collection (repeating rows belonging to ONE parent record — e.g. BOM items
565
+ // of a part) must be a TABULAR PART: suppa_create_tabular_part auto-creates
566
+ // the child's `owner` relation and the parent-side link, so hand-building it
567
+ // as parent.one-to-many + child.owner produces a wrong, half-wired model.
568
+ // (Verified pain: FastenerBomItem created standalone + manual owner + manual
569
+ // `bom` one-to-many instead of a tabular part.) The reverse/one-to-many side
570
+ // is managed by the platform and is never added by hand.
571
+ if (resolvedType === "one-to-many") {
572
+ return jsonResponse({
573
+ error: "Refused: 'one-to-many' fields must not be created manually. For an owned " +
574
+ "child collection (repeating rows that belong to one parent record), create a " +
575
+ "TABULAR PART with suppa_create_tabular_part(parent_entity, name, ...) — it " +
576
+ "auto-creates the child's 'owner' relation and the parent link. For a shared " +
577
+ "lookup referenced by many records, use 'many-to-many' instead.",
578
+ hint: `suppa_create_tabular_part(parent_entity="${entityName}", name="<Child>") for an ` +
579
+ "owned child; suppa_add_field(field_type='many-to-many') for a shared lookup.",
580
+ });
581
+ }
388
582
  // Validate client-side: the builder's own errors for these are opaque.
389
583
  if (!VALID_FIELD_TYPES.includes(resolvedType)) {
390
584
  return jsonResponse({
@@ -407,10 +601,21 @@ export async function addField(entityName, fieldName, fieldType, title, opts = {
407
601
  "with suppa_add_enum_values.",
408
602
  });
409
603
  }
604
+ // Relation pre-flight: verify the target exists and the field is new, so we
605
+ // never leave a dangling or duplicate relation on the entity. May correct a
606
+ // case-only target-name mismatch.
607
+ let relTarget = relationEntity;
608
+ if (RELATION_FIELD_TYPES.includes(resolvedType) && relTarget) {
609
+ const pf = await _relationPreflight(entityName, fieldName, resolvedType, relTarget);
610
+ if (pf.error) {
611
+ return pf.error;
612
+ }
613
+ relTarget = pf.relationEntity;
614
+ }
410
615
  const fieldDef = {
411
616
  name: fieldName,
412
617
  type: resolvedType,
413
- title: isPlainObject(title) ? title : { en: title || fieldName },
618
+ title: await _expandTitle(title, fieldName),
414
619
  required,
415
620
  unique,
416
621
  };
@@ -436,8 +641,8 @@ export async function addField(entityName, fieldName, fieldType, title, opts = {
436
641
  if (onlyPositive) {
437
642
  fieldDef.isOnlyPositive = true;
438
643
  }
439
- if (relationEntity) {
440
- fieldDef.relationTarget = relationEntity;
644
+ if (relTarget) {
645
+ fieldDef.relationTarget = relTarget;
441
646
  }
442
647
  if (enumName) {
443
648
  fieldDef.enumName = enumName;
@@ -510,7 +715,12 @@ export async function listFieldTypes() {
510
715
  type: "many-to-one",
511
716
  description: "Relation: many records → one target (requires relation_entity)",
512
717
  },
513
- { type: "one-to-many", description: "Relation: one record → many targets" },
718
+ {
719
+ type: "one-to-many",
720
+ description: "Relation: one record → many targets. NOT creatable via suppa_add_field — an " +
721
+ "owned child collection is a tabular part (suppa_create_tabular_part); the " +
722
+ "one-to-many side is auto-managed by the platform.",
723
+ },
514
724
  { type: "many-to-many", description: "Relation: many ↔ many" },
515
725
  { type: "many-to-many-backref", description: "Back-reference side of a many-to-many" },
516
726
  { type: "file", description: "Single file attachment" },
@@ -531,20 +741,11 @@ const _MULTI_REF_TYPES = [
531
741
  /**
532
742
  * Detect relation/enum values the platform would silently store as NULL.
533
743
  *
534
- * Conservative on purpose: only flags values whose field type is positively
535
- * identified as a reference type AND whose shape is definitely wrong. If the
536
- * schema can't be read, validation is skipped — never block a write on a
537
- * transient schema error.
744
+ * Pure: works from an already-loaded field-definition list. Conservative — only
745
+ * flags values whose field type is positively identified as a reference type
746
+ * AND whose shape is definitely wrong.
538
747
  */
539
- async function _refShapeProblems(entityName, fields) {
540
- let defs;
541
- try {
542
- const schema = await makeRequest("GET", `/api/core/schema/${entityName}`);
543
- defs = _extractFields(schema);
544
- }
545
- catch {
546
- return [];
547
- }
748
+ function _shapeProblemsFromDefs(defs, fields) {
548
749
  const types = {};
549
750
  for (const f of defs) {
550
751
  if (f.name) {
@@ -580,17 +781,112 @@ async function _refShapeProblems(entityName, fields) {
580
781
  function _truncJson(val) {
581
782
  return jsonResponse(val).slice(0, 60);
582
783
  }
583
- async function _refuseSilentNull(entityName, fields) {
584
- const problems = await _refShapeProblems(entityName, fields);
585
- if (problems.length > 0) {
586
- return jsonResponse({
587
- error: "Refused: these values would be SILENTLY stored as NULL by the platform.",
588
- problems,
589
- hint: "Look up ids via suppa_search_records (Enums for enum values; the " +
590
- 'target entity for relations), then re-send as {"id": N}.',
591
- });
784
+ /** Live entity names on this tenant, or null if the schema list is unreadable. */
785
+ async function _liveEntityList() {
786
+ try {
787
+ const listing = await makeRequest("GET", "/api/core/schema");
788
+ if (!Array.isArray(listing)) {
789
+ return null;
790
+ }
791
+ return listing
792
+ .filter((e) => isPlainObject(e))
793
+ .map((e) => String(e.name ?? ""))
794
+ .filter(Boolean);
795
+ }
796
+ catch {
797
+ return null;
592
798
  }
593
- return null;
799
+ }
800
+ /**
801
+ * Resolve an entity name against the live schema so we never act on one that
802
+ * doesn't exist. Best-effort: an unreadable list means "can't verify" and the
803
+ * original name is returned (never block on a transient read). A case-only
804
+ * mismatch is corrected (entity names are case-sensitive); a genuine miss
805
+ * returns an error with near-matches.
806
+ */
807
+ async function _resolveEntity(name) {
808
+ const names = await _liveEntityList();
809
+ if (names === null || names.length === 0) {
810
+ return { name };
811
+ }
812
+ if (names.includes(name)) {
813
+ return { name };
814
+ }
815
+ const ci = names.find((n) => n.toLowerCase() === name.toLowerCase());
816
+ if (ci) {
817
+ return { name: ci };
818
+ }
819
+ const nl = name.toLowerCase();
820
+ const near = names
821
+ .filter((n) => n.toLowerCase().includes(nl) || nl.includes(n.toLowerCase()))
822
+ .slice(0, 8);
823
+ return {
824
+ name,
825
+ error: jsonResponse({
826
+ error: `Refused: entity '${name}' does not exist on this tenant — acting on a non-existent ` +
827
+ "entity would fail or create junk. Create it first (suppa_create_entity) or fix the " +
828
+ "name. If you just created it, retry in a moment (the schema list is briefly " +
829
+ "eventually-consistent).",
830
+ did_you_mean: near,
831
+ }),
832
+ };
833
+ }
834
+ /**
835
+ * Validate a record write end-to-end BEFORE touching the platform, so a
836
+ * hallucinated field/entity can never produce a broken record:
837
+ * 1. the entity must exist (case-corrected if needed);
838
+ * 2. every field key must be a real field on that entity — the platform
839
+ * silently DROPS unknown keys (a record missing that data), so we refuse;
840
+ * 3. relation/enum values must have the reference shape (else silently NULL).
841
+ *
842
+ * Reads the entity schema ONCE for (2)+(3). Best-effort: an unreadable schema
843
+ * skips field/shape checks rather than blocking a legitimate write. Returns the
844
+ * (possibly case-corrected) entity name and an error string when refused.
845
+ */
846
+ async function _validateRecordWrite(entityName, fields) {
847
+ const ent = await _resolveEntity(entityName);
848
+ if (ent.error) {
849
+ return { entityName, error: ent.error };
850
+ }
851
+ entityName = ent.name;
852
+ let defs;
853
+ try {
854
+ const schema = await makeRequest("GET", `/api/core/schema/${entityName}`);
855
+ defs = _extractFields(schema);
856
+ }
857
+ catch {
858
+ defs = null; // unreadable → can't validate fields; proceed
859
+ }
860
+ if (defs && defs.length > 0) {
861
+ const fieldNames = new Set(defs.map((f) => f.name).filter((n) => Boolean(n)));
862
+ const unknown = Object.keys(fields).filter((k) => !fieldNames.has(k));
863
+ if (unknown.length > 0) {
864
+ return {
865
+ entityName,
866
+ error: jsonResponse({
867
+ error: `Refused: field(s) [${unknown.join(", ")}] do not exist on '${entityName}'. ` +
868
+ "The platform silently drops unknown keys, so this would create a record missing " +
869
+ "that data (a 'broken' entity). Use only real fields (see valid_fields), or add " +
870
+ "the field first with suppa_add_field.",
871
+ unknown_fields: unknown,
872
+ valid_fields: [...fieldNames].sort(),
873
+ }),
874
+ };
875
+ }
876
+ const problems = _shapeProblemsFromDefs(defs, fields);
877
+ if (problems.length > 0) {
878
+ return {
879
+ entityName,
880
+ error: jsonResponse({
881
+ error: "Refused: these values would be SILENTLY stored as NULL by the platform.",
882
+ problems,
883
+ hint: "Look up ids via suppa_search_records (Enums for enum values; the " +
884
+ 'target entity for relations), then re-send as {"id": N}.',
885
+ }),
886
+ };
887
+ }
888
+ }
889
+ return { entityName };
594
890
  }
595
891
  /**
596
892
  * Create a new record in any entity. fields_json: JSON object of field values.
@@ -607,11 +903,11 @@ export async function createRecord(entityName, fieldsJson) {
607
903
  catch (e) {
608
904
  return jsonResponse({ error: e instanceof Error ? e.message : String(e) });
609
905
  }
610
- const refusal = await _refuseSilentNull(entityName, fields);
611
- if (refusal) {
612
- return refusal;
906
+ const v = await _validateRecordWrite(entityName, fields);
907
+ if (v.error) {
908
+ return v.error;
613
909
  }
614
- const result = await insertEntity(entityName, [fields]);
910
+ const result = await insertEntity(v.entityName, [fields]);
615
911
  return jsonResponse(result && result.length ? result[0] : null);
616
912
  }
617
913
  /**
@@ -630,10 +926,11 @@ export async function updateRecord(entityName, recordId, fieldsJson) {
630
926
  catch (e) {
631
927
  return jsonResponse({ error: e instanceof Error ? e.message : String(e) });
632
928
  }
633
- const refusal = await _refuseSilentNull(entityName, fields);
634
- if (refusal) {
635
- return refusal;
929
+ const v = await _validateRecordWrite(entityName, fields);
930
+ if (v.error) {
931
+ return v.error;
636
932
  }
933
+ entityName = v.entityName;
637
934
  const result = await updateEntity(entityName, recordId, fields);
638
935
  if (!result || (Array.isArray(result) && result.length === 0)) {
639
936
  return jsonResponse({
@@ -820,7 +1117,13 @@ export async function attachFileToRecord(entityName, recordId, filePath, fieldNa
820
1117
  * removed manually via the Suppa UI. Do not add one here.
821
1118
  */
822
1119
  export async function deleteRecord(entityName, recordId) {
823
- const result = await removeEntity(entityName, [makeFilter("id", recordId)]);
1120
+ // Verify the entity exists (best-effort) so a typo'd name gives a clear error
1121
+ // rather than an opaque platform failure.
1122
+ const ent = await _resolveEntity(entityName);
1123
+ if (ent.error) {
1124
+ return ent.error;
1125
+ }
1126
+ const result = await removeEntity(ent.name, [makeFilter("id", recordId)]);
824
1127
  return jsonResponse(result);
825
1128
  }
826
1129
  // ---------------------------------------------------------------------------