suppa-mcp-2 1.2.4 → 1.3.1

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,134 @@ 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
+ const SINGLE_DOT_SEGMENT = /^(?:\.|%2e)$/i;
73
+ const DOUBLE_DOT_SEGMENT = /^(?:\.|%2e){2}$/i;
74
+ /**
75
+ * Resolve '.' and '..' the way the URL parser inside fetch() will.
76
+ *
77
+ * EMPTY segments are preserved while resolving, because the URL parser keeps
78
+ * them: on the wire `/core/data//../Tasks/delete` walks up out of the empty
79
+ * segment and lands on the permanent-delete route. Collapsing `//` first would
80
+ * instead pop `data` and let that route through — which is why the collapse
81
+ * happens after this, never before.
82
+ */
83
+ function resolveDotSegments(path) {
84
+ const out = [];
85
+ for (const segment of path.split("/")) {
86
+ if (DOUBLE_DOT_SEGMENT.test(segment)) {
87
+ out.pop(); // one level up — and never below the root
88
+ }
89
+ else if (!SINGLE_DOT_SEGMENT.test(segment)) {
90
+ out.push(segment);
91
+ }
92
+ }
93
+ return out.join("/");
94
+ }
95
+ /**
96
+ * Strip an input down to its path, undoing the rewrites fetch performs BEFORE
97
+ * it parses.
98
+ *
99
+ * The URL parser inside fetch DELETES every tab, LF and CR from the input and
100
+ * trims leading/trailing C0 controls and spaces, so `de<TAB>lete` and
101
+ * `delete\x00` are the segment `delete` on the wire. It also maps `\` to `/`
102
+ * for http(s). Undoing all three here is what keeps this matcher and the wire
103
+ * looking at the same path — each was a live bypass.
104
+ */
105
+ function rawPath(pathOrUrl) {
106
+ let p = String(pathOrUrl ?? "");
107
+ p = p.replace(/[\t\n\r]/g, "").replace(/^[\x00-\x20]+|[\x00-\x20]+$/g, "").replace(/\\/g, "/");
108
+ const scheme = p.indexOf("://");
109
+ if (scheme !== -1) {
110
+ const slash = p.indexOf("/", scheme + 3);
111
+ p = slash === -1 ? "" : p.slice(slash);
112
+ }
113
+ return p.split("?")[0].split("#")[0];
114
+ }
115
+ /** Collapse, trim and lowercase a resolved path into comparable route segments. */
116
+ function comparable(path) {
117
+ return path
118
+ .replace(/\/+/g, "/")
119
+ .replace(/^\/+|\/+$/g, "")
120
+ .toLowerCase();
121
+ }
122
+ /**
123
+ * Every path this input can be READ as by the time it reaches the platform's
124
+ * router — the block is the OR over all of them, because a single normalization
125
+ * cannot model both ends of the wire at once.
126
+ *
127
+ * Resolving dot segments on a DECODED path was a live bypass:
128
+ * `/core/data/%252e/%2e%2e/Tasks/delete` decodes to `.../%2e/../Tasks/delete`,
129
+ * where the matcher read `%2e` as a dot segment, DROPPED it, and then let the
130
+ * real `..` pop `data` — landing on `core/Tasks/delete`, which is not the
131
+ * blocked shape. fetch never decodes, so on the wire `%252e` stays a literal
132
+ * segment, `%2e%2e` pops THAT instead, and the request left as
133
+ * POST /core/data/Tasks/delete. Treating a decoded escape as a dot segment
134
+ * REMOVES a segment, so it under-matches as readily as it over-matches — the
135
+ * earlier "over-matches by one decoding level, the safe direction" reasoning
136
+ * was simply wrong.
137
+ *
138
+ * So each candidate is derived for one reader, and none of them has to be
139
+ * conservative on its own:
140
+ * 1. what fetch puts on the wire — dot segments resolved, nothing decoded;
141
+ * 2. that path decoded once, for a router that decodes before routing (this
142
+ * is also what keeps %2F from smuggling a separator past the matcher);
143
+ * 3. the decoded path re-resolved, for one that normalizes after decoding.
144
+ */
145
+ function routeCandidates(pathOrUrl) {
146
+ const onWire = resolveDotSegments(rawPath(pathOrUrl));
147
+ const candidates = [comparable(onWire)];
148
+ let decoded = null;
149
+ try {
150
+ decoded = decodeURIComponent(onWire);
151
+ }
152
+ catch {
153
+ // Malformed escapes: the wire form above is the whole answer. A router
154
+ // cannot decode this either, so there is no second reading to model.
155
+ }
156
+ if (decoded !== null && decoded !== onWire) {
157
+ candidates.push(comparable(decoded), comparable(resolveDotSegments(decoded)));
158
+ }
159
+ return candidates;
160
+ }
161
+ /** True for POST /core/data/:entityName/delete — and only for that route. */
162
+ export function isPermanentDeletePath(pathOrUrl) {
163
+ return routeCandidates(pathOrUrl).some((p) => PERMANENT_DELETE_ROUTE.test(p));
164
+ }
165
+ /** The refusal raised in place of a permanent delete. Names the reversible pair. */
166
+ export function permanentDeleteRefusal(pathOrUrl) {
167
+ return new Error("REFUSED BY POLICY — permanent delete is not available through this server. " +
168
+ `'${pathOrUrl}' is POST /core/data/:entityName/delete, the platform's PERMANENT ` +
169
+ "delete: the rows leave the table and cannot be restored (api-entity-builder-data.txt:509). " +
170
+ "Nothing was sent. Use the reversible pair instead: /remove (soft delete — sets " +
171
+ "deletedAt and leaves the row in place; tool suppa_delete_record), undone with " +
172
+ "suppa_restore_record. No flag, confirm=true or other tool lifts this block.");
173
+ }
46
174
  function noTokenError(ctx) {
47
175
  return new Error(`NOT SIGNED IN to Suppa tenant '${ctx.host}'. This is expected on first use ` +
48
176
  "and is not a failure to report back as 'broken'. ACTION REQUIRED: call the " +
@@ -100,6 +228,15 @@ function safeStatusText(res) {
100
228
  }
101
229
  }
102
230
  async function sendWithReauth(ctx, buildHeaders, method, url, data, timeout, opts) {
231
+ // The choke point: every request to a 2.0 tenant — makeRequest and
232
+ // makeRequestRawBytes alike — funnels through here, so the permanent-delete
233
+ // route is refused before a single fetch is issued. (The two fetches outside
234
+ // this function, the OAuth calls in auth.ts and the read-only Suppa 1.0 calls
235
+ // in tools/migrate.ts, target different hosts and cannot reach a 2.0 data
236
+ // route at all.)
237
+ if (isPermanentDeletePath(url)) {
238
+ throw permanentDeleteRefusal(url);
239
+ }
103
240
  let refreshed = false;
104
241
  let transientRetried = false;
105
242
  const retriable = isSafeRequest(method, url);
@@ -216,7 +353,17 @@ export function dataUrl(entity, action) {
216
353
  export function customOrderUrl(entity) {
217
354
  return `/api/core/data/custom-order/${entity}`;
218
355
  }
219
- export async function searchEntity(entity, filters = null, fields = null, limit = 50, offset = 0, orderBy = null, searchValue = "", operator = "and") {
356
+ /**
357
+ * Which records a read returns with respect to soft deletion.
358
+ * (docs/superpowers/specs/captures/api-entity-builder-data.txt:76 — deletedScope
359
+ * "active | deleted | all ... Which records to return with respect to soft
360
+ * deletion. Defaults to active only.")
361
+ */
362
+ export const DELETED_SCOPES = ["active", "deleted", "all"];
363
+ /** The platform's own defaults for the two soft-delete read parameters. */
364
+ export const DEFAULT_DELETED_SCOPE = "active"; // data.txt:76
365
+ export const DEFAULT_INCLUDE_DELETED_RELATIONS = true; // data.txt:75
366
+ 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
367
  const body = {
221
368
  conditions: { operator, filters: filters !== null ? filters : [] },
222
369
  fields: fields || { id: true },
@@ -228,17 +375,25 @@ export async function searchEntity(entity, filters = null, fields = null, limit
228
375
  orderBy: orderBy !== null ? orderBy : [{ field: "createdAt", order: "desc" }],
229
376
  searchValue,
230
377
  getAccessByFields: true,
231
- includeDeletedRelations: false,
378
+ // data.txt:75 — includeDeletedRelations "Keep related records that are
379
+ // soft-deleted. Defaults to true." This client used to hard-code false,
380
+ // which silently dropped soft-deleted relations from every read: a deleted
381
+ // relation then read back identically to one that was never set.
382
+ includeDeletedRelations,
383
+ // data.txt:76 — deletedScope "active | deleted | all". Sent explicitly so
384
+ // callers can page over removed rows (search body = Select body, data.txt:226).
385
+ deletedScope,
232
386
  };
233
387
  const result = await makeRequest("POST", dataUrl(entity, "search"), body);
234
388
  return Array.isArray(result) ? result : [];
235
389
  }
236
- export async function selectEntity(entity, filters, fields = null) {
390
+ export async function selectEntity(entity, filters, fields = null, deletedScope = DEFAULT_DELETED_SCOPE, includeDeletedRelations = DEFAULT_INCLUDE_DELETED_RELATIONS) {
237
391
  const body = {
238
392
  conditions: { operator: "and", filters },
239
393
  fields: fields || { id: true },
240
394
  getAccessByFields: true,
241
- includeDeletedRelations: false,
395
+ includeDeletedRelations, // data.txt:75 (platform default true; was hard-coded false)
396
+ deletedScope, // data.txt:76
242
397
  };
243
398
  const result = await makeRequest("POST", dataUrl(entity, "select") + "?markAsView=false", body);
244
399
  // The select endpoint returns a list of matching rows; return the first.
@@ -249,6 +404,33 @@ export async function selectEntity(entity, filters, fields = null) {
249
404
  ? result
250
405
  : null;
251
406
  }
407
+ /**
408
+ * Check a select payload against the entity metadata WITHOUT running it:
409
+ * POST /core/data/:entityName/select/validate (data.txt:126) — "Use it to tell a
410
+ * malformed query from an empty result" (data.txt:128).
411
+ *
412
+ * The body is the Select body, but only `fields`, `conditions`, `orderBy` and
413
+ * `groupBy` are inspected (data.txt:132), so only those are sent.
414
+ */
415
+ export async function validateSelect(entity, payload) {
416
+ const body = {};
417
+ if (payload.fields) {
418
+ body.fields = payload.fields;
419
+ }
420
+ if (payload.conditions !== null && payload.conditions !== undefined) {
421
+ body.conditions = payload.conditions;
422
+ }
423
+ if (payload.orderBy && payload.orderBy.length > 0) {
424
+ body.orderBy = payload.orderBy;
425
+ }
426
+ if (payload.groupBy && payload.groupBy.length > 0) {
427
+ body.groupBy = payload.groupBy;
428
+ }
429
+ const result = await makeRequest("POST", dataUrl(entity, "select/validate"), body);
430
+ return result !== null && typeof result === "object" && !Array.isArray(result)
431
+ ? result
432
+ : null;
433
+ }
252
434
  export async function insertEntity(entity, fieldsList, returning = null) {
253
435
  const body = { fields: fieldsList };
254
436
  if (returning) {
@@ -291,10 +473,49 @@ export async function updateEntity(entity, instanceId, fields, merge = null, unm
291
473
  }
292
474
  /**
293
475
  * 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.
476
+ * in place, so the delete is reversible with restoreEntity. The rows do drop out
477
+ * of every normal read, which is why callers still gate on confirm.
478
+ *
479
+ * This is deliberately NOT /core/data/:entityName/delete — that endpoint is the
480
+ * PERMANENT delete ("the rows leave the table and cannot be restored",
481
+ * data.txt:509) and is not exposed by this server.
296
482
  */
297
483
  export async function removeEntity(entity, filters) {
298
484
  const body = { conditions: { operator: "and", filters } };
299
485
  return makeRequest("POST", dataUrl(entity, "remove"), body);
300
486
  }
487
+ /**
488
+ * UNDO a soft delete: /restore clears deletedAt on the matching rows.
489
+ *
490
+ * The body carries ONLY `conditions` (data.txt:543 — "conditions | object |
491
+ * true | Condition selecting the records."); there is no scope flag to add,
492
+ * because the platform appends `deletedAt IS NOT NULL` to those conditions
493
+ * itself (data.txt:538), leaving never-removed records untouched.
494
+ */
495
+ export async function restoreEntity(entity, filters) {
496
+ const body = { conditions: { operator: "and", filters } };
497
+ return makeRequest("POST", dataUrl(entity, "restore"), body);
498
+ }
499
+ /**
500
+ * Duplicate one instance server-side: POST /core/data/:entityName/copy/:id
501
+ * (data.txt:452). `fields` is applied ON TOP of the copied values, so it is
502
+ * where the caller overrides what must differ (data.txt:454, :459 — required,
503
+ * "May be {}"). `options.copyFiles` (data.txt:461) duplicates the attachments
504
+ * instead of skipping them and `options.copyRelatedEntities` (data.txt:462)
505
+ * also copies the related records; both are omitted when false so a plain copy
506
+ * sends exactly the documented minimal body.
507
+ */
508
+ export async function copyEntity(entity, instanceId, fields = {}, copyFiles = false, copyRelatedEntities = false) {
509
+ const body = { fields };
510
+ const options = {};
511
+ if (copyFiles) {
512
+ options.copyFiles = true;
513
+ }
514
+ if (copyRelatedEntities) {
515
+ options.copyRelatedEntities = true;
516
+ }
517
+ if (Object.keys(options).length > 0) {
518
+ body.options = options;
519
+ }
520
+ return makeRequest("POST", dataUrl(entity, "copy") + `/${instanceId}`, body);
521
+ }