suppa-mcp-2 1.28.1 → 1.30.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.
@@ -0,0 +1,179 @@
1
+ /**
2
+ * Prove, at install time, that what just landed actually works.
3
+ *
4
+ * Two outages reached users because nothing verified the install itself:
5
+ *
6
+ * - 1.15.0 added a second bin and `npx -y suppa-mcp-2@latest` stopped being
7
+ * able to pick one. Twelve releases shipped over it. Every test drove
8
+ * dist/bin.js directly — the one path a host never takes.
9
+ * - An interrupted npx download left the package without ajv. The server died
10
+ * during module resolution, so the host reported CONNECT_TIMEOUT and
11
+ * Server disconnected, as though the server had crashed rather than never
12
+ * having run.
13
+ *
14
+ * Both are invisible to a unit test and obvious to a smoke test: start the
15
+ * thing as a host starts it, and ask it to speak MCP. That is all this does.
16
+ *
17
+ * IT NEVER FAILS AN INSTALL. A package that refuses to install is a worse
18
+ * outcome than one that installs and complains, and this runs in sandboxes,
19
+ * offline boxes and CI images where spawning a child may be restricted. Every
20
+ * path here ends in a report, never a throw.
21
+ */
22
+ import { spawn } from "node:child_process";
23
+ import { existsSync } from "node:fs";
24
+ import { join } from "node:path";
25
+ /** Every bin the manifest declares, and whether its file is actually there. */
26
+ export function checkBins(pkg, root, exists = existsSync) {
27
+ return Object.entries(pkg.bin ?? {}).map(([name, target]) => ({
28
+ name,
29
+ target,
30
+ present: exists(join(root, target)),
31
+ }));
32
+ }
33
+ /** Read the package a module-resolution failure was about, out of stderr. */
34
+ export function missingModuleFrom(stderr) {
35
+ const m = /Cannot find (?:package|module) ['"]([^'"]+)['"]/.exec(stderr);
36
+ if (m)
37
+ return m[1];
38
+ // startupRepair's own wording, when the server got far enough to explain
39
+ // itself rather than dying on a bare Node stack.
40
+ const own = /could not resolve ([^.\s]+)/.exec(stderr);
41
+ return own ? own[1] : undefined;
42
+ }
43
+ /**
44
+ * Start the server exactly as an MCP host does and hold a real conversation:
45
+ * initialize, then tools/list. Answers the three questions that matter — does
46
+ * it start, does it speak the protocol, and are the tools there.
47
+ */
48
+ export function smokeTest(binPath, timeoutMs = 25_000) {
49
+ return new Promise((resolve) => {
50
+ let child;
51
+ try {
52
+ child = spawn(process.execPath, [binPath], {
53
+ stdio: ["pipe", "pipe", "pipe"],
54
+ env: {
55
+ ...process.env,
56
+ // Nothing here may touch the network during an install.
57
+ SUPPA_MCP_NO_UPDATE_CHECK: "1",
58
+ // Critical: the child must NOT try to repair a broken npx cache while
59
+ // npm is still writing into that very directory. A self-check that
60
+ // deletes the package mid-install would be far worse than the fault
61
+ // it is checking for.
62
+ SUPPA_MCP_NO_CACHE_REPAIR: "1",
63
+ },
64
+ });
65
+ }
66
+ catch (e) {
67
+ resolve({ ok: false, error: e instanceof Error ? e.message : String(e) });
68
+ return;
69
+ }
70
+ let out = "";
71
+ let err = "";
72
+ let settled = false;
73
+ const finish = (r) => {
74
+ if (settled)
75
+ return;
76
+ settled = true;
77
+ clearTimeout(timer);
78
+ try {
79
+ child.kill();
80
+ }
81
+ catch {
82
+ /* already gone */
83
+ }
84
+ resolve(r);
85
+ };
86
+ const timer = setTimeout(() => finish({ ok: false, error: `no answer within ${Math.round(timeoutMs / 1000)}s` }), timeoutMs);
87
+ let version;
88
+ child.stdout?.on("data", (d) => {
89
+ out += String(d);
90
+ let nl;
91
+ while ((nl = out.indexOf("\n")) !== -1) {
92
+ const line = out.slice(0, nl).trim();
93
+ out = out.slice(nl + 1);
94
+ if (!line)
95
+ continue;
96
+ let msg;
97
+ try {
98
+ msg = JSON.parse(line);
99
+ }
100
+ catch {
101
+ continue;
102
+ }
103
+ if (msg.id === 1) {
104
+ const info = msg.result?.serverInfo;
105
+ version = info?.version;
106
+ child.stdin?.write(JSON.stringify({ jsonrpc: "2.0", method: "notifications/initialized" }) + "\n");
107
+ child.stdin?.write(JSON.stringify({ jsonrpc: "2.0", id: 2, method: "tools/list", params: {} }) + "\n");
108
+ }
109
+ else if (msg.id === 2) {
110
+ const tools = msg.result?.tools ?? [];
111
+ finish({ ok: true, version, tools: tools.length });
112
+ }
113
+ }
114
+ });
115
+ child.stderr?.on("data", (d) => (err += String(d)));
116
+ child.on("error", (e) => finish({ ok: false, error: e.message }));
117
+ child.on("exit", (code) => finish({
118
+ ok: false,
119
+ missingModule: missingModuleFrom(err),
120
+ error: `exited with code ${code} before answering` + (err.trim() ? `: ${err.trim().slice(0, 300)}` : ""),
121
+ }));
122
+ child.stdin?.write(JSON.stringify({
123
+ jsonrpc: "2.0",
124
+ id: 1,
125
+ method: "initialize",
126
+ params: {
127
+ protocolVersion: "2024-11-05",
128
+ capabilities: {},
129
+ clientInfo: { name: "suppa-mcp-selfcheck", version: "1" },
130
+ },
131
+ }) + "\n");
132
+ });
133
+ }
134
+ /**
135
+ * What the operator reads. Pure, so the wording is pinned by tests rather than
136
+ * discovered in the middle of somebody's install.
137
+ */
138
+ export function report(o) {
139
+ const missingBins = o.bins.filter((b) => !b.present);
140
+ const lines = [];
141
+ if (missingBins.length) {
142
+ lines.push(`suppa-mcp-2: INSTALL IS INCOMPLETE — ${missingBins
143
+ .map((b) => b.target)
144
+ .join(", ")} missing. The download was truncated.`);
145
+ }
146
+ if (o.smoke.ok) {
147
+ if (o.smoke.version && o.smoke.version !== o.expectedVersion) {
148
+ lines.push(`suppa-mcp-2: self-check ran ${o.smoke.version} but this package is ` +
149
+ `${o.expectedVersion} — an older copy is shadowing it on the module path.`);
150
+ return { ok: false, lines };
151
+ }
152
+ if (!missingBins.length) {
153
+ lines.push(`suppa-mcp-2: self-check ok — v${o.smoke.version}, ${o.smoke.tools} tools.`);
154
+ return { ok: true, lines };
155
+ }
156
+ return { ok: false, lines };
157
+ }
158
+ lines.push("suppa-mcp-2: THE SERVER DID NOT START — " +
159
+ (o.smoke.missingModule
160
+ ? `could not resolve ${o.smoke.missingModule}. This is a truncated download.`
161
+ : (o.smoke.error ?? "unknown reason")));
162
+ lines.push(" A host would show this as CONNECT_TIMEOUT or 'Server disconnected', which looks " +
163
+ "like a crash but means the server never ran.");
164
+ lines.push(" Fix: npm cache clean --force && npm install suppa-mcp-2 --force " +
165
+ "(for npx, delete the _npx/<hash> directory the error names and rerun).");
166
+ return { ok: false, lines };
167
+ }
168
+ /** Run everything against an installed package root. Never throws. */
169
+ export async function runSelfCheck(root, pkg) {
170
+ const bins = checkBins(pkg, root);
171
+ const entry = join(root, "dist", "bin.js");
172
+ if (!existsSync(entry)) {
173
+ // A source checkout before its first build. Not a fault, and not ours to
174
+ // report on.
175
+ return { ok: true, lines: [] };
176
+ }
177
+ const smoke = await smokeTest(entry);
178
+ return report({ bins, smoke, expectedVersion: String(pkg.version ?? "") });
179
+ }
@@ -0,0 +1,28 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * The self-check as a command, so postinstall can run it in a child process and
4
+ * a user can run it by hand: `node dist/selfcheckCli.js`.
5
+ *
6
+ * A separate file from selfcheck.ts on purpose — importing a module must never
7
+ * start a server as a side effect.
8
+ *
9
+ * Exit code is 0 on success and 1 on a finding, but the postinstall that calls
10
+ * it ignores that: the code is here for anyone scripting around it.
11
+ */
12
+ import { readFileSync } from "node:fs";
13
+ import { dirname, join, resolve } from "node:path";
14
+ import { fileURLToPath } from "node:url";
15
+ import { runSelfCheck } from "./selfcheck.js";
16
+ const ROOT = resolve(dirname(fileURLToPath(import.meta.url)), "..");
17
+ let pkg = {};
18
+ try {
19
+ pkg = JSON.parse(readFileSync(join(ROOT, "package.json"), "utf-8"));
20
+ }
21
+ catch {
22
+ process.stderr.write("suppa-mcp-2: self-check could not read package.json; skipped.\n");
23
+ process.exit(0);
24
+ }
25
+ const { ok, lines } = await runSelfCheck(ROOT, pkg);
26
+ for (const line of lines)
27
+ process.stderr.write(line + "\n");
28
+ process.exit(ok ? 0 : 1);
package/dist/server.js CHANGED
@@ -14,6 +14,7 @@ import * as docs from "./tools/docs.js";
14
14
  import * as entity from "./tools/entity.js";
15
15
  import * as customFields from "./tools/customFields.js";
16
16
  import * as customFieldSets from "./tools/customFieldSets.js";
17
+ import * as customFieldsAsCode from "./tools/customFieldsAsCode.js";
17
18
  import * as entityCode from "./tools/entityCode.js";
18
19
  import { houseRulesDigest } from "./tools/entityCode.js";
19
20
  import * as files from "./tools/files.js";
@@ -1518,6 +1519,27 @@ export function buildServer() {
1518
1519
  contextValue: a.context_value,
1519
1520
  setIds: a.set_ids,
1520
1521
  })));
1522
+ reg("suppa_apply_custom_fields", {
1523
+ description: "Custom fields DECLARED IN A REPO FILE, applied to a tenant — the file is the source of truth.\n" +
1524
+ " The SDK has no decorator for them, so they are the one part of a schema with no home in git.\n" +
1525
+ ' declaration: {"entity","context_field","fields":[{"name","type","title","contexts":["PL"]}]}.\n' +
1526
+ " Idempotent — a second run answers already_converged. Creates per context in ONE atomic\n" +
1527
+ " batch, then links existing fields into their other contexts.\n" +
1528
+ " NEVER deletes (a dropped field is reported as not_declared; removal reserves its name for\n" +
1529
+ " good) and never changes a type (type_drift — that is a data migration).\n" +
1530
+ " Dry run by default; confirm=true applies.",
1531
+ inputSchema: {
1532
+ declaration: z
1533
+ .string()
1534
+ .describe('JSON: {"entity","context_field","fields":[...]}. Every field needs "contexts" — one offered ' +
1535
+ "everywhere is an ordinary field and belongs in the entity class."),
1536
+ confirm: z
1537
+ .boolean()
1538
+ .default(false)
1539
+ .describe("false (default) returns the plan and changes nothing; true applies it."),
1540
+ },
1541
+ annotations: _ADD,
1542
+ }, async (a) => text(await customFieldsAsCode.applyCustomFieldsDeclaration(a.declaration, { confirm: a.confirm })));
1521
1543
  reg("suppa_link_custom_field", {
1522
1544
  description: "Put EXISTING custom fields into another context, take them out of one, or set required.\n" +
1523
1545
  " A field joins a context through a row, so ONE field can be live in several contexts at\n" +
@@ -102,8 +102,11 @@ export async function resolveTargetSets(entityName, sel) {
102
102
  return { ids: rows.map((r) => Number(r.id)).filter(Number.isInteger) };
103
103
  }
104
104
  /** FieldMetadata rows for an extension entity, by field name. */
105
- async function extensionFields(extension) {
106
- const rows = asRows(await searchEntity(META_ENTITY, [{ field: "entity.name", value: extension, comparator: "=" }], { id: true, name: true, deletedAt: true }, 500));
105
+ export async function extensionFields(extension) {
106
+ const rows = asRows(await searchEntity(META_ENTITY, [{ field: "entity.name", value: extension, comparator: "=" }],
107
+ // `type` is read so a declaration file can be diffed against the live
108
+ // column: without it every existing field looks like a type change.
109
+ { id: true, name: true, type: true, deletedAt: true }, 500));
107
110
  const out = new Map();
108
111
  for (const r of rows) {
109
112
  const name = String(r.name ?? "");
@@ -0,0 +1,237 @@
1
+ /**
2
+ * Custom fields, declared in the repository instead of typed into a chat.
3
+ *
4
+ * THE PROBLEM THIS FIXES. Every other part of a Suppa application is code: an
5
+ * entity class IS its migration, and a seed is a file. Custom fields are the
6
+ * exception — the SDK has no decorator for them, they exist only as runtime
7
+ * rows (CustomFieldSets + CustomFieldSetFields + values under the reserved
8
+ * `customFields` key), and the only way to create one was to call a tool by
9
+ * hand. So the one part of a schema that varies per context was also the one
10
+ * part that lived nowhere in git: not reviewable, not diffable, and not
11
+ * reproducible on a second tenant.
12
+ *
13
+ * The platform will not grow a decorator for us, but nothing forces the
14
+ * DECLARATION to be a chat message. A declaration file in the repo is the
15
+ * source of truth; this converges a tenant to it.
16
+ *
17
+ * { "entity": "ServiceRequests",
18
+ * "context_field": "country",
19
+ * "fields": [
20
+ * { "name": "plTaxId", "type": "text", "title": "NIP", "contexts": ["PL"] }
21
+ * ] }
22
+ *
23
+ * IT NEVER DELETES ANYTHING. A custom field removed from the file is REPORTED,
24
+ * not dropped: removing one parks its column as <name>_<timestamp> and keeps
25
+ * its name reserved forever, so an accidental deletion cannot be undone by
26
+ * putting the line back. Convergence is create-and-link only; taking a field
27
+ * away stays a deliberate act through suppa_remove_custom_field.
28
+ *
29
+ * A TYPE CHANGE IS ALSO ONLY REPORTED. Changing the type of a live column is a
30
+ * migration with data in it, and guessing at one from a diff is how data is
31
+ * lost.
32
+ */
33
+ import { customFieldsEntity } from "./customFields.js";
34
+ import { addCustomFieldsBatch, extensionFields, linkCustomFields } from "./customFieldSets.js";
35
+ import { jsonResponse, parseJsonParam } from "../utils.js";
36
+ import { makeRequest } from "../httpClient.js";
37
+ /** Read a declaration from JSON, saying plainly what is wrong with a bad one. */
38
+ export function parseDeclaration(input) {
39
+ let raw;
40
+ try {
41
+ raw = parseJsonParam(input, "declaration", "object");
42
+ }
43
+ catch (e) {
44
+ return { error: e instanceof Error ? e.message : String(e) };
45
+ }
46
+ const d = raw;
47
+ if (!d || typeof d.entity !== "string" || !d.entity.trim()) {
48
+ return { error: 'Refused: the declaration needs "entity" — the owner entity name. Nothing was sent.' };
49
+ }
50
+ if (typeof d.context_field !== "string" || !d.context_field.trim()) {
51
+ return {
52
+ error: 'Refused: the declaration needs "context_field" — the owner field a set keys on, e.g. "country". ' +
53
+ "A custom field must belong to a context. Nothing was sent.",
54
+ };
55
+ }
56
+ if (!Array.isArray(d.fields) || !d.fields.length) {
57
+ return { error: 'Refused: the declaration needs a non-empty "fields" array. Nothing was sent.' };
58
+ }
59
+ const fields = [];
60
+ for (const [i, f] of d.fields.entries()) {
61
+ const at = `fields[${i}]`;
62
+ if (!f || typeof f !== "object")
63
+ return { error: `Refused: ${at} is not an object. Nothing was sent.` };
64
+ const spec = f;
65
+ if (typeof spec.name !== "string" || !spec.name.trim()) {
66
+ return { error: `Refused: ${at} has no "name". Nothing was sent.` };
67
+ }
68
+ if (typeof spec.type !== "string" || !spec.type.trim()) {
69
+ return { error: `Refused: ${at} ("${spec.name}") has no "type". Nothing was sent.` };
70
+ }
71
+ const contexts = Array.isArray(spec.contexts) ? spec.contexts.filter((c) => c !== null && c !== "") : [];
72
+ if (!contexts.length) {
73
+ return {
74
+ error: `Refused: ${at} ("${spec.name}") declares no contexts. A field offered everywhere is an ` +
75
+ `ordinary field — put it in the entity class, not here. Nothing was sent.`,
76
+ };
77
+ }
78
+ fields.push({ ...spec, contexts });
79
+ }
80
+ return { decl: { entity: d.entity.trim(), context_field: d.context_field.trim(), fields } };
81
+ }
82
+ /**
83
+ * The difference between the file and the tenant. Pure: the caller does the
84
+ * reading, so every branch here is testable without a network.
85
+ *
86
+ * @param live every custom field name on the extension entity → its type
87
+ * @param offered context value → the set of field names live in that context
88
+ */
89
+ export function diffDeclaration(decl, live, offered) {
90
+ const plan = {
91
+ entity: decl.entity,
92
+ extension: customFieldsEntity(decl.entity),
93
+ context_field: decl.context_field,
94
+ create: [],
95
+ link: [],
96
+ unchanged: [],
97
+ type_drift: [],
98
+ not_declared: [],
99
+ };
100
+ const byContext = new Map();
101
+ const declaredAnywhere = new Set();
102
+ for (const f of decl.fields) {
103
+ declaredAnywhere.add(f.name);
104
+ const liveType = live.get(f.name);
105
+ // An unknown live type is not a drift. Claiming one would be worse than
106
+ // saying nothing: it reads as "your schema moved" when nothing moved.
107
+ if (liveType !== undefined && liveType !== "" && liveType !== f.type) {
108
+ plan.type_drift.push({ field: f.name, declared: f.type, live: liveType });
109
+ continue; // a type change is a migration; nothing else about it is safe
110
+ }
111
+ let everywhere = true;
112
+ // Tracked as a local, not re-read from `live`: a field created in THIS run
113
+ // exists from its second context onward, and treating that second context
114
+ // as another create would collide the name with itself.
115
+ let exists = liveType !== undefined;
116
+ for (const ctx of f.contexts) {
117
+ const key = String(ctx);
118
+ if (offered.get(key)?.has(f.name) ?? false)
119
+ continue;
120
+ everywhere = false;
121
+ if (exists) {
122
+ plan.link.push({ context: ctx, field: f.name });
123
+ continue;
124
+ }
125
+ // Born in its first declared context; every later one is a link.
126
+ if (!byContext.has(key))
127
+ byContext.set(key, []);
128
+ byContext.get(key).push(f);
129
+ exists = true;
130
+ }
131
+ if (everywhere)
132
+ plan.unchanged.push(f.name);
133
+ }
134
+ for (const [context, fields] of byContext)
135
+ plan.create.push({ context, fields });
136
+ for (const [context, names] of offered) {
137
+ for (const n of names) {
138
+ if (!declaredAnywhere.has(n))
139
+ plan.not_declared.push({ context, field: n });
140
+ }
141
+ }
142
+ return plan;
143
+ }
144
+ /** Is there anything to do? */
145
+ export function planIsEmpty(plan) {
146
+ return !plan.create.length && !plan.link.length;
147
+ }
148
+ /** Read what the tenant currently offers in each declared context. */
149
+ async function readOffered(entity, contextField, contexts) {
150
+ const offered = new Map();
151
+ for (const ctx of contexts) {
152
+ let names = [];
153
+ try {
154
+ const resolved = (await makeRequest("POST", `/api/core/custom-fields/${entity}/resolve`, {
155
+ context: { [contextField]: ctx },
156
+ }));
157
+ names = Array.isArray(resolved?.fields)
158
+ ? resolved.fields.map((f) => String(f.fieldName ?? ""))
159
+ : [];
160
+ }
161
+ catch {
162
+ // A context with no set yet simply offers nothing.
163
+ names = [];
164
+ }
165
+ offered.set(String(ctx), new Set(names.filter(Boolean)));
166
+ }
167
+ return offered;
168
+ }
169
+ /**
170
+ * Bring a tenant to what the repository declares.
171
+ *
172
+ * Defaults to a dry run, like the migration tool: the plan is the thing worth
173
+ * reading, and it is what a reviewer approves.
174
+ */
175
+ export async function applyCustomFieldsDeclaration(declaration, opts = {}) {
176
+ const { decl, error } = parseDeclaration(declaration);
177
+ if (error || !decl)
178
+ return jsonResponse({ error });
179
+ const extension = customFieldsEntity(decl.entity);
180
+ const meta = await extensionFields(extension);
181
+ const live = new Map();
182
+ for (const [name, row] of meta) {
183
+ if (!row.deletedAt)
184
+ live.set(name, String(row.type ?? ""));
185
+ }
186
+ const contexts = [...new Set(decl.fields.flatMap((f) => f.contexts.map(String)))];
187
+ const offered = await readOffered(decl.entity, decl.context_field, contexts);
188
+ const plan = diffDeclaration(decl, live, offered);
189
+ if (!opts.confirm) {
190
+ return jsonResponse({
191
+ status: planIsEmpty(plan) ? "already_converged" : "dry_run",
192
+ plan,
193
+ next: planIsEmpty(plan)
194
+ ? "Nothing to do — the tenant already matches the file."
195
+ : "Re-call with confirm=true to apply. Nothing has been created yet.",
196
+ note: "A field the file no longer lists is reported under not_declared and never removed: removing " +
197
+ "one parks its column and reserves its name for good. Use suppa_remove_custom_field deliberately.",
198
+ });
199
+ }
200
+ const applied = { created: [], linked: [] };
201
+ for (const group of plan.create) {
202
+ const out = JSON.parse(await addCustomFieldsBatch(decl.entity, JSON.stringify(group.fields.map((f) => ({
203
+ name: f.name,
204
+ type: f.type,
205
+ ...(f.sub_type ? { sub_type: f.sub_type } : {}),
206
+ ...(f.title === undefined ? {} : { title: f.title }),
207
+ ...(f.options ?? {}),
208
+ }))), { contextField: decl.context_field, contextValue: group.context }));
209
+ if (out.error) {
210
+ return jsonResponse({
211
+ status: "stopped",
212
+ failed_context: group.context,
213
+ error: out.error,
214
+ note: "The batch is atomic, so nothing in THIS context was created. Earlier contexts in this run " +
215
+ "were applied — re-run after fixing; convergence is idempotent.",
216
+ applied,
217
+ });
218
+ }
219
+ applied.created.push({ context: group.context, fields: group.fields.map((f) => f.name) });
220
+ }
221
+ for (const l of plan.link) {
222
+ const out = JSON.parse(await linkCustomFields(decl.entity, [l.field], { contextField: decl.context_field, contextValue: l.context }, { confirm: true }));
223
+ if (out.error) {
224
+ return jsonResponse({ status: "stopped", error: out.error, applied });
225
+ }
226
+ applied.linked.push(l);
227
+ }
228
+ return jsonResponse({
229
+ status: "converged",
230
+ entity: decl.entity,
231
+ extension,
232
+ applied,
233
+ unchanged: plan.unchanged.length,
234
+ type_drift: plan.type_drift,
235
+ not_declared: plan.not_declared,
236
+ });
237
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "suppa-mcp-2",
3
- "version": "1.28.1",
3
+ "version": "1.30.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": {
@@ -20,12 +20,17 @@
20
20
  * @suppa/sdk dependency and no *.entity.ts. A package install is not
21
21
  * permission to configure an unrelated project.
22
22
  *
23
+ * EVERYTHING HERE WRITES TO STDERR. Under `npx -y suppa-mcp-2`, npm installs
24
+ * and then execs the server on the SAME stdio the MCP host is connected to,
25
+ * so a line of install chatter on stdout lands in the middle of the JSON-RPC
26
+ * stream. Diagnostics belong on stderr; stdout belongs to the protocol.
27
+ *
23
28
  * It also never fails an install: whatever happens, this exits 0. A package
24
29
  * that cannot be added because its postinstall threw is worse than a repo
25
30
  * without hooks.
26
31
  */
27
32
 
28
- import { execFileSync } from "node:child_process";
33
+ import { execFileSync, spawnSync } from "node:child_process";
29
34
  import { existsSync, readdirSync, readFileSync, statSync } from "node:fs";
30
35
  import { dirname, join, resolve } from "node:path";
31
36
  import { fileURLToPath } from "node:url";
@@ -36,7 +41,7 @@ const PACKAGE_ROOT = resolve(HERE, "..", "..", "..");
36
41
 
37
42
  /** Say why nothing happened, but only where a reader would wonder. */
38
43
  function skip(reason, loud = false) {
39
- if (loud) process.stdout.write(`suppa-mcp-2: entity-code guards not installed — ${reason}\n`);
44
+ if (loud) process.stderr.write(`suppa-mcp-2: entity-code guards not installed — ${reason}\n`);
40
45
  process.exit(0);
41
46
  }
42
47
 
@@ -102,6 +107,41 @@ function looksLikeSuppaApp(root) {
102
107
  return walk(root, 0);
103
108
  }
104
109
 
110
+ /**
111
+ * Before anything else: did this package actually arrive intact?
112
+ *
113
+ * This runs on EVERY install — CI, global, a repo with no Suppa code — because
114
+ * unlike the guards below it is about this package, not about the repo that
115
+ * pulled it in. Two outages reached users through exactly this gap: a bin npx
116
+ * could not choose, and an interrupted download missing ajv. Both would have
117
+ * been caught here, before a host ever tried to start the server.
118
+ *
119
+ * It never fails the install and never propagates: a package that refuses to
120
+ * install is worse than one that installs and says what is wrong.
121
+ */
122
+ function selfCheck() {
123
+ if (process.env.SUPPA_MCP_NO_SELFTEST) return;
124
+ const cli = join(PACKAGE_ROOT, "dist", "selfcheckCli.js");
125
+ if (!existsSync(cli)) return; // a source checkout before its first build
126
+ // spawnSync, not execFileSync: the report comes back on the child's STDERR
127
+ // (stdout belongs to the MCP protocol), and execFileSync hands back stderr
128
+ // only when the child fails. Reading the wrong stream made this silent.
129
+ const r = spawnSync(process.execPath, [cli], {
130
+ cwd: PACKAGE_ROOT,
131
+ encoding: "utf-8",
132
+ timeout: 60_000,
133
+ });
134
+ const said = String(r.stderr ?? "") + String(r.stdout ?? "");
135
+ if (said.trim()) {
136
+ process.stderr.write(said.endsWith("\n") ? said : said + "\n");
137
+ } else if (r.error) {
138
+ process.stderr.write(
139
+ `suppa-mcp-2: self-check could not run (${r.error.message.split("\n")[0]}).\n`,
140
+ );
141
+ }
142
+ }
143
+ selfCheck();
144
+
105
145
  try {
106
146
  if (process.env.SUPPA_NO_GUARD_INSTALL) skip("SUPPA_NO_GUARD_INSTALL is set");
107
147
  if (process.env.CI) skip("running in CI");
@@ -145,16 +185,16 @@ try {
145
185
  const needsAttention = out
146
186
  .split("\n")
147
187
  .filter((l) => l.trimStart().startsWith("·") && !noise.test(l));
148
- process.stdout.write(
188
+ process.stderr.write(
149
189
  "suppa-mcp-2: entity-code guards in place (agent hooks, AGENTS.md/CLAUDE.md, pre-commit, " +
150
190
  "CI job, npm run schema:gate). SUPPA_NO_GUARD_INSTALL=1 turns this off; " +
151
191
  "`npx suppa-entity-guards .` re-runs it.\n",
152
192
  );
153
- for (const line of needsAttention) process.stdout.write(` ${line.trim()}\n`);
193
+ for (const line of needsAttention) process.stderr.write(` ${line.trim()}\n`);
154
194
  } catch (e) {
155
195
  // An install that cannot be completed is a worse outcome than a repo without
156
196
  // hooks, so this never propagates.
157
- process.stdout.write(
197
+ process.stderr.write(
158
198
  `suppa-mcp-2: could not install the entity-code guards (${
159
199
  e instanceof Error ? e.message.split("\n")[0] : String(e)
160
200
  }). Run \`npx suppa-entity-guards .\` when convenient.\n`,