suppa-mcp-2 1.1.2 → 1.1.4

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/auth.js CHANGED
@@ -448,51 +448,78 @@ export function browserGoogleLogin(host, timeout = 180) {
448
448
  return new Promise((resolve, reject) => {
449
449
  let settled = false;
450
450
  let timer;
451
+ // Guarded response: writing to an already-closed socket throws, which in a
452
+ // bare request callback becomes an uncaughtException and kills the process.
453
+ const safeRespond = (res, status, ctype, body) => {
454
+ try {
455
+ if (!res.writableEnded) {
456
+ res.writeHead(status, { "Content-Type": ctype });
457
+ res.end(body);
458
+ }
459
+ }
460
+ catch {
461
+ /* socket already gone — ignore */
462
+ }
463
+ };
451
464
  const server = createServer((req, res) => {
452
- const method = req.method ?? "GET";
453
- const url = req.url ?? "/";
454
- if (method === "GET") {
455
- res.writeHead(200, { "Content-Type": "text/html; charset=utf-8" });
456
- res.end(page);
457
- return;
465
+ // A client that aborts mid-request makes `req` emit 'error'; with no
466
+ // listener Node re-throws it as an uncaughtException. Swallow it.
467
+ req.on("error", () => {
468
+ /* client aborted — ignore */
469
+ });
470
+ try {
471
+ const method = req.method ?? "GET";
472
+ const url = req.url ?? "/";
473
+ if (method === "GET") {
474
+ safeRespond(res, 200, "text/html; charset=utf-8", page);
475
+ return;
476
+ }
477
+ if (method === "POST" && url === "/callback") {
478
+ const chunks = [];
479
+ req.on("data", (c) => chunks.push(c));
480
+ req.on("end", () => {
481
+ try {
482
+ let data = {};
483
+ try {
484
+ const raw = Buffer.concat(chunks).toString("utf-8") || "{}";
485
+ data = JSON.parse(raw);
486
+ }
487
+ catch {
488
+ data = {};
489
+ }
490
+ const cred = typeof data.credential === "string" ? data.credential : "";
491
+ let msg;
492
+ let error = null;
493
+ let idToken = null;
494
+ if (data.state !== state) {
495
+ error = "state mismatch (possible CSRF) — login rejected";
496
+ msg = "Login rejected.";
497
+ }
498
+ else if (cred) {
499
+ idToken = cred;
500
+ msg = "Signed in successfully.";
501
+ }
502
+ else {
503
+ error = "no credential returned by Google";
504
+ msg = "Login failed.";
505
+ }
506
+ safeRespond(res, 200, "text/plain; charset=utf-8", msg);
507
+ finish(error, idToken);
508
+ }
509
+ catch (e) {
510
+ // Never let the 'end' callback throw escape to uncaughtException.
511
+ finish(e instanceof Error ? e.message : String(e), null);
512
+ }
513
+ });
514
+ return;
515
+ }
516
+ // Any other request: just serve the page.
517
+ safeRespond(res, 200, "text/html; charset=utf-8", page);
458
518
  }
459
- if (method === "POST" && url === "/callback") {
460
- const chunks = [];
461
- req.on("data", (c) => chunks.push(c));
462
- req.on("end", () => {
463
- let data = {};
464
- try {
465
- const raw = Buffer.concat(chunks).toString("utf-8") || "{}";
466
- data = JSON.parse(raw);
467
- }
468
- catch {
469
- data = {};
470
- }
471
- const cred = typeof data.credential === "string" ? data.credential : "";
472
- let msg;
473
- let error = null;
474
- let idToken = null;
475
- if (data.state !== state) {
476
- error = "state mismatch (possible CSRF) — login rejected";
477
- msg = "Login rejected.";
478
- }
479
- else if (cred) {
480
- idToken = cred;
481
- msg = "Signed in successfully.";
482
- }
483
- else {
484
- error = "no credential returned by Google";
485
- msg = "Login failed.";
486
- }
487
- res.writeHead(200, { "Content-Type": "text/plain; charset=utf-8" });
488
- res.end(msg);
489
- finish(error, idToken);
490
- });
491
- return;
519
+ catch (e) {
520
+ // Contain any synchronous throw in the request handler.
521
+ finish(e instanceof Error ? e.message : String(e), null);
492
522
  }
493
- // Any other request: just serve the page.
494
- res.writeHead(200, { "Content-Type": "text/html; charset=utf-8" });
495
- res.end(page);
496
523
  });
497
524
  const finish = (error, idToken) => {
498
525
  if (settled) {
package/dist/bin.js CHANGED
@@ -7,5 +7,27 @@
7
7
  */
8
8
  import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
9
9
  import { buildServer } from "./server.js";
10
- const server = buildServer();
11
- await server.connect(new StdioServerTransport());
10
+ // Safety net: a long-running MCP stdio server must never be killed by a stray
11
+ // async rejection or a synchronous throw in some callback (a background token
12
+ // refresh, an aborted login-loopback request, a write to a closed socket…).
13
+ // Node's default is to terminate the process, which drops the client connection
14
+ // ("Connection closed"). Log to stderr and keep serving instead. These fire
15
+ // only for errors that escaped every local handler; normal per-request errors
16
+ // are already turned into MCP error responses by the SDK.
17
+ process.on("unhandledRejection", (reason) => {
18
+ const msg = reason instanceof Error ? reason.stack || reason.message : String(reason);
19
+ process.stderr.write(`[suppa-mcp] unhandled rejection (ignored): ${msg}\n`);
20
+ });
21
+ process.on("uncaughtException", (err) => {
22
+ process.stderr.write(`[suppa-mcp] uncaught exception (ignored): ${err instanceof Error ? err.stack || err.message : String(err)}\n`);
23
+ });
24
+ // Startup is the one place a failure SHOULD stop the process — if the server
25
+ // can't build or connect, there's nothing to serve.
26
+ try {
27
+ const server = buildServer();
28
+ await server.connect(new StdioServerTransport());
29
+ }
30
+ catch (e) {
31
+ process.stderr.write(`[suppa-mcp] fatal startup error: ${e instanceof Error ? e.stack || e.message : String(e)}\n`);
32
+ process.exit(1);
33
+ }
package/dist/server.js CHANGED
@@ -199,7 +199,7 @@ export function buildServer() {
199
199
  // Reset so repeated buildServer() calls (e.g. in tests) do not double-count.
200
200
  TOOL_NAMES.length = 0;
201
201
  PROMPT_NAMES.length = 0;
202
- const server = new McpServer({ name: "suppa-2.0", version: "1.1.2" }, { instructions: INSTRUCTIONS });
202
+ const server = new McpServer({ name: "suppa-2.0", version: "1.1.4" }, { instructions: INSTRUCTIONS });
203
203
  const reg = (name, cfg, handler) => {
204
204
  server.registerTool(name, {
205
205
  description: cfg.description,
@@ -1213,12 +1213,26 @@ export function buildServer() {
1213
1213
  annotations: _READ,
1214
1214
  }, async (a) => text(await migrate.readV1Entities(a.search)));
1215
1215
  reg("suppa_read_v1_entity_props", {
1216
- description: "List the fields (properties) of one Suppa 1.0 entity (read-only).",
1216
+ description: "Describe ALL fields of one Suppa 1.0 entity (read-only). Returns a clean, " +
1217
+ "type-aware summary per field (type, sub_type, relation target, constraints, " +
1218
+ "required/readonly/visible flags, title), resolves custom-enum values inline, " +
1219
+ "and — for tabular parts (Табличні частини, i.e. one-to-many relations into " +
1220
+ "custom child entities) — expands the child entity's own fields. Also returns " +
1221
+ "`tabular_parts` (child-table field names) and `relations` (every relation + its target).",
1217
1222
  inputSchema: {
1218
1223
  entity: z.string().describe("Suppa 1.0 entity name or alias."),
1224
+ expand: z
1225
+ .boolean()
1226
+ .default(true)
1227
+ .describe("Expand tabular-part / custom relation targets one level to include their fields (default true). " +
1228
+ "Set false for a flat, cheaper listing."),
1229
+ resolve_enums: z
1230
+ .boolean()
1231
+ .default(true)
1232
+ .describe("Resolve custom-enum fields to their value labels (default true)."),
1219
1233
  },
1220
1234
  annotations: _READ,
1221
- }, async (a) => text(await migrate.readV1EntityProps(a.entity)));
1235
+ }, async (a) => text(await migrate.readV1EntityProps(a.entity, a.expand, a.resolve_enums)));
1222
1236
  reg("suppa_read_v1_enum", {
1223
1237
  description: "Read a Suppa 1.0 custom-enum's values (read-only).",
1224
1238
  inputSchema: {
package/dist/tenants.js CHANGED
@@ -153,7 +153,18 @@ export function activate(baseUrl, host) {
153
153
  */
154
154
  export async function ensureValid(ctx) {
155
155
  const auth = await import("./auth.js");
156
- auth.maybeRefresh(ctx);
156
+ // Must AWAIT: maybeRefresh can reject (dead/expired refresh token →
157
+ // ReloginRequired, or a keychain write error). A fire-and-forget call would
158
+ // surface that as an UNHANDLED promise rejection, which crashes the whole
159
+ // MCP stdio server ("Connection closed"). Swallow it here — the pending
160
+ // request then proceeds with the current token and, if it's truly invalid,
161
+ // gets a clean 401 → "run suppa_login" from httpClient instead of a crash.
162
+ try {
163
+ await auth.maybeRefresh(ctx);
164
+ }
165
+ catch {
166
+ /* refresh failed — non-fatal; the request path surfaces a clean 401 */
167
+ }
157
168
  }
158
169
  /** Force a token refresh (used after a 401). Returns True on success. */
159
170
  export async function reauth(ctx) {
@@ -153,6 +153,80 @@ async function _v1EnumValues(prop) {
153
153
  }
154
154
  return out;
155
155
  }
156
+ /**
157
+ * Fetch `api/all_entities` once and index it by id and by lowercased name/alias.
158
+ * Reused when expanding relation targets so we don't re-fetch the full list per
159
+ * relation.
160
+ */
161
+ async function _v1EntityMaps() {
162
+ const byId = new Map();
163
+ const byKey = new Map();
164
+ const all = await _v1Request("api/all_entities");
165
+ for (const e of (Array.isArray(all) ? all : [])) {
166
+ if (!_isDict(e)) {
167
+ continue;
168
+ }
169
+ if (e.id) {
170
+ byId.set(String(e.id), e);
171
+ }
172
+ const nm = String(e.name ?? "").toLowerCase();
173
+ const al = String(e.alias ?? "").toLowerCase();
174
+ if (nm) {
175
+ byKey.set(nm, e);
176
+ }
177
+ if (al) {
178
+ byKey.set(al, e);
179
+ }
180
+ }
181
+ return { byId, byKey };
182
+ }
183
+ /**
184
+ * Condense a raw Suppa 1.0 property (~40 mostly-null keys) into the meaningful
185
+ * field metadata: type, sub_type, relation target, constraints, flags, title.
186
+ * Enum values and relation child-fields are attached by the caller.
187
+ */
188
+ function _summarizeV1Field(p) {
189
+ const s = { name: p.name, type: p.type };
190
+ if (p.title) {
191
+ s.title = p.title;
192
+ }
193
+ if (p.sub_type) {
194
+ s.sub_type = p.sub_type;
195
+ }
196
+ if (p.multiple === true) {
197
+ s.multiple = true;
198
+ }
199
+ // v1 flags are strings ("never"/"always"/a condition) — surface only the
200
+ // non-default ones so the summary stays readable.
201
+ if (p.required && p.required !== "never") {
202
+ s.required = p.required;
203
+ }
204
+ if (p.readonly && p.readonly !== "never") {
205
+ s.readonly = p.readonly;
206
+ }
207
+ if (p.visible && p.visible !== "always") {
208
+ s.visible = p.visible;
209
+ }
210
+ if (p.system === true) {
211
+ s.system = true;
212
+ }
213
+ if (p.default_value !== null && p.default_value !== undefined && p.default_value !== "") {
214
+ s.default_value = p.default_value;
215
+ }
216
+ for (const k of ["max_length", "min_length", "min_value", "max_value", "precision"]) {
217
+ if (p[k] !== null && p[k] !== undefined && p[k] !== 0) {
218
+ s[k] = p[k];
219
+ }
220
+ }
221
+ if (p.type === "relation") {
222
+ const rel = _isDict(p.relation) ? p.relation : {};
223
+ s.relation_target = rel.relation_target_entity_name ?? rel.relation_target_entity_id ?? null;
224
+ if (rel.relation_type) {
225
+ s.relation_type = rel.relation_type;
226
+ }
227
+ }
228
+ return s;
229
+ }
156
230
  /** Find one 1.0 entity by name or alias (case-insensitive). */
157
231
  async function _resolveV1Entity(nameOrAlias) {
158
232
  const key = (nameOrAlias || "").trim().toLowerCase();
@@ -209,20 +283,95 @@ export async function readV1Entities(search = "") {
209
283
  *
210
284
  * entity: 1.0 entity name or alias.
211
285
  */
212
- export async function readV1EntityProps(entity) {
213
- const ent = await _resolveV1Entity(entity);
286
+ export async function readV1EntityProps(entity, expand = true, resolveEnums = true) {
287
+ const maps = await _v1EntityMaps();
288
+ const ent = maps.byKey.get((entity || "").trim().toLowerCase()) ??
289
+ maps.byId.get((entity || "").trim());
214
290
  if (!ent) {
215
291
  return jsonResponse({ error: `No Suppa 1.0 entity named/aliased '${entity}'.` });
216
292
  }
217
- let props = await _v1Request(`api/entity_props/${ent.id}`);
218
- if (!Array.isArray(props)) {
219
- props = [];
293
+ const rawProps = await _v1Request(`api/entity_props/${ent.id}`);
294
+ const props = (Array.isArray(rawProps) ? rawProps : []).filter((p) => _isDict(p) && p.type != null);
295
+ // Memoize child entity_props so two relations to the same target only fetch once.
296
+ const childCache = new Map();
297
+ const childFields = async (targetKey) => {
298
+ const child = maps.byKey.get(targetKey.toLowerCase()) ?? maps.byId.get(targetKey);
299
+ if (!child || !child.id) {
300
+ return null;
301
+ }
302
+ const cid = String(child.id);
303
+ if (!childCache.has(cid)) {
304
+ const cp = await _v1Request(`api/entity_props/${cid}`);
305
+ childCache.set(cid, (Array.isArray(cp) ? cp : [])
306
+ .filter((x) => _isDict(x) && x.type != null)
307
+ .map(_summarizeV1Field));
308
+ }
309
+ return childCache.get(cid) ?? null;
310
+ };
311
+ const fields = [];
312
+ const relations = [];
313
+ const tabularParts = [];
314
+ for (const p of props) {
315
+ const s = _summarizeV1Field(p);
316
+ if ((p.type === "custom_enum" || p.type === "enum") && resolveEnums) {
317
+ try {
318
+ const vals = await _v1EnumValues(p);
319
+ if (vals.length) {
320
+ s.enum_values = vals;
321
+ }
322
+ }
323
+ catch {
324
+ /* enum values unavailable — leave the field without them */
325
+ }
326
+ const ce = _isDict(p.custom_enum) ? p.custom_enum : {};
327
+ if (ce.enum_id) {
328
+ s.enum_id = ce.enum_id;
329
+ }
330
+ }
331
+ if (p.type === "relation") {
332
+ const rel = _isDict(p.relation) ? p.relation : {};
333
+ const targetName = rel.relation_target_entity_name ?? rel.relation_target_entity_id;
334
+ const targetKey = targetName ? String(targetName) : "";
335
+ const target = targetKey
336
+ ? maps.byKey.get(targetKey.toLowerCase()) ?? maps.byId.get(targetKey)
337
+ : null;
338
+ const isSelf = target ? String(target.id) === String(ent.id) : false;
339
+ const isBuiltin = target ? Boolean(target.builtin) : false;
340
+ relations.push({
341
+ field: p.name,
342
+ target: targetKey || null,
343
+ multiple: p.multiple === true,
344
+ sub_type: p.sub_type,
345
+ });
346
+ // A tabular part ("Табличні частини") is an OWNED child: the target entity
347
+ // carries an `owner` relation pointing back to THIS entity. (Multi-valued
348
+ // many-to-many fields like `skills`/`vacancies` are shared lookups, NOT
349
+ // child tables — `multiple` is not the marker.) Only owned children are
350
+ // expanded, with the platform-managed owner field(s) hidden.
351
+ if (target && !isSelf && !isBuiltin) {
352
+ const cf = await childFields(targetKey);
353
+ const ownsBack = cf != null &&
354
+ cf.some((f) => f.name === "owner" &&
355
+ [String(ent.name).toLowerCase(), String(ent.alias).toLowerCase()].includes(String(f.relation_target ?? "").toLowerCase()));
356
+ if (ownsBack) {
357
+ tabularParts.push(String(p.name));
358
+ if (expand && cf) {
359
+ s.child_entity = targetKey;
360
+ s.child_fields = cf.filter((f) => f.name !== "owner" && f.name !== "owner_id");
361
+ }
362
+ }
363
+ }
364
+ }
365
+ fields.push(s);
220
366
  }
221
367
  return jsonResponse({
222
368
  entity: ent.name,
223
369
  alias: ent.alias,
224
- field_count: props.length,
225
- fields: props,
370
+ id: ent.id,
371
+ field_count: fields.length,
372
+ tabular_parts: tabularParts,
373
+ relations,
374
+ fields,
226
375
  });
227
376
  }
228
377
  /**
@@ -314,6 +463,114 @@ export async function readV1Enum(enumInput) {
314
463
  function _enumNameFor(entityName, fieldName) {
315
464
  return `${entityName}_${fieldName}`;
316
465
  }
466
+ /**
467
+ * Classify one 1.0 entity's props into scalar/enum/relation buckets and choose a
468
+ * title field. `dropNames` skips specific field names (used to drop a tabular
469
+ * part's `owner` field, which the platform auto-creates). Shared by top-level
470
+ * entities and their tabular-part children.
471
+ */
472
+ async function _planFields(props, entName, v2EntName, targetResolver, entIndex, warnings, dropNames = new Set()) {
473
+ const scalarFields = [];
474
+ const enumFields = [];
475
+ const relationFields = [];
476
+ for (const p of props) {
477
+ if (!_isDict(p) || p.system) {
478
+ continue; // system/built-in fields are auto-created in 2.0
479
+ }
480
+ const fname = String(p.name ?? "");
481
+ if (dropNames.has(fname)) {
482
+ continue; // e.g. a tabular part's `owner` (auto-created by the platform)
483
+ }
484
+ const v2Fname = normalizeFieldName(fname);
485
+ const ftitle = String(p.title ?? "") || fname;
486
+ const ftype = String(p.type ?? "");
487
+ const fsub = typeof p.sub_type === "string" ? p.sub_type : null;
488
+ const required = !["", "never", "false"].includes(String(p.required ?? "never").toLowerCase());
489
+ const rawLen = p.max_length;
490
+ const maxLength = typeof rawLen === "number" && Number.isInteger(rawLen) && rawLen > 0 ? rawLen : null;
491
+ const rawPrec = p.precision;
492
+ const decimalPlaces = typeof rawPrec === "number" && Number.isInteger(rawPrec) && rawPrec > 0 ? rawPrec : null;
493
+ const cls = classifyV1Field(ftype, fsub, { isSystem: Boolean(p.system) });
494
+ if (cls.kind === KIND_SKIP) {
495
+ warnings.push(`${entName}.${fname}: ${cls.note || `unsupported type ${ftype}/${fsub}`} — skipped`);
496
+ continue;
497
+ }
498
+ if (cls.kind === KIND_RELATION) {
499
+ const rel = _isDict(p.relation) ? p.relation : {};
500
+ const target = String(rel.relation_target_entity_name ?? "");
501
+ const v2Target = targetResolver[target.toLowerCase()];
502
+ const inSet = v2Target !== undefined;
503
+ if (target && !inSet) {
504
+ warnings.push(`${entName}.${fname}: relation target '${target}' is not in the migration set`);
505
+ }
506
+ relationFields.push({
507
+ v1_name: fname,
508
+ name: v2Fname,
509
+ title: ftitle,
510
+ type: cls.v2Type,
511
+ required,
512
+ relation_entity: v2Target ?? (target ? normalizeEntityName(target) : null),
513
+ target_in_set: inSet,
514
+ });
515
+ continue;
516
+ }
517
+ if (cls.kind === KIND_ENUM) {
518
+ const values = await _v1EnumValues(p);
519
+ enumFields.push({
520
+ v1_name: fname,
521
+ name: v2Fname,
522
+ title: ftitle,
523
+ type: cls.v2Type,
524
+ required,
525
+ enum_name: _enumNameFor(v2EntName, v2Fname),
526
+ values,
527
+ });
528
+ continue;
529
+ }
530
+ if (cls.kind === KIND_SCALAR || cls.kind === KIND_FILE) {
531
+ const field = {
532
+ v1_name: fname,
533
+ name: v2Fname,
534
+ title: ftitle,
535
+ type: cls.v2Type,
536
+ required,
537
+ sub_type: cls.v2SubType,
538
+ max_length: cls.v2Type === "text" ? maxLength : null,
539
+ decimal_places: cls.v2Type === "numeric" ? decimalPlaces : null,
540
+ multilingual: cls.multilingual,
541
+ };
542
+ if (cls.note) {
543
+ field.note = cls.note;
544
+ }
545
+ scalarFields.push(field);
546
+ continue;
547
+ }
548
+ warnings.push(`${entName}.${fname}: unclassified field '${ftype}/${fsub}' — skipped`);
549
+ }
550
+ const scalarNames = scalarFields.map((f) => f.name);
551
+ const textLike = scalarFields
552
+ .filter((f) => f.type === "text" || f.type === "multi-language")
553
+ .map((f) => f.name);
554
+ let titleFieldName;
555
+ if (scalarNames.includes("name")) {
556
+ titleFieldName = "name";
557
+ }
558
+ else if (scalarNames.includes("title")) {
559
+ titleFieldName = "title";
560
+ }
561
+ else if (textLike.length > 0) {
562
+ titleFieldName = textLike[0];
563
+ }
564
+ else {
565
+ titleFieldName = scalarNames.length > 0 ? scalarNames[0] : "name";
566
+ }
567
+ const allV1FieldNames = [
568
+ ...scalarFields.map((f) => f.v1_name),
569
+ ...enumFields.map((f) => f.v1_name),
570
+ ...relationFields.map((f) => f.v1_name),
571
+ ];
572
+ return { scalarFields, enumFields, relationFields, allV1FieldNames, titleFieldName };
573
+ }
317
574
  // ---------------------------------------------------------------------------
318
575
  // Planning
319
576
  // ---------------------------------------------------------------------------
@@ -354,16 +611,40 @@ export async function _buildPlan(entityNames = "", includeBuiltin = false, skipR
354
611
  }
355
612
  }
356
613
  }
357
- const planEntities = [];
614
+ // Index ALL 1.0 entities (not just selected) so relation/tabular targets can
615
+ // be resolved and their `builtin` flag checked even when outside the selection.
616
+ const entIndex = new Map();
617
+ for (const e of allEntities) {
618
+ if (!_isDict(e)) {
619
+ continue;
620
+ }
621
+ const v1Name = String(e.name ?? "");
622
+ const alias = String(e.alias ?? "");
623
+ const info = {
624
+ v1Name,
625
+ alias: alias || v1Name,
626
+ builtin: Boolean(e.builtin),
627
+ id: String(e.id ?? ""),
628
+ };
629
+ if (v1Name) {
630
+ entIndex.set(v1Name.toLowerCase(), info);
631
+ }
632
+ if (alias) {
633
+ entIndex.set(alias.toLowerCase(), info);
634
+ }
635
+ }
358
636
  const warnings = [];
359
- for (const e of selected) {
360
- const entName = String(e.name ?? "");
361
- const entTitle = String(e.alias ?? "") || entName;
362
- const entId = e.id;
363
- const v2EntName = normalizeEntityName(entName);
637
+ // Fetch + cache each entity's props once (children may be fetched on demand).
638
+ const propsCache = new Map();
639
+ const fetchProps = async (id, entName) => {
640
+ const key = entName.toLowerCase();
641
+ const cached = propsCache.get(key);
642
+ if (cached) {
643
+ return cached;
644
+ }
364
645
  let props;
365
646
  try {
366
- props = await _v1Request(`api/entity_props/${entId}`);
647
+ props = await _v1Request(`api/entity_props/${id}`);
367
648
  }
368
649
  catch (ex) {
369
650
  if (!(ex instanceof Error)) {
@@ -372,136 +653,98 @@ export async function _buildPlan(entityNames = "", includeBuiltin = false, skipR
372
653
  warnings.push(`${entName}: failed to read props (${ex.message})`);
373
654
  props = [];
374
655
  }
375
- if (!Array.isArray(props)) {
376
- props = [];
656
+ const arr = Array.isArray(props) ? props : [];
657
+ propsCache.set(key, arr);
658
+ return arr;
659
+ };
660
+ // Phase A: detect tabular-part children. The reliable v1 marker is CHILD-side:
661
+ // a tabular part carries an `owner` relation pointing back to its parent.
662
+ // (Multi-valued many-to-many fields like `skills`/`vacancies` are shared
663
+ // lookups, NOT owned child tables — they stay normal relations.) A child is
664
+ // only nested when its parent is also in the migration set.
665
+ const selectedLower = new Set();
666
+ for (const e of selected) {
667
+ selectedLower.add(String(e.name ?? "").toLowerCase());
668
+ if (e.alias) {
669
+ selectedLower.add(String(e.alias).toLowerCase());
377
670
  }
378
- const scalarFields = [];
379
- const enumFields = [];
380
- const relationFields = [];
381
- for (const p of props) {
382
- if (!_isDict(p)) {
383
- continue;
384
- }
385
- if (p.system) {
386
- // System/built-in fields (id, createdAt, *_id, ...) are auto-created in 2.0.
387
- continue;
388
- }
389
- const fname = String(p.name ?? "");
390
- const v2Fname = normalizeFieldName(fname);
391
- const ftitle = String(p.title ?? "") || fname;
392
- const ftype = String(p.type ?? "");
393
- const fsub = typeof p.sub_type === "string" ? p.sub_type : null;
394
- const required = !["", "never", "false"].includes(String(p.required ?? "never").toLowerCase());
395
- // max_length: 0 (or None) means "unlimited" in 1.0 -> omit in 2.0.
396
- const rawLen = p.max_length;
397
- const maxLength = typeof rawLen === "number" && Number.isInteger(rawLen) && rawLen > 0 ? rawLen : null;
398
- const rawPrec = p.precision;
399
- const decimalPlaces = typeof rawPrec === "number" && Number.isInteger(rawPrec) && rawPrec > 0 ? rawPrec : null;
400
- // Classify against the hardcoded 1.0 field catalog (v1Fields.ts).
401
- const cls = classifyV1Field(ftype, fsub, { isSystem: Boolean(p.system) });
402
- if (cls.kind === KIND_SKIP) {
403
- warnings.push(`${entName}.${fname}: ${cls.note || `unsupported type ${ftype}/${fsub}`} — skipped`);
404
- continue;
671
+ }
672
+ const ownerOf = new Map(); // childV1(lower) -> parentV1 (canonical)
673
+ for (const e of selected) {
674
+ const entName = String(e.name ?? "");
675
+ const props = await fetchProps(String(e.id ?? ""), entName);
676
+ const ownerField = props.find((p) => _isDict(p) && p.name === "owner" && p.type === "relation");
677
+ if (!ownerField) {
678
+ continue;
679
+ }
680
+ const rel = _isDict(ownerField.relation) ? ownerField.relation : {};
681
+ const parentInfo = entIndex.get(String(rel.relation_target_entity_name ?? "").toLowerCase());
682
+ if (parentInfo && selectedLower.has(parentInfo.v1Name.toLowerCase())) {
683
+ ownerOf.set(entName.toLowerCase(), parentInfo.v1Name);
684
+ }
685
+ else if (parentInfo) {
686
+ warnings.push(`${entName}: is a tabular part of '${parentInfo.v1Name}', which is not in the migration set — migrating standalone`);
687
+ }
688
+ }
689
+ const isChild = (nameLower) => ownerOf.has(nameLower);
690
+ // Phase B: emit top-level entities; nest each parent's tabular-part children
691
+ // (dropping their platform-managed `owner` field).
692
+ const planEntities = [];
693
+ let tabularCount = 0;
694
+ for (const e of selected) {
695
+ const entName = String(e.name ?? "");
696
+ const entLower = entName.toLowerCase();
697
+ if (isChild(entLower)) {
698
+ const parent = ownerOf.get(entLower);
699
+ if (!isChild(parent.toLowerCase())) {
700
+ continue; // nested under its parent below (v2 supports one level)
405
701
  }
406
- // Relations (FK / many-to-many) — second pass, once targets exist.
407
- if (cls.kind === KIND_RELATION) {
408
- if (skipRelations) {
409
- continue;
410
- }
411
- const rel = _isDict(p.relation) ? p.relation : {};
412
- const target = _isDict(rel) ? String(rel.relation_target_entity_name ?? "") : "";
413
- const v2Target = targetResolver[target.toLowerCase()];
414
- const inSet = v2Target !== undefined;
415
- if (target && !inSet) {
416
- warnings.push(`${entName}.${fname}: relation target '${target}' is not in the migration set`);
702
+ warnings.push(`${entName}: nested tabular part (parent '${parent}' is itself a tabular part) — migrating standalone`);
703
+ }
704
+ const entTitle = String(e.alias ?? "") || entName;
705
+ const v2EntName = normalizeEntityName(entName);
706
+ const props = await fetchProps(String(e.id ?? ""), entName);
707
+ const pf = await _planFields(props, entName, v2EntName, targetResolver, entIndex, warnings);
708
+ const tabularParts = [];
709
+ if (!isChild(entLower)) {
710
+ for (const c of selected) {
711
+ const cName = String(c.name ?? "");
712
+ if (ownerOf.get(cName.toLowerCase()) !== entName) {
713
+ continue; // not a tabular part of this entity
417
714
  }
418
- relationFields.push({
419
- v1_name: fname,
420
- name: v2Fname,
421
- title: ftitle,
422
- type: cls.v2Type,
423
- required,
424
- relation_entity: v2Target ?? (target ? normalizeEntityName(target) : null),
425
- target_in_set: inSet,
426
- });
427
- continue;
428
- }
429
- // Enums (single 'enum' / 'multi-enum') — values seeded before the field.
430
- if (cls.kind === KIND_ENUM) {
431
- const values = await _v1EnumValues(p);
432
- enumFields.push({
433
- v1_name: fname,
434
- name: v2Fname,
435
- title: ftitle,
436
- type: cls.v2Type,
437
- required,
438
- enum_name: _enumNameFor(v2EntName, v2Fname),
439
- values,
715
+ const cprops = await fetchProps(String(c.id ?? ""), cName);
716
+ const cv2 = normalizeEntityName(cName);
717
+ const cf = await _planFields(cprops, cName, cv2, targetResolver, entIndex, warnings, new Set(["owner", "owner_id"]));
718
+ tabularParts.push({
719
+ v1_name: cName,
720
+ name: cv2,
721
+ title: String(c.alias ?? "") || cName,
722
+ title_field_name: cf.titleFieldName,
723
+ scalar_fields: cf.scalarFields,
724
+ enum_fields: cf.enumFields,
725
+ relation_fields: skipRelations ? [] : cf.relationFields,
726
+ name_map: buildNameMap(cName, cf.allV1FieldNames),
440
727
  });
441
- continue;
728
+ tabularCount++;
442
729
  }
443
- // Scalars + file attachments (file / multi-file are added like scalars).
444
- if (cls.kind === KIND_SCALAR || cls.kind === KIND_FILE) {
445
- const field = {
446
- v1_name: fname,
447
- name: v2Fname,
448
- title: ftitle,
449
- type: cls.v2Type,
450
- required,
451
- sub_type: cls.v2SubType,
452
- max_length: cls.v2Type === "text" ? maxLength : null,
453
- decimal_places: cls.v2Type === "numeric" ? decimalPlaces : null,
454
- multilingual: cls.multilingual,
455
- };
456
- if (cls.note) {
457
- field.note = cls.note;
458
- }
459
- scalarFields.push(field);
460
- continue;
461
- }
462
- // Defensive: an unclassified kind should never reach here.
463
- warnings.push(`${entName}.${fname}: unclassified field '${ftype}/${fsub}' — skipped`);
464
- }
465
- // Choose the entity title field: prefer 'name', then 'title', then the first
466
- // text-like scalar (a number/date/boolean/icon makes a poor display title),
467
- // then any scalar, else 'name'.
468
- const scalarNames = scalarFields.map((f) => f.name);
469
- const textLike = scalarFields
470
- .filter((f) => f.type === "text" || f.type === "multi-language")
471
- .map((f) => f.name);
472
- let titleField;
473
- if (scalarNames.includes("name")) {
474
- titleField = "name";
475
- }
476
- else if (scalarNames.includes("title")) {
477
- titleField = "title";
478
- }
479
- else if (textLike.length > 0) {
480
- titleField = textLike[0];
481
- }
482
- else {
483
- titleField = scalarNames.length > 0 ? scalarNames[0] : "name";
484
730
  }
485
- const allV1FieldNames = [
486
- ...scalarFields.map((f) => f.v1_name),
487
- ...enumFields.map((f) => f.v1_name),
488
- ...relationFields.map((f) => f.v1_name),
489
- ];
490
731
  planEntities.push({
491
732
  v1_name: entName,
492
733
  name: v2EntName,
493
734
  title: entTitle,
494
- title_field_name: titleField,
495
- scalar_fields: scalarFields,
496
- enum_fields: enumFields,
497
- relation_fields: relationFields,
498
- name_map: buildNameMap(entName, allV1FieldNames),
735
+ title_field_name: pf.titleFieldName,
736
+ scalar_fields: pf.scalarFields,
737
+ enum_fields: pf.enumFields,
738
+ relation_fields: skipRelations ? [] : pf.relationFields,
739
+ tabular_parts: tabularParts,
740
+ name_map: buildNameMap(entName, pf.allV1FieldNames),
499
741
  });
500
742
  }
501
743
  return {
502
744
  source: config.V1_BASE_URL,
503
745
  target: tenants.current().baseUrl,
504
746
  entity_count: planEntities.length,
747
+ tabular_part_count: tabularCount,
505
748
  entities: planEntities,
506
749
  warnings,
507
750
  };
@@ -710,6 +953,52 @@ export async function _execute(plan, mode = "create") {
710
953
  details.push(step);
711
954
  }
712
955
  void live;
956
+ // Tabular parts: create each owned child sub-table (type="tabular-part",
957
+ // auto owner FK back to the parent), then add its scalar + enum fields.
958
+ for (const tp of (ent.tabular_parts ?? [])) {
959
+ const tpName = tp.name;
960
+ const tpStep = await _runWrite(`create_tabular_part:${tpName}`, () => entityTools.createTabularPart(name, // parent entity
961
+ tpName, tp.title, tp.title_field_name, false, // add the real fields ourselves
962
+ "text", tpName));
963
+ tpStep.entity = name;
964
+ tpStep.tabular_part = tpName;
965
+ details.push(tpStep);
966
+ const tlive = await _liveFields(tpName);
967
+ for (const f of tp.scalar_fields) {
968
+ if (f.name in tlive) {
969
+ details.push({ entity: tpName, action: `add_field:${f.name}`, status: "skipped", reason: "exists" });
970
+ continue;
971
+ }
972
+ const step = await _runWrite(`add_field:${f.name}`, () => entityTools.addField(tpName, f.name, f.type, f.title, {
973
+ required: f.required ?? false,
974
+ subType: f.sub_type ?? null,
975
+ maxLength: f.max_length ?? null,
976
+ decimalPlaces: f.decimal_places ?? null,
977
+ }));
978
+ step.entity = tpName;
979
+ details.push(step);
980
+ }
981
+ for (const f of tp.enum_fields) {
982
+ if (f.name in tlive) {
983
+ details.push({ entity: tpName, action: `add_enum_field:${f.name}`, status: "skipped", reason: "exists" });
984
+ continue;
985
+ }
986
+ if (f.values && f.values.length) {
987
+ try {
988
+ await entityTools.addEnumValues(f.enum_name, f.values.join(","));
989
+ }
990
+ catch {
991
+ // enum-values failure is reported via the field add below
992
+ }
993
+ }
994
+ const step = await _runWrite(`add_enum_field:${f.name}`, () => entityTools.addField(tpName, f.name, f.type ?? "enum", f.title, {
995
+ required: f.required ?? false,
996
+ enumName: f.enum_name,
997
+ }));
998
+ step.entity = tpName;
999
+ details.push(step);
1000
+ }
1001
+ }
713
1002
  }
714
1003
  // Pass 2: relations (targets now exist).
715
1004
  for (const ent of plan.entities) {
@@ -745,14 +1034,44 @@ export async function _execute(plan, mode = "create") {
745
1034
  details.push(step);
746
1035
  }
747
1036
  }
748
- // Verify: re-read each entity and confirm every planned field is present.
749
- const verify = {};
1037
+ // Pass 2b: relations declared on tabular parts (targets now exist).
750
1038
  for (const ent of plan.entities) {
751
- const name = ent.name;
1039
+ for (const tp of (ent.tabular_parts ?? [])) {
1040
+ if (!tp.relation_fields || tp.relation_fields.length === 0) {
1041
+ continue;
1042
+ }
1043
+ const tlive = await _liveFields(tp.name);
1044
+ for (const f of tp.relation_fields) {
1045
+ if (f.name in tlive) {
1046
+ details.push({ entity: tp.name, action: `add_relation:${f.name}`, status: "skipped", reason: "exists" });
1047
+ continue;
1048
+ }
1049
+ if (!f.relation_entity || !(f.target_in_set ?? true)) {
1050
+ details.push({
1051
+ entity: tp.name,
1052
+ action: `add_relation:${f.name}`,
1053
+ status: "skipped",
1054
+ reason: `relation target not in migration set (${f.relation_entity})`,
1055
+ });
1056
+ continue;
1057
+ }
1058
+ const step = await _runWrite(`add_relation:${f.name}`, () => entityTools.addField(tp.name, f.name, f.type, f.title, {
1059
+ required: f.required ?? false,
1060
+ relationEntity: f.relation_entity,
1061
+ }));
1062
+ step.entity = tp.name;
1063
+ details.push(step);
1064
+ }
1065
+ }
1066
+ }
1067
+ // Verify: re-read each entity (and each tabular part) and confirm every
1068
+ // planned field is present.
1069
+ const verify = {};
1070
+ const verifyOne = async (name, spec) => {
752
1071
  const planned = [
753
- ...ent.scalar_fields.map((f) => f.name),
754
- ...ent.enum_fields.map((f) => f.name),
755
- ...ent.relation_fields
1072
+ ...spec.scalar_fields.map((f) => f.name),
1073
+ ...spec.enum_fields.map((f) => f.name),
1074
+ ...(spec.relation_fields ?? [])
756
1075
  .filter((f) => f.relation_entity && (f.target_in_set ?? true))
757
1076
  .map((f) => f.name),
758
1077
  ];
@@ -762,6 +1081,12 @@ export async function _execute(plan, mode = "create") {
762
1081
  present: planned.filter((p) => present.has(p)).sort(),
763
1082
  missing: planned.filter((p) => !present.has(p)).sort(),
764
1083
  };
1084
+ };
1085
+ for (const ent of plan.entities) {
1086
+ await verifyOne(ent.name, ent);
1087
+ for (const tp of (ent.tabular_parts ?? [])) {
1088
+ await verifyOne(tp.name, tp);
1089
+ }
765
1090
  }
766
1091
  return {
767
1092
  executed: true,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "suppa-mcp-2",
3
- "version": "1.1.2",
3
+ "version": "1.1.4",
4
4
  "description": "MCP server for the Suppa platform (modern.suppa.me) — Tasks, Docs/Pages, Entities & Schema, Forms, Automations, and file attachments, with multi-tenant Google auth. Node port of PyPI suppa-mcp.",
5
5
  "type": "module",
6
6
  "bin": { "suppa-mcp": "dist/bin.js" },