suppa-mcp-2 1.1.2 → 1.1.3

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.3" }, { 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,93 @@ 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 a MULTI-valued relation
347
+ // (`multiple: true` — an embedded child collection) into a custom
348
+ // (non-builtin), non-self entity. Single-valued relations (multiple:false)
349
+ // are plain lookups, not child tables. Expand only the real tabular parts
350
+ // to reveal their sub-fields; lookups just show their target name.
351
+ const isTabular = p.multiple === true && target != null && !isSelf && !isBuiltin;
352
+ if (isTabular) {
353
+ tabularParts.push(String(p.name));
354
+ if (expand) {
355
+ const cf = await childFields(targetKey);
356
+ if (cf) {
357
+ s.child_entity = targetKey;
358
+ s.child_fields = cf;
359
+ }
360
+ }
361
+ }
362
+ }
363
+ fields.push(s);
220
364
  }
221
365
  return jsonResponse({
222
366
  entity: ent.name,
223
367
  alias: ent.alias,
224
- field_count: props.length,
225
- fields: props,
368
+ id: ent.id,
369
+ field_count: fields.length,
370
+ tabular_parts: tabularParts,
371
+ relations,
372
+ fields,
226
373
  });
227
374
  }
228
375
  /**
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.3",
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" },