suppa-mcp-2 1.18.0 → 1.20.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.
@@ -5,8 +5,9 @@
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
+ import { assertMergeLists, elideEchoedResponse, stripAccessMetadata } from "./utils.js";
9
9
  import * as tenants from "./tenants.js";
10
+ import * as schemaCache from "./schemaCache.js";
10
11
  // HTTP statuses that signal a transient upstream problem worth one retry.
11
12
  const TRANSIENT_CODES = new Set([429, 502, 503, 504]);
12
13
  function debug(msg) {
@@ -268,6 +269,25 @@ async function sendWithReauth(ctx, buildHeaders, method, url, data, timeout, opt
268
269
  if (isPermanentDeletePath(url)) {
269
270
  throw permanentDeleteRefusal(url);
270
271
  }
272
+ // A schema read repeated inside one burst of work is the same schema. The
273
+ // lookup sits here rather than at the twelve call sites, so a new caller gets
274
+ // the benefit without knowing the cache exists. See schemaCache.
275
+ // sendWithReauth is handed an absolute URL; the cache is keyed by the path so
276
+ // the same entity on two tenants cannot collide.
277
+ const path = url.startsWith(ctx.baseUrl) ? url.slice(ctx.baseUrl.length) : url;
278
+ const cacheable = schemaCache.isCacheableSchemaRead(method, path);
279
+ if (cacheable && !opts.fresh) {
280
+ const hit = schemaCache.get(ctx.host, path);
281
+ if (hit !== schemaCache.MISS) {
282
+ debug(`${method} ${url} -> schema cache hit`);
283
+ return opts.unwrap ? unwrapEnvelope(hit) : hit;
284
+ }
285
+ }
286
+ // Likewise the invalidation: every builder write passes through here, so no
287
+ // call site can change a schema and forget to say so.
288
+ if (schemaCache.invalidatesSchema(method, path)) {
289
+ schemaCache.invalidate(ctx.host);
290
+ }
271
291
  let refreshed = false;
272
292
  let transientRetried = false;
273
293
  const retriable = isSafeRequest(method, url);
@@ -356,7 +376,13 @@ async function sendWithReauth(ctx, buildHeaders, method, url, data, timeout, opt
356
376
  if (!raw || !raw.trim()) {
357
377
  return null;
358
378
  }
359
- const result = JSON.parse(raw);
379
+ // Every JSON response this server ever sees passes through here, which is
380
+ // the only place a backstop can cover the endpoints whose access flag is
381
+ // undocumented as well as the ones where it is set. See stripAccessMetadata.
382
+ const result = stripAccessMetadata(JSON.parse(raw));
383
+ if (cacheable) {
384
+ schemaCache.set(ctx.host, path, result);
385
+ }
360
386
  return opts.unwrap ? unwrapEnvelope(result) : result;
361
387
  }
362
388
  }
@@ -379,7 +405,7 @@ export async function makeRequest(method, path, body = null, opts = {}) {
379
405
  data = JSON.stringify(body);
380
406
  extra["Content-Type"] = "application/json; charset=UTF-8";
381
407
  }
382
- return sendWithReauth(ctx, (t) => headers(ctx, t, extra), method, url, data, timeout, { unwrap: !opts.raw });
408
+ return sendWithReauth(ctx, (t) => headers(ctx, t, extra), method, url, data, timeout, { unwrap: !opts.raw, fresh: opts.fresh });
383
409
  }
384
410
  /** Make a raw-bytes request (for multipart uploads). */
385
411
  export async function makeRequestRawBytes(method, path, data, contentType, opts = {}) {
@@ -505,10 +531,15 @@ export async function insertEntity(entity, fieldsList, returning = null) {
505
531
  body.returning = returning;
506
532
  }
507
533
  const result = await makeRequest("POST", dataUrl(entity, "insert"), body);
508
- if (Array.isArray(result)) {
509
- return result;
534
+ // With no `returning` projection the platform answers with the whole stored
535
+ // record, so a long value just uploaded comes straight back. Only values that
536
+ // are byte-identical to what was sent are replaced — see elideEchoedResponse.
537
+ const sent = fieldsList.length === 1 ? fieldsList[0] : {};
538
+ const lean = elideEchoedResponse(result, sent);
539
+ if (Array.isArray(lean)) {
540
+ return lean;
510
541
  }
511
- return result ? [result] : [];
542
+ return lean ? [lean] : [];
512
543
  }
513
544
  /**
514
545
  * Update one instance.
@@ -537,7 +568,11 @@ export async function updateEntity(entity, instanceId, fields, merge = null, unm
537
568
  if (unmerge && unmerge.length > 0) {
538
569
  body.unmerge = [...unmerge];
539
570
  }
540
- return makeRequest("POST", dataUrl(entity, "update") + `/${instanceId}`, body);
571
+ const result = await makeRequest("POST", dataUrl(entity, "update") + `/${instanceId}`, body);
572
+ // Same echo as insert, and here there is no documented flag to turn it off at
573
+ // the source — the update endpoint's body (data.txt:588-593) has no
574
+ // getAccessByFields. Only byte-identical values are replaced.
575
+ return elideEchoedResponse(result, fields);
541
576
  }
542
577
  /**
543
578
  * SOFT-delete the matching instances: /remove sets deletedAt and leaves the row
@@ -0,0 +1,112 @@
1
+ /**
2
+ * A short-lived, per-tenant cache for entity schema reads.
3
+ *
4
+ * WHY THIS EXISTS
5
+ *
6
+ * Every record write pays for the schema twice before it does any work:
7
+ * `GET /api/core/schema` to resolve the entity name, then
8
+ * `GET /api/core/schema/<entity>` to check the field names against the real
9
+ * columns. Measured on suppa_create_record and suppa_update_record, that is two
10
+ * of three requests — and the second one averages ~24 KB. An agent creating ten
11
+ * records in a row fetched the identical schema twenty times.
12
+ *
13
+ * Those two reads are what make the write path SAFE (the platform silently drops
14
+ * unknown keys, so a write that skipped validation would create a record quietly
15
+ * missing its data). They are not optional. They are just repetitive.
16
+ *
17
+ * WHY IT IS SAFE
18
+ *
19
+ * A cache trades freshness for speed, and a stale schema is not a harmless
20
+ * slowdown — it is a wrong answer. Three things bound that:
21
+ *
22
+ * 1. Anything this server does that CHANGES a schema clears the tenant's cache,
23
+ * and the clearing happens in makeRequest, where every builder request must
24
+ * pass. No call site can forget to invalidate, because no call site does it.
25
+ * 2. A short TTL bounds a change made ELSEWHERE — another session, the UI, or
26
+ * the platform's own convergence on application start.
27
+ * 3. The one place staleness could produce a wrong ANSWER rather than a slow
28
+ * one — refusing a write because a field looks unknown — re-reads with
29
+ * `fresh` before it refuses. See _validateRecordWrites.
30
+ *
31
+ * Set SUPPA_SCHEMA_CACHE_TTL=0 to switch it off entirely.
32
+ */
33
+ /** Seconds a cached schema read stays usable. 0 disables the cache. */
34
+ export const SCHEMA_CACHE_TTL = (() => {
35
+ const raw = process.env.SUPPA_SCHEMA_CACHE_TTL;
36
+ if (raw === undefined || raw === "") {
37
+ return 30;
38
+ }
39
+ const n = Number.parseInt(raw, 10);
40
+ return Number.isFinite(n) && n >= 0 ? n : 30;
41
+ })();
42
+ /** host → (path → entry). Keyed by tenant, because suppa_use_tenant switches. */
43
+ const store = new Map();
44
+ /**
45
+ * Schema READS, and only reads.
46
+ *
47
+ * `/api/core/schema`, `/api/core/schema/<entity>` and the tabular-parts listing
48
+ * hanging off it. Deliberately not `/api/core/builder/...`: those are writes,
49
+ * and a write is what invalidates.
50
+ */
51
+ export function isCacheableSchemaRead(method, path) {
52
+ if (method.toUpperCase() !== "GET") {
53
+ return false;
54
+ }
55
+ return /^\/api\/core\/schema(\/|$|\?)/.test(path);
56
+ }
57
+ /**
58
+ * Does this request change what a schema read would return?
59
+ *
60
+ * The entity builder is the whole surface: add-fields, update-field,
61
+ * create-entity, update-options, remove. Data writes (`/api/core/data/...`) move
62
+ * rows, not columns, and leave the schema alone.
63
+ */
64
+ export function invalidatesSchema(method, path) {
65
+ if (method.toUpperCase() === "GET") {
66
+ return false;
67
+ }
68
+ return path.includes("/api/core/builder/");
69
+ }
70
+ /** A cached value, or MISS. `undefined` is a legal cached value, so use MISS. */
71
+ export const MISS = Symbol("schema-cache-miss");
72
+ export function get(host, path) {
73
+ if (SCHEMA_CACHE_TTL <= 0) {
74
+ return MISS;
75
+ }
76
+ const byPath = store.get(host);
77
+ const entry = byPath?.get(path);
78
+ if (!entry) {
79
+ return MISS;
80
+ }
81
+ if (Date.now() >= entry.expires) {
82
+ byPath.delete(path);
83
+ return MISS;
84
+ }
85
+ return entry.value;
86
+ }
87
+ export function set(host, path, value) {
88
+ if (SCHEMA_CACHE_TTL <= 0) {
89
+ return;
90
+ }
91
+ let byPath = store.get(host);
92
+ if (!byPath) {
93
+ byPath = new Map();
94
+ store.set(host, byPath);
95
+ }
96
+ byPath.set(path, { value, expires: Date.now() + SCHEMA_CACHE_TTL * 1000 });
97
+ }
98
+ /**
99
+ * Drop everything cached for one tenant — or, with no argument, for all of them.
100
+ *
101
+ * Coarse on purpose. A builder call can change an entity this server never named
102
+ * (a back-reference lands a column on the OTHER side of a relation), so clearing
103
+ * only the entity in the URL would leave a stale entry behind that nothing would
104
+ * ever correct. The cache refills in one request.
105
+ */
106
+ export function invalidate(host) {
107
+ if (host === undefined) {
108
+ store.clear();
109
+ return;
110
+ }
111
+ store.delete(host);
112
+ }
package/dist/server.js CHANGED
@@ -243,6 +243,7 @@ APPROVAL GATES (human-in-the-loop)
243
243
  - Every update/move/close/delete tool returns {"status": "confirmation_required"} when called without confirm=true, and performs NOTHING.
244
244
  - On that response: show the user what will change, get explicit approval, then re-call the same tool with confirm=true. Never set confirm=true on the first call without the user's go-ahead.
245
245
  - Create/read tools (and comments) need no confirmation.
246
+ - A value shown as <N chars — exactly as sent / unchanged from this call's arguments> is NOT the stored text: it is the long string you yourself supplied in this same call, named instead of repeated. Quote it to the user from your own arguments; never report the marker as the record's content.
246
247
 
247
248
  ENTITY BUILDER (create + edit fields; removal is UI-only) — suppa_add_field's description carries the real field types, the sub_type matrix and the field options; suppa_update_field's carries what may still be changed on a field that exists. Two things those cannot decide for you:
248
249
  - OWNED CHILD COLLECTIONS ARE TABULAR PARTS. Repeating rows belonging to ONE parent record (a part's BOM items) go through suppa_create_tabular_part(parent_entity, name), which creates the child's 'owner' relation and the parent link. Never model it by hand — suppa_add_field REFUSES field_type='one-to-many'. 'many-to-many' is for a shared lookup referenced by many records.
@@ -1861,9 +1861,9 @@ function _truncJson(val) {
1861
1861
  return jsonResponse(val).slice(0, 60);
1862
1862
  }
1863
1863
  /** Live entity names on this tenant, or null if the schema list is unreadable. */
1864
- async function _liveEntityList() {
1864
+ async function _liveEntityList(fresh = false) {
1865
1865
  try {
1866
- const listing = await makeRequest("GET", "/api/core/schema");
1866
+ const listing = await makeRequest("GET", "/api/core/schema", null, { fresh });
1867
1867
  if (!Array.isArray(listing)) {
1868
1868
  return null;
1869
1869
  }
@@ -1884,17 +1884,31 @@ async function _liveEntityList() {
1884
1884
  * returns an error with near-matches.
1885
1885
  */
1886
1886
  async function _resolveEntity(name) {
1887
- const names = await _liveEntityList();
1887
+ let names = await _liveEntityList();
1888
1888
  if (names === null || names.length === 0) {
1889
1889
  return { name };
1890
1890
  }
1891
1891
  if (names.includes(name)) {
1892
1892
  return { name };
1893
1893
  }
1894
- const ci = names.find((n) => n.toLowerCase() === name.toLowerCase());
1894
+ let ci = names.find((n) => n.toLowerCase() === name.toLowerCase());
1895
1895
  if (ci) {
1896
1896
  return { name: ci };
1897
1897
  }
1898
+ // About to refuse a name for not existing. The list may have come from the
1899
+ // cache, and an entity created elsewhere since would be refused wrongly — so
1900
+ // the refusal is only allowed to stand against a list read from the platform.
1901
+ const latest = await _liveEntityList(true);
1902
+ if (latest !== null && latest.length > 0) {
1903
+ names = latest;
1904
+ if (names.includes(name)) {
1905
+ return { name };
1906
+ }
1907
+ ci = names.find((n) => n.toLowerCase() === name.toLowerCase());
1908
+ if (ci) {
1909
+ return { name: ci };
1910
+ }
1911
+ }
1898
1912
  const nl = name.toLowerCase();
1899
1913
  const near = names
1900
1914
  .filter((n) => n.toLowerCase().includes(nl) || nl.includes(n.toLowerCase()))
@@ -1937,20 +1951,36 @@ async function _validateRecordWrites(entityName, records) {
1937
1951
  return { entityName, error: ent.error };
1938
1952
  }
1939
1953
  entityName = ent.name;
1940
- let defs;
1941
- try {
1942
- const schema = await makeRequest("GET", `/api/core/schema/${entityName}`);
1943
- defs = _extractFields(schema);
1944
- }
1945
- catch {
1946
- defs = null; // unreadable → can't validate fields; proceed
1947
- }
1954
+ const readDefs = async (fresh) => {
1955
+ try {
1956
+ return _extractFields(await makeRequest("GET", `/api/core/schema/${entityName}`, null, { fresh }));
1957
+ }
1958
+ catch {
1959
+ return null; // unreadable → can't validate fields; proceed
1960
+ }
1961
+ };
1962
+ const unknownIn = (names) => [
1963
+ ...new Set(records.flatMap((r) => Object.keys(r).filter((k) => !names.has(k)))),
1964
+ ];
1965
+ const namesOf = (list) => new Set(list.map((f) => f.name).filter((n) => Boolean(n)));
1966
+ let defs = await readDefs(false);
1948
1967
  if (defs && defs.length > 0) {
1949
1968
  const many = records.length > 1;
1950
- const fieldNames = new Set(defs.map((f) => f.name).filter((n) => Boolean(n)));
1951
- const unknown = [
1952
- ...new Set(records.flatMap((r) => Object.keys(r).filter((k) => !fieldNames.has(k)))),
1953
- ];
1969
+ let fieldNames = namesOf(defs);
1970
+ let unknown = unknownIn(fieldNames);
1971
+ if (unknown.length > 0) {
1972
+ // The schema read above may have been served from the cache, and the one
1973
+ // way a stale schema turns into a WRONG answer rather than a slow one is
1974
+ // right here: refusing a field that somebody added since. Re-read from the
1975
+ // platform before refusing. Costs a request only on the path that was
1976
+ // about to fail anyway.
1977
+ const latest = await readDefs(true);
1978
+ if (latest && latest.length > 0) {
1979
+ defs = latest;
1980
+ fieldNames = namesOf(latest);
1981
+ unknown = unknownIn(fieldNames);
1982
+ }
1983
+ }
1954
1984
  if (unknown.length > 0) {
1955
1985
  const body = {
1956
1986
  error: `Refused: field(s) [${unknown.join(", ")}] do not exist on '${entityName}'. ` +
package/dist/utils.js CHANGED
@@ -586,7 +586,175 @@ export function confirmRequired(action, target, proposedChanges) {
586
586
  "soft — sets deletedAt, row remains, reversible via suppa_restore_record";
587
587
  }
588
588
  if (proposedChanges !== undefined) {
589
- body.proposed_changes = proposedChanges;
589
+ // The preview was a verbatim copy of this call's own arguments. Long values
590
+ // are named and sized instead of repeated — see elideEchoedArgs.
591
+ body.proposed_changes = elideEchoedArgs(proposedChanges);
590
592
  }
591
593
  return jsonResponse(body);
592
594
  }
595
+ // ---------------------------------------------------------------------------
596
+ // Payload thrift: three things this server was paying for and reading never.
597
+ //
598
+ // A tool result is not paid once. The whole context is re-sent on every turn,
599
+ // so a 12k-char string returned in turn 5 is charged again in turns 6..N and is
600
+ // still occupying the window when compaction fires. The reductions below are
601
+ // therefore worth real money — but each one has to be information-preserving,
602
+ // or it buys tokens with the model's ability to do the job.
603
+ //
604
+ // The test each of these passes: the bytes removed carry NOTHING the caller does
605
+ // not already hold. That is a stronger claim than "probably unimportant", and it
606
+ // is the only claim that justifies removing anything at all.
607
+ // ---------------------------------------------------------------------------
608
+ /**
609
+ * Per-record access metadata the platform attaches to rows.
610
+ *
611
+ * These are lists of FIELD NAMES, identical on every row of an entity, and no
612
+ * code in this server reads any of them. `getAccessByFields: false` suppresses
613
+ * the first two at the source (api-entity-builder-data.txt:72) — this list is
614
+ * the backstop for the rest: `$instanceAccess` appears in no documented flag,
615
+ * and the update endpoint documents no flag at all, so an endpoint that ignores
616
+ * the request would otherwise put them back without anyone noticing.
617
+ *
618
+ * NAMED KEYS ONLY, deliberately. A blanket "drop every key starting with $"
619
+ * would also drop any future `$`-prefixed key the platform introduces to carry
620
+ * something that matters, and it would do so silently.
621
+ */
622
+ export const ACCESS_METADATA_KEYS = [
623
+ "$readAccess",
624
+ "$updateAccess",
625
+ "$instanceAccess",
626
+ ];
627
+ /**
628
+ * Recursively drop ACCESS_METADATA_KEYS from a parsed response.
629
+ *
630
+ * Returns the input unchanged — the same reference — when there is nothing to
631
+ * strip, so the common case (schema reads, error bodies, anything without ACL)
632
+ * costs a walk and no allocation.
633
+ */
634
+ export function stripAccessMetadata(value) {
635
+ if (Array.isArray(value)) {
636
+ let changed = false;
637
+ const out = value.map((item) => {
638
+ const next = stripAccessMetadata(item);
639
+ if (next !== item) {
640
+ changed = true;
641
+ }
642
+ return next;
643
+ });
644
+ return changed ? out : value;
645
+ }
646
+ if (value === null || typeof value !== "object") {
647
+ return value;
648
+ }
649
+ // Only plain objects: a Buffer, Date or class instance is left alone.
650
+ const proto = Object.getPrototypeOf(value);
651
+ if (proto !== Object.prototype && proto !== null) {
652
+ return value;
653
+ }
654
+ const entries = Object.entries(value);
655
+ let changed = false;
656
+ const out = {};
657
+ for (const [key, item] of entries) {
658
+ if (ACCESS_METADATA_KEYS.includes(key)) {
659
+ changed = true;
660
+ continue;
661
+ }
662
+ const next = stripAccessMetadata(item);
663
+ if (next !== item) {
664
+ changed = true;
665
+ }
666
+ out[key] = next;
667
+ }
668
+ return changed ? out : value;
669
+ }
670
+ /**
671
+ * Below this many characters, a value is cheaper to repeat than to describe.
672
+ *
673
+ * The marker that replaces an elided value costs ~60 characters, so eliding a
674
+ * short title would COST tokens and lose the at-a-glance readability that makes
675
+ * a confirmation preview reviewable. Only values long enough for the saving to
676
+ * dominate are elided.
677
+ */
678
+ export const ECHO_ELISION_THRESHOLD = 200;
679
+ /** The stand-in for a value the caller already holds verbatim. */
680
+ function echoMarker(chars, why) {
681
+ return `<${chars} chars — ${why}>`;
682
+ }
683
+ /**
684
+ * Replace long string values the CALLER SUPPLIED IN THIS CALL with a marker.
685
+ *
686
+ * This is the confirmation-preview half. `proposed_changes` exists so the agent
687
+ * can show the user what is about to change; it was built by copying the tool's
688
+ * own arguments back out. For a task description that is a verbatim second copy
689
+ * of a string sitting in the same assistant turn's tool-call arguments — the
690
+ * model cannot learn anything from reading it twice, and it pays for it on
691
+ * every subsequent turn.
692
+ *
693
+ * What survives: the key (so the user still sees WHICH fields change), every
694
+ * short value in full (titles, ids, deadlines — the things a human actually
695
+ * eyeballs before approving), and the size of what was elided.
696
+ */
697
+ export function elideEchoedArgs(changes) {
698
+ if (typeof changes === "string") {
699
+ return changes.length > ECHO_ELISION_THRESHOLD
700
+ ? echoMarker(changes.length, "unchanged from this call's arguments")
701
+ : changes;
702
+ }
703
+ if (Array.isArray(changes)) {
704
+ return changes.map((item) => elideEchoedArgs(item));
705
+ }
706
+ if (changes === null || typeof changes !== "object") {
707
+ return changes;
708
+ }
709
+ const proto = Object.getPrototypeOf(changes);
710
+ if (proto !== Object.prototype && proto !== null) {
711
+ return changes;
712
+ }
713
+ // Recurses: suppa_update_record nests the real payload one level down, in
714
+ // proposed_changes.fields, and a top-level-only pass walked straight past the
715
+ // one value on that tool big enough to matter.
716
+ const out = {};
717
+ for (const [key, value] of Object.entries(changes)) {
718
+ out[key] = elideEchoedArgs(value);
719
+ }
720
+ return out;
721
+ }
722
+ /**
723
+ * Replace values in a write RESPONSE that came back byte-identical to what was
724
+ * sent, when they are long enough to be worth it.
725
+ *
726
+ * This is the platform-echo half. An insert with no `returning` projection
727
+ * answers with the whole stored record, which means the HTML description just
728
+ * uploaded is billed a second time on the way back.
729
+ *
730
+ * The identity test is what makes this safe, and it is not a heuristic: a value
731
+ * is only replaced when it is EXACTLY the string that was sent. If the platform
732
+ * normalised the markup, filled a default, or rejected part of the input, the
733
+ * stored value differs from the sent one — that difference is real information
734
+ * about what the platform did, and it is returned in full. The key is always
735
+ * kept, so "the field was written" is never in doubt.
736
+ */
737
+ export function elideEchoedResponse(result, sent) {
738
+ if (Array.isArray(result)) {
739
+ return result.map((row) => elideEchoedResponse(row, sent));
740
+ }
741
+ if (result === null || typeof result !== "object") {
742
+ return result;
743
+ }
744
+ const proto = Object.getPrototypeOf(result);
745
+ if (proto !== Object.prototype && proto !== null) {
746
+ return result;
747
+ }
748
+ const out = {};
749
+ for (const [key, value] of Object.entries(result)) {
750
+ const supplied = sent[key];
751
+ out[key] =
752
+ typeof value === "string" &&
753
+ value.length > ECHO_ELISION_THRESHOLD &&
754
+ typeof supplied === "string" &&
755
+ supplied === value
756
+ ? echoMarker(value.length, "exactly as sent in this call")
757
+ : value;
758
+ }
759
+ return out;
760
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "suppa-mcp-2",
3
- "version": "1.18.0",
3
+ "version": "1.20.0",
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": {