suppa-mcp-2 1.23.1 → 1.25.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/README.md CHANGED
@@ -168,7 +168,7 @@ When an AI agent connects, the server provides built-in instructions describing
168
168
 
169
169
  ### What the server does not send back
170
170
 
171
- A tool result is not paid once: the whole conversation is re-sent on every turn, so a long string returned early is charged again on every later turn and is still occupying the window when compaction fires. Three kinds of bytes are therefore removed on the way out — all three chosen because they carry nothing the caller does not already hold:
171
+ A tool result is not paid once: the whole conversation is re-sent on every turn, so a long string returned early is charged again on every later turn and is still occupying the window when compaction fires. These bytes are therefore removed on the way out — each chosen because it carries nothing the reader does not already hold or is not told:
172
172
 
173
173
  | Removed | Why it is safe |
174
174
  |---|---|
@@ -176,8 +176,15 @@ A tool result is not paid once: the whole conversation is re-sent on every turn,
176
176
  | Long values in a **confirmation preview** | `proposed_changes` was built by copying the tool's own arguments back out. The value is verbatim in the same tool call, so it is named and sized instead: `<4231 chars — unchanged from this call's arguments>`. Short values stay verbatim, and `target` — the half that says *what* is about to change — is never touched. |
177
177
  | Long values a **write echoed back** | An insert with no `returning` projection answers with the whole stored record, so the HTML just uploaded returns with it. Replaced only when byte-identical to what was sent, and the marker says what was checked — `<4231 chars — identical to the value this call wrote>`, not a claim about what you typed (a task description passes through `wrapHtml()` on the way out). If the platform normalised the markup or filled a default, the stored value differs — that difference is real information and comes back in full. |
178
178
 
179
+ | **Schema reads** (`suppa_describe_entity`) | A field lists only what departs from the platform defaults: constraints that are `null`, flags that are `false`/`0` and options at their default (`canGroup`/`canSort`/`showInTable`/`editFromTable`/`canFilter` true, `readOnly`/`searchable` false) are omitted, and a title keeps its language keys only. The result leads with a `_legend` stating exactly that rule, and `full=true` returns the platform's raw schema. Measured on a live tenant: Tasks 43,316 → 16,687 characters, Users 14,829 → 4,858. `suppa_list_entities` reduces each title the same way (24,840 → 13,132 for 202 entities; `full=true` keeps it whole). |
180
+ | `deletedAt: null` **on expanded relations** | The platform adds `deletedAt` to every relation it expands — `null` on every live row, nine times per task. Dropped only inside relations named by a projection **this server wrote** (tasks, docs, forms, automations), never inside a `json` value and never where the projection asked for it; a non-null value — the related row *is* deleted — always comes back. A projection the caller supplied (`suppa_search_records`) is returned as sent. |
181
+ | **A stage's status object** | `suppa_list_workflows` / `suppa_list_stages` return `status` as its value (`"completed"`) instead of the expanded enum row; the value is the one word every stage decision reads. 68,565 → 41,119 characters for 162 workflows. |
182
+ | **A task's second description** | `suppa_get_task` drops `plainDescription` when it is exactly `htmlDescription` with the tags removed — the HTML is what an edit has to send back, and the text is one strip away. When the two differ, both come back. |
183
+
179
184
  The key is always kept, so "the field was written" is never in doubt. A marker is not the stored text: quote the value to the user from your own arguments.
180
185
 
186
+ The same discipline applies to what every session pays before the first call. The `instructions` block is budgeted (`test/instructionsBudget.test.ts`), and `tools/list` goes out without the JSON-Schema boilerplate no model reads — the `$schema` URI on each tool, `"default": null` on optional parameters, the two-branch `anyOf` where a type array says the same — while every property, `required` list, enum, non-null default and description is kept and compared against the SDK's own output in `test/toolsListEconomy.test.ts` (103,058 → about 93,000 characters for 89 tools).
187
+
181
188
 
182
189
  ### Deletes are reversible — permanent delete is blocked
183
190
 
@@ -268,7 +275,7 @@ work normally. Erasing data for good is an admin action in the platform's own UI
268
275
  | Tool | Description |
269
276
  |---|---|
270
277
  | `suppa_list_entities` | List entities (tables) |
271
- | `suppa_describe_entity` | Field definitions + types for an entity |
278
+ | `suppa_describe_entity` | Field definitions + types for an entity (compact by default; `full=true` for the raw schema) |
272
279
  | `suppa_list_tabular_parts` | List tabular parts (ТЧ) of an entity |
273
280
  | `suppa_search_records` | Search / filter records in any entity — nested AND/OR groups, auto-diagnoses an empty result (`deleted_scope` finds soft-deleted rows) |
274
281
  | `suppa_validate_select` | Check a select/filter payload against the entity without running it — names the field that does not resolve |
@@ -8,6 +8,10 @@ import { config } from "./config.js";
8
8
  import { assertMergeLists, elideEchoedResponse, stripAccessMetadata } from "./utils.js";
9
9
  import * as tenants from "./tenants.js";
10
10
  import { lastRefreshError } from "./sessionDiag.js";
11
+ import { isOwnProjection, withoutPaths } from "./projection.js";
12
+ import { dropNullDeletedAt } from "./readEconomy.js";
13
+ // Re-exported so the transport stays the single import for entity reads.
14
+ export { ownProjection, isOwnProjection } from "./projection.js";
11
15
  // HTTP statuses that signal a transient upstream problem worth one retry.
12
16
  const TRANSIENT_CODES = new Set([429, 502, 503, 504]);
13
17
  function debug(msg) {
@@ -216,6 +220,32 @@ export function permanentDeleteRefusal(pathOrUrl) {
216
220
  "deletedAt and leaves the row in place; tool suppa_delete_record), undone with " +
217
221
  "suppa_restore_record. No flag, confirm=true or other tool lifts this block.");
218
222
  }
223
+ /**
224
+ * A non-2xx answer from the platform, with its body already parsed.
225
+ *
226
+ * The message is byte-for-byte what the plain Error carried before; the fields
227
+ * exist so a caller can act on WHAT the platform objected to — the invalid
228
+ * field paths it names, in particular — instead of matching on prose.
229
+ */
230
+ export class ApiError extends Error {
231
+ status;
232
+ body;
233
+ parsedBody;
234
+ constructor(status, statusText, body) {
235
+ super(`HTTP ${status} ${statusText}: ${body}`);
236
+ this.name = "ApiError";
237
+ this.status = status;
238
+ this.body = body;
239
+ let parsed = null;
240
+ try {
241
+ parsed = body ? JSON.parse(body) : null;
242
+ }
243
+ catch {
244
+ parsed = null; // HTML error page, empty body, truncated JSON
245
+ }
246
+ this.parsedBody = parsed;
247
+ }
248
+ }
219
249
  function noTokenError(ctx) {
220
250
  return new Error(`NOT SIGNED IN to Suppa tenant '${ctx.host}'. This is expected on first use ` +
221
251
  "and is not a failure to report back as 'broken'. ACTION REQUIRED: call the " +
@@ -403,7 +433,7 @@ async function readResponse(res, rc) {
403
433
  "SUPPA_API_KEY, set a valid key") +
404
434
  `. ${errorBody}`);
405
435
  }
406
- throw new Error(`HTTP ${code} ${safeStatusText(res)}: ${errorBody}`);
436
+ throw new ApiError(code, safeStatusText(res), errorBody);
407
437
  }
408
438
  // A download returns bytes, not JSON — reading it as text would corrupt
409
439
  // anything that is not UTF-8 (every PDF, image and zip). Content-Type comes
@@ -588,6 +618,77 @@ export const DELETED_SCOPES = ["active", "deleted", "all"];
588
618
  /** The platform's own defaults for the two soft-delete read parameters. */
589
619
  export const DEFAULT_DELETED_SCOPE = "active"; // data.txt:76
590
620
  export const DEFAULT_INCLUDE_DELETED_RELATIONS = true; // data.txt:75
621
+ /** `host::entity` -> field paths this tenant has rejected, for this process. */
622
+ const rejectedFields = new Map();
623
+ function rejectKey(ctx, entity) {
624
+ return `${ctx.host}::${entity}`;
625
+ }
626
+ /**
627
+ * The field paths the platform rejected — and ONLY those from the projection.
628
+ *
629
+ * A field named in a filter or an order is part of the question being asked;
630
+ * dropping it would answer a different one, so those are left to fail loudly
631
+ * (data.txt:145-148 — path / location / kind / reason).
632
+ */
633
+ function invalidProjectionPaths(e) {
634
+ if (!(e instanceof ApiError) || e.status !== 400) {
635
+ return [];
636
+ }
637
+ const list = e.parsedBody?.invalidFields;
638
+ if (!Array.isArray(list)) {
639
+ return [];
640
+ }
641
+ return list
642
+ .filter((f) => Boolean(f) &&
643
+ typeof f.path === "string" &&
644
+ f.location === "fields")
645
+ .map((f) => f.path);
646
+ }
647
+ /**
648
+ * POST an entity read, trimming this server's own projection to fit the tenant.
649
+ *
650
+ * The platform names the offending paths in its own 400, so the fix is to
651
+ * believe it: drop them, retry once, and remember for the rest of the process
652
+ * so the wasted round trip is paid once per tenant and entity, not per call.
653
+ */
654
+ async function postEntityRead(entity, path, body, fields, opts = {}) {
655
+ const ctx = opts.ctx ?? tenants.current();
656
+ const own = fields !== null && isOwnProjection(fields);
657
+ let payload = body;
658
+ if (own) {
659
+ const known = rejectedFields.get(rejectKey(ctx, entity));
660
+ if (known && known.size > 0) {
661
+ payload = { ...body, fields: withoutPaths(fields, known) };
662
+ }
663
+ }
664
+ // A projection this server wrote also comes back without the platform's
665
+ // `deletedAt: null` on every relation it expanded — see dropNullDeletedAt.
666
+ const shaped = (result) => (own ? dropNullDeletedAt(result, fields) : result);
667
+ try {
668
+ return shaped(await makeRequest("POST", path, payload, opts));
669
+ }
670
+ catch (e) {
671
+ if (!own) {
672
+ throw e;
673
+ }
674
+ const bad = invalidProjectionPaths(e);
675
+ if (bad.length === 0) {
676
+ throw e;
677
+ }
678
+ const key = rejectKey(ctx, entity);
679
+ const known = rejectedFields.get(key) ?? new Set();
680
+ const before = known.size;
681
+ for (const p of bad) {
682
+ known.add(p);
683
+ }
684
+ rejectedFields.set(key, known);
685
+ if (known.size === before) {
686
+ throw e; // the retry named the same fields — the problem is elsewhere
687
+ }
688
+ debug(`${entity}: this tenant has no ${bad.join(", ")} — retrying without them`);
689
+ return shaped(await makeRequest("POST", path, { ...body, fields: withoutPaths(fields, known) }, opts));
690
+ }
691
+ }
591
692
  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) {
592
693
  const body = {
593
694
  conditions: { operator, filters: filters !== null ? filters : [] },
@@ -614,7 +715,7 @@ export async function searchEntity(entity, filters = null, fields = null, limit
614
715
  // callers can page over removed rows (search body = Select body, data.txt:226).
615
716
  deletedScope,
616
717
  };
617
- const result = await makeRequest("POST", dataUrl(entity, "search"), body);
718
+ const result = await postEntityRead(entity, dataUrl(entity, "search"), body, fields);
618
719
  return Array.isArray(result) ? result : [];
619
720
  }
620
721
  export async function selectEntity(entity, filters, fields = null, deletedScope = DEFAULT_DELETED_SCOPE, includeDeletedRelations = DEFAULT_INCLUDE_DELETED_RELATIONS) {
@@ -625,7 +726,7 @@ export async function selectEntity(entity, filters, fields = null, deletedScope
625
726
  includeDeletedRelations, // data.txt:75 (platform default true; was hard-coded false)
626
727
  deletedScope, // data.txt:76
627
728
  };
628
- const result = await makeRequest("POST", dataUrl(entity, "select"), body, {
729
+ const result = await postEntityRead(entity, dataUrl(entity, "select"), body, fields, {
629
730
  query: { markAsView: false },
630
731
  });
631
732
  // The select endpoint returns a list of matching rows; return the first.
@@ -0,0 +1,42 @@
1
+ /**
2
+ * Which field projections belong to THIS SERVER, and how to trim one.
3
+ *
4
+ * A tenant's entities are editable, so a field this server names may simply not
5
+ * be there — `Tasks.author` is absent on tenants that renamed it `createdBy`,
6
+ * and that one field failed every task read with an opaque 400 about a
7
+ * projection the user never chose and could not change.
8
+ *
9
+ * A projection tagged here may be trimmed to fit the tenant. One a caller
10
+ * supplied never is: quietly returning everything except what someone asked for
11
+ * is a wrong answer, where the error is at least the truth.
12
+ *
13
+ * Kept in its own dependency-free module so the tool modules can tag their
14
+ * constants without importing the transport — a tool module that imports
15
+ * httpClient for this alone breaks every test that mocks httpClient partially.
16
+ */
17
+ const OWN_PROJECTIONS = new WeakSet();
18
+ /** Mark `fields` as this server's own, so it can be pruned to fit a tenant. */
19
+ export function ownProjection(fields) {
20
+ OWN_PROJECTIONS.add(fields);
21
+ return fields;
22
+ }
23
+ /** True when `fields` is a projection this server owns. */
24
+ export function isOwnProjection(fields) {
25
+ return OWN_PROJECTIONS.has(fields);
26
+ }
27
+ /** A copy of `fields` with each dotted path removed. The original is untouched. */
28
+ export function withoutPaths(fields, paths) {
29
+ const clone = JSON.parse(JSON.stringify(fields));
30
+ for (const path of paths) {
31
+ const segments = path.split(".");
32
+ let node = clone;
33
+ for (let i = 0; i < segments.length - 1 && node; i++) {
34
+ const next = node[segments[i]];
35
+ node = next !== null && typeof next === "object" ? next : null;
36
+ }
37
+ if (node) {
38
+ delete node[segments[segments.length - 1]];
39
+ }
40
+ }
41
+ return clone;
42
+ }
@@ -0,0 +1,200 @@
1
+ /**
2
+ * Read results, minus the bytes that carry no information.
3
+ *
4
+ * A read is re-sent on every later turn of the conversation, so a schema read
5
+ * of 43,000 characters is not paid once. Measured on a live tenant, one
6
+ * `describe_entity` on Tasks spent 339 keys on `null`, 69 copies of each of the
7
+ * seven field options at their platform default, and a 110-character
8
+ * localisation record per field of which the model reads one word.
9
+ *
10
+ * Every reduction here is reversible in the reader's head, and the reader is
11
+ * told the rule (the `_legend` key on a schema): an absent constraint is null,
12
+ * an absent flag is false, an absent option is at its default, an absent
13
+ * deletedAt on a relation is a live row. Nothing that DIFFERS from the default
14
+ * is ever removed, so no field is misdescribed — the compact form says exactly
15
+ * what the full one says. The full form stays one flag away (`full=true`).
16
+ *
17
+ * Only the server's OWN reads are shaped: the schema tools and the projections
18
+ * this server wrote (tasks, forms, automations). A projection the caller wrote
19
+ * is returned as the platform sent it — they asked for those keys.
20
+ *
21
+ * Dependency-light on purpose (utils only), so tool modules and the transport
22
+ * can both import it without a cycle.
23
+ */
24
+ import { stripHtml } from "./utils.js";
25
+ const isObj = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
26
+ /**
27
+ * The field options the platform applies when none is given (verified on a live
28
+ * tenant 2026-08-17; the builder doc lists them as false, which the platform
29
+ * contradicts). House rule 3 says never to WRITE one of these; the same fact
30
+ * says there is nothing to READ in one either.
31
+ */
32
+ export const PLATFORM_OPTION_DEFAULTS = Object.freeze({
33
+ canGroup: true,
34
+ canSort: true,
35
+ showInTable: true,
36
+ editFromTable: true,
37
+ canFilter: true,
38
+ readOnly: false,
39
+ searchable: false,
40
+ });
41
+ /** Field flags at the value the platform stores when nothing was asked for. */
42
+ const FIELD_FLAG_DEFAULTS = Object.freeze({
43
+ isArray: false,
44
+ isPrimary: false,
45
+ isOnlyPositive: false,
46
+ isCustom: false,
47
+ unique: false,
48
+ notNull: false,
49
+ decimalPlaces: 0,
50
+ });
51
+ /** The keys of a platform localisation record that are bookkeeping, not text. */
52
+ const I18N_BOOKKEEPING = new Set(["id", "key", "name"]);
53
+ export const SCHEMA_LEGEND = "Compact schema: a field omits constraints that are null, flags that are false/0 " +
54
+ "(isArray, isPrimary, isOnlyPositive, unique, notNull, decimalPlaces) and options at the " +
55
+ "platform defaults (canGroup/canSort/showInTable/editFromTable/canFilter true; " +
56
+ "readOnly/searchable false); titles keep language keys only. Absent means default, " +
57
+ "not unknown. full=true returns the platform's raw schema.";
58
+ /**
59
+ * A localisation record `{id, key, name, en, uk, …}` reduced to its language
60
+ * keys. The bookkeeping names the i18n row and the entity it was declared on —
61
+ * nothing a reader of the schema acts on, and 90 characters per field.
62
+ */
63
+ export function slimTitle(title) {
64
+ if (!isObj(title))
65
+ return title;
66
+ const out = {};
67
+ for (const [k, v] of Object.entries(title)) {
68
+ if (I18N_BOOKKEEPING.has(k) || v === null || v === undefined)
69
+ continue;
70
+ out[k] = v;
71
+ }
72
+ return Object.keys(out).length > 0 ? out : title;
73
+ }
74
+ /** Field options with the platform defaults removed. */
75
+ export function compactOptions(options) {
76
+ const out = {};
77
+ for (const [k, v] of Object.entries(options)) {
78
+ if (v === null || v === undefined)
79
+ continue;
80
+ if (k in PLATFORM_OPTION_DEFAULTS && v === PLATFORM_OPTION_DEFAULTS[k])
81
+ continue;
82
+ out[k] = v;
83
+ }
84
+ return out;
85
+ }
86
+ /** One field of an entity schema in compact form (see SCHEMA_LEGEND). */
87
+ export function compactField(field) {
88
+ if (!isObj(field))
89
+ return field;
90
+ const out = {};
91
+ for (const [k, v] of Object.entries(field)) {
92
+ if (v === null || v === undefined)
93
+ continue;
94
+ if (k in FIELD_FLAG_DEFAULTS && v === FIELD_FLAG_DEFAULTS[k])
95
+ continue;
96
+ if (k === "options" && isObj(v)) {
97
+ const o = compactOptions(v);
98
+ if (Object.keys(o).length > 0)
99
+ out.options = o;
100
+ continue;
101
+ }
102
+ if (k === "title") {
103
+ out.title = slimTitle(v);
104
+ continue;
105
+ }
106
+ out[k] = v;
107
+ }
108
+ return out;
109
+ }
110
+ /**
111
+ * An entity schema (GET /api/core/schema/<name>) in compact form. Every key the
112
+ * platform sent at the entity level is kept except nulls; `fields` and
113
+ * `customFields` are compacted per field; the legend goes first so it is read
114
+ * before the fields it explains.
115
+ */
116
+ export function compactEntitySchema(raw) {
117
+ if (!isObj(raw))
118
+ return raw;
119
+ const out = { _legend: SCHEMA_LEGEND };
120
+ for (const [k, v] of Object.entries(raw)) {
121
+ if (v === null || v === undefined)
122
+ continue;
123
+ if ((k === "fields" || k === "customFields") && Array.isArray(v)) {
124
+ out[k] = v.map(compactField);
125
+ continue;
126
+ }
127
+ if (k === "title") {
128
+ out.title = slimTitle(v);
129
+ continue;
130
+ }
131
+ out[k] = v;
132
+ }
133
+ return out;
134
+ }
135
+ /**
136
+ * Relation expansions come back with the platform's own `deletedAt` on each —
137
+ * null on every live row, nine times per task, on every task. Removed where
138
+ * null, only inside the relation objects the PROJECTION itself names (so a
139
+ * `json` field's contents are never walked), and never where the projection
140
+ * asked for deletedAt. A non-null value — the related row IS deleted — is
141
+ * information and stays. The row's own top-level deletedAt is never touched.
142
+ *
143
+ * Mutates in place: the input is a response body this process just parsed.
144
+ */
145
+ export function dropNullDeletedAt(result, projection) {
146
+ if (Array.isArray(result)) {
147
+ for (const row of result)
148
+ dropNullDeletedAt(row, projection);
149
+ return result;
150
+ }
151
+ if (!isObj(result))
152
+ return result;
153
+ for (const [key, sub] of Object.entries(projection)) {
154
+ if (!isObj(sub))
155
+ continue; // a leaf — never descend into a value
156
+ const value = result[key];
157
+ const related = Array.isArray(value) ? value : [value];
158
+ for (const row of related) {
159
+ if (!isObj(row))
160
+ continue;
161
+ if (row.deletedAt === null && sub.deletedAt !== true)
162
+ delete row.deletedAt;
163
+ dropNullDeletedAt(row, sub);
164
+ }
165
+ }
166
+ return result;
167
+ }
168
+ /**
169
+ * A stage's status as the one word that matters. The platform expands the
170
+ * enum reference into `{id, value, title, deletedAt}`; `value` is what every
171
+ * stage decision in this server (active? completed?) reads, and `title` is its
172
+ * capitalised twin.
173
+ */
174
+ export function statusValue(status) {
175
+ return isObj(status) && typeof status.value === "string" ? status.value : status;
176
+ }
177
+ const collapseWs = (s) => s.replace(/\s+/g, " ").trim();
178
+ /**
179
+ * A task carries its description twice — as HTML and as the platform's plain
180
+ * rendering of the same HTML — and on a real task that is the whole payload
181
+ * (51,000 characters, of which half is the other half without tags). When the
182
+ * plain text is exactly the HTML with its tags removed, it is dropped and the
183
+ * HTML kept: HTML is what an edit has to send back, and the text is one
184
+ * tag-strip away. When they differ — the platform rendered something the strip
185
+ * does not — both come back, because the difference is information.
186
+ */
187
+ export function dropDerivablePlainDescription(row) {
188
+ if (Array.isArray(row))
189
+ return row.map(dropDerivablePlainDescription);
190
+ if (!isObj(row))
191
+ return row;
192
+ const html = row.htmlDescription;
193
+ const plain = row.plainDescription;
194
+ if (typeof html !== "string" || typeof plain !== "string" || !html || !plain)
195
+ return row;
196
+ if (collapseWs(stripHtml(html)) !== collapseWs(plain))
197
+ return row;
198
+ const { plainDescription: _derivable, ...rest } = row;
199
+ return rest;
200
+ }