suppa-mcp-2 1.2.4 → 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";
@@ -43,6 +43,107 @@ function headers(ctx, token, extra) {
43
43
  }
44
44
  return h;
45
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
+ }
46
147
  function noTokenError(ctx) {
47
148
  return new Error(`NOT SIGNED IN to Suppa tenant '${ctx.host}'. This is expected on first use ` +
48
149
  "and is not a failure to report back as 'broken'. ACTION REQUIRED: call the " +
@@ -100,6 +201,15 @@ function safeStatusText(res) {
100
201
  }
101
202
  }
102
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
+ }
103
213
  let refreshed = false;
104
214
  let transientRetried = false;
105
215
  const retriable = isSafeRequest(method, url);
@@ -216,7 +326,17 @@ export function dataUrl(entity, action) {
216
326
  export function customOrderUrl(entity) {
217
327
  return `/api/core/data/custom-order/${entity}`;
218
328
  }
219
- 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) {
220
340
  const body = {
221
341
  conditions: { operator, filters: filters !== null ? filters : [] },
222
342
  fields: fields || { id: true },
@@ -228,17 +348,25 @@ export async function searchEntity(entity, filters = null, fields = null, limit
228
348
  orderBy: orderBy !== null ? orderBy : [{ field: "createdAt", order: "desc" }],
229
349
  searchValue,
230
350
  getAccessByFields: true,
231
- 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,
232
359
  };
233
360
  const result = await makeRequest("POST", dataUrl(entity, "search"), body);
234
361
  return Array.isArray(result) ? result : [];
235
362
  }
236
- 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) {
237
364
  const body = {
238
365
  conditions: { operator: "and", filters },
239
366
  fields: fields || { id: true },
240
367
  getAccessByFields: true,
241
- includeDeletedRelations: false,
368
+ includeDeletedRelations, // data.txt:75 (platform default true; was hard-coded false)
369
+ deletedScope, // data.txt:76
242
370
  };
243
371
  const result = await makeRequest("POST", dataUrl(entity, "select") + "?markAsView=false", body);
244
372
  // The select endpoint returns a list of matching rows; return the first.
@@ -249,6 +377,33 @@ export async function selectEntity(entity, filters, fields = null) {
249
377
  ? result
250
378
  : null;
251
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
+ }
252
407
  export async function insertEntity(entity, fieldsList, returning = null) {
253
408
  const body = { fields: fieldsList };
254
409
  if (returning) {
@@ -291,10 +446,49 @@ export async function updateEntity(entity, instanceId, fields, merge = null, unm
291
446
  }
292
447
  /**
293
448
  * SOFT-delete the matching instances: /remove sets deletedAt and leaves the row
294
- * in place, so the delete is reversible (restore is UI-only for now). The rows
295
- * do drop out of every normal read, which is why callers still gate on confirm.
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.
296
455
  */
297
456
  export async function removeEntity(entity, filters) {
298
457
  const body = { conditions: { operator: "and", filters } };
299
458
  return makeRequest("POST", dataUrl(entity, "remove"), body);
300
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
+ }