suppa-mcp-2 1.2.3 → 1.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/bin.js CHANGED
@@ -2,7 +2,7 @@
2
2
  /**
3
3
  * stdio entrypoint for the Suppa MCP server (npm `suppa-mcp-2`).
4
4
  *
5
- * Builds the server (all 79 tools) and connects it to stdio, exactly like the
5
+ * Builds the server (all 84 tools) and connects it to stdio, exactly like the
6
6
  * Python package's console script. Faithful 1:1 port.
7
7
  */
8
8
  import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
@@ -5,6 +5,7 @@
5
5
  * global `fetch` in place of `urllib`, with an AbortController for timeouts.
6
6
  */
7
7
  import { config } from "./config.js";
8
+ import { assertMergeLists } from "./utils.js";
8
9
  import * as tenants from "./tenants.js";
9
10
  // HTTP statuses that signal a transient upstream problem worth one retry.
10
11
  const TRANSIENT_CODES = new Set([429, 502, 503, 504]);
@@ -42,6 +43,107 @@ function headers(ctx, token, extra) {
42
43
  }
43
44
  return h;
44
45
  }
46
+ // ---------------------------------------------------------------------------
47
+ // PERMANENT-DELETE BLOCK
48
+ //
49
+ // POST /core/data/:entityName/delete is the platform's PERMANENT delete —
50
+ // "Permanently deletes records. Unlike Remove, the rows leave the table and
51
+ // cannot be restored." (captures/api-entity-builder-data.txt:507-509).
52
+ //
53
+ // This server performs REVERSIBLE deletes only, so the route is blocked at the
54
+ // single choke point every request to a 2.0 tenant passes through — makeRequest
55
+ // and makeRequestRawBytes both call sendWithReauth — rather than inside any one
56
+ // tool: a tool added later inherits the block for free, and no flag,
57
+ // confirm=true or direct makeRequest call can lift it.
58
+ // ---------------------------------------------------------------------------
59
+ /**
60
+ * The route SHAPE, not one hard-coded string: `<entity>` is any single path
61
+ * segment, and the optional `api/` prefix mirrors dataUrl(), which builds
62
+ * `/api/core/data/...`. Matching runs on a path that has already been stripped
63
+ * of scheme+host, query string and fragment, had its dot segments resolved, and
64
+ * been collapsed, trimmed and lowercased.
65
+ */
66
+ const PERMANENT_DELETE_ROUTE = /^(?:api\/)?core\/data\/[^/]+\/delete$/;
67
+ // The segments the WHATWG URL parser (the one inside fetch) removes or walks up
68
+ // on. It matches them ASCII case-insensitively AND through their %2e escapes —
69
+ // "a single-dot path segment must be '.' or '%2e'; a double-dot path segment
70
+ // must be '..', '.%2e', '%2e.' or '%2e%2e'" (URL Standard) — so `%2e%2e` climbs
71
+ // a level on the wire exactly like `..` does.
72
+ //
73
+ // These are tested AFTER one decodeURIComponent pass, where a surviving `%2e`
74
+ // can only have come from a double-encoded `%252e`. fetch would leave that one
75
+ // encoded, so accepting it here over-matches by exactly one decoding level:
76
+ // the safe direction for a block, and the reason no second decode pass is
77
+ // needed to be sure the matcher has seen every form the wire can resolve.
78
+ const SINGLE_DOT_SEGMENT = /^(?:\.|%2e)$/i;
79
+ const DOUBLE_DOT_SEGMENT = /^(?:\.|%2e){2}$/i;
80
+ /**
81
+ * Resolve '.' and '..' the way the URL parser inside fetch() will.
82
+ *
83
+ * EMPTY segments are preserved while resolving, because the URL parser keeps
84
+ * them: on the wire `/core/data//../Tasks/delete` walks up out of the empty
85
+ * segment and lands on the permanent-delete route. Collapsing `//` first would
86
+ * instead pop `data` and let that route through — which is why the collapse
87
+ * happens after this, never before.
88
+ */
89
+ function resolveDotSegments(path) {
90
+ const out = [];
91
+ for (const segment of path.split("/")) {
92
+ if (DOUBLE_DOT_SEGMENT.test(segment)) {
93
+ out.pop(); // one level up — and never below the root
94
+ }
95
+ else if (!SINGLE_DOT_SEGMENT.test(segment)) {
96
+ out.push(segment);
97
+ }
98
+ }
99
+ return out.join("/");
100
+ }
101
+ /** Normalize a path or absolute URL down to comparable route segments. */
102
+ function routePath(pathOrUrl) {
103
+ let p = String(pathOrUrl ?? "");
104
+ // The URL parser inside fetch DELETES every tab, LF and CR from the input and
105
+ // trims leading/trailing C0 controls and spaces, so `de<TAB>lete` and
106
+ // `delete\x00` are the segment `delete` on the wire. It also maps `\` to `/`
107
+ // for http(s). Undoing all three here first is what keeps this matcher and
108
+ // the wire looking at the same path — each was a live bypass.
109
+ p = p.replace(/[\t\n\r]/g, "").replace(/^[\x00-\x20]+|[\x00-\x20]+$/g, "").replace(/\\/g, "/");
110
+ const scheme = p.indexOf("://");
111
+ if (scheme !== -1) {
112
+ const slash = p.indexOf("/", scheme + 3);
113
+ p = slash === -1 ? "" : p.slice(slash);
114
+ }
115
+ p = p.split("?")[0].split("#")[0];
116
+ try {
117
+ // %2F-encoded separators must not smuggle the route past the matcher.
118
+ p = decodeURIComponent(p);
119
+ }
120
+ catch {
121
+ // Malformed escapes: match the raw form rather than giving up. The dot
122
+ // segment patterns below still catch the %2e forms in that raw path.
123
+ }
124
+ // Decode first, THEN resolve dot segments, THEN collapse and lowercase: the
125
+ // matcher and fetch must agree on the path, and fetch resolves '.' / '..'
126
+ // while this function used to leave them in place — `Tasks/./delete` reached
127
+ // the permanent delete with the block silently looking at a different path.
128
+ p = resolveDotSegments(p);
129
+ return p
130
+ .replace(/\/+/g, "/")
131
+ .replace(/^\/+|\/+$/g, "")
132
+ .toLowerCase();
133
+ }
134
+ /** True for POST /core/data/:entityName/delete — and only for that route. */
135
+ export function isPermanentDeletePath(pathOrUrl) {
136
+ return PERMANENT_DELETE_ROUTE.test(routePath(pathOrUrl));
137
+ }
138
+ /** The refusal raised in place of a permanent delete. Names the reversible pair. */
139
+ export function permanentDeleteRefusal(pathOrUrl) {
140
+ return new Error("REFUSED BY POLICY — permanent delete is not available through this server. " +
141
+ `'${pathOrUrl}' is POST /core/data/:entityName/delete, the platform's PERMANENT ` +
142
+ "delete: the rows leave the table and cannot be restored (api-entity-builder-data.txt:509). " +
143
+ "Nothing was sent. Use the reversible pair instead: /remove (soft delete — sets " +
144
+ "deletedAt and leaves the row in place; tool suppa_delete_record), undone with " +
145
+ "suppa_restore_record. No flag, confirm=true or other tool lifts this block.");
146
+ }
45
147
  function noTokenError(ctx) {
46
148
  return new Error(`NOT SIGNED IN to Suppa tenant '${ctx.host}'. This is expected on first use ` +
47
149
  "and is not a failure to report back as 'broken'. ACTION REQUIRED: call the " +
@@ -99,6 +201,15 @@ function safeStatusText(res) {
99
201
  }
100
202
  }
101
203
  async function sendWithReauth(ctx, buildHeaders, method, url, data, timeout, opts) {
204
+ // The choke point: every request to a 2.0 tenant — makeRequest and
205
+ // makeRequestRawBytes alike — funnels through here, so the permanent-delete
206
+ // route is refused before a single fetch is issued. (The two fetches outside
207
+ // this function, the OAuth calls in auth.ts and the read-only Suppa 1.0 calls
208
+ // in tools/migrate.ts, target different hosts and cannot reach a 2.0 data
209
+ // route at all.)
210
+ if (isPermanentDeletePath(url)) {
211
+ throw permanentDeleteRefusal(url);
212
+ }
102
213
  let refreshed = false;
103
214
  let transientRetried = false;
104
215
  const retriable = isSafeRequest(method, url);
@@ -215,7 +326,17 @@ export function dataUrl(entity, action) {
215
326
  export function customOrderUrl(entity) {
216
327
  return `/api/core/data/custom-order/${entity}`;
217
328
  }
218
- export async function searchEntity(entity, filters = null, fields = null, limit = 50, offset = 0, orderBy = null, searchValue = "", operator = "and") {
329
+ /**
330
+ * Which records a read returns with respect to soft deletion.
331
+ * (docs/superpowers/specs/captures/api-entity-builder-data.txt:76 — deletedScope
332
+ * "active | deleted | all ... Which records to return with respect to soft
333
+ * deletion. Defaults to active only.")
334
+ */
335
+ export const DELETED_SCOPES = ["active", "deleted", "all"];
336
+ /** The platform's own defaults for the two soft-delete read parameters. */
337
+ export const DEFAULT_DELETED_SCOPE = "active"; // data.txt:76
338
+ export const DEFAULT_INCLUDE_DELETED_RELATIONS = true; // data.txt:75
339
+ export async function searchEntity(entity, filters = null, fields = null, limit = 50, offset = 0, orderBy = null, searchValue = "", operator = "and", deletedScope = DEFAULT_DELETED_SCOPE, includeDeletedRelations = DEFAULT_INCLUDE_DELETED_RELATIONS) {
219
340
  const body = {
220
341
  conditions: { operator, filters: filters !== null ? filters : [] },
221
342
  fields: fields || { id: true },
@@ -227,17 +348,25 @@ export async function searchEntity(entity, filters = null, fields = null, limit
227
348
  orderBy: orderBy !== null ? orderBy : [{ field: "createdAt", order: "desc" }],
228
349
  searchValue,
229
350
  getAccessByFields: true,
230
- includeDeletedRelations: false,
351
+ // data.txt:75 — includeDeletedRelations "Keep related records that are
352
+ // soft-deleted. Defaults to true." This client used to hard-code false,
353
+ // which silently dropped soft-deleted relations from every read: a deleted
354
+ // relation then read back identically to one that was never set.
355
+ includeDeletedRelations,
356
+ // data.txt:76 — deletedScope "active | deleted | all". Sent explicitly so
357
+ // callers can page over removed rows (search body = Select body, data.txt:226).
358
+ deletedScope,
231
359
  };
232
360
  const result = await makeRequest("POST", dataUrl(entity, "search"), body);
233
361
  return Array.isArray(result) ? result : [];
234
362
  }
235
- export async function selectEntity(entity, filters, fields = null) {
363
+ export async function selectEntity(entity, filters, fields = null, deletedScope = DEFAULT_DELETED_SCOPE, includeDeletedRelations = DEFAULT_INCLUDE_DELETED_RELATIONS) {
236
364
  const body = {
237
365
  conditions: { operator: "and", filters },
238
366
  fields: fields || { id: true },
239
367
  getAccessByFields: true,
240
- includeDeletedRelations: false,
368
+ includeDeletedRelations, // data.txt:75 (platform default true; was hard-coded false)
369
+ deletedScope, // data.txt:76
241
370
  };
242
371
  const result = await makeRequest("POST", dataUrl(entity, "select") + "?markAsView=false", body);
243
372
  // The select endpoint returns a list of matching rows; return the first.
@@ -248,6 +377,33 @@ export async function selectEntity(entity, filters, fields = null) {
248
377
  ? result
249
378
  : null;
250
379
  }
380
+ /**
381
+ * Check a select payload against the entity metadata WITHOUT running it:
382
+ * POST /core/data/:entityName/select/validate (data.txt:126) — "Use it to tell a
383
+ * malformed query from an empty result" (data.txt:128).
384
+ *
385
+ * The body is the Select body, but only `fields`, `conditions`, `orderBy` and
386
+ * `groupBy` are inspected (data.txt:132), so only those are sent.
387
+ */
388
+ export async function validateSelect(entity, payload) {
389
+ const body = {};
390
+ if (payload.fields) {
391
+ body.fields = payload.fields;
392
+ }
393
+ if (payload.conditions !== null && payload.conditions !== undefined) {
394
+ body.conditions = payload.conditions;
395
+ }
396
+ if (payload.orderBy && payload.orderBy.length > 0) {
397
+ body.orderBy = payload.orderBy;
398
+ }
399
+ if (payload.groupBy && payload.groupBy.length > 0) {
400
+ body.groupBy = payload.groupBy;
401
+ }
402
+ const result = await makeRequest("POST", dataUrl(entity, "select/validate"), body);
403
+ return result !== null && typeof result === "object" && !Array.isArray(result)
404
+ ? result
405
+ : null;
406
+ }
251
407
  export async function insertEntity(entity, fieldsList, returning = null) {
252
408
  const body = { fields: fieldsList };
253
409
  if (returning) {
@@ -259,11 +415,80 @@ export async function insertEntity(entity, fieldsList, returning = null) {
259
415
  }
260
416
  return result ? [result] : [];
261
417
  }
262
- export async function updateEntity(entity, instanceId, fields) {
418
+ /**
419
+ * Update one instance.
420
+ *
421
+ * A field sent in `fields` REPLACES the stored value — for a list-valued field
422
+ * that means every item not in the payload is dropped. `merge` and `unmerge`
423
+ * (arrays of field names) opt individual fields out of that: merged names have
424
+ * their items ADDED to the existing list, unmerged names have theirs REMOVED.
425
+ * Both lists are pre-flighted (assertMergeLists) so a name the platform would
426
+ * silently ignore — and thus a replace the caller did not intend — never leaves
427
+ * this process. Empty lists are omitted from the body entirely.
428
+ *
429
+ * The platform reads the current values before writing, which is why merge /
430
+ * unmerge is bounded by the number of records the update MATCHES (500), not by
431
+ * how many items are sent (data.txt:396). This call matches one instance by id.
432
+ */
433
+ export async function updateEntity(entity, instanceId, fields, merge = null, unmerge = null) {
434
+ assertMergeLists(fields, merge ?? [], unmerge ?? []);
435
+ // Body keys per docs/superpowers/specs/captures/api-entity-builder-data.txt:
436
+ // fields :367, merge :370 ("string[] ... Array fields to add to instead of
437
+ // replacing"), unmerge :371. Both are arrays of field NAMES, never values.
263
438
  const body = { fields };
439
+ if (merge && merge.length > 0) {
440
+ body.merge = [...merge];
441
+ }
442
+ if (unmerge && unmerge.length > 0) {
443
+ body.unmerge = [...unmerge];
444
+ }
264
445
  return makeRequest("POST", dataUrl(entity, "update") + `/${instanceId}`, body);
265
446
  }
447
+ /**
448
+ * SOFT-delete the matching instances: /remove sets deletedAt and leaves the row
449
+ * in place, so the delete is reversible with restoreEntity. The rows do drop out
450
+ * of every normal read, which is why callers still gate on confirm.
451
+ *
452
+ * This is deliberately NOT /core/data/:entityName/delete — that endpoint is the
453
+ * PERMANENT delete ("the rows leave the table and cannot be restored",
454
+ * data.txt:509) and is not exposed by this server.
455
+ */
266
456
  export async function removeEntity(entity, filters) {
267
457
  const body = { conditions: { operator: "and", filters } };
268
458
  return makeRequest("POST", dataUrl(entity, "remove"), body);
269
459
  }
460
+ /**
461
+ * UNDO a soft delete: /restore clears deletedAt on the matching rows.
462
+ *
463
+ * The body carries ONLY `conditions` (data.txt:543 — "conditions | object |
464
+ * true | Condition selecting the records."); there is no scope flag to add,
465
+ * because the platform appends `deletedAt IS NOT NULL` to those conditions
466
+ * itself (data.txt:538), leaving never-removed records untouched.
467
+ */
468
+ export async function restoreEntity(entity, filters) {
469
+ const body = { conditions: { operator: "and", filters } };
470
+ return makeRequest("POST", dataUrl(entity, "restore"), body);
471
+ }
472
+ /**
473
+ * Duplicate one instance server-side: POST /core/data/:entityName/copy/:id
474
+ * (data.txt:452). `fields` is applied ON TOP of the copied values, so it is
475
+ * where the caller overrides what must differ (data.txt:454, :459 — required,
476
+ * "May be {}"). `options.copyFiles` (data.txt:461) duplicates the attachments
477
+ * instead of skipping them and `options.copyRelatedEntities` (data.txt:462)
478
+ * also copies the related records; both are omitted when false so a plain copy
479
+ * sends exactly the documented minimal body.
480
+ */
481
+ export async function copyEntity(entity, instanceId, fields = {}, copyFiles = false, copyRelatedEntities = false) {
482
+ const body = { fields };
483
+ const options = {};
484
+ if (copyFiles) {
485
+ options.copyFiles = true;
486
+ }
487
+ if (copyRelatedEntities) {
488
+ options.copyRelatedEntities = true;
489
+ }
490
+ if (Object.keys(options).length > 0) {
491
+ body.options = options;
492
+ }
493
+ return makeRequest("POST", dataUrl(entity, "copy") + `/${instanceId}`, body);
494
+ }