@nifrajs/cli 2.14.1 → 3.2.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 (203) hide show
  1. package/README.md +10 -0
  2. package/dist/assure-hydration.d.ts.map +1 -1
  3. package/dist/assure-hydration.js +6 -1
  4. package/dist/assure-hydration.js.map +1 -1
  5. package/dist/assure.d.ts.map +1 -1
  6. package/dist/assure.js +3 -2
  7. package/dist/assure.js.map +1 -1
  8. package/dist/check-diagnostics.d.ts +165 -0
  9. package/dist/check-diagnostics.d.ts.map +1 -0
  10. package/dist/check-diagnostics.js +1009 -0
  11. package/dist/check-diagnostics.js.map +1 -0
  12. package/dist/check-scan.d.ts +245 -0
  13. package/dist/check-scan.d.ts.map +1 -0
  14. package/dist/check-scan.js +1599 -0
  15. package/dist/check-scan.js.map +1 -0
  16. package/dist/check.d.ts +4 -324
  17. package/dist/check.d.ts.map +1 -1
  18. package/dist/check.js +8 -2346
  19. package/dist/check.js.map +1 -1
  20. package/dist/cli.d.ts.map +1 -1
  21. package/dist/cli.js +285 -10
  22. package/dist/cli.js.map +1 -1
  23. package/dist/command-catalog.d.ts +27 -1
  24. package/dist/command-catalog.d.ts.map +1 -1
  25. package/dist/command-catalog.js +142 -2
  26. package/dist/command-catalog.js.map +1 -1
  27. package/dist/doctor.d.ts +42 -0
  28. package/dist/doctor.d.ts.map +1 -1
  29. package/dist/doctor.js +64 -7
  30. package/dist/doctor.js.map +1 -1
  31. package/dist/env-file.d.ts +17 -0
  32. package/dist/env-file.d.ts.map +1 -0
  33. package/dist/env-file.js +113 -0
  34. package/dist/env-file.js.map +1 -0
  35. package/dist/fix-recipes.d.ts.map +1 -1
  36. package/dist/fix-recipes.js +91 -15
  37. package/dist/fix-recipes.js.map +1 -1
  38. package/dist/frontend-guidance.d.ts +57 -0
  39. package/dist/frontend-guidance.d.ts.map +1 -0
  40. package/dist/frontend-guidance.js +195 -0
  41. package/dist/frontend-guidance.js.map +1 -0
  42. package/dist/internal/reserved-segment-codemod.d.ts +36 -0
  43. package/dist/internal/reserved-segment-codemod.d.ts.map +1 -0
  44. package/dist/internal/reserved-segment-codemod.js +134 -0
  45. package/dist/internal/reserved-segment-codemod.js.map +1 -0
  46. package/dist/internal/typescript-import.d.ts +1 -1
  47. package/dist/internal/typescript-import.d.ts.map +1 -1
  48. package/dist/internal/typescript-import.js +62 -11
  49. package/dist/internal/typescript-import.js.map +1 -1
  50. package/dist/introspect.d.ts +26 -1
  51. package/dist/introspect.d.ts.map +1 -1
  52. package/dist/introspect.js +74 -24
  53. package/dist/introspect.js.map +1 -1
  54. package/dist/levels-tool.d.ts.map +1 -1
  55. package/dist/levels-tool.js +6 -0
  56. package/dist/levels-tool.js.map +1 -1
  57. package/dist/load.d.ts.map +1 -1
  58. package/dist/load.js +4 -1
  59. package/dist/load.js.map +1 -1
  60. package/dist/mcp-context.d.ts +48 -0
  61. package/dist/mcp-context.d.ts.map +1 -0
  62. package/dist/mcp-context.js +215 -0
  63. package/dist/mcp-context.js.map +1 -0
  64. package/dist/mcp-docs-tools.d.ts.map +1 -1
  65. package/dist/mcp-docs-tools.js +31 -0
  66. package/dist/mcp-docs-tools.js.map +1 -1
  67. package/dist/mcp-exec.d.ts +74 -0
  68. package/dist/mcp-exec.d.ts.map +1 -0
  69. package/dist/mcp-exec.js +844 -0
  70. package/dist/mcp-exec.js.map +1 -0
  71. package/dist/mcp-http.js +1 -1
  72. package/dist/mcp-http.js.map +1 -1
  73. package/dist/mcp-io.d.ts +26 -0
  74. package/dist/mcp-io.d.ts.map +1 -0
  75. package/dist/mcp-io.js +100 -0
  76. package/dist/mcp-io.js.map +1 -0
  77. package/dist/mcp-reflect.d.ts +16 -0
  78. package/dist/mcp-reflect.d.ts.map +1 -0
  79. package/dist/mcp-reflect.js +101 -0
  80. package/dist/mcp-reflect.js.map +1 -0
  81. package/dist/mcp-root.d.ts +7 -0
  82. package/dist/mcp-root.d.ts.map +1 -1
  83. package/dist/mcp-root.js +51 -3
  84. package/dist/mcp-root.js.map +1 -1
  85. package/dist/mcp.d.ts +10 -84
  86. package/dist/mcp.d.ts.map +1 -1
  87. package/dist/mcp.js +13 -1170
  88. package/dist/mcp.js.map +1 -1
  89. package/dist/openapi-tool.d.ts +5 -10
  90. package/dist/openapi-tool.d.ts.map +1 -1
  91. package/dist/openapi-tool.js +21 -2
  92. package/dist/openapi-tool.js.map +1 -1
  93. package/dist/openapi-types.d.ts +21 -0
  94. package/dist/openapi-types.d.ts.map +1 -0
  95. package/dist/openapi-types.js +214 -0
  96. package/dist/openapi-types.js.map +1 -0
  97. package/dist/port.d.ts.map +1 -1
  98. package/dist/port.js +2 -1
  99. package/dist/port.js.map +1 -1
  100. package/dist/project-facts.d.ts +2 -1
  101. package/dist/project-facts.d.ts.map +1 -1
  102. package/dist/project-facts.js.map +1 -1
  103. package/dist/recipes/3.0.0.d.ts +10 -0
  104. package/dist/recipes/3.0.0.d.ts.map +1 -0
  105. package/dist/recipes/3.0.0.js +23 -0
  106. package/dist/recipes/3.0.0.js.map +1 -0
  107. package/dist/recipes/index.d.ts.map +1 -1
  108. package/dist/recipes/index.js +2 -0
  109. package/dist/recipes/index.js.map +1 -1
  110. package/dist/release-verification.d.ts +4 -1
  111. package/dist/release-verification.d.ts.map +1 -1
  112. package/dist/release-verification.js +6 -123
  113. package/dist/release-verification.js.map +1 -1
  114. package/dist/rules/codes.d.ts +4 -0
  115. package/dist/rules/codes.d.ts.map +1 -1
  116. package/dist/rules/codes.js +4 -0
  117. package/dist/rules/codes.js.map +1 -1
  118. package/dist/rules/islands.d.ts +4 -0
  119. package/dist/rules/islands.d.ts.map +1 -0
  120. package/dist/rules/islands.js +155 -0
  121. package/dist/rules/islands.js.map +1 -0
  122. package/dist/rules/nano.d.ts +6 -0
  123. package/dist/rules/nano.d.ts.map +1 -0
  124. package/dist/rules/nano.js +264 -0
  125. package/dist/rules/nano.js.map +1 -0
  126. package/dist/rules/routes.d.ts.map +1 -1
  127. package/dist/rules/routes.js +17 -30
  128. package/dist/rules/routes.js.map +1 -1
  129. package/dist/rules/security.d.ts.map +1 -1
  130. package/dist/rules/security.js +38 -4
  131. package/dist/rules/security.js.map +1 -1
  132. package/dist/scaffold.d.ts +12 -6
  133. package/dist/scaffold.d.ts.map +1 -1
  134. package/dist/scaffold.js +149 -10
  135. package/dist/scaffold.js.map +1 -1
  136. package/dist/search-terms.d.ts.map +1 -1
  137. package/dist/search-terms.js +5 -3
  138. package/dist/search-terms.js.map +1 -1
  139. package/dist/stylex-migrate.d.ts +38 -0
  140. package/dist/stylex-migrate.d.ts.map +1 -0
  141. package/dist/stylex-migrate.js +1052 -0
  142. package/dist/stylex-migrate.js.map +1 -0
  143. package/dist/sync-manifest.d.ts.map +1 -1
  144. package/dist/sync-manifest.js +2 -1
  145. package/dist/sync-manifest.js.map +1 -1
  146. package/dist/verification-plan.d.ts +24 -0
  147. package/dist/verification-plan.d.ts.map +1 -0
  148. package/dist/verification-plan.js +116 -0
  149. package/dist/verification-plan.js.map +1 -0
  150. package/dist/work-graph.d.ts.map +1 -1
  151. package/dist/work-graph.js +6 -3
  152. package/dist/work-graph.js.map +1 -1
  153. package/dist/workspace-link.d.ts +37 -0
  154. package/dist/workspace-link.d.ts.map +1 -0
  155. package/dist/workspace-link.js +72 -0
  156. package/dist/workspace-link.js.map +1 -0
  157. package/docs/examples.json +37 -1
  158. package/docs/llms-full.txt +1598 -44
  159. package/docs/types.json +5157 -172
  160. package/package.json +9 -9
  161. package/src/assure-hydration.ts +6 -1
  162. package/src/assure.ts +4 -2
  163. package/src/check-diagnostics.ts +1219 -0
  164. package/src/check-scan.ts +1825 -0
  165. package/src/check.ts +47 -2731
  166. package/src/cli.ts +291 -10
  167. package/src/command-catalog.ts +177 -2
  168. package/src/doctor.ts +99 -8
  169. package/src/env-file.ts +121 -0
  170. package/src/fix-recipes.ts +101 -15
  171. package/src/frontend-guidance.ts +259 -0
  172. package/src/internal/reserved-segment-codemod.ts +150 -0
  173. package/src/internal/typescript-import.ts +61 -11
  174. package/src/introspect.ts +82 -21
  175. package/src/levels-tool.ts +6 -0
  176. package/src/load.ts +4 -1
  177. package/src/mcp-context.ts +266 -0
  178. package/src/mcp-docs-tools.ts +37 -0
  179. package/src/mcp-exec.ts +1040 -0
  180. package/src/mcp-http.ts +1 -1
  181. package/src/mcp-io.ts +118 -0
  182. package/src/mcp-reflect.ts +140 -0
  183. package/src/mcp-root.ts +62 -4
  184. package/src/mcp.ts +61 -1436
  185. package/src/openapi-tool.ts +32 -2
  186. package/src/openapi-types.ts +261 -0
  187. package/src/port.ts +2 -1
  188. package/src/project-facts.ts +2 -4
  189. package/src/recipes/3.0.0.ts +24 -0
  190. package/src/recipes/index.ts +2 -0
  191. package/src/release-verification.ts +22 -147
  192. package/src/rules/codes.ts +4 -0
  193. package/src/rules/islands.ts +171 -0
  194. package/src/rules/nano.ts +295 -0
  195. package/src/rules/routes.ts +17 -30
  196. package/src/rules/security.ts +40 -4
  197. package/src/scaffold.ts +169 -9
  198. package/src/search-terms.ts +7 -3
  199. package/src/stylex-migrate.ts +1139 -0
  200. package/src/sync-manifest.ts +2 -1
  201. package/src/verification-plan.ts +242 -0
  202. package/src/work-graph.ts +6 -3
  203. package/src/workspace-link.ts +80 -0
package/dist/mcp.js CHANGED
@@ -34,1132 +34,23 @@
34
34
  * minimal-surface choice as the rest of nifra. The pure dispatch lives in `./mcp-protocol.ts`; this
35
35
  * module is the I/O shell (stdin loop, tool wiring, the run subprocess).
36
36
  */
37
- import { realpathSync } from "node:fs";
38
- import { readFile, stat } from "node:fs/promises";
39
- import { basename, isAbsolute, relative, resolve, sep } from "node:path";
40
- import { fileURLToPath } from "node:url";
41
- import { reflectRoutes } from "@nifrajs/core/reflection";
42
- import { Glob } from "bun";
43
- import { commandCatalog, commandMcpName, findCommandSpec, } from "./command-catalog.js";
44
- import { collectContractProof } from "./contract-proof.js";
37
+ import { stat } from "node:fs/promises";
38
+ import { resolve } from "node:path";
45
39
  import { loadDocsCorpus } from "./docs-search.js";
46
40
  import { loadExamplesCorpus } from "./examples.js";
47
41
  import { detectMonorepo, loadMonorepoApps } from "./load.js";
48
42
  import { docsTools } from "./mcp-docs-tools.js";
49
43
  import { createMcpProtocolState, handleRpc, rpcError, } from "./mcp-protocol.js";
50
- import { applyClientRoots, detectToolingDrift, driftNote, pathsFromRootsResult, resolveRootState, rootInstructions, rootVerdict, } from "./mcp-root.js";
44
+ import { extractBackendPrompts, extractBackendResources, extractBackendTools, } from "./mcp-reflect.js";
51
45
  import { loadTypesCorpus } from "./types-search.js";
52
- /** Path to a sibling child entry (`mcp-run` / `mcp-render` / `mcp-ws`), resolved next to this module (`.ts` in
53
- * dev, `.js` once built). Each runs in a FRESH subprocess per call so the project's current code loads. */
54
- function childPath(name) {
55
- return fileURLToPath(new URL(import.meta.url)).replace(/mcp\.(ts|js)$/, `${name}.$1`);
56
- }
57
- /** Spawn `bun <child> <cwd>`, pipe `input` to its stdin, return its stdout (or a stderr-backed error). */
58
- /**
59
- * How long a child gets before it is killed.
60
- *
61
- * A child loads the app, which runs its module side effects - a database pool, a Redis client, a
62
- * metrics interval. Any of those keeps the child's event loop alive after the work is done, and the
63
- * parent is sitting in `await proc.exited`. The children now exit explicitly, so this is the backstop
64
- * rather than the fix: without it a single wedged child blocks an agent indefinitely, and the caller
65
- * has no way to tell "still working" from "never returning".
66
- *
67
- * Generous enough for a cold start that compiles route modules, short enough that a hang is reported
68
- * within one attention span rather than after minutes of polling.
69
- */
70
- const CHILD_TIMEOUT_MS = 30_000;
71
- /** Local dev-tool reads are intentionally bounded: MCP runs in an agent process and must not hang on or
72
- * buffer an unrelated loopback service just because a caller supplied its port. */
73
- export const LOCAL_TOOL_FETCH_TIMEOUT_MS = 2_000;
74
- export const LOCAL_TOOL_MAX_RESPONSE_BYTES = 1_048_576;
75
- /** Accept only a concrete TCP port. Port 0 (bind-any-free-port) is not a valid read target. */
76
- export function validateLocalPort(port) {
77
- return typeof port === "number" && Number.isInteger(port) && port >= 1 && port <= 65_535
78
- ? port
79
- : undefined;
80
- }
81
- /** Read a dev-tool response without allowing an untrusted localhost service to allocate unbounded memory. */
82
- export async function readBoundedResponse(response, maxBytes = LOCAL_TOOL_MAX_RESPONSE_BYTES) {
83
- const declared = response.headers.get("content-length");
84
- if (declared !== null) {
85
- const length = Number(declared);
86
- if (Number.isFinite(length) && length > maxBytes)
87
- throw new Error("response exceeded the size limit");
88
- }
89
- if (response.body === null)
90
- return "";
91
- const reader = response.body.getReader();
92
- const chunks = [];
93
- let total = 0;
94
- try {
95
- for (;;) {
96
- const { done, value } = await reader.read();
97
- if (done)
98
- break;
99
- if (value === undefined)
100
- continue;
101
- total += value.byteLength;
102
- if (total > maxBytes) {
103
- await reader.cancel();
104
- throw new Error("response exceeded the size limit");
105
- }
106
- chunks.push(value);
107
- }
108
- }
109
- finally {
110
- reader.releaseLock();
111
- }
112
- const bytes = new Uint8Array(total);
113
- let offset = 0;
114
- for (const chunk of chunks) {
115
- bytes.set(chunk, offset);
116
- offset += chunk.byteLength;
117
- }
118
- return new TextDecoder().decode(bytes);
119
- }
120
- const notNifraResponse = (service) => JSON.stringify({
121
- code: "NIFRA_NOT_DEV_SERVER",
122
- message: `The service on this port is not a Nifra ${service} endpoint.`,
123
- }, null, 2);
124
- const timeoutMessage = (label, ms) => `${label} timed out after ${ms / 1000}s and was terminated.\n` +
125
- `The app was loaded but the process did not finish. Most often this is a module-level side effect ` +
126
- `that keeps the event loop alive (a database pool, a Redis client, an interval) opened during import ` +
127
- `rather than lazily. Check for top-level connections in the app entry or anything it imports.`;
128
- async function spawnChild(child, cwd, input, label, signal) {
129
- if (signal?.aborted)
130
- return `${label} cancelled before it started.`;
131
- const proc = Bun.spawn(["bun", childPath(child), cwd], {
132
- stdin: "pipe",
133
- stdout: "pipe",
134
- stderr: "pipe",
135
- });
136
- const abort = () => proc.kill();
137
- signal?.addEventListener("abort", abort, { once: true });
138
- let timedOut = false;
139
- const timer = setTimeout(() => {
140
- timedOut = true;
141
- proc.kill();
142
- }, CHILD_TIMEOUT_MS);
143
- try {
144
- proc.stdin.write(JSON.stringify(input));
145
- await proc.stdin.end();
146
- const [out, err] = await Promise.all([
147
- new Response(proc.stdout).text(),
148
- new Response(proc.stderr).text(),
149
- ]);
150
- await proc.exited;
151
- if (signal?.aborted) {
152
- const reason = typeof signal.reason === "string" ? `: ${signal.reason}` : "";
153
- return `${label} cancelled${reason}.`;
154
- }
155
- // A killed child may still have flushed a complete result before the timer fired; prefer real
156
- // output over the timeout message so a slow-but-successful render is not reported as a failure.
157
- const text = out.trim();
158
- if (timedOut && text === "")
159
- return timeoutMessage(label, CHILD_TIMEOUT_MS);
160
- return text || `${label} failed:\n${err.trim() || "(no output)"}`;
161
- }
162
- finally {
163
- clearTimeout(timer);
164
- signal?.removeEventListener("abort", abort);
165
- }
166
- }
167
- const WARM_RUN_GLOB = new Glob("**/*.{ts,tsx,mts,cts,js,jsx,mjs,cjs,json}");
168
- const WARM_RUN_IGNORED = /(^|\/)(node_modules|dist(-[a-z0-9]+)?|build|\.nifra|\.git|\.wrangler|coverage)\//;
169
- const WARM_RUN_EXTRA_FILES = ["bun.lock", "bun.lockb"];
170
- async function warmRunFingerprint(cwd) {
171
- const parts = [];
172
- for await (const rel of WARM_RUN_GLOB.scan({ cwd, dot: false })) {
173
- if (WARM_RUN_IGNORED.test(rel))
174
- continue;
175
- try {
176
- const s = await stat(resolve(cwd, rel));
177
- if (s.isFile())
178
- parts.push(`${rel}:${s.mtimeMs}:${s.size}`);
179
- }
180
- catch {
181
- // A file can disappear while an agent is editing. The next call will rescan the settled tree.
182
- }
183
- }
184
- for (const rel of WARM_RUN_EXTRA_FILES) {
185
- parts.push(`${rel}:${await fileFingerprint(resolve(cwd, rel))}`);
186
- }
187
- return cacheToken(parts.sort().join("|"));
188
- }
189
- function boundedAppend(current, next, max = 12_000) {
190
- const combined = `${current}${next}`;
191
- return combined.length <= max ? combined : combined.slice(combined.length - max);
192
- }
193
- /** A persistent `mcp-run`/`mcp-render` `--worker` subprocess: the backend/web app is loaded ONCE and
194
- * reused across newline-delimited `{ id, input }` requests, replying `{ id, output }`. The same machinery
195
- * powers both `nifra_run warm` and `nifra_render warm` - `child` selects which engine, `label` shapes the
196
- * cancellation message. The owning handler ({@link createWarmHandler}) fingerprints the source tree and
197
- * replaces the worker when a file changes, so warm reuse never serves a stale result. Exported for the
198
- * concurrency test that proves a single per-request cancel doesn't tear down the shared worker. */
199
- export class WarmWorker {
200
- fingerprint;
201
- label;
202
- proc;
203
- pending = new Map();
204
- stdoutBuffer = "";
205
- stderrBuffer = "";
206
- nextId = 0;
207
- closed = false;
208
- constructor(child, cwd, fingerprint, label) {
209
- this.fingerprint = fingerprint;
210
- this.label = label;
211
- this.proc = Bun.spawn(["bun", childPath(child), cwd, "--worker"], {
212
- stdin: "pipe",
213
- stdout: "pipe",
214
- stderr: "pipe",
215
- });
216
- void this.readStdout();
217
- void this.readStderr();
218
- void this.proc.exited.then((code) => {
219
- this.closed = true;
220
- const err = new Error(`warm ${this.label} worker exited (${code})${this.stderrBuffer ? `:\n${this.stderrBuffer}` : ""}`);
221
- for (const pending of this.pending.values()) {
222
- pending.cleanup();
223
- pending.reject(err);
224
- }
225
- this.pending.clear();
226
- });
227
- }
228
- stop() {
229
- if (!this.closed)
230
- this.proc.kill();
231
- }
232
- async request(input, signal) {
233
- if (this.closed)
234
- throw new Error(`warm ${this.label} worker is closed`);
235
- if (signal?.aborted)
236
- return `${this.label} cancelled before it started.`;
237
- const id = ++this.nextId;
238
- return new Promise((resolve, reject) => {
239
- const abort = () => {
240
- // Per-request cancel: drop just THIS id and resolve its cancellation. The worker is shared
241
- // across concurrent requests (`pending` is id-keyed for exactly this reason), so killing the
242
- // process here would reject every OTHER in-flight request via the `exited` handler and force a
243
- // cold rebuild. Leave it hot - `createWarmHandler` already replaces it on file change.
244
- this.pending.delete(id);
245
- clearTimeout(timer);
246
- const reason = typeof signal?.reason === "string" ? `: ${signal.reason}` : "";
247
- resolve(`${this.label} cancelled${reason}.`);
248
- };
249
- // Same backstop as the cold path: a worker wedged mid-request would otherwise leave this
250
- // promise unsettled forever. Drop the id and replace the worker - unlike a per-request cancel,
251
- // a timeout means the worker itself is suspect, so the next call should start from a fresh one.
252
- const timer = setTimeout(() => {
253
- if (!this.pending.delete(id))
254
- return;
255
- signal?.removeEventListener("abort", abort);
256
- this.stop();
257
- resolve(timeoutMessage(this.label, CHILD_TIMEOUT_MS));
258
- }, CHILD_TIMEOUT_MS);
259
- const cleanup = () => {
260
- clearTimeout(timer);
261
- signal?.removeEventListener("abort", abort);
262
- };
263
- signal?.addEventListener("abort", abort, { once: true });
264
- this.pending.set(id, { resolve, reject, cleanup });
265
- try {
266
- this.proc.stdin.write(`${JSON.stringify({ id, input })}\n`);
267
- }
268
- catch (err) {
269
- this.pending.delete(id);
270
- cleanup();
271
- reject(err instanceof Error ? err : new Error(String(err)));
272
- }
273
- });
274
- }
275
- async readStdout() {
276
- const decoder = new TextDecoder();
277
- const reader = this.proc.stdout.getReader();
278
- for (;;) {
279
- const { done, value } = await reader.read();
280
- if (done)
281
- break;
282
- this.stdoutBuffer += decoder.decode(value, { stream: true });
283
- let nl = this.stdoutBuffer.indexOf("\n");
284
- while (nl !== -1) {
285
- const line = this.stdoutBuffer.slice(0, nl).trim();
286
- this.stdoutBuffer = this.stdoutBuffer.slice(nl + 1);
287
- nl = this.stdoutBuffer.indexOf("\n");
288
- if (line !== "")
289
- this.handleLine(line);
290
- }
291
- }
292
- }
293
- async readStderr() {
294
- const decoder = new TextDecoder();
295
- const reader = this.proc.stderr.getReader();
296
- for (;;) {
297
- const { done, value } = await reader.read();
298
- if (done)
299
- break;
300
- this.stderrBuffer = boundedAppend(this.stderrBuffer, decoder.decode(value, { stream: true }));
301
- }
302
- }
303
- handleLine(line) {
304
- let message;
305
- try {
306
- message = JSON.parse(line);
307
- }
308
- catch {
309
- this.stderrBuffer = boundedAppend(this.stderrBuffer, `invalid warm ${this.label} worker line: ${line}\n`);
310
- return;
311
- }
312
- if (typeof message.id !== "number")
313
- return;
314
- const pending = this.pending.get(message.id);
315
- if (pending === undefined)
316
- return;
317
- this.pending.delete(message.id);
318
- pending.cleanup();
319
- pending.resolve(JSON.stringify(message.output, null, 2));
320
- }
321
- }
322
- /** A warm handler that reuses a hot {@link WarmWorker} across calls and falls back to a one-shot fresh
323
- * subprocess on any worker failure. Shared by `nifra_run` (`child: "mcp-run"`, `label: "run"`) and
324
- * `nifra_render` (`child: "mcp-render"`, `label: "render"`) - the only differences are the engine and the
325
- * message label, so there's a single source for the reuse + auto-restart-on-file-change logic. */
326
- function createWarmHandler(child, cwd, label) {
327
- let worker;
328
- return async (input, signal) => {
329
- const fingerprint = await warmRunFingerprint(cwd);
330
- if (worker === undefined || worker.fingerprint !== fingerprint) {
331
- worker?.stop();
332
- worker = new WarmWorker(child, cwd, fingerprint, label);
333
- }
334
- try {
335
- return await worker.request(input, signal);
336
- }
337
- catch {
338
- worker.stop();
339
- worker = undefined;
340
- if (signal?.aborted) {
341
- const reason = typeof signal.reason === "string" ? `: ${signal.reason}` : "";
342
- return `${label} cancelled${reason}.`;
343
- }
344
- return spawnChild(child, cwd, input, label, signal);
345
- }
346
- };
347
- }
348
- /** The `nifra_run` handler: run requests through the project's CURRENT backend, return structured results. */
349
- async function runHandler(cwd, args, context, warmRun) {
350
- const requests = Array.isArray(args.requests) ? args.requests : [];
351
- if (requests.length === 0) {
352
- return 'No requests provided. Pass { "requests": [{ "path": "/..." }] }.';
353
- }
354
- const input = { requests, entry: args.entry };
355
- if (args.warm === true) {
356
- context.reportProgress(0.2, 1);
357
- return warmRun(input, context.signal);
358
- }
359
- return spawnChild("mcp-run", cwd, input, "run", context.signal);
360
- }
361
- /** The `nifra_render` handler: SSR page routes through the project's CURRENT web app, return the HTML.
362
- * By default a fresh subprocess loads the current code each call; `warm:true` reuses a hot worker (like
363
- * `nifra_run`) that auto-restarts when a source file changes. */
364
- async function renderHandler(cwd, args, context, warmRender) {
365
- const requests = Array.isArray(args.requests) ? args.requests : [];
366
- if (requests.length === 0) {
367
- return 'No requests provided. Pass { "requests": [{ "path": "/..." }] }.';
368
- }
369
- const input = { requests };
370
- if (args.warm === true) {
371
- context.reportProgress(0.2, 1);
372
- return warmRender(input, context.signal);
373
- }
374
- return spawnChild("mcp-render", cwd, input, "render", context.signal);
375
- }
376
- /** The `nifra_ws` handler: verify WebSocket routes through a fresh app subprocess. */
377
- async function wsHandler(cwd, args, context) {
378
- return spawnChild("mcp-ws", cwd, args, "websocket", context.signal);
379
- }
380
- function openApiFormat(args) {
381
- const format = args.format;
382
- return format === "yaml" ? "yaml" : "json";
383
- }
384
- const APP_FINGERPRINT_FILES = ["nifra.config.ts", "framework.ts", "backend.ts"];
385
- function cacheToken(input) {
386
- let hash = 2166136261;
387
- for (let i = 0; i < input.length; i++) {
388
- hash ^= input.charCodeAt(i);
389
- hash = Math.imul(hash, 16777619);
390
- }
391
- return `mcp=${(hash >>> 0).toString(36)}`;
392
- }
393
- async function fileFingerprint(path) {
394
- try {
395
- const s = await stat(path);
396
- return `${s.mtimeMs}:${s.size}`;
397
- }
398
- catch (err) {
399
- if (err && typeof err === "object" && err.code === "ENOENT") {
400
- return "missing";
401
- }
402
- throw err;
403
- }
404
- }
405
- async function appFingerprint(cwd) {
406
- return (await Promise.all(APP_FINGERPRINT_FILES.map(async (file) => `${file}:${await fileFingerprint(resolve(cwd, file))}`))).join("|");
407
- }
408
- /** Cache LoadedApp inside one MCP server process, invalidating when config/backend mtimes change. */
409
- export function createCachedAppLoader(cwd, options = {}) {
410
- const loadAppCached = options.loadApp ??
411
- (async (root, outDirName, loadOptions) => {
412
- const mod = await import("./load.js");
413
- return mod.loadApp(root, outDirName, loadOptions);
414
- });
415
- const fingerprint = options.fingerprint ?? appFingerprint;
416
- let cached;
417
- return async (outDirName = "dist") => {
418
- const nextFingerprint = await fingerprint(cwd);
419
- if (cached !== undefined &&
420
- cached.outDirName === outDirName &&
421
- cached.fingerprint === nextFingerprint) {
422
- return cached.app;
423
- }
424
- const app = await loadAppCached(cwd, outDirName, {
425
- importQuery: cacheToken(nextFingerprint),
426
- });
427
- cached = { outDirName, fingerprint: nextFingerprint, app };
428
- return app;
429
- };
430
- }
431
- async function openApiHandler(args, loadAppCached) {
432
- const { renderOpenApi } = await import("./openapi-tool.js");
433
- const pathPrefix = typeof args.path === "string" ? args.path : undefined;
434
- return renderOpenApi(await loadAppCached(), openApiFormat(args), pathPrefix);
435
- }
436
- async function readProjectFile(cwd, relativeFile, maxChars) {
437
- const target = resolve(cwd, relativeFile);
438
- const root = resolve(cwd);
439
- if (target !== root && !target.startsWith(`${root}${sep}`)) {
440
- throw new Error(`refusing to read outside project root: ${relativeFile}`);
441
- }
442
- try {
443
- const text = await readFile(target, "utf8");
444
- return text.length <= maxChars
445
- ? text
446
- : `${text.slice(0, maxChars)}\n…(trimmed; read ${relativeFile} directly for the rest)`;
447
- }
448
- catch (err) {
449
- if (err && typeof err === "object" && err.code === "ENOENT") {
450
- return `No ${relativeFile} found in ${basename(cwd)}.`;
451
- }
452
- throw err;
453
- }
454
- }
455
- function promptText(text) {
456
- return [{ role: "user", content: { type: "text", text } }];
457
- }
458
- export function projectResources(cwd, loadAppCached = createCachedAppLoader(cwd)) {
459
- return [
460
- {
461
- uri: "nifra://routes",
462
- name: "API routes",
463
- description: "Structured API routes with typed-client calls and compact request/response shapes.",
464
- mimeType: "application/json",
465
- read: async () => {
466
- const { routesToJson } = await import("./introspect.js");
467
- return { text: JSON.stringify(routesToJson(await loadAppCached()), null, 2) };
468
- },
469
- },
470
- {
471
- uri: "nifra://openapi",
472
- name: "OpenAPI 3.1",
473
- description: "OpenAPI document generated from backend.ts using @nifrajs/schema.",
474
- mimeType: "application/json",
475
- read: async () => ({ text: await openApiHandler({ format: "json" }, loadAppCached) }),
476
- },
477
- {
478
- uri: "nifra://package-json",
479
- name: "package.json",
480
- description: "Project package metadata and scripts.",
481
- mimeType: "application/json",
482
- read: async () => ({ text: await readProjectFile(cwd, "package.json", 40_000) }),
483
- },
484
- {
485
- uri: "nifra://agents-md",
486
- name: "AGENTS.md",
487
- description: "Repository-specific agent instructions if the project has them.",
488
- mimeType: "text/markdown",
489
- read: async () => ({ text: await readProjectFile(cwd, "AGENTS.md", 40_000) }),
490
- },
491
- ];
492
- }
493
- export function projectPrompts() {
494
- return [
495
- {
496
- name: "nifra_new_route",
497
- description: "Implement a new file route with the right routes/ filename, examples, and checks.",
498
- arguments: [
499
- { name: "path", description: 'URL path, e.g. "/users/:id".', required: true },
500
- { name: "goal", description: "What the page should do.", required: false },
501
- ],
502
- handler: async (args) => promptText([
503
- `Create a nifra page route for ${JSON.stringify(args.path ?? "/new-route")}.`,
504
- args.goal ? `Goal: ${String(args.goal)}` : undefined,
505
- 'Use `nifra_context` with `{ kind: "pages" }`, then `nifra_scaffold` for the exact file path.',
506
- "If the stub is not writable for this framework, call `nifra_example` for a verified page/loader example before editing.",
507
- "Verify with `nifra_render` for the route and finish with `nifra_check`.",
508
- ]
509
- .filter(Boolean)
510
- .join("\n")),
511
- },
512
- {
513
- name: "nifra_add_endpoint",
514
- description: "Add or update a backend endpoint with schemas, typed-client usage, and verification.",
515
- arguments: [
516
- { name: "method", description: "HTTP method.", required: true },
517
- { name: "path", description: 'API path, e.g. "/users/:id".', required: true },
518
- { name: "goal", description: "What the endpoint should do.", required: false },
519
- ],
520
- handler: async (args) => promptText([
521
- `Add a nifra backend endpoint: ${String(args.method ?? "GET").toUpperCase()} ${String(args.path ?? "/api")}.`,
522
- args.goal ? `Goal: ${String(args.goal)}` : undefined,
523
- "Read `nifra://routes` or call `nifra_routes` first so the new route fits the existing API shape.",
524
- "Use route schemas for untrusted body/query input and declare `response` when the frontend consumes the shape.",
525
- "Verify behavior with `nifra_run`, then run `nifra_check` and `nifra_test` for the touched area.",
526
- ]
527
- .filter(Boolean)
528
- .join("\n")),
529
- },
530
- {
531
- name: "nifra_debug_drift",
532
- description: "Debug frontend/backend contract drift using the typed client and checker output.",
533
- arguments: [
534
- { name: "symptom", description: "The error or behavior to investigate.", required: false },
535
- ],
536
- handler: async (args) => promptText([
537
- "Debug nifra contract drift.",
538
- args.symptom ? `Symptom: ${String(args.symptom)}` : undefined,
539
- "Start with `nifra_check`; use each diagnostic as the source of truth.",
540
- "Read `nifra://routes` for the exact typed-client calls and compact body/query/response shapes.",
541
- "Prefer `client<typeof app>` over hand-rolled internal `fetch`. Verify fixed endpoints with `nifra_run`.",
542
- ]
543
- .filter(Boolean)
544
- .join("\n")),
545
- },
546
- ];
547
- }
548
- export function projectFeatures(cwd, loadAppCached = createCachedAppLoader(cwd)) {
549
- return { resources: projectResources(cwd, loadAppCached), prompts: projectPrompts() };
550
- }
551
- /**
552
- * Resolve an optional `dir` tool argument - a subdirectory of the project root the caller wants to scope a
553
- * check/test to (e.g. `nifra check` on `app/` when the MCP server's root is a monorepo). Returns the
554
- * absolute target, or `null` if `dir` escapes the root (a path-traversal guard: no `..` out, no absolute
555
- * path elsewhere). `undefined`/empty → the root itself.
556
- */
557
- export function resolveProjectDir(root, dir) {
558
- if (dir === undefined || dir === "")
559
- return root;
560
- const target = resolve(root, dir);
561
- let canonicalRoot;
562
- try {
563
- canonicalRoot = realpathSync(root);
564
- }
565
- catch {
566
- const lexical = relative(root, target);
567
- return lexical === "" || (!lexical.startsWith("..") && !isAbsolute(lexical)) ? target : null;
568
- }
569
- let probe = target;
570
- const missing = [];
571
- while (true) {
572
- try {
573
- const canonicalProbe = realpathSync(probe);
574
- const rel = relative(canonicalRoot, canonicalProbe);
575
- if (rel.startsWith("..") || isAbsolute(rel))
576
- return null;
577
- return missing.length === 0 ? canonicalProbe : resolve(canonicalProbe, ...missing.reverse());
578
- }
579
- catch {
580
- const parent = resolve(probe, "..");
581
- if (parent === probe)
582
- return null;
583
- // `basename`, not a slice past `parent`: when `parent` is the filesystem root its trailing
584
- // separator is part of it, so `parent.length + 1` eats the first character of the segment and
585
- // the path gets rebuilt wrong.
586
- missing.push(basename(probe));
587
- probe = parent;
588
- }
589
- }
590
- }
591
- /** Consistent error string for a `dir` that escapes the project root. */
592
- function dirError(dir) {
593
- return JSON.stringify({ ok: false, error: `dir must be a subdirectory of the project root - "${dir}" escapes it.` }, null, 2);
594
- }
595
- /** Adapt one executable catalog spec to its MCP descriptor and project-scoped handler. */
596
- export function toMcpTool(source, options) {
597
- const spec = "run" in source ? source : findCommandSpec(source.name);
598
- if (spec === undefined)
599
- throw new Error(`missing command spec for ${source.name}`);
600
- const entry = "run" in source ? undefined : source;
601
- const { cwd } = options;
602
- const loadAppCached = options.loadAppCached ?? createCachedAppLoader(cwd);
603
- return {
604
- name: commandMcpName(entry?.name ?? spec.name),
605
- description: entry?.summary ?? spec.summary,
606
- inputSchema: entry?.inputSchema ?? spec.input.jsonSchema,
607
- handler: async (args, context) => {
608
- const raw = { ...args };
609
- const dir = raw.dir;
610
- if (dir !== undefined && typeof dir !== "string")
611
- return dirError(undefined);
612
- const target = resolveProjectDir(cwd, dir);
613
- if (target === null)
614
- return dirError(dir);
615
- if (typeof raw.config === "string") {
616
- const config = resolve(target, raw.config);
617
- if (config !== target && !config.startsWith(`${target}${sep}`))
618
- return JSON.stringify({ ok: false, error: "config must stay inside the selected project directory" }, null, 2);
619
- }
620
- delete raw.dir;
621
- let input;
622
- try {
623
- input = spec.input.parse(raw);
624
- }
625
- catch (error) {
626
- return JSON.stringify({ ok: false, error: error instanceof Error ? error.message : String(error) }, null, 2);
627
- }
628
- const commandContext = {
629
- cwd: target,
630
- signal: context.signal,
631
- progress: () => context.reportProgress?.(0.5, 1),
632
- ...(target === cwd ? { loadApp: loadAppCached } : {}),
633
- };
634
- const output = await spec.run(input, commandContext);
635
- const value = spec.json?.(output, input) ?? output;
636
- return typeof value === "string" ? value : JSON.stringify(value, null, 2);
637
- },
638
- };
639
- }
640
- export function catalogProjectTools(cwd, loadAppCached = createCachedAppLoader(cwd)) {
641
- return commandCatalog
642
- .filter((entry) => entry.transports.includes("mcp"))
643
- .map((entry) => {
644
- const spec = findCommandSpec(entry.name);
645
- if (spec === undefined)
646
- throw new Error(`missing command spec for ${entry.name}`);
647
- return toMcpTool(spec, { cwd, loadAppCached });
648
- });
649
- }
650
- export function projectTools(cwd, loadAppCached = createCachedAppLoader(cwd)) {
651
- const warmRun = createWarmHandler("mcp-run", cwd, "run");
652
- const warmRender = createWarmHandler("mcp-render", cwd, "render");
653
- const catalogTools = catalogProjectTools(cwd, () => loadAppCached());
654
- const legacyTools = [
655
- {
656
- name: "nifra_contract_proof",
657
- description: "Compare the current route contract with its snapshot and join each changed route to its route-assurance and capability evidence. Returns hasBreaking as the gate. The typed-contract check is lazy and runs only when check is true.",
658
- inputSchema: {
659
- type: "object",
660
- properties: {
661
- baseline: {
662
- type: "string",
663
- description: "Snapshot path relative to the selected project directory. Defaults to api-snapshot.json.",
664
- },
665
- check: {
666
- type: "boolean",
667
- description: "Also run the typed-contract check. Default false to keep the diff lazy.",
668
- },
669
- dir: {
670
- type: "string",
671
- description: "Project subdirectory to inspect.",
672
- },
673
- },
674
- additionalProperties: false,
675
- },
676
- handler: async (args) => {
677
- const raw = args;
678
- if (raw.dir !== undefined && typeof raw.dir !== "string") {
679
- return JSON.stringify({ ok: false, error: "dir must be a string" }, null, 2);
680
- }
681
- if (raw.baseline !== undefined && typeof raw.baseline !== "string") {
682
- return JSON.stringify({ ok: false, error: "baseline must be a string" }, null, 2);
683
- }
684
- const dir = raw.dir;
685
- const baseline = raw.baseline;
686
- const target = resolveProjectDir(cwd, dir);
687
- if (target === null)
688
- return dirError(dir);
689
- if (baseline !== undefined && baseline.trim() === "") {
690
- return JSON.stringify({ ok: false, error: "baseline must not be empty" }, null, 2);
691
- }
692
- try {
693
- return JSON.stringify(await collectContractProof(target, {
694
- ...(baseline === undefined ? {} : { baselinePath: baseline }),
695
- ...(raw.check === undefined ? {} : { check: raw.check === true }),
696
- }), null, 2);
697
- }
698
- catch (error) {
699
- return JSON.stringify({ ok: false, error: error instanceof Error ? error.message : String(error) }, null, 2);
700
- }
701
- },
702
- },
703
- {
704
- name: "nifra_explain",
705
- description: "Turn a nifra error into a STRUCTURED diagnostic instead of eyeballing a stack trace: a stable `code`, the top frame in YOUR source, a codeframe around the offending line, and - when nifra recognises the failure - the plain-language `cause` + `fix` + docs anchor. Pass `error` (and `stack` if you have it, e.g. from nifra_run/nifra_test output or a failing build) to explain a specific failure; or pass `port` to fetch the running dev server's most recent SSR failure from `/__nifra/last-error`. Returns the same JSON the dev overlay renders.",
706
- inputSchema: {
707
- type: "object",
708
- properties: {
709
- error: {
710
- type: "string",
711
- description: "The error message to explain (copy it from nifra_run/nifra_test output or a failing build).",
712
- },
713
- stack: {
714
- type: "string",
715
- description: "The error's stack trace, if you have it - enables the source codeframe and the top user frame.",
716
- },
717
- name: {
718
- type: "string",
719
- description: "The error's class name (e.g. TypeError, SchemaError), if known - sharpens classification.",
720
- },
721
- port: {
722
- type: "number",
723
- description: "Instead of a pasted error, fetch the running dev server's most recent SSR failure from this port.",
724
- },
725
- },
726
- additionalProperties: false,
727
- },
728
- handler: async (args) => {
729
- const { error, stack, name, port } = args;
730
- if (error !== undefined || stack !== undefined) {
731
- const { buildDiagnostic } = await import("@nifrajs/web/diagnostic");
732
- const e = new Error(error ?? "");
733
- if (name !== undefined)
734
- e.name = name;
735
- if (stack !== undefined)
736
- e.stack = stack;
737
- return JSON.stringify(buildDiagnostic(e, { root: cwd }), null, 2);
738
- }
739
- if (port !== undefined) {
740
- const validPort = validateLocalPort(port);
741
- if (validPort === undefined) {
742
- return JSON.stringify({ code: "NIFRA_INVALID_PORT", message: "port must be an integer from 1 to 65535." }, null, 2);
743
- }
744
- const { LAST_ERROR_PATH } = await import("@nifrajs/web/diagnostic");
745
- try {
746
- const res = await fetch(`http://127.0.0.1:${validPort}${LAST_ERROR_PATH}`, {
747
- signal: AbortSignal.timeout(LOCAL_TOOL_FETCH_TIMEOUT_MS),
748
- });
749
- if (res.headers.get("x-nifra-diagnostic") !== "true")
750
- return notNifraResponse("diagnostic");
751
- if (!res.ok) {
752
- return JSON.stringify({
753
- code: "NIFRA_NONE",
754
- message: `dev server at :${validPort} returned ${res.status}`,
755
- }, null, 2);
756
- }
757
- return await readBoundedResponse(res);
758
- }
759
- catch (cause) {
760
- return JSON.stringify({
761
- code: "NIFRA_NONE",
762
- message: `could not reach a nifra dev server at :${validPort} - ${cause instanceof Error ? cause.message : String(cause)}`,
763
- }, null, 2);
764
- }
765
- }
766
- return JSON.stringify({
767
- code: "NIFRA_NONE",
768
- message: "Pass `error` (and `stack` if available) to explain a failure, or `port` to fetch the dev server's last error.",
769
- }, null, 2);
770
- },
771
- },
772
- {
773
- name: "nifra_inspect",
774
- description: "Observe what your requests ACTUALLY did on the running dev server - the recent request traces the DevTools plugin records: `{ method, path, status, durationMs, isrStatus, bodyBytes }` per request. The read no other tool gives you: after nifra_run or a real browser request, call this to SEE the outcome (which route answered, the status, how long, ISR hit/miss) instead of guessing. Pass `port` (the running dev server); narrow with `path` (a path prefix) or `limit` (most recent N). Requires the app to mount `@nifrajs/web`'s `devtools()` plugin (which auto-enables in development).",
775
- inputSchema: {
776
- type: "object",
777
- properties: {
778
- port: { type: "number", description: "The running dev server's port." },
779
- path: { type: "string", description: "Only traces whose path starts with this prefix." },
780
- limit: { type: "number", description: "Return only the most recent N traces." },
781
- },
782
- required: ["port"],
783
- additionalProperties: false,
784
- },
785
- handler: async (args) => {
786
- const { port, path, limit } = args;
787
- if (port === undefined) {
788
- return JSON.stringify({
789
- events: [],
790
- note: "Pass `port` - the running dev server whose request traces to read.",
791
- }, null, 2);
792
- }
793
- try {
794
- const validPort = validateLocalPort(port);
795
- if (validPort === undefined) {
796
- return JSON.stringify({
797
- events: [],
798
- code: "NIFRA_INVALID_PORT",
799
- note: "port must be an integer from 1 to 65535.",
800
- }, null, 2);
801
- }
802
- const url = new URL(`http://127.0.0.1:${validPort}/_nifra/devtools/state`);
803
- if (path !== undefined)
804
- url.searchParams.set("path", path);
805
- if (limit !== undefined)
806
- url.searchParams.set("limit", String(limit));
807
- const res = await fetch(url, {
808
- signal: AbortSignal.timeout(LOCAL_TOOL_FETCH_TIMEOUT_MS),
809
- });
810
- if (res.headers.get("x-nifra-devtools") !== "true")
811
- return notNifraResponse("DevTools");
812
- if (res.status === 404) {
813
- return JSON.stringify({
814
- events: [],
815
- note: "No DevTools endpoint on that server. Mount `devtools()` from @nifrajs/web and run in development.",
816
- }, null, 2);
817
- }
818
- if (!res.ok) {
819
- return JSON.stringify({ events: [], note: `DevTools state returned ${res.status}.` }, null, 2);
820
- }
821
- return await readBoundedResponse(res);
822
- }
823
- catch (cause) {
824
- const validPort = validateLocalPort(port);
825
- return JSON.stringify({
826
- events: [],
827
- note: `Could not reach a dev server at :${validPort ?? String(port)} - ${cause instanceof Error ? cause.message : String(cause)}`,
828
- }, null, 2);
829
- }
830
- },
831
- },
832
- {
833
- name: "nifra_openapi",
834
- description: 'Return this project\'s backend OpenAPI 3.1 document generated from backend.ts route schemas via @nifrajs/schema. Use `format:"json"` for machine edits (default) or `format:"yaml"` for humans. Pass `path` (a route prefix like /api/orders, mirroring nifra_routes) to narrow a large backend to operations under that prefix instead of the whole document. Frontend-only apps return a valid empty paths object.',
835
- inputSchema: {
836
- type: "object",
837
- properties: {
838
- format: {
839
- type: "string",
840
- enum: ["json", "yaml"],
841
- description: "Output format (default: json).",
842
- },
843
- path: {
844
- type: "string",
845
- description: "Only operations whose path starts with this prefix (omit for the whole document).",
846
- },
847
- },
848
- additionalProperties: false,
849
- },
850
- handler: (args) => openApiHandler(args, loadAppCached),
851
- },
852
- {
853
- name: "nifra_run",
854
- description: "Run HTTP requests through this project's backend and return structured results (status, headers, parsed body, and any thrown error). Use it to verify code after editing: by default the backend is re-loaded in a fresh process each call. Pass warm:true to reuse a hot worker while source files are unchanged; it restarts automatically when files change. Each request: { method?, path, body?, headers? }.",
855
- inputSchema: {
856
- type: "object",
857
- properties: {
858
- requests: {
859
- type: "array",
860
- items: {
861
- type: "object",
862
- properties: {
863
- method: { type: "string" },
864
- path: { type: "string" },
865
- body: {},
866
- headers: { type: "object" },
867
- },
868
- required: ["path"],
869
- },
870
- },
871
- entry: {
872
- type: "string",
873
- description: "Backend entry file (default: backend.ts | app.ts).",
874
- },
875
- warm: {
876
- type: "boolean",
877
- description: "Reuse a hot backend worker while source files are unchanged. Default false for maximum isolation.",
878
- },
879
- },
880
- required: ["requests"],
881
- additionalProperties: false,
882
- },
883
- handler: (args, context) => runHandler(cwd, args, context, warmRun),
884
- },
885
- {
886
- name: "nifra_render",
887
- description: "SSR a page route (routes/) through this project's CURRENT web app and return { status, headers, body: the rendered HTML }. The page half of nifra_run: use it to verify a page renders and its loader ran after an edit. No build needed (a placeholder client entry is used; the SSR HTML renders regardless). Each request: { path, headers? }. By default re-loaded in a fresh process each call; pass warm:true to reuse a hot worker while source files are unchanged (it restarts automatically when files change), mirroring nifra_run.",
888
- inputSchema: {
889
- type: "object",
890
- properties: {
891
- requests: {
892
- type: "array",
893
- items: {
894
- type: "object",
895
- properties: {
896
- path: { type: "string" },
897
- headers: { type: "object" },
898
- },
899
- required: ["path"],
900
- },
901
- },
902
- warm: {
903
- type: "boolean",
904
- description: "Reuse a hot web-app worker while source files are unchanged. Default false for maximum isolation.",
905
- },
906
- },
907
- required: ["requests"],
908
- additionalProperties: false,
909
- },
910
- handler: (args, context) => renderHandler(cwd, args, context, warmRender),
911
- },
912
- {
913
- name: "nifra_ws",
914
- description: 'Verify a WebSocket route against this project by starting the backend on an ephemeral localhost port, opening a real Bun WebSocket, sending string frames, and returning structured evidence: { ok, opened, sent, received, close?, error? }. Use after adding or editing app.ws() routes. Pass path including query, e.g. "/chat?token=secret". By default expects one message when no messages are sent, or one response per sent message; set expectMessages:0 to verify connect-only routes.',
915
- inputSchema: {
916
- type: "object",
917
- properties: {
918
- path: {
919
- type: "string",
920
- description: 'App-local WebSocket path, optionally with query, e.g. "/chat?token=secret".',
921
- },
922
- messages: {
923
- type: "array",
924
- items: { type: "string" },
925
- description: "String frames to send after the socket opens (max 50).",
926
- },
927
- expectMessages: {
928
- type: "number",
929
- description: "How many inbound messages must be observed before success (default: messages.length, or 1 with no sent messages; max 50).",
930
- },
931
- timeoutMs: {
932
- type: "number",
933
- description: "Bounded verification timeout in milliseconds (default 3000, max 30000).",
934
- },
935
- entry: {
936
- type: "string",
937
- description: "Backend entry file (default: backend.ts | app.ts).",
938
- },
939
- },
940
- required: ["path"],
941
- additionalProperties: false,
942
- },
943
- handler: (args, context) => wsHandler(cwd, args, context),
944
- },
945
- {
946
- name: "nifra_test",
947
- description: "Run `bun test` for this project and return bounded structured results: { ok, command, durationMs, exitCode, timedOut, summary, stdout, stderr }. Pass `pattern` to narrow to a test file/path; pass `timeoutMs` (default 30000, max 300000). Use after editing code, alongside nifra_run/nifra_render for behavioral checks.",
948
- inputSchema: {
949
- type: "object",
950
- properties: {
951
- pattern: {
952
- type: "string",
953
- description: "Optional test file/path pattern passed as an argv item to `bun test`.",
954
- },
955
- timeoutMs: {
956
- type: "number",
957
- description: "Timeout in milliseconds (default 30000, max 300000).",
958
- },
959
- dir: {
960
- type: "string",
961
- description: 'Run the tests in this subdirectory (relative to the project root), e.g. "app". Use it when the MCP server\'s root is a monorepo but you want to test just one app. Default: the project root.',
962
- },
963
- },
964
- additionalProperties: false,
965
- },
966
- handler: async (args, context) => {
967
- const { collectTestResult } = await import("./test-tool.js");
968
- const opts = args;
969
- const target = resolveProjectDir(cwd, opts.dir);
970
- if (target === null)
971
- return dirError(opts.dir);
972
- return JSON.stringify(await collectTestResult(target, args, { signal: context.signal }), null, 2);
973
- },
974
- },
975
- // nifra_docs + nifra_example are project-independent (corpus-backed); the shared factory keeps their
976
- // definitions identical to the CLI HTTP server and the site's edge worker.
977
- ...docsTools(loadDocsCorpus, loadExamplesCorpus, loadTypesCorpus),
978
- {
979
- name: "nifra_scaffold",
980
- description: 'Map a URL path to the CORRECT routes/ file and get a contract-correct page stub. Agents routinely place file routes wrong - this applies the convention for you: ":id"/"[id]" → [id], "*rest" → [...rest], "/" → index. Pass path (e.g. "/users/:id"). Returns the file to create + the route-module contract (loader/action/meta/default) + a stub (ready-to-write for react/preact/solid; path+contract for vue/svelte/vanilla - use nifra_example for those bodies).',
981
- inputSchema: {
982
- type: "object",
983
- properties: {
984
- path: {
985
- type: "string",
986
- description: 'The URL path for the new page route, e.g. "/users/:id" or "/blog/*slug".',
987
- },
988
- write: {
989
- type: "boolean",
990
- description: "When true, create the file if a verified ready-to-write stub exists. Refuses overwrite.",
991
- },
992
- },
993
- required: ["path"],
994
- additionalProperties: false,
995
- },
996
- handler: async (args) => {
997
- const { path, write } = args;
998
- if (typeof path !== "string" || path.length === 0)
999
- return "scaffold: `path` is required.";
1000
- const { frameworkFromClientModule, renderScaffold, writeScaffoldRoute } = await import("./scaffold.js");
1001
- const app = await loadAppCached();
1002
- const framework = frameworkFromClientModule(app.framework.clientModule);
1003
- if (write !== true)
1004
- return renderScaffold(path, framework);
1005
- const result = await writeScaffoldRoute(cwd, path, framework);
1006
- const status = result.written
1007
- ? `Written: \`${result.file}\``
1008
- : `Not written: ${result.reason ?? "no write performed"}`;
1009
- return `${status}\n\n${renderScaffold(path, framework)}`;
1010
- },
1011
- },
1012
- {
1013
- name: "nifra_hydrate",
1014
- description: "Run the hydration assurance gate and return stable NF-H diagnostics.",
1015
- inputSchema: {
1016
- type: "object",
1017
- properties: {
1018
- dir: { type: "string", description: "Project subdirectory to inspect." },
1019
- interact: { type: "boolean", description: "Run declared hydration probes." },
1020
- },
1021
- additionalProperties: false,
1022
- },
1023
- handler: async (args) => {
1024
- const opts = args;
1025
- const target = resolveProjectDir(cwd, opts.dir);
1026
- if (target === null)
1027
- return dirError(opts.dir);
1028
- const { runHydrationAssurance } = await import("./assure-hydration.js");
1029
- return JSON.stringify(await runHydrationAssurance(target, { interact: opts.interact === true }), null, 2);
1030
- },
1031
- },
1032
- ];
1033
- return [...catalogTools, ...legacyTools];
1034
- }
1035
- /** Extract tools registered via .tool() routes on the Nifra backend. Exported for the test that proves a
1036
- * `server().tool()` route surfaces in `tools/list` and executes through `tools/call`. */
1037
- export function extractBackendTools(backend) {
1038
- const b = backend;
1039
- if (!b || typeof b.routes !== "function")
1040
- return [];
1041
- const routes = reflectRoutes(b);
1042
- return routes
1043
- .filter((r) => r.schema !== undefined && r.tool !== undefined)
1044
- .map((r) => {
1045
- const toolInfo = r.tool;
1046
- const s = r.schema;
1047
- return {
1048
- name: toolInfo.name,
1049
- description: toolInfo.description,
1050
- inputSchema: (s.body?.jsonSchema ?? {
1051
- type: "object",
1052
- properties: {},
1053
- }),
1054
- ...(toolInfo.annotations !== undefined ? { annotations: toolInfo.annotations } : {}),
1055
- handler: async (args) => {
1056
- const res = await b.fetch(new Request(`http://localhost/_nifra/tool/${toolInfo.name}`, {
1057
- method: "POST",
1058
- headers: { "content-type": "application/json" },
1059
- body: JSON.stringify(args),
1060
- }));
1061
- if (!res.ok) {
1062
- const text = await res.text();
1063
- throw new Error(`Tool execution failed (${res.status}): ${text}`);
1064
- }
1065
- const body = await res.json();
1066
- if (typeof body === "string")
1067
- return body;
1068
- if (body && typeof body === "object") {
1069
- if ("content" in body || "structuredContent" in body) {
1070
- return body;
1071
- }
1072
- return {
1073
- content: [{ type: "text", text: JSON.stringify(body, null, 2) }],
1074
- structuredContent: body,
1075
- };
1076
- }
1077
- return String(body);
1078
- },
1079
- };
1080
- });
1081
- }
1082
- /** Extract MCP resources registered via `.resource()` on the Nifra backend. Exported for the surfacing test. */
1083
- export function extractBackendResources(backend) {
1084
- const b = backend;
1085
- if (!b || typeof b.mcpResources !== "function")
1086
- return [];
1087
- let list;
1088
- try {
1089
- list = b.mcpResources();
1090
- }
1091
- catch {
1092
- return [];
1093
- }
1094
- return list.map((r) => ({
1095
- uri: r.uri,
1096
- name: r.name,
1097
- ...(r.description !== undefined ? { description: r.description } : {}),
1098
- ...(r.mimeType !== undefined ? { mimeType: r.mimeType } : {}),
1099
- read: async () => {
1100
- const out = await r.read();
1101
- if (typeof out === "string")
1102
- return { text: out };
1103
- const o = out;
1104
- return o.mimeType !== undefined ? { text: o.text, mimeType: o.mimeType } : { text: o.text };
1105
- },
1106
- }));
1107
- }
1108
- /** Extract MCP prompts registered via `.prompt()` on the Nifra backend. Exported for the surfacing test. */
1109
- export function extractBackendPrompts(backend) {
1110
- const b = backend;
1111
- if (!b || typeof b.mcpPrompts !== "function")
1112
- return [];
1113
- let list;
1114
- try {
1115
- list = b.mcpPrompts();
1116
- }
1117
- catch {
1118
- return [];
1119
- }
1120
- return list.map((p) => ({
1121
- name: p.name,
1122
- description: p.description,
1123
- ...(p.arguments !== undefined ? { arguments: p.arguments } : {}),
1124
- handler: async (args) => (await p.handler(args)),
1125
- }));
1126
- }
1127
- /** Prefix every tool name and resource URI for a named app in a monorepo. */
1128
- function namespaceForApp(name, tools, features) {
1129
- const prefix = `nifra_${name}_`;
1130
- const namespacedTools = tools.map((t) => ({
1131
- ...t,
1132
- name: t.name.startsWith("nifra_") ? t.name.replace(/^nifra_/, prefix) : `${name}_${t.name}`,
1133
- }));
1134
- const namespacedResources = (features.resources ?? []).map((r) => ({
1135
- ...r,
1136
- uri: r.uri.replace(/^nifra:\/\//, `nifra://${name}/`),
1137
- }));
1138
- const namespacedPrompts = (features.prompts ?? []).map((p) => ({
1139
- ...p,
1140
- name: p.name.replace(/^nifra_/, prefix),
1141
- }));
1142
- return {
1143
- tools: namespacedTools,
1144
- features: { resources: namespacedResources, prompts: namespacedPrompts },
1145
- };
1146
- }
1147
- /**
1148
- * Merge the backend-derived resources/prompts into `base` - and keep a project that cannot be loaded
1149
- * from deciding whether the server starts at all.
1150
- *
1151
- * Resources and prompts are OPTIONAL capabilities extracted from the app's backend, so this load is a
1152
- * best-effort enrichment. It was awaited unguarded, which made it a hard boot requirement: `loadApp`
1153
- * needs a web config (`adapter` + `clientModule`) and a `routes/` directory, and a backend-only
1154
- * project - the shape `create-nifra`'s DEFAULT template produces - has neither. On those projects the
1155
- * throw escaped before the JSON-RPC loop began, so the server wrote nothing and exited. `nifra
1156
- * init-agents` would happily register an `.mcp.json` pointing at a server that could never start, and
1157
- * every tool went with it, including the twelve that never touch the app (docs, examples, types,
1158
- * check, doctor, levels, test).
1159
- *
1160
- * Degrading costs only the backend resources/prompts. Tools that genuinely need the app still fail,
1161
- * but per call, with their own message - which is a diagnosis instead of a silence.
1162
- */
46
+ export { extractBackendPrompts, extractBackendResources, extractBackendTools, } from "./mcp-reflect.js";
47
+ import { applyClientRoots, clientSupportsRoots, detectToolingDrift, driftNote, guardTools, pathsFromRootsResult, resolveRootState, rootInstructions, rootVerdict, } from "./mcp-root.js";
48
+ export { CHILD_OUTPUT_MAX_BYTES, CHILD_TIMEOUT_MS, LOCAL_TOOL_FETCH_TIMEOUT_MS, LOCAL_TOOL_MAX_RESPONSE_BYTES, notNifraResponse, readBoundedResponse, readBoundedStream, timeoutMessage, validateLocalPort, } from "./mcp-io.js";
49
+ export { clientSupportsRoots, guardTools } from "./mcp-root.js";
50
+ import { createCachedAppLoader, projectTools } from "./mcp-exec.js";
51
+ export { catalogProjectTools, createCachedAppLoader, createWarmHandler, projectTools, renderHandler, runHandler, spawnChild, toMcpTool, WarmWorker, wsHandler, } from "./mcp-exec.js";
52
+ import { namespaceForApp, projectFeatures } from "./mcp-context.js";
53
+ export { dirError, namespaceForApp, projectFeatures, projectPrompts, projectResources, resolveProjectDir, } from "./mcp-context.js";
1163
54
  async function backendFeatures(loader, base) {
1164
55
  const resources = [...(base.resources ?? [])];
1165
56
  const prompts = [...(base.prompts ?? [])];
@@ -1189,12 +80,6 @@ async function appDeclaredTools(loader) {
1189
80
  return [];
1190
81
  }
1191
82
  }
1192
- /** Tool names that never touch the project - they serve the bundled docs/examples/types corpus, so
1193
- * they stay available (and unstamped) whatever the root state is. */
1194
- const PROJECT_FREE_TOOLS = new Set(["nifra_docs", "nifra_example", "nifra_types", "nifra_learn"]);
1195
- /** The id of this server's own `roots/list` request to the client. A fixed, namespaced string: the
1196
- * server only ever has one roots request in flight, and no response to a CLIENT-initiated request can
1197
- * carry it (clients pick their own ids; this one is recognisably ours). */
1198
83
  const ROOTS_REQUEST_ID = "nifra:roots/list";
1199
84
  async function createProjectContext(root) {
1200
85
  const monorepo = await detectMonorepo(root);
@@ -1221,50 +106,11 @@ async function createProjectContext(root) {
1221
106
  loadAppCached,
1222
107
  };
1223
108
  }
1224
- /**
1225
- * Wrap every project-scoped tool with the root guard: a bad root ({@link rootVerdict} `blocked`) makes
1226
- * the tool refuse with the remediation message instead of answering about whatever directory the
1227
- * server happened to start in; a good root stamps the result with `[nifra] project root: …` so the
1228
- * agent (and the human reading its transcript) can see WHICH project answered. Docs tools pass
1229
- * through untouched - they serve the bundled corpus, not the project.
1230
- */
1231
- export function guardTools(tools, verdict) {
1232
- return tools.map((tool) => {
1233
- if (PROJECT_FREE_TOOLS.has(tool.name))
1234
- return tool;
1235
- return {
1236
- ...tool,
1237
- handler: async (args, context) => {
1238
- if (verdict.blocked !== undefined) {
1239
- return { content: [{ type: "text", text: verdict.blocked }], isError: true };
1240
- }
1241
- const result = await tool.handler(args, context);
1242
- const note = { type: "text", text: verdict.note };
1243
- if (typeof result === "string") {
1244
- return { content: [{ type: "text", text: result }, note] };
1245
- }
1246
- return { ...result, content: [...(result.content ?? []), note] };
1247
- },
1248
- };
1249
- });
1250
- }
1251
- /** Whether the client's `initialize` params declare the `roots` capability - the precondition for
1252
- * this server sending it a `roots/list` request. */
1253
- export function clientSupportsRoots(params) {
1254
- const capabilities = params?.capabilities;
1255
- if (typeof capabilities !== "object" || capabilities === null)
1256
- return false;
1257
- const roots = capabilities.roots;
1258
- return typeof roots === "object" && roots !== null;
1259
- }
1260
109
  /**
1261
110
  * Run the stdio MCP server: read newline-delimited JSON-RPC from stdin, write responses to stdout.
1262
111
  *
1263
- * The project root is resolved defensively rather than assumed (`./mcp-root.ts`): explicit
1264
- * `nifra mcp <dir>` beats a cwd guess, a cwd guess walks up to the nearest nifra marker, the client's
1265
- * MCP `roots` (requested after the handshake, re-requested on `roots/list_changed`) can correct an
1266
- * unambiguous wrong guess, and anything still unresolved fails closed per tool call. The effective
1267
- * root is announced in the `initialize` instructions and stamped on every project tool result.
112
+ * Root resolution, trust, and project-tool execution are delegated to their own seams; this function
113
+ * owns only the stdio lifecycle and JSON-RPC dispatch loop.
1268
114
  */
1269
115
  export async function runMcpServer(cwd, version, explicitDir) {
1270
116
  const requested = explicitDir !== undefined ? resolve(cwd, explicitDir) : cwd;
@@ -1273,9 +119,6 @@ export async function runMcpServer(cwd, version, explicitDir) {
1273
119
  }
1274
120
  let rootState = await resolveRootState(requested, explicitDir !== undefined);
1275
121
  let ctx = await createProjectContext(rootState.root);
1276
- // The CLI answering may not be the nifra the project builds with (a globally installed server, a
1277
- // stale agent config). Recomputed whenever the root moves, since a different project can install a
1278
- // different version.
1279
122
  let drift = await detectToolingDrift(rootState.root, version);
1280
123
  const serverInfo = { name: "nifra", version };
1281
124
  const state = createMcpProtocolState();