suppa-mcp-2 1.40.5 → 1.41.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.
Files changed (53) hide show
  1. package/README.md +53 -11
  2. package/dist/bin.js +68 -1
  3. package/dist/cli/api.js +238 -0
  4. package/dist/cli/help.js +1 -0
  5. package/dist/cli/run.js +12 -25
  6. package/dist/cli/tenantPoint.js +35 -0
  7. package/dist/config.js +30 -1
  8. package/dist/customFieldHints.js +19 -22
  9. package/dist/readEconomy.js +32 -3
  10. package/dist/server.js +236 -81
  11. package/dist/toolTable.js +3 -3
  12. package/dist/tools/customFieldSets.js +5 -2
  13. package/dist/tools/customFields.js +9 -3
  14. package/dist/tools/customFieldsAsCode.js +62 -19
  15. package/dist/tools/entity.js +417 -114
  16. package/dist/tools/fieldTypeChange.js +364 -0
  17. package/dist/tools/formLifecycle.js +567 -0
  18. package/dist/tools/formV2.js +311 -45
  19. package/dist/tools/nameMap.js +24 -4
  20. package/dist/tools/query.js +279 -0
  21. package/dist/utils.js +9 -1
  22. package/package.json +1 -1
  23. package/skills/suppa-cli/SKILL.md +9 -1
  24. package/skills/suppa-entity-code/SKILL.md +458 -416
  25. package/skills/suppa-entity-code/references/custom-fields.md +4 -1
  26. package/skills/suppa-entity-code/references/enforcement.md +2 -1
  27. package/skills/suppa-entity-code/references/entities.md +503 -482
  28. package/skills/suppa-entity-code/references/extensions.md +1 -1
  29. package/skills/suppa-entity-code/references/registration.md +66 -16
  30. package/skills/suppa-entity-code/references/runtime.md +136 -0
  31. package/skills/suppa-entity-code/references/seeds.md +38 -1
  32. package/skills/suppa-entity-code/references/tabular-parts.md +11 -11
  33. package/skills/suppa-entity-code/references/v1-mapping.md +1 -1
  34. package/skills/suppa-entity-code/scripts/house-rules.mjs +7 -1
  35. package/skills/suppa-entity-code/scripts/validate-suppa-schema.mjs +1104 -38
  36. package/skills/suppa-entity-code/templates/AGENTS.entity-code.md +9 -6
  37. package/skills/suppa-entity-code/templates/custom-fields.template.ts +5 -3
  38. package/skills/suppa-entity-code/templates/entity-extension.template.ts +3 -0
  39. package/skills/suppa-entity-code/templates/relation-target-stub.template.ts +7 -1
  40. package/skills/suppa-entity-code/templates/seed.template.ts +27 -12
  41. package/skills/suppa-entity-code/templates/tabular-part.template.ts +14 -13
  42. package/skills/suppa-form-v2/SKILL.md +16 -15
  43. package/skills/suppa-form-v2/data/component-index.json +1 -1
  44. package/skills/suppa-form-v2/data/component-props.json +2 -1
  45. package/skills/suppa-form-v2/notes/embeddedForm.md +6 -4
  46. package/skills/suppa-form-v2/notes/table.md +1 -1
  47. package/skills/suppa-form-v2/references/charts.md +10 -2
  48. package/skills/suppa-form-v2/references/layout.md +2 -2
  49. package/skills/suppa-form-v2/references/publishing.md +34 -13
  50. package/skills/suppa-form-v2/references/tables.md +7 -7
  51. package/skills/suppa-form-v2/scripts/form-rules.mjs +8 -6
  52. package/skills/suppa-form-v2/scripts/manifest-corrections.mjs +56 -0
  53. package/skills/suppa-form-v2/scripts/validate-form-schema.mjs +195 -7
package/README.md CHANGED
@@ -30,7 +30,7 @@ No API key needed to start — the server authenticates interactively via the `s
30
30
 
31
31
  ## The `suppa` command
32
32
 
33
- The same 96 operations the MCP server exposes are available as a command, for
33
+ The same 104 operations the MCP server exposes are available as a command, for
34
34
  shells, scripts and CI:
35
35
 
36
36
  ```bash
@@ -56,6 +56,17 @@ call elsewhere; `--pretty` re-indents the answer. Exit codes: `0` done, `1`
56
56
  refused or not fully done (`passed: false`, `created: false`, a non-zero
57
57
  `failed`), `2` refused before anything was sent.
58
58
 
59
+ For an endpoint no command covers there is `suppa api <METHOD> <path>` — the raw
60
+ call, with the CLI's session and tenant resolution. It exists only in the CLI,
61
+ never as an MCP tool, and it is gated because it skips every check the commands
62
+ make. Reads (GET, and POST to `…/select`, `…/search`, `…/query`, `…/count`) are
63
+ sent at once. Anything else prints the request and sends nothing. With
64
+ `--confirm` it is sent, but only to a tenant named by `--tenant`, never to the
65
+ remembered one. The permanent delete stays refused. `suppa help api` has the
66
+ flags. In Git Bash, leave off the path's leading slash (`core/schema`): MSYS
67
+ rewrites an argument that starts with `/` into a Windows path, and the command
68
+ refuses that path and says why.
69
+
59
70
  ---
60
71
 
61
72
  ## Authentication
@@ -76,8 +87,8 @@ All variables are optional — the server works out of the box and authenticates
76
87
  | `SUPPA_API_KEY` | (none) | JWT / API key; skips interactive login when set (CI) |
77
88
  | `SUPPA_REFRESH_TOKEN` | (none) | Refresh token; paired with `SUPPA_API_KEY` for long-lived CI sessions |
78
89
  | `SUPPA_LANG` | `en` | Language (`en` / `uk`) |
79
- | `SUPPA_LANGS` | (auto) | Languages a multi-language title/Name is written into. When unset, resolved from the platform (the languages already used by existing entity titles), falling back to `en,uk`. Set e.g. `en,uk` to force it. |
80
- | `SUPPA_TZ` | `Europe/Kyiv` | Timezone |
90
+ | `SUPPA_LANGS` | (auto) | Languages a multi-language title/Name is written into. When unset, resolved from the platform: the languages the tenant has enabled (`SystemPreferences.availableLanguages`, what the builder UI reads), else the language keys of existing entity titles, falling back to `en,uk`. Only the 24 `Localizations` language columns are kept, and `en` is always included. Set e.g. `en,uk` to force it. |
91
+ | `SUPPA_TZ` | `Europe/Kyiv` | Timezone, sent as `X-Timezone`. Must be an IANA name (`Europe/Kyiv`, `UTC`): the platform refuses an offset such as `+03:00` on every request, so an invalid value falls back to the default with a warning on stderr. |
81
92
  | `SUPPA_MCP_LOGIN_PORT` | `8080` | Local loopback port for the browser login callback |
82
93
  | `SUPPA_MCP_HOME` | `~/.suppa-mcp` | Directory for the tenant registry |
83
94
  | `SUPPA_HTTP_TIMEOUT` | `60` | Per-request timeout, seconds |
@@ -189,6 +200,31 @@ Add to `.vscode/mcp.json`:
189
200
 
190
201
  Then run **`suppa_login`** once per tenant to authenticate.
191
202
 
203
+ ### Windows: prefer `node` over `npx`
204
+
205
+ On Windows `npx` runs through a `.cmd` shim, so a host that starts the server that way gets a chain
206
+ of processes — `cmd` → `npx` → `node` — and ends only the first one. The server exits on its own
207
+ once its client is gone (its stdin closes), and `npx` follows it; but a direct launch has no chain
208
+ to leave behind and starts faster. Install once and point the host at the entry file:
209
+
210
+ ```
211
+ npm i -g suppa-mcp-2
212
+ npm root -g # e.g. C:\Users\<you>\AppData\Roaming\npm\node_modules
213
+ ```
214
+
215
+ ```json
216
+ {
217
+ "mcpServers": {
218
+ "suppa-2.0": {
219
+ "command": "node",
220
+ "args": ["C:\\Users\\<you>\\AppData\\Roaming\\npm\\node_modules\\suppa-mcp-2\\dist\\bin.js"]
221
+ }
222
+ }
223
+ }
224
+ ```
225
+
226
+ Update with `npm i -g suppa-mcp-2@latest`; the path stays the same.
227
+
192
228
  ---
193
229
 
194
230
  ## Which version is running (and is it current)
@@ -343,9 +379,10 @@ live 2.0 tenant. The first two are refusals that name the next step; the rest ar
343
379
  call, or you will be told the old field list for the next minute.
344
380
  - **Removal is reversible.** `suppa_remove_custom_field` soft-deletes the metadata and the
345
381
  platform *renames* the column to `<name>_<timestamp>` rather than dropping it, so
346
- `suppa_restore_custom_field` brings the field and every value back. The NAME stays reserved
347
- while it is parked — a new field cannot take it until the old one is purged, which is not
348
- something this server can do.
382
+ `suppa_restore_custom_field` brings the field and every value back. The NAME is freed
383
+ (entity-builder, 2026-09-25): a new field can take it, but that field starts empty, and the
384
+ removed one can then not be restored while its twin lives. `suppa_apply_custom_fields`
385
+ therefore never re-creates a removed field — it reports it under `parked`.
349
386
  - **Restoring a record restores its values with it.** Deleting a record soft-deletes the row
350
387
  holding its custom values; the platform's own restore does not clear that row, which reads
351
388
  back as stale values (or as none, with `include_deleted_relations=false`) and makes the next
@@ -377,7 +414,7 @@ extension table is created outside that check and is not subject to it.
377
414
 
378
415
  ## Available tools
379
416
 
380
- 99 tools across the areas below.
417
+ 104 tools across the areas below.
381
418
 
382
419
  ### Session & identity
383
420
 
@@ -444,12 +481,14 @@ extension table is created outside that check and is not subject to it.
444
481
  | `suppa_list_tabular_parts` | List tabular parts (ТЧ) of an entity |
445
482
  | `suppa_search_records` | Search / filter records in any entity — nested AND/OR groups, auto-diagnoses an empty result (`deleted_scope` finds soft-deleted rows) |
446
483
  | `suppa_validate_select` | Check a select/filter payload against the entity without running it — names the field that does not resolve |
484
+ | `suppa_query` | Run one read-only SuppaSQL statement (SELECT/WITH) with the caller's read permissions — check a SQL chart or table source before writing the form |
447
485
  | `suppa_get_record` | Get a single record (`deleted_scope` reads a soft-deleted one) |
448
486
  | `suppa_create_entity` | Create a new entity (`options_json`: comments / globalSearch / hierarchy …) |
449
487
  | `suppa_create_tabular_part` | Create a tabular part (owned rows) of a parent |
450
488
  | `suppa_add_field` | Add a field to an entity (`options_json`: searchable / showInTable / canFilter …) |
451
489
  | `suppa_update_field` | Edit an existing field — name, title, flags, options, encryption (confirm-gated) |
452
- | `suppa_update_entity_options` | Toggle the 16 per-entity features — comments, hierarchy, approvals, customFields … (confirm-gated) |
490
+ | `suppa_change_field_type` | Change a field's type, converting every row — the platform's plan first, a refused plan never sent, a loss (locale loss, restoring an earlier column) sent only when accepted by name, a default the new type cannot hold replaced in the same call (confirm-gated) |
491
+ | `suppa_update_entity_options` | Toggle the 20 per-entity features — comments, hierarchy, approvals, customFields … (confirm-gated) |
453
492
  | `suppa_add_enum_values` | Add values to an enum field — the group is read from the field's subType |
454
493
  | `suppa_resolve_custom_fields` | Which custom fields are live for a record or context, and their values |
455
494
  | `suppa_add_custom_field` | Create a custom field in one context (its set is created if missing) |
@@ -501,14 +540,17 @@ extension table is created outside that check and is not subject to it.
501
540
 
502
541
  The seven above are **Suppa 1.0** forms: they read and write `data.formShema` (the platform's
503
542
  misspelling) and the v1 field types. A **Suppa 2.0** entity-builder form is a different product —
504
- the `schema` column on the row since 2.1, 58 component types — and is served by the two below plus the bundled
505
- `skills/suppa-form-v2` skill. Neither touches a tenant: both read files inside the package.
543
+ the `schema` column on the row since 2.1, 58 component types — and is served by the six below plus the bundled
544
+ `skills/suppa-form-v2` skill. The first two touch no tenant: they read files inside the package.
506
545
 
507
546
  | Tool | Description |
508
547
  |---|---|
509
548
  | `suppa_form_kb` | The 2.0 form knowledge base: the 58 element types, one type's prop table, a behaviour note, a reference topic, a template |
510
549
  | `suppa_validate_form_schema` | Run the 2.0 form gate over a draft before writing it — 37 structural error codes (the authoring lints live in the source agent, not here) |
511
- | `suppa_write_form_draft` | Save a checked draft to a form's `schema` column. Gates first, reads before it merges, creates no version — it never publishes |
550
+ | `suppa_write_form_draft` | Save a checked draft through the builder's own save (`PUT /core/forms/:id/schema`) — gated first, guarded by the form's revision, recorded in History; `variables` only when the draft lists some. It never publishes |
551
+ | `suppa_create_form_v2` | Create a 2.0 form (create / update / custom) with its draft in one transaction — the routing flag and default variable the builder adds, optionally filed into a folder (confirm-gated) |
552
+ | `suppa_form_versions` | A form's published versions, the component diff between two of them, and a summary of recent draft saves (read-only) |
553
+ | `suppa_form_lifecycle` | Publish, roll back (restore + publish), discard (unrecoverable) or promote — gated on the form gate and on the version belonging to the form (confirm-gated) |
512
554
 
513
555
  ### Migration (Suppa 1.0 → 2.0) & workspace
514
556
 
package/dist/bin.js CHANGED
@@ -23,6 +23,71 @@ process.on("unhandledRejection", (reason) => {
23
23
  process.on("uncaughtException", (err) => {
24
24
  process.stderr.write(`[suppa-mcp] uncaught exception (ignored): ${err instanceof Error ? err.stack || err.message : String(err)}\n`);
25
25
  });
26
+ /**
27
+ * Exit when the client is gone — do not linger as an orphan.
28
+ *
29
+ * A host that starts this server through `npx` on Windows gets a chain, cmd → npx → node, and ends
30
+ * only its direct child; this process then kept running (a token-refresh timer, a keep-alive socket
31
+ * or the background version check is enough to hold the event loop open), `npx` kept waiting on it,
32
+ * and the orphans piled up until the machine slowed down (reported 2026-09-30). The signal that
33
+ * reaches this process whoever was killed is its stdin reaching end-of-file — the host holds the
34
+ * only write end of that pipe — and a write to a stdout nobody reads failing with EPIPE. Neither is
35
+ * handled by the SDK's StdioServerTransport, which listens for `data` and `error` only. Once this
36
+ * process exits, the `npx` waiting on it exits too.
37
+ *
38
+ * End-of-file on stdin is not the end of the work, though: `printf <requests> | suppa-mcp` closes
39
+ * stdin right after its last request, and an answer still waiting on its HTTP call was dropped. So
40
+ * the requests in flight are answered first (for at most DRAIN_MS); a stdout nobody reads ends the
41
+ * process at once, since no answer can arrive anyway.
42
+ */
43
+ const DRAIN_MS = 30_000;
44
+ function exitWhenClientIsGone(transport) {
45
+ const inFlight = new Set();
46
+ let leaving = false;
47
+ const done = () => process.exit(0);
48
+ const deliver = transport.onmessage;
49
+ transport.onmessage = (message, extra) => {
50
+ if (message && message.method !== undefined && message.id !== undefined)
51
+ inFlight.add(message.id);
52
+ deliver?.call(transport, message, extra);
53
+ };
54
+ const send = transport.send.bind(transport);
55
+ transport.send = async (message, options) => {
56
+ try {
57
+ await send(message, options);
58
+ }
59
+ finally {
60
+ if (message && message.method === undefined && message.id !== undefined) {
61
+ inFlight.delete(message.id);
62
+ if (leaving && inFlight.size === 0)
63
+ done();
64
+ }
65
+ }
66
+ };
67
+ const leave = (why, drain) => {
68
+ if (!drain) {
69
+ process.stderr.write(`[suppa-mcp] ${why} — the client is gone; exiting.\n`);
70
+ done();
71
+ return;
72
+ }
73
+ if (leaving)
74
+ return;
75
+ leaving = true;
76
+ const waiting = inFlight.size;
77
+ process.stderr.write(`[suppa-mcp] ${why} — the client is gone; exiting` +
78
+ (waiting ? ` once ${waiting} request(s) in flight are answered.\n` : ".\n"));
79
+ if (waiting === 0)
80
+ done();
81
+ else
82
+ setTimeout(done, DRAIN_MS).unref();
83
+ };
84
+ process.stdin.on("end", () => leave("stdin reached end-of-file", true));
85
+ process.stdin.on("close", () => leave("stdin closed", true));
86
+ process.stdout.on("error", (e) => {
87
+ if (e?.code === "EPIPE" || e?.code === "ERR_STREAM_DESTROYED")
88
+ leave("stdout closed", false);
89
+ });
90
+ }
26
91
  // Startup is the one place a failure SHOULD stop the process — if the server
27
92
  // can't build or connect, there's nothing to serve. What it must not do is stop
28
93
  // without saying why.
@@ -31,7 +96,9 @@ try {
31
96
  const { buildServer } = await import("./server.js");
32
97
  const { refreshLatestVersionInBackground } = await import("./version.js");
33
98
  const server = buildServer();
34
- await server.connect(new StdioServerTransport());
99
+ const transport = new StdioServerTransport();
100
+ await server.connect(transport);
101
+ exitWhenClientIsGone(transport);
35
102
  // Only once the server is actually serving, and detached: refresh the cached
36
103
  // "newest published version" so the NEXT session's instructions can say the
37
104
  // running build is behind. Never awaited, never fatal, skipped entirely when
@@ -0,0 +1,238 @@
1
+ /**
2
+ * `suppa api <METHOD> <path>` — a raw call to the platform API, with this CLI's session and tenant.
3
+ *
4
+ * It exists for the endpoint no operation command covers, so an agent does not rebuild the token,
5
+ * the tenant URL and the error reporting by hand. It is also the one command that skips every
6
+ * check the operation commands make — a preview, a confirm, a read before a merge — and reaches
7
+ * endpoints the MCP server deliberately does not expose (removing an entity or a field is UI-only
8
+ * there). So the user's decision (2026-09-29) is the gate:
9
+ *
10
+ * - CLI only. There is no MCP tool for it.
11
+ * - Reads run at once: GET, and a POST whose last segment is select / search / query / count.
12
+ * `resolve` is NOT one — `/forms/:id/inheritance-issues/:id/resolve` writes.
13
+ * - Anything else prints the request and sends nothing. With `--confirm` it is sent — and only
14
+ * to a tenant named by `--tenant`, never to the remembered one: the tenant a CLI remembers can
15
+ * be production, and one forgotten flag must not put a raw write there.
16
+ * - The platform's permanent delete is refused whatever is passed (the same block the HTTP
17
+ * client enforces on every request, checked here first so it is never offered as a preview).
18
+ */
19
+ import { readFileSync } from "node:fs";
20
+ import { assertSafePath, isPermanentDeletePath, makeRequest, permanentDeleteRefusal } from "../httpClient.js";
21
+ import { pointAtTenant } from "./tenantPoint.js";
22
+ import { readOnlyProblem } from "../tools/query.js";
23
+ export const API_METHODS = ["GET", "POST", "PUT", "PATCH", "DELETE"];
24
+ export const READ_POST_SUFFIXES = ["select", "search", "query", "count"];
25
+ /** A read is sent at once; a write is shown first. Decided from the method and the last segment. */
26
+ export function classify(method, path) {
27
+ const m = method.toUpperCase();
28
+ if (m === "GET")
29
+ return "read";
30
+ if (m !== "POST")
31
+ return "write";
32
+ const last = path.split("?")[0].split("/").filter(Boolean).pop() ?? "";
33
+ return READ_POST_SUFFIXES.includes(last) ? "read" : "write";
34
+ }
35
+ export const API_HELP = "suppa api <METHOD> <path> — a raw call to the platform API, with this CLI's session and tenant.\n\n" +
36
+ " METHOD GET POST PUT PATCH DELETE\n" +
37
+ " path /api/core/… or /core/… (a ?query in it is moved into --query); the\n" +
38
+ " leading slash is optional — in Git Bash leave it off (core/schema)\n" +
39
+ " --query <k=v> a query parameter; repeat the flag per parameter\n" +
40
+ " --body-file <json> the request body, from a file\n" +
41
+ " --body-stdin the request body, from standard input\n" +
42
+ " --confirm send a write (see below)\n" +
43
+ " --tenant <alias> the tenant for this call — REQUIRED to send a write\n" +
44
+ " --pretty re-indent the JSON answer\n\n" +
45
+ "Reads — GET, and POST to …/select, …/search, …/query, …/count — are sent at once.\n" +
46
+ "Anything else is a write: without --confirm it prints the request and sends nothing; with\n" +
47
+ "--confirm it goes only to the tenant --tenant names, never to the remembered one. A raw call\n" +
48
+ "skips every check the operation commands make — prefer one when it exists (suppa help <group>).\n" +
49
+ "The platform's permanent delete (/core/data/<entity>/delete) is refused always; /remove is the\n" +
50
+ "reversible delete.\n";
51
+ export async function runApi(argv, io) {
52
+ const { out, err, stdin } = io;
53
+ const refuse = (...lines) => {
54
+ err(`refused before sending anything:\n${lines.map((l) => " " + l).join("\n")}\nrun: suppa help api\n`);
55
+ return 2;
56
+ };
57
+ // ---- argv -------------------------------------------------------------
58
+ const positional = [];
59
+ const query = {};
60
+ let bodyFile = null;
61
+ let bodyStdin = false;
62
+ let confirm = false;
63
+ let tenant = null;
64
+ let pretty = false;
65
+ const problems = [];
66
+ for (let i = 0; i < argv.length; i++) {
67
+ const token = argv[i];
68
+ if (!token.startsWith("--") && token !== "-h") {
69
+ positional.push(token);
70
+ continue;
71
+ }
72
+ const eq = token.indexOf("=");
73
+ const flag = eq === -1 ? token : token.slice(0, eq);
74
+ const inline = eq === -1 ? undefined : token.slice(eq + 1);
75
+ const value = () => {
76
+ if (inline !== undefined)
77
+ return inline;
78
+ const next = argv[i + 1];
79
+ if (next === undefined || next.startsWith("--")) {
80
+ problems.push(`${flag} given with no value`);
81
+ return null;
82
+ }
83
+ i++;
84
+ return next;
85
+ };
86
+ const bare = () => {
87
+ if (inline !== undefined)
88
+ problems.push(`${flag} takes no value`);
89
+ return true;
90
+ };
91
+ switch (flag) {
92
+ case "--help":
93
+ case "-h":
94
+ out(API_HELP);
95
+ return 0;
96
+ case "--query": {
97
+ const v = value();
98
+ if (v === null)
99
+ break;
100
+ const k = v.indexOf("=");
101
+ if (k <= 0)
102
+ problems.push(`--query ${v}: write it as key=value`);
103
+ else
104
+ query[v.slice(0, k)] = v.slice(k + 1);
105
+ break;
106
+ }
107
+ case "--body-file":
108
+ bodyFile = value();
109
+ break;
110
+ case "--body-stdin":
111
+ bodyStdin = bare();
112
+ break;
113
+ case "--confirm":
114
+ confirm = bare();
115
+ break;
116
+ case "--tenant":
117
+ tenant = value();
118
+ break;
119
+ case "--pretty":
120
+ pretty = bare();
121
+ break;
122
+ default:
123
+ problems.push(`unknown flag ${flag} — this command takes --query, --body-file, --body-stdin, --confirm, --tenant, --pretty`);
124
+ }
125
+ }
126
+ if (problems.length)
127
+ return refuse(...problems);
128
+ const [rawMethod, rawPath, ...extra] = positional;
129
+ if (!rawMethod || !rawPath)
130
+ return refuse("give a METHOD and a path: suppa api GET /core/schema");
131
+ if (extra.length)
132
+ return refuse(`unexpected argument${extra.length > 1 ? "s" : ""}: ${extra.join(" ")}`);
133
+ const method = rawMethod.toUpperCase();
134
+ if (!API_METHODS.includes(method)) {
135
+ return refuse(`method '${rawMethod}' is not one of ${API_METHODS.join(", ")}`);
136
+ }
137
+ // ---- path and query ---------------------------------------------------
138
+ // Git Bash (MSYS) rewrites an argument that starts with "/" into a Windows path before node ever
139
+ // sees it — measured on this machine: `/core/schema` arrived as C:/Users/…/Git/core/schema. That
140
+ // is refused with the reason, not repaired by guessing where the install prefix ends; the
141
+ // slash-less form below is the one MSYS leaves alone.
142
+ if (/^[A-Za-z]:[\\/]/.test(rawPath)) {
143
+ return refuse(`path '${rawPath}' is a Windows path — Git Bash (MSYS) rewrites an argument that starts with / ` +
144
+ "into one. Write it without the leading slash (core/schema), or run with MSYS_NO_PATHCONV=1.");
145
+ }
146
+ const slashed = /^(api|core)\//.test(rawPath) ? `/${rawPath}` : rawPath;
147
+ if (!slashed.startsWith("/"))
148
+ return refuse(`path '${rawPath}' must start with /api/ or /core/`);
149
+ const q = slashed.indexOf("?");
150
+ let path = q === -1 ? slashed : slashed.slice(0, q);
151
+ if (q !== -1) {
152
+ for (const [k, v] of new URLSearchParams(slashed.slice(q + 1)))
153
+ if (!(k in query))
154
+ query[k] = v;
155
+ }
156
+ if (path.startsWith("/core/"))
157
+ path = `/api${path}`;
158
+ else if (!path.startsWith("/api/"))
159
+ return refuse(`path '${rawPath}' must start with /api/ or /core/ — the platform API lives there`);
160
+ try {
161
+ assertSafePath(path);
162
+ }
163
+ catch (e) {
164
+ return refuse(e instanceof Error ? e.message : String(e));
165
+ }
166
+ if (isPermanentDeletePath(path))
167
+ return refuse(permanentDeleteRefusal(path).message);
168
+ // ---- body -------------------------------------------------------------
169
+ if (bodyFile !== null && bodyStdin)
170
+ return refuse("give the body once: --body-file or --body-stdin");
171
+ let body = null;
172
+ if (bodyFile !== null || bodyStdin) {
173
+ if (method === "GET")
174
+ return refuse("a GET carries no body — send it as --query, or use POST");
175
+ let text;
176
+ try {
177
+ text = bodyFile !== null ? readFileSync(bodyFile, "utf-8") : stdin();
178
+ }
179
+ catch (e) {
180
+ return refuse(`${bodyFile !== null ? `--body-file ${bodyFile}` : "--body-stdin"}: ${e instanceof Error ? e.message : String(e)}`);
181
+ }
182
+ try {
183
+ body = JSON.parse(text.charCodeAt(0) === 0xfeff ? text.slice(1) : text);
184
+ }
185
+ catch (e) {
186
+ return refuse(`the body is not valid JSON: ${e instanceof Error ? e.message : String(e)}`);
187
+ }
188
+ }
189
+ // ---- the tenant, and the gate -----------------------------------------
190
+ const point = await pointAtTenant(tenant, err);
191
+ if (!point.ok)
192
+ return 2;
193
+ let kind = classify(method, path);
194
+ // `…/query` is a read only for what suppa_query itself would send. The engine is SELECT-only,
195
+ // but "read" here means "sent at once, to the remembered tenant" — so a statement suppa_query
196
+ // would refuse is shown and gated like any write instead.
197
+ let readRefusedBecause = null;
198
+ if (kind === "read" && path === "/api/core/data/query") {
199
+ const statement = body && typeof body === "object" ? body.query : undefined;
200
+ if (typeof statement === "string") {
201
+ readRefusedBecause = readOnlyProblem(statement);
202
+ if (readRefusedBecause)
203
+ kind = "write";
204
+ }
205
+ }
206
+ const request = {
207
+ method,
208
+ tenant: point.host,
209
+ path,
210
+ ...(Object.keys(query).length ? { query } : {}),
211
+ ...(body !== null ? { body } : {}),
212
+ };
213
+ if (kind === "write" && !confirm) {
214
+ out(JSON.stringify({
215
+ status: "confirmation_required",
216
+ message: "NOT sent. A raw write skips every check the operation commands make. Show this request to " +
217
+ "the user; to send it, re-run with --confirm --tenant <alias> — a write never goes to the " +
218
+ "remembered tenant by default.",
219
+ would_send: request,
220
+ ...(readRefusedBecause ? { read_refused_because: readRefusedBecause } : {}),
221
+ }, null, pretty ? 2 : undefined) + "\n");
222
+ return 0;
223
+ }
224
+ if (kind === "write" && !point.explicit) {
225
+ return refuse(`a raw write names its tenant: add --tenant <alias>. Without it this would go to the remembered tenant, ${point.host}.`);
226
+ }
227
+ // ---- send -------------------------------------------------------------
228
+ let answer;
229
+ try {
230
+ answer = await makeRequest(method, path, body, { raw: true, ...(Object.keys(query).length ? { query } : {}) });
231
+ }
232
+ catch (e) {
233
+ out(JSON.stringify({ error: e instanceof Error ? e.message : String(e), request: { method, tenant: point.host, path } }) + "\n");
234
+ return 1;
235
+ }
236
+ out((typeof answer === "string" ? answer : JSON.stringify(answer ?? null, null, pretty ? 2 : undefined)) + "\n");
237
+ return 0;
238
+ }
package/dist/cli/help.js CHANGED
@@ -37,6 +37,7 @@ export function helpRoot(table) {
37
37
  `groups: ${groups}\n` +
38
38
  `suppa help <group> the commands in one group\n` +
39
39
  `suppa help <command> its full description and flags\n` +
40
+ `suppa api <METHOD> <path> a raw call — suppa help api\n` +
40
41
  `${GLOBAL_FLAGS_LINE}\n`);
41
42
  }
42
43
  export function helpGroup(table, group) {
package/dist/cli/run.js CHANGED
@@ -29,7 +29,9 @@ import { readFileSync } from "node:fs";
29
29
  import { buildToolTable } from "../server.js";
30
30
  import { commandOf, toolNameOf, parseArgv, nearestFlag, flagOf } from "./flags.js";
31
31
  import { helpRoot, helpGroup, helpCommand } from "./help.js";
32
- import { inspectState, writeState } from "./state.js";
32
+ import { writeState } from "./state.js";
33
+ import { pointAtTenant } from "./tenantPoint.js";
34
+ import { API_HELP, runApi } from "./api.js";
33
35
  import { rewriteToolNames } from "./rewrite.js";
34
36
  import { PROFILES } from "../toolTable.js";
35
37
  /**
@@ -132,6 +134,9 @@ export async function run(argv, io = {}) {
132
134
  if (!what) {
133
135
  out(helpRoot(table));
134
136
  }
137
+ else if (what === "api") {
138
+ out(API_HELP);
139
+ }
135
140
  else if (table.some((s) => commandOf(s.name) === what)) {
136
141
  out(helpCommand(table, what));
137
142
  }
@@ -147,6 +152,9 @@ export async function run(argv, io = {}) {
147
152
  }
148
153
  return 0;
149
154
  }
155
+ // ---- the raw call: not a tool, and gated here (see api.ts) -------------
156
+ if (first === "api")
157
+ return runApi(rest, { out, err, stdin });
150
158
  // ---- resolve the command ---------------------------------------------
151
159
  const spec = table.find((s) => s.name === toolNameOf(first));
152
160
  if (!spec) {
@@ -224,31 +232,10 @@ export async function run(argv, io = {}) {
224
232
  return 2;
225
233
  }
226
234
  // ---- the tenant this process is pointed at ----------------------------
227
- const tenants = await import("../tenants.js");
228
235
  const isTenantSwitch = spec.name === "suppa_use_tenant";
229
- if (g.tenant !== null) {
230
- // One call, one tenant, nothing remembered: resolve like use-tenant does,
231
- // activate in THIS process only, and refuse the same way for an unknown name.
232
- const resolved = tenants.resolve(g.tenant);
233
- if (resolved === null) {
234
- err(`refused before sending anything:\n --tenant ${g.tenant}: unknown tenant — pass a known alias, a host or a full URL (suppa list-tenants shows them)\n`);
235
- return 2;
236
- }
237
- const [baseUrl, host] = resolved;
238
- tenants.activate(baseUrl, host);
239
- }
240
- else if (!isTenantSwitch) {
241
- const { state, problem } = inspectState();
242
- if (problem !== null) {
243
- // The one fallback that must never be silent: a present-but-unusable
244
- // state file means the command runs against the environment default,
245
- // and the caller is told which host that is before anything is sent.
246
- err(`warning: ${problem}; this command runs against the default tenant ${tenants.current().host}\n`);
247
- }
248
- else if (state.host && state.base_url) {
249
- tenants.activate(state.base_url, state.host);
250
- }
251
- }
236
+ const point = await pointAtTenant(g.tenant, err, { useRemembered: !isTenantSwitch });
237
+ if (!point.ok)
238
+ return 2;
252
239
  // ---- the same handler the MCP server calls ----------------------------
253
240
  // The MCP SDK catches anything a handler throws and turns it into a clean
254
241
  // answer ({content:[...], isError:true}). Most tools here return
@@ -0,0 +1,35 @@
1
+ /**
2
+ * Point this process at a tenant: the one `--tenant` names, or else the one the CLI remembers.
3
+ *
4
+ * Shared by every command and by `suppa api`, which needs to know which of the two it got —
5
+ * a raw write is sent only to a tenant the caller named on the command line.
6
+ */
7
+ import { inspectState } from "./state.js";
8
+ export async function pointAtTenant(tenant, err, { useRemembered = true } = {}) {
9
+ const tenants = await import("../tenants.js");
10
+ if (tenant !== null) {
11
+ // One call, one tenant, nothing remembered: resolve like use-tenant does,
12
+ // activate in THIS process only, and refuse the same way for an unknown name.
13
+ const resolved = tenants.resolve(tenant);
14
+ if (resolved === null) {
15
+ err(`refused before sending anything:\n --tenant ${tenant}: unknown tenant — pass a known alias, a host or a full URL (suppa list-tenants shows them)\n`);
16
+ return { ok: false };
17
+ }
18
+ const [baseUrl, host] = resolved;
19
+ tenants.activate(baseUrl, host);
20
+ return { ok: true, host, explicit: true };
21
+ }
22
+ if (useRemembered) {
23
+ const { state, problem } = inspectState();
24
+ if (problem !== null) {
25
+ // The one fallback that must never be silent: a present-but-unusable
26
+ // state file means the command runs against the environment default,
27
+ // and the caller is told which host that is before anything is sent.
28
+ err(`warning: ${problem}; this command runs against the default tenant ${tenants.current().host}\n`);
29
+ }
30
+ else if (state.host && state.base_url) {
31
+ tenants.activate(state.base_url, state.host);
32
+ }
33
+ }
34
+ return { ok: true, host: tenants.current().host, explicit: false };
35
+ }
package/dist/config.js CHANGED
@@ -117,7 +117,36 @@ const BASE_URL = (process.env.SUPPA_BASE_URL || "https://modern.suppa.me").repla
117
117
  const API_KEY = process.env.SUPPA_API_KEY || process.env.SUPPA_TOKEN || "";
118
118
  const REFRESH_TOKEN = process.env.SUPPA_REFRESH_TOKEN || "";
119
119
  const LANG = process.env.SUPPA_LANG || "en";
120
- const TZ = process.env.SUPPA_TZ || "Europe/Kyiv";
120
+ /**
121
+ * `tz` when it is an IANA zone name the platform accepts, else null. entity-builder refuses any other
122
+ * X-Timezone with 400 `request.invalid_timezone` on every request (timezone.util.ts, c2dcf582) — and
123
+ * Node's Intl accepts offsets ("+03:00") that it does not, so both are asked.
124
+ */
125
+ export function ianaZoneOrNull(tz) {
126
+ const zone = (tz ?? "").trim();
127
+ if (!zone || /^[+-]\d/.test(zone) || /^(utc|gmt)[+-]/i.test(zone))
128
+ return null;
129
+ try {
130
+ new Intl.DateTimeFormat("en-US", { timeZone: zone }).format(0);
131
+ return zone;
132
+ }
133
+ catch {
134
+ return null;
135
+ }
136
+ }
137
+ function timeZoneEnv(name, fallback) {
138
+ const raw = process.env[name];
139
+ if (raw === undefined || raw.trim() === "")
140
+ return fallback;
141
+ const zone = ianaZoneOrNull(raw);
142
+ if (!zone) {
143
+ process.stderr.write(`suppa-mcp: ${name}=${JSON.stringify(raw)} is not an IANA time zone name (e.g. "Europe/Kyiv") — ` +
144
+ `the platform refuses any other on every request; using ${fallback}.\n`);
145
+ return fallback;
146
+ }
147
+ return zone;
148
+ }
149
+ const TZ = timeZoneEnv("SUPPA_TZ", "Europe/Kyiv");
121
150
  /**
122
151
  * A positive integer from the environment, or the fallback.
123
152
  *