suppa-mcp-2 1.21.2 → 1.23.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.
@@ -7,6 +7,7 @@
7
7
  import { config } from "./config.js";
8
8
  import { assertMergeLists, elideEchoedResponse, stripAccessMetadata } from "./utils.js";
9
9
  import * as tenants from "./tenants.js";
10
+ import { lastRefreshError } from "./sessionDiag.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) {
@@ -22,7 +23,15 @@ function debug(msg) {
22
23
  * removes must NOT be retried blindly — a retry could double-apply them.
23
24
  */
24
25
  function isSafeRequest(method, url) {
25
- return method === "GET" || url.includes("/search") || url.includes("/select");
26
+ if (method === "GET") {
27
+ return true;
28
+ }
29
+ // Decided on the ACTION segment, never by substring: `url.includes("/search")`
30
+ // made every write to an entity named `searchLogs` or `selections` retryable,
31
+ // and a retry after a gateway 504 that the backend had already committed is a
32
+ // duplicate row reported as one clean success.
33
+ const path = parsedPath(url) ?? rawPath(url);
34
+ return /\/core\/data\/[^/]+\/(?:search|select|select\/validate)$/.test(path);
26
35
  }
27
36
  function headers(ctx, token, extra) {
28
37
  const h = {
@@ -63,7 +72,12 @@ function headers(ctx, token, extra) {
63
72
  * of scheme+host, query string and fragment, had its dot segments resolved, and
64
73
  * been collapsed, trimmed and lowercased.
65
74
  */
66
- const PERMANENT_DELETE_ROUTE = /^(?:api\/)?core\/data\/[^/]+\/delete$/;
75
+ // Anchored on the TAIL, not the head. A tenant reached through a reverse proxy
76
+ // under a path prefix (tenants.resolve deliberately preserves a base-URL path,
77
+ // e.g. https://proxy.example/suppa) put `suppa/api/core/data/X/delete` on the
78
+ // wire, and a head-anchored `^(?:api/)?core/...` let it through. Over-matching
79
+ // is the safe direction: no legitimate route ends in core/data/<x>/delete.
80
+ const PERMANENT_DELETE_ROUTE = /(?:^|\/)core\/data\/[^/]+\/delete$/;
67
81
  // The segments the WHATWG URL parser (the one inside fetch) removes or walks up
68
82
  // on. It matches them ASCII case-insensitively AND through their %2e escapes —
69
83
  // "a single-dot path segment must be '.' or '%2e'; a double-dot path segment
@@ -278,94 +292,237 @@ async function sendWithReauth(ctx, buildHeaders, method, url, data, timeout, opt
278
292
  throw noTokenError(ctx);
279
293
  }
280
294
  const controller = new AbortController();
295
+ // The timer is NOT cleared when headers arrive. It covers the body too:
296
+ // a proxy or platform that sends `200` and then stalls used to hang the
297
+ // tool call forever, because the abort was disarmed the moment fetch()
298
+ // resolved. Every path out of this iteration clears it in `finally`.
281
299
  const timer = setTimeout(() => controller.abort(), timeout * 1000);
282
300
  const started = Date.now();
283
- let res;
301
+ const timedOut = () => new Error(`Request to ${ctx.host} timed out after ${timeout}s. ` +
302
+ "The platform may be slow — retry, or narrow the request (smaller limit/fields).");
284
303
  try {
285
- res = await fetch(url, {
304
+ let res;
305
+ try {
306
+ res = await fetch(url, {
307
+ method,
308
+ headers: buildHeaders(token),
309
+ body: data,
310
+ signal: controller.signal,
311
+ });
312
+ }
313
+ catch (e) {
314
+ const err = e;
315
+ if (err && err.name === "AbortError") {
316
+ debug(`${method} ${url} -> timeout after ${timeout}s`);
317
+ throw timedOut();
318
+ }
319
+ const reason = e instanceof Error ? e.message : String(e);
320
+ debug(`${method} ${url} -> URLError ${reason}`);
321
+ if (retriable && !transientRetried) {
322
+ transientRetried = true;
323
+ await sleep(500);
324
+ continue;
325
+ }
326
+ throw new Error(`Connection error: ${reason}`);
327
+ }
328
+ const outcome = await readResponse(res, {
286
329
  method,
287
- headers: buildHeaders(token),
288
- body: data,
289
- signal: controller.signal,
330
+ url,
331
+ ctx,
332
+ refreshed,
333
+ transientRetried,
334
+ retriable,
335
+ opts,
336
+ started,
337
+ timedOut,
290
338
  });
291
- }
292
- catch (e) {
293
- clearTimeout(timer);
294
- const err = e;
295
- if (err && err.name === "AbortError") {
296
- // Timeout while connecting or reading the response body.
297
- debug(`${method} ${url} -> timeout after ${timeout}s`);
298
- throw new Error(`Request to ${ctx.host} timed out after ${timeout}s. ` +
299
- "The platform may be slow — retry, or narrow the request (smaller limit/fields).");
300
- }
301
- const reason = e instanceof Error ? e.message : String(e);
302
- debug(`${method} ${url} -> URLError ${reason}`);
303
- if (retriable && !transientRetried) {
304
- transientRetried = true;
305
- await sleep(500);
339
+ if (outcome.kind === "retry") {
340
+ if (outcome.refreshed)
341
+ refreshed = true;
342
+ if (outcome.transient)
343
+ transientRetried = true;
306
344
  continue;
307
345
  }
308
- throw new Error(`Connection error: ${reason}`);
346
+ return outcome.value;
309
347
  }
310
348
  finally {
311
349
  clearTimeout(timer);
312
350
  }
313
- const code = res.status;
314
- if (code >= 400) {
315
- debug(`${method} ${url} -> HTTP ${code} (${((Date.now() - started) / 1000).toFixed(2)}s)`);
316
- if (code === 401 && !refreshed && (await tenants.reauth(ctx))) {
317
- refreshed = true;
318
- continue; // token refreshed — retry once
319
- }
320
- if (TRANSIENT_CODES.has(code) && retriable && !transientRetried) {
321
- transientRetried = true;
322
- await sleep(500);
323
- continue;
324
- }
325
- let errorBody = "";
326
- try {
327
- errorBody = await res.text();
328
- }
329
- catch {
330
- // ignore
331
- }
332
- if (code === 401) {
333
- throw new Error(`HTTP 401 for tenant '${ctx.host}': session could not be refreshed. ` +
334
- `Run suppa_login. ${errorBody}`);
335
- }
336
- throw new Error(`HTTP ${code} ${safeStatusText(res)}: ${errorBody}`);
351
+ }
352
+ }
353
+ /**
354
+ * Everything that happens after fetch() resolves, kept inside the timer's
355
+ * scope by the caller. Returns the value to hand back, or an instruction to go
356
+ * round the loop again.
357
+ */
358
+ async function readResponse(res, rc) {
359
+ const { method, url, ctx, opts, started, timedOut } = rc;
360
+ const code = res.status;
361
+ const isAbort = (e) => e?.name === "AbortError";
362
+ /** Read the body as text; an abort during the read IS the timeout. */
363
+ const bodyText = async () => {
364
+ try {
365
+ return await res.text();
337
366
  }
338
- // A download returns bytes, not JSON — reading it as text would corrupt
339
- // anything that is not UTF-8 (every PDF, image and zip). Content-Type comes
340
- // back with it so the caller can name the file sensibly.
341
- if (opts.binary) {
342
- const buf = Buffer.from(await res.arrayBuffer());
343
- if (config.DEBUG) {
344
- debug(`${method} ${url} -> ${code} ${buf.length}B (${((Date.now() - started) / 1000).toFixed(2)}s)`);
345
- }
346
- return {
347
- bytes: buf,
348
- contentType: res.headers.get("content-type") ?? "",
349
- contentDisposition: res.headers.get("content-disposition") ?? "",
350
- };
367
+ catch (e) {
368
+ if (isAbort(e))
369
+ throw timedOut();
370
+ throw e;
351
371
  }
352
- const raw = await res.text();
353
- if (config.DEBUG) {
354
- debug(`${method} ${url} -> ${code} (${((Date.now() - started) / 1000).toFixed(2)}s)`);
372
+ };
373
+ if (code >= 400) {
374
+ debug(`${method} ${url} -> HTTP ${code} (${((Date.now() - started) / 1000).toFixed(2)}s)`);
375
+ if (code === 401 && !rc.refreshed && (await tenants.reauth(ctx))) {
376
+ return { kind: "retry", refreshed: true }; // token refreshed — retry once
355
377
  }
356
- if (!raw || !raw.trim()) {
357
- return null;
378
+ if (TRANSIENT_CODES.has(code) && rc.retriable && !rc.transientRetried) {
379
+ await sleep(500);
380
+ return { kind: "retry", transient: true };
358
381
  }
359
- // Every JSON response this server ever sees passes through here, which is
360
- // the only place a backstop can cover the endpoints whose access flag is
361
- // undocumented as well as the ones where it is set. See stripAccessMetadata.
362
- const result = stripAccessMetadata(JSON.parse(raw));
363
- return opts.unwrap ? unwrapEnvelope(result) : result;
382
+ let errorBody = "";
383
+ try {
384
+ errorBody = await bodyText();
385
+ }
386
+ catch {
387
+ // ignore — the status code is the message
388
+ }
389
+ if (code === 401) {
390
+ // The refresh that failed knows WHY it failed; without this the sentence
391
+ // was the same whether the session had aged out or the endpoint had
392
+ // moved — and only the first of those is fixed by signing in again.
393
+ const why = lastRefreshError(ctx.host);
394
+ throw new Error(`HTTP 401 for tenant '${ctx.host}': the session could not be refreshed ` +
395
+ (why
396
+ ? `— ${why}. `
397
+ : "(no stored session to refresh, or the platform rejected the refresh). ") +
398
+ "Run suppa_login — or, if this tenant is configured through SUPPA_API_KEY, " +
399
+ `set a valid key. ${errorBody}`);
400
+ }
401
+ throw new Error(`HTTP ${code} ${safeStatusText(res)}: ${errorBody}`);
364
402
  }
403
+ // A download returns bytes, not JSON — reading it as text would corrupt
404
+ // anything that is not UTF-8 (every PDF, image and zip). Content-Type comes
405
+ // back with it so the caller can name the file sensibly.
406
+ if (opts.binary) {
407
+ let buf;
408
+ try {
409
+ buf = Buffer.from(await res.arrayBuffer());
410
+ }
411
+ catch (e) {
412
+ if (isAbort(e))
413
+ throw timedOut();
414
+ throw e;
415
+ }
416
+ if (config.DEBUG) {
417
+ debug(`${method} ${url} -> ${code} ${buf.length}B (${((Date.now() - started) / 1000).toFixed(2)}s)`);
418
+ }
419
+ return {
420
+ kind: "value",
421
+ value: {
422
+ bytes: buf,
423
+ contentType: res.headers.get("content-type") ?? "",
424
+ contentDisposition: res.headers.get("content-disposition") ?? "",
425
+ },
426
+ };
427
+ }
428
+ const raw = await bodyText();
429
+ if (config.DEBUG) {
430
+ debug(`${method} ${url} -> ${code} (${((Date.now() - started) / 1000).toFixed(2)}s)`);
431
+ }
432
+ if (!raw || !raw.trim()) {
433
+ return { kind: "value", value: null };
434
+ }
435
+ let parsed;
436
+ try {
437
+ parsed = JSON.parse(raw);
438
+ }
439
+ catch {
440
+ // A bare SyntaxError names neither the request nor the cause. The usual
441
+ // cause is a proxy or login page answering 200 with HTML.
442
+ const preview = raw.slice(0, 160).replace(/\s+/g, " ");
443
+ throw new Error(`${method} ${url} answered ${code} with a body that is not JSON: ${preview}` +
444
+ (raw.length > 160 ? "…" : ""));
445
+ }
446
+ // Unwrap FIRST, then strip. The strip is record-level by design (it never
447
+ // descends into a value), so stripping the {data:[...]} envelope object did
448
+ // nothing and every row inside kept its access arrays. See stripAccessMetadata.
449
+ const result = opts.unwrap ? unwrapEnvelope(parsed) : parsed;
450
+ return { kind: "value", value: stripAccessMetadata(result) };
365
451
  }
366
452
  function sleep(ms) {
367
453
  return new Promise((resolve) => setTimeout(resolve, ms));
368
454
  }
455
+ /**
456
+ * The only characters a path segment may contain on the way to a tenant.
457
+ *
458
+ * Every route this server calls is built from fixed literals, entity and field
459
+ * names (builder.txt:38/:103 — "letters, numbers, underscores", 1–50 chars) and
460
+ * numeric ids. Nothing legitimate needs a dot, a percent sign, a slash inside a
461
+ * segment, a `?` or a `#`. So those are refused — not encoded, REFUSED — at the
462
+ * funnel every request passes through.
463
+ *
464
+ * This is the fix for a real bypass: `suppa_search_records` with
465
+ * entity_name "Tasks/remove?" built `/api/core/data/Tasks/remove?/search`, which
466
+ * the platform routed as POST /core/data/Tasks/remove with the search body's
467
+ * conditions — a mass soft-delete issued by a tool annotated read-only, with no
468
+ * confirmation, reported back as an empty search. Twenty-odd call sites
469
+ * interpolate a caller-supplied name into a path; validating each one is how
470
+ * one gets missed. The funnel cannot be missed.
471
+ */
472
+ const PATH_SEGMENT = /^[A-Za-z0-9_-]+$/;
473
+ export class UnsafePathError extends Error {
474
+ constructor(path, why) {
475
+ super(`REFUSED: '${path}' is not a valid API path — ${why}. ` +
476
+ "Entity and field names may contain only letters, digits and underscores; " +
477
+ "this request was not sent.");
478
+ this.name = "UnsafePathError";
479
+ }
480
+ }
481
+ /**
482
+ * Refuse any path that could be routed as something other than what its
483
+ * literal segments say. Returns the path unchanged when it is acceptable.
484
+ */
485
+ export function assertSafePath(path) {
486
+ if (typeof path !== "string" || !path.startsWith("/")) {
487
+ throw new UnsafePathError(String(path), "it must start with '/'");
488
+ }
489
+ if (/[?#%\\]/.test(path)) {
490
+ throw new UnsafePathError(path, "a path may not contain '?', '#', '%' or a backslash (pass query parameters via opts.query)");
491
+ }
492
+ const segments = path.slice(1).split("/");
493
+ for (const segment of segments) {
494
+ if (segment === "") {
495
+ throw new UnsafePathError(path, "it contains an empty segment ('//' or a trailing '/')");
496
+ }
497
+ if (!PATH_SEGMENT.test(segment)) {
498
+ throw new UnsafePathError(path, `the segment '${segment}' contains characters outside [A-Za-z0-9_-]`);
499
+ }
500
+ }
501
+ return path;
502
+ }
503
+ /**
504
+ * Build the absolute URL for a tenant request: validated path plus an
505
+ * explicitly encoded query string. The one place a path becomes a URL.
506
+ */
507
+ function tenantUrl(ctx, path, query) {
508
+ // Policy before syntax. A hard-delete attempt is refused with the message
509
+ // that names the reversible pair, whatever else is wrong with its path; the
510
+ // generic allowlist is the second layer, for everything else.
511
+ const naive = path.startsWith("/") ? `${ctx.baseUrl}${path}` : path;
512
+ if (isPermanentDeletePath(naive)) {
513
+ throw permanentDeleteRefusal(naive);
514
+ }
515
+ assertSafePath(path);
516
+ let url = `${ctx.baseUrl}${path}`;
517
+ if (query && Object.keys(query).length > 0) {
518
+ const qs = new URLSearchParams();
519
+ for (const [k, v] of Object.entries(query)) {
520
+ qs.set(k, String(v));
521
+ }
522
+ url += `?${qs.toString()}`;
523
+ }
524
+ return url;
525
+ }
369
526
  /**
370
527
  * Make an HTTP request to a Suppa tenant. Returns parsed JSON or null.
371
528
  *
@@ -375,7 +532,7 @@ export async function makeRequest(method, path, body = null, opts = {}) {
375
532
  const ctx = opts.ctx ?? tenants.current();
376
533
  await tenants.ensureValid(ctx);
377
534
  const timeout = opts.timeout ?? config.HTTP_TIMEOUT;
378
- const url = path.startsWith("/") ? `${ctx.baseUrl}${path}` : path;
535
+ const url = tenantUrl(ctx, path, opts.query);
379
536
  let data = null;
380
537
  const extra = { ...(opts.extraHeaders ?? {}) };
381
538
  if (body !== null && body !== undefined) {
@@ -389,7 +546,7 @@ export async function makeRequestRawBytes(method, path, data, contentType, opts
389
546
  const ctx = tenants.current();
390
547
  await tenants.ensureValid(ctx);
391
548
  const timeout = opts.timeout ?? Math.max(120, config.HTTP_TIMEOUT); // uploads need headroom
392
- const url = path.startsWith("/") ? `${ctx.baseUrl}${path}` : path;
549
+ const url = tenantUrl(ctx, path);
393
550
  return sendWithReauth(ctx, (t) => headers(ctx, t, { "Content-Type": contentType }), method, url, data, timeout, { unwrap: false });
394
551
  }
395
552
  /**
@@ -403,7 +560,7 @@ export async function makeRequestBinary(method, path, body = null, opts = {}) {
403
560
  const ctx = tenants.current();
404
561
  await tenants.ensureValid(ctx);
405
562
  const timeout = opts.timeout ?? Math.max(120, config.HTTP_TIMEOUT); // downloads need headroom
406
- const url = path.startsWith("/") ? `${ctx.baseUrl}${path}` : path;
563
+ const url = tenantUrl(ctx, path, opts.query);
407
564
  const payload = body === null || body === undefined ? null : JSON.stringify(body);
408
565
  return (await sendWithReauth(ctx, (t) => headers(ctx, t, payload === null ? null : { "Content-Type": "application/json" }), method, url, payload, timeout, { unwrap: false, binary: true }));
409
566
  }
@@ -463,7 +620,9 @@ export async function selectEntity(entity, filters, fields = null, deletedScope
463
620
  includeDeletedRelations, // data.txt:75 (platform default true; was hard-coded false)
464
621
  deletedScope, // data.txt:76
465
622
  };
466
- const result = await makeRequest("POST", dataUrl(entity, "select") + "?markAsView=false", body);
623
+ const result = await makeRequest("POST", dataUrl(entity, "select"), body, {
624
+ query: { markAsView: false },
625
+ });
467
626
  // The select endpoint returns a list of matching rows; return the first.
468
627
  if (Array.isArray(result)) {
469
628
  return (result.length ? result[0] : null);
package/dist/registry.js CHANGED
@@ -1,3 +1,4 @@
1
+ import { randomUUID } from "node:crypto";
1
2
  /**
2
3
  * Non-secret registry of known tenants, keyed by host.
3
4
  *
@@ -89,9 +90,24 @@ export function load() {
89
90
  export function save(reg) {
90
91
  const p = path();
91
92
  mkdirSync(homeDir(), { recursive: true });
92
- const tmp = join(homeDir(), "tenants.json.tmp");
93
+ // A UNIQUE temp name per writer. Two MCP clients logging in at once shared
94
+ // one "tenants.json.tmp" and threw EPERM/ENOENT out of rename — after login
95
+ // had already stored the tokens, so it reported failure having succeeded.
96
+ const tmp = join(homeDir(), `tenants.json.${process.pid}.${randomUUID()}.tmp`);
93
97
  writeFileSync(tmp, JSON.stringify(reg, null, 2), "utf-8");
94
- renameSync(tmp, p);
98
+ try {
99
+ renameSync(tmp, p);
100
+ }
101
+ catch (e) {
102
+ // Windows: an antivirus or indexer can hold the target for a moment.
103
+ if (e?.code !== "EPERM")
104
+ throw e;
105
+ const until = Date.now() + 200;
106
+ while (Date.now() < until) {
107
+ /* brief spin — rename is synchronous and this path is rare */
108
+ }
109
+ renameSync(tmp, p);
110
+ }
95
111
  }
96
112
  /** Register (or overwrite) a tenant. */
97
113
  export function add(host, alias, baseUrl) {
package/dist/server.js CHANGED
@@ -1,7 +1,7 @@
1
1
  /**
2
2
  * Suppa MCP Server — unified gateway to the Suppa platform.
3
3
  *
4
- * Faithful 1:1 port of the Python `suppa_mcp/server.py`. Wires all 87 tools,
4
+ * Faithful 1:1 port of the Python `suppa_mcp/server.py`. Wires every tool,
5
5
  * mirrors the tool-behavior annotations (_READ/_ADD/_MUT), reproduces the
6
6
  * server `instructions` string verbatim, and OWNS all confirm-gating (the tool
7
7
  * modules mutate unconditionally, exactly like the Python tool functions).
@@ -29,6 +29,22 @@ export { PACKAGE_VERSION };
29
29
  // existing data (and is additionally approval-gated via confirm=true).
30
30
  // ---------------------------------------------------------------------------
31
31
  const _READ = { readOnlyHint: true };
32
+ /**
33
+ * A download reads on the platform but WRITES to the user's disk, so it is not
34
+ * read-only: readOnlyHint means "does not modify its environment", and a host
35
+ * that auto-approves read-only tools would let a model drop files anywhere the
36
+ * process can write.
37
+ *
38
+ * destructiveHint stays false deliberately. In this server that flag means "may
39
+ * destroy data on the platform" and carries the confirm gate with it (see
40
+ * destructiveToolsAreGated). A download destroys nothing remotely, and its own
41
+ * guard is `overwrite`, which defaults to false and refuses an existing file.
42
+ */
43
+ const _DOWNLOAD = {
44
+ readOnlyHint: false,
45
+ destructiveHint: false,
46
+ idempotentHint: true,
47
+ };
32
48
  const _ADD = {
33
49
  readOnlyHint: false,
34
50
  destructiveHint: false,
@@ -768,7 +784,10 @@ export function buildServer() {
768
784
  return text(await docs.deleteBlock(a.block_id));
769
785
  });
770
786
  reg("suppa_reorder_blocks", {
771
- description: "Reorder blocks on a page. block_ids: comma-separated IDs to move. Provide after_id or before_id as anchor.",
787
+ description: "Reorder blocks on a page. block_ids: comma-separated IDs to move. Provide after_id or before_id as anchor.\n" +
788
+ "\n" +
789
+ " APPROVAL GATE: without confirm=true this returns a confirmation request and\n" +
790
+ " changes nothing. Get the user's approval, then re-call with confirm=true.",
772
791
  inputSchema: {
773
792
  page_id: z.number().int(),
774
793
  block_ids: z
@@ -1314,15 +1333,29 @@ export function buildServer() {
1314
1333
  annotations: _ADD,
1315
1334
  }, async (a) => text(await entity.addEnumValues(a.enum_name, a.values)));
1316
1335
  reg("suppa_set_title_field", {
1317
- description: "Set an entity's display-title (representative) field; creates it if missing.",
1336
+ description: "Set an entity's display-title (representative) field; creates it if missing.\n" +
1337
+ "\n" +
1338
+ " This CHANGES what every existing record of the entity displays as its label,\n" +
1339
+ " so it is confirm-gated like any other edit to live data.\n" +
1340
+ " APPROVAL GATE: without confirm=true this returns a confirmation request and\n" +
1341
+ " changes nothing. Get the user's approval, then re-call with confirm=true.",
1318
1342
  inputSchema: {
1319
1343
  entity_name: EntityName,
1320
1344
  field_name: z
1321
1345
  .string()
1322
1346
  .describe("Field to use as the record display title; created (multi-language) if missing."),
1347
+ confirm: Confirm,
1323
1348
  },
1324
- annotations: _ADD,
1325
- }, async (a) => text(await entity.setTitleField(a.entity_name, a.field_name)));
1349
+ annotations: _MUT,
1350
+ }, async (a) => {
1351
+ if (!a.confirm) {
1352
+ return text(confirmRequired("set title field", {
1353
+ entity: a.entity_name,
1354
+ field: a.field_name,
1355
+ }));
1356
+ }
1357
+ return text(await entity.setTitleField(a.entity_name, a.field_name));
1358
+ });
1326
1359
  reg("suppa_list_field_types", {
1327
1360
  description: "List all available field types for entity/form creation.",
1328
1361
  annotations: _READ,
@@ -1483,10 +1516,10 @@ export function buildServer() {
1483
1516
  reg("suppa_list_record_files", {
1484
1517
  description: "List the files attached to one record of any entity.\n" +
1485
1518
  "\n" +
1486
- " Returns fileName, filePath, pdfPath, previewPath, size, mimeType and type\n" +
1487
- " for each attachment. It does NOT return the file id, and\n" +
1488
- " suppa_download_file needs one — read ids from the 'Files' entity with\n" +
1489
- " suppa_search_records, or keep the id suppa_attach_file_to_record returns.\n" +
1519
+ " Returns file_ids ready for suppa_download_file / suppa_download_files_zip,\n" +
1520
+ " plus fileName, filePath, pdfPath, previewPath, size, mimeType and type for\n" +
1521
+ " each attachment. A row that carries no id can be looked up on the 'Files'\n" +
1522
+ " entity with suppa_search_records.\n" +
1490
1523
  " An empty list can also mean the entity has no file field at all; check it\n" +
1491
1524
  " with suppa_describe_entity.\n",
1492
1525
  inputSchema: {
@@ -1522,7 +1555,7 @@ export function buildServer() {
1522
1555
  .default(false)
1523
1556
  .describe("Allow replacing an existing file at dest_path."),
1524
1557
  },
1525
- annotations: _READ,
1558
+ annotations: _DOWNLOAD,
1526
1559
  }, async (a) => text(await files.downloadFile(a.file_id, a.dest_path, a.file_type, a.overwrite)));
1527
1560
  reg("suppa_download_files_zip", {
1528
1561
  description: "Download several attachments at once as one ZIP archive.\n" +
@@ -1560,7 +1593,7 @@ export function buildServer() {
1560
1593
  .default(false)
1561
1594
  .describe("Allow replacing an existing archive at dest_path."),
1562
1595
  },
1563
- annotations: _READ,
1596
+ annotations: _DOWNLOAD,
1564
1597
  }, async (a) => text(await files.downloadFilesZip(a.file_ids, a.dest_path, a.overwrite, a.entity_name, a.record_ids)));
1565
1598
  reg("suppa_attach_file_to_record", {
1566
1599
  description: "Attach a local file to a record (instance) of any entity.\n\n" +
@@ -1571,8 +1604,7 @@ export function buildServer() {
1571
1604
  " field — check with suppa_describe_entity and add one with suppa_add_field if it\n" +
1572
1605
  " has none. KEEP THE RETURNED file_ids: they are the only handle that gets the bytes\n" +
1573
1606
  " back (suppa_download_file / suppa_download_files_zip). suppa_list_record_files\n" +
1574
- " lists what a record carries but does NOT return ids; the other source for them is\n" +
1575
- " suppa_search_records on the 'Files' entity. To put a record's attachments on a\n" +
1607
+ " returns them too, for files already attached. To put a record's attachments on a\n" +
1576
1608
  " copy, use suppa_copy_record(copy_files=true) — a file already on the platform has\n" +
1577
1609
  " no local path to re-upload from.",
1578
1610
  inputSchema: {
@@ -1830,9 +1862,13 @@ export function buildServer() {
1830
1862
  .boolean()
1831
1863
  .default(true)
1832
1864
  .describe("Exclude relation fields with no populated instances in v1 (create:false). Probe errors keep the field; set false to keep every relation."),
1865
+ overwrite: z
1866
+ .boolean()
1867
+ .default(false)
1868
+ .describe("Allow output_file to replace a file that already exists. Off by default so a second dry run cannot quietly destroy a plan you edited by hand."),
1833
1869
  },
1834
1870
  annotations: _ADD,
1835
- }, async (a) => text(await migrate.migrateEntities(a.dry_run, a.entity_names, a.include_builtin, a.skip_relations, a.output_file, a.plan_file, a.mode, a.check_relation_instances, a.skip_empty_relations)));
1871
+ }, async (a) => text(await migrate.migrateEntities(a.dry_run, a.entity_names, a.include_builtin, a.skip_relations, a.output_file, a.plan_file, a.mode, a.check_relation_instances, a.skip_empty_relations, a.overwrite)));
1836
1872
  reg("suppa_read_v1_entities", {
1837
1873
  description: "List entities on the configured Suppa 1.0 backend (read-only).",
1838
1874
  inputSchema: {
@@ -1990,7 +2026,8 @@ export function buildServer() {
1990
2026
  }, async (a) => text(await forms.getForm(a.form_id)));
1991
2027
  reg("suppa_create_form", {
1992
2028
  description: "Create a new form. Provide schema_json (array of fields or {formShema}), or set\n" +
1993
- " generate_from_entity=True with entity_name to auto-build fields from the entity.\n" +
2029
+ " generate_from_entity=true WITH entity_name to auto-build fields from the entity\n" +
2030
+ " (without entity_name it is refused, rather than creating an empty form).\n" +
1994
2031
  " Form names are UNIQUE platform-wide — a duplicate name fails; pick a distinct one.",
1995
2032
  inputSchema: {
1996
2033
  name: z.string(),
@@ -0,0 +1,29 @@
1
+ /**
2
+ * Why the last token refresh for a tenant failed.
3
+ *
4
+ * A refresh failure is swallowed on purpose — an unhandled rejection out of
5
+ * `ensureValid` kills the stdio server — so the only thing a user ever saw was
6
+ * the 401 that came next: "the session could not be refreshed … run
7
+ * suppa_login". When the platform moved this route from POST to GET, that
8
+ * message sent people to re-login every fifteen minutes and never once named
9
+ * the 404 that was the actual cause. Someone had to read the web client's
10
+ * source to find it.
11
+ *
12
+ * This module is the one place that remembers the reason. It is kept
13
+ * dependency-free so the auth layer that produces it and the transport that
14
+ * reports it can both import it without an import cycle.
15
+ */
16
+ /** host -> why its last refresh attempt failed. */
17
+ const reasons = new Map();
18
+ /** Remember why `host` could not refresh, for the 401 that is about to follow. */
19
+ export function recordRefreshFailure(host, reason) {
20
+ reasons.set(host, reason);
21
+ }
22
+ /** Forget the last failure for `host` — called when a refresh succeeds. */
23
+ export function clearRefreshFailure(host) {
24
+ reasons.delete(host);
25
+ }
26
+ /** The last refresh failure for `host`, or null if the last attempt worked. */
27
+ export function lastRefreshError(host) {
28
+ return reasons.get(host) ?? null;
29
+ }