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