@nifrajs/cli 5.5.1 → 5.6.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 (138) hide show
  1. package/CHANGELOG.md +155 -0
  2. package/dist/cdn-check.d.ts +7 -6
  3. package/dist/cdn-check.d.ts.map +1 -1
  4. package/dist/cdn-check.js +13 -1
  5. package/dist/cdn-check.js.map +1 -1
  6. package/dist/check-diagnostics.d.ts.map +1 -1
  7. package/dist/check-diagnostics.js +5 -3
  8. package/dist/check-diagnostics.js.map +1 -1
  9. package/dist/check-scan.d.ts.map +1 -1
  10. package/dist/check-scan.js +29 -2
  11. package/dist/check-scan.js.map +1 -1
  12. package/dist/cli.d.ts.map +1 -1
  13. package/dist/cli.js +14 -5
  14. package/dist/cli.js.map +1 -1
  15. package/dist/command-catalog.d.ts +14 -1
  16. package/dist/command-catalog.d.ts.map +1 -1
  17. package/dist/command-catalog.js +93 -0
  18. package/dist/command-catalog.js.map +1 -1
  19. package/dist/doctor.d.ts +9 -1
  20. package/dist/doctor.d.ts.map +1 -1
  21. package/dist/doctor.js +52 -0
  22. package/dist/doctor.js.map +1 -1
  23. package/dist/fix-recipes.d.ts.map +1 -1
  24. package/dist/fix-recipes.js +27 -0
  25. package/dist/fix-recipes.js.map +1 -1
  26. package/dist/frontend-guidance.d.ts +1 -1
  27. package/dist/frontend-guidance.d.ts.map +1 -1
  28. package/dist/frontend-guidance.js +17 -8
  29. package/dist/frontend-guidance.js.map +1 -1
  30. package/dist/introspect.js +1 -1
  31. package/dist/introspect.js.map +1 -1
  32. package/dist/load.d.ts +4 -1
  33. package/dist/load.d.ts.map +1 -1
  34. package/dist/load.js +8 -0
  35. package/dist/load.js.map +1 -1
  36. package/dist/mcp-exec.d.ts.map +1 -1
  37. package/dist/mcp-exec.js +57 -3
  38. package/dist/mcp-exec.js.map +1 -1
  39. package/dist/mcp-http.d.ts +2 -1
  40. package/dist/mcp-http.d.ts.map +1 -1
  41. package/dist/mcp-http.js +3 -2
  42. package/dist/mcp-http.js.map +1 -1
  43. package/dist/mcp-tool-meta.d.ts +21 -0
  44. package/dist/mcp-tool-meta.d.ts.map +1 -0
  45. package/dist/mcp-tool-meta.js +246 -0
  46. package/dist/mcp-tool-meta.js.map +1 -0
  47. package/dist/mcp.d.ts +3 -2
  48. package/dist/mcp.d.ts.map +1 -1
  49. package/dist/mcp.js +36 -98
  50. package/dist/mcp.js.map +1 -1
  51. package/dist/output-schemas.d.ts +8 -0
  52. package/dist/output-schemas.d.ts.map +1 -1
  53. package/dist/output-schemas.js +14 -0
  54. package/dist/output-schemas.js.map +1 -1
  55. package/dist/ppr-read-fix.d.ts +8 -0
  56. package/dist/ppr-read-fix.d.ts.map +1 -0
  57. package/dist/ppr-read-fix.js +356 -0
  58. package/dist/ppr-read-fix.js.map +1 -0
  59. package/dist/recipes/5.6.0.d.ts +10 -0
  60. package/dist/recipes/5.6.0.d.ts.map +1 -0
  61. package/dist/recipes/5.6.0.js +68 -0
  62. package/dist/recipes/5.6.0.js.map +1 -0
  63. package/dist/recipes/index.d.ts.map +1 -1
  64. package/dist/recipes/index.js +2 -0
  65. package/dist/recipes/index.js.map +1 -1
  66. package/dist/review.d.ts.map +1 -1
  67. package/dist/review.js +7 -2
  68. package/dist/review.js.map +1 -1
  69. package/dist/rules/codes.d.ts +8 -3
  70. package/dist/rules/codes.d.ts.map +1 -1
  71. package/dist/rules/codes.js +9 -4
  72. package/dist/rules/codes.js.map +1 -1
  73. package/dist/rules/explanations.d.ts.map +1 -1
  74. package/dist/rules/explanations.js +39 -13
  75. package/dist/rules/explanations.js.map +1 -1
  76. package/dist/rules/islands.d.ts +91 -0
  77. package/dist/rules/islands.d.ts.map +1 -1
  78. package/dist/rules/islands.js +757 -3
  79. package/dist/rules/islands.js.map +1 -1
  80. package/dist/rules/ppr.d.ts +16 -0
  81. package/dist/rules/ppr.d.ts.map +1 -0
  82. package/dist/rules/ppr.js +114 -0
  83. package/dist/rules/ppr.js.map +1 -0
  84. package/dist/rules/swap.d.ts +7 -0
  85. package/dist/rules/swap.d.ts.map +1 -0
  86. package/dist/rules/swap.js +338 -0
  87. package/dist/rules/swap.js.map +1 -0
  88. package/dist/scaffold-hole.d.ts +105 -0
  89. package/dist/scaffold-hole.d.ts.map +1 -0
  90. package/dist/scaffold-hole.js +688 -0
  91. package/dist/scaffold-hole.js.map +1 -0
  92. package/dist/scaffold.d.ts +5 -3
  93. package/dist/scaffold.d.ts.map +1 -1
  94. package/dist/scaffold.js +56 -46
  95. package/dist/scaffold.js.map +1 -1
  96. package/dist/verification-plan.d.ts.map +1 -1
  97. package/dist/verification-plan.js +12 -1
  98. package/dist/verification-plan.js.map +1 -1
  99. package/dist/web-app-options.d.ts +1 -1
  100. package/dist/web-app-options.d.ts.map +1 -1
  101. package/dist/web-app-options.js.map +1 -1
  102. package/docs/examples.json +63 -9
  103. package/docs/llms-full.txt +2060 -430
  104. package/docs/types.json +1300 -270
  105. package/package.json +11 -11
  106. package/src/cdn-check.ts +21 -7
  107. package/src/check-diagnostics.ts +5 -3
  108. package/src/check-scan.ts +34 -3
  109. package/src/cli.ts +14 -5
  110. package/src/command-catalog.ts +126 -0
  111. package/src/doctor.ts +44 -1
  112. package/src/fix-recipes.ts +28 -0
  113. package/src/frontend-guidance.ts +20 -8
  114. package/src/introspect.ts +1 -1
  115. package/src/load.ts +13 -0
  116. package/src/mcp-exec.ts +74 -3
  117. package/src/mcp-http.ts +3 -2
  118. package/src/mcp-tool-meta.ts +268 -0
  119. package/src/mcp.ts +35 -99
  120. package/src/output-schemas.ts +28 -0
  121. package/src/ppr-read-fix.ts +426 -0
  122. package/src/recipes/5.6.0.ts +69 -0
  123. package/src/recipes/index.ts +2 -0
  124. package/src/review.ts +7 -2
  125. package/src/rules/codes.ts +9 -4
  126. package/src/rules/explanations.ts +39 -13
  127. package/src/rules/islands.ts +875 -3
  128. package/src/rules/ppr.ts +143 -0
  129. package/src/rules/swap.ts +402 -0
  130. package/src/scaffold-hole.ts +880 -0
  131. package/src/scaffold.ts +60 -49
  132. package/src/verification-plan.ts +20 -1
  133. package/src/web-app-options.ts +1 -0
  134. package/dist/rules/nano.d.ts +0 -6
  135. package/dist/rules/nano.d.ts.map +0 -1
  136. package/dist/rules/nano.js +0 -273
  137. package/dist/rules/nano.js.map +0 -1
  138. package/src/rules/nano.ts +0 -307
package/src/load.ts CHANGED
@@ -119,6 +119,9 @@ export interface NifraFramework {
119
119
  /** Which pages and files each host serves, from `createHostPolicy()`: checked before the app's
120
120
  * static files, mounts and pages. See `createWebApp`'s `hostPolicy`. */
121
121
  readonly hostPolicy?: CreateWebAppOptions["hostPolicy"]
122
+ /** Live data refresh, the runtime `live()` from `@nifrajs/web/live` returns: the app serves its
123
+ * endpoints and the client entry keeps what is on screen fresh, in `nifra dev` and in the build. */
124
+ readonly live?: CreateWebAppOptions["live"]
122
125
  }
123
126
 
124
127
  /** The {@link NifraFramework} fields forwarded to `createWebApp` and imported by the generated server
@@ -132,6 +135,7 @@ export const FRAMEWORK_WEB_OPTIONS = [
132
135
  "serverComponents",
133
136
  "i18n",
134
137
  "hostPolicy",
138
+ "live",
135
139
  ] as const
136
140
  export type FrameworkWebOption = (typeof FRAMEWORK_WEB_OPTIONS)[number]
137
141
 
@@ -187,6 +191,15 @@ function assertFrameworkWebOptions(fw: Partial<NifraFramework>, configFile: stri
187
191
  ) {
188
192
  wrong("hostPolicy", "the policy createHostPolicy() from @nifrajs/web returns")
189
193
  }
194
+ if (
195
+ fw.live !== undefined &&
196
+ (typeof fw.live !== "object" ||
197
+ fw.live === null ||
198
+ typeof fw.live.publish !== "function" ||
199
+ typeof fw.live.clientEntry !== "object")
200
+ ) {
201
+ wrong("live", "the runtime live() from @nifrajs/web/live returns")
202
+ }
190
203
  if (fw.publicEnvPrefix !== undefined && typeof fw.publicEnvPrefix !== "string") {
191
204
  wrong("publicEnvPrefix", 'a string such as "PUBLIC_", or "" to expose no environment variable')
192
205
  }
package/src/mcp-exec.ts CHANGED
@@ -49,6 +49,7 @@ import {
49
49
  } from "./mcp-io.ts"
50
50
  import { mcpProjectPathError, resolveMcpProjectPath } from "./mcp-path.ts"
51
51
  import type { McpTool, McpToolContext } from "./mcp-protocol.ts"
52
+ import { withToolMeta } from "./mcp-tool-meta.ts"
52
53
  import { loadTypesCorpus } from "./types-search.ts"
53
54
 
54
55
  const CODEFRAME_SOURCE = /\.(?:[cm]?[jt]sx?|vue|svelte|astro|mdx)$/i
@@ -617,23 +618,93 @@ export function projectTools(
617
618
  description:
618
619
  "When true, create both files if a verified ready-to-write page stub exists. Refuses overwrite.",
619
620
  },
621
+ hole: {
622
+ type: "object",
623
+ description:
624
+ "Add a partially prerendered hole to the existing route at `path` instead of a new page: its definition and <Hole> in the page, its loader in the backend half. The route's backend half must export shellLoader. A Vue or Svelte page gets the snippet to paste.",
625
+ properties: {
626
+ name: {
627
+ type: "string",
628
+ description:
629
+ "1 to 32 lowercase letters, digits and single hyphens, starting with a letter.",
630
+ },
631
+ shared: {
632
+ type: "boolean",
633
+ description: "The same for every visitor, cached on its own revalidate.",
634
+ },
635
+ interactive: {
636
+ type: "boolean",
637
+ description: "Ships its props and hydrates as its own root.",
638
+ },
639
+ timeout: {
640
+ type: "integer",
641
+ description: "The hole's deadline in milliseconds, 1 to 30000.",
642
+ },
643
+ server: {
644
+ type: "boolean",
645
+ description: "Show a React server component, built by the coordinated compiler.",
646
+ },
647
+ },
648
+ required: ["name"],
649
+ additionalProperties: false,
650
+ },
620
651
  variant: {
621
652
  type: "string",
622
653
  enum: ["default", "stateful"],
623
654
  description:
624
- 'Stub flavour. "default" is the plain page stub. "stateful" (vanilla only) emits the golden nano pattern - explicit reactivity (signal + computed(fn,[deps]) + keyed bindList + collected cleanups) whose three mistakes NF-C021/C022/C023 catch statically. Use it for a small app with local state (a list a human edits) instead of reaching for a framework.',
655
+ 'Stub flavour. "default" is the plain page stub. "stateful" (vanilla only) emits a reactive island - bindIsland state, data-bind-* markup and a keyed bindList - whose binding names, binding hosts and list keys NF-C047/C048/C022 check statically. Use it for a small app with local state (a list a human edits) instead of reaching for a framework.',
625
656
  },
626
657
  },
627
658
  required: ["path"],
628
659
  additionalProperties: false,
629
660
  },
630
661
  handler: async (args) => {
631
- const { path, write, variant } = args as {
662
+ const { path, write, variant, hole } = args as {
632
663
  path?: string
633
664
  write?: boolean
665
+ hole?: {
666
+ name?: string
667
+ shared?: boolean
668
+ interactive?: boolean
669
+ timeout?: number
670
+ server?: boolean
671
+ }
634
672
  variant?: "default" | "stateful"
635
673
  }
636
674
  if (typeof path !== "string" || path.length === 0) return "scaffold: `path` is required."
675
+ if (hole !== undefined) {
676
+ if (typeof hole.name !== "string") return "scaffold: `hole.name` is required."
677
+ const { frameworkFromClientModule } = await import("./scaffold.ts")
678
+ const { holeRouteFiles, renderHoleScaffold, routeTypeScript, scaffoldHole } =
679
+ await import("./scaffold-hole.ts")
680
+ const framework = frameworkFromClientModule(
681
+ (await loadAppCached()).framework.clientModule,
682
+ )
683
+ const { page, backend } = holeRouteFiles(path, framework)
684
+ const loaded = await routeTypeScript(cwd, [page, backend])
685
+ if (loaded.unsupported !== undefined) return loaded.unsupported.message
686
+ if (loaded.compiler === undefined)
687
+ return "scaffold: a hole is placed through the route's syntax tree, so it needs TypeScript (`bun add -d typescript`)."
688
+ try {
689
+ const result = await scaffoldHole(
690
+ cwd,
691
+ path,
692
+ hole.name,
693
+ framework,
694
+ {
695
+ shared: hole.shared,
696
+ interactive: hole.interactive,
697
+ timeout: hole.timeout,
698
+ server: hole.server,
699
+ },
700
+ loaded.compiler,
701
+ write === true,
702
+ )
703
+ return renderHoleScaffold(hole.name, framework, result)
704
+ } finally {
705
+ await loaded.session?.close()
706
+ }
707
+ }
637
708
  const flavour = variant === "stateful" ? "stateful" : "default"
638
709
  const { frameworkFromClientModule, renderScaffold, writeScaffoldRoute } = await import(
639
710
  "./scaffold.ts"
@@ -676,7 +747,7 @@ export function projectTools(
676
747
  },
677
748
  },
678
749
  ]
679
- return [...catalogTools, ...legacyTools]
750
+ return [...catalogTools, ...legacyTools].map(withToolMeta)
680
751
  }
681
752
 
682
753
  function childPath(name: "mcp-run" | "mcp-render" | "mcp-ws"): string {
package/src/mcp-http.ts CHANGED
@@ -1,6 +1,7 @@
1
1
  /**
2
2
  * The PUBLIC nifra docs MCP - Streamable-HTTP transport exposing the project-INDEPENDENT tools
3
- * (`nifra_docs`, `nifra_example`, `nifra_types`, `nifra_learn` + the `nifra_gallery` MCP Apps widget)
3
+ * (`nifra_docs`, `nifra_example`, `nifra_types`, `nifra_learn`, `nifra_frontend` + the `nifra_gallery`
4
+ * MCP Apps widget)
4
5
  * so any remote AI agent can learn nifra without a local checkout. They read the bundled corpus
5
6
  * (llms-full.txt / examples.json / types.json shipped in this package) and ignore `cwd`, so they reuse the
6
7
  * exact definitions from {@link projectTools} - one source, no drift.
@@ -29,7 +30,7 @@ export { docsTools } from "./mcp-docs-tools.ts"
29
30
  export type { TypeEntry } from "./types-search.ts"
30
31
 
31
32
  // Kept in lockstep with packages/cli/package.json by check:publish's version-consistency gate.
32
- const VERSION = "5.5.1"
33
+ const VERSION = "5.6.0"
33
34
  const SERVER_INFO = { name: "nifra-docs", version: VERSION }
34
35
  // Derive the GET/health tool list from the tools actually served, so the line can never drift from them.
35
36
  const docsHealth = (tools: McpTool[]): string =>
@@ -0,0 +1,268 @@
1
+ /**
2
+ * What each `nifra mcp` project tool may do, as MCP tool annotations, and a description for each
3
+ * input field its definition leaves bare. A host reads the annotations to decide which calls need
4
+ * the user's confirmation, so a tool that can write a file or run project code must never look
5
+ * read-only. Importing the project's config or backend runs its top-level code, so a tool that
6
+ * imports either runs project code. The hints describe the tool for any input: a tool that writes
7
+ * only under a flag is a writer. mcp-tool-meta.test.ts fails on a tool or a field missing here, and
8
+ * on a read-only tool that imports the project.
9
+ */
10
+ import type { McpTool, McpToolAnnotations } from "./mcp-protocol.ts"
11
+
12
+ const READ: McpToolAnnotations = {
13
+ readOnlyHint: true,
14
+ destructiveHint: false,
15
+ idempotentHint: true,
16
+ openWorldHint: false,
17
+ }
18
+ // Writes or overwrites project files, at least for some inputs.
19
+ const WRITE: McpToolAnnotations = {
20
+ readOnlyHint: false,
21
+ destructiveHint: true,
22
+ idempotentHint: true,
23
+ openWorldHint: false,
24
+ }
25
+ // Runs project code, tests, builds or scripts, which can do anything that code does.
26
+ const EXECUTE: McpToolAnnotations = {
27
+ readOnlyHint: false,
28
+ destructiveHint: true,
29
+ idempotentHint: false,
30
+ openWorldHint: true,
31
+ }
32
+
33
+ const DIR = "Project subdirectory to run in, relative to the project root this server serves."
34
+ const JSON_RESULT = "Return the structured JSON result instead of the human-readable report."
35
+ const CONFIG = "Config file to read instead of the project's default nifra.config.ts."
36
+ const TARGET = "Deploy target to judge against (bun, node, deno, cloudflare, vercel)."
37
+
38
+ interface ToolMeta {
39
+ readonly annotations: McpToolAnnotations
40
+ readonly fields?: Readonly<Record<string, string>>
41
+ }
42
+
43
+ /** Every project tool by name. The docs tools set their own annotations and are not repeated. */
44
+ export const PROJECT_TOOL_META: Readonly<Record<string, ToolMeta>> = {
45
+ nifra_check: {
46
+ annotations: READ,
47
+ fields: {
48
+ lintsOnly: "Skip tsc and run only the source lints, a near-instant pass.",
49
+ json: JSON_RESULT,
50
+ sarif: "Return the diagnostics as a SARIF 2.1.0 log.",
51
+ maxDiagnostics: "Return at most this many diagnostics.",
52
+ dir: DIR,
53
+ },
54
+ },
55
+ nifra_review: {
56
+ annotations: WRITE,
57
+ fields: {
58
+ strict: "Treat warnings as blocking.",
59
+ diff: "Review only the files changed since this git ref, instead of the whole project.",
60
+ sarif: "Also write the findings as SARIF 2.1.0 to this project-relative file.",
61
+ fix: "Plan the registered recipes for the findings.",
62
+ dryRun: "With fix: show the planned edits without writing them.",
63
+ write: "With fix: apply the planned edits to the project's files.",
64
+ json: JSON_RESULT,
65
+ },
66
+ },
67
+ nifra_assure: {
68
+ annotations: EXECUTE,
69
+ fields: {
70
+ config: CONFIG,
71
+ bundle: "Build the deploy bundle and verify the routes it serves, not only the source.",
72
+ strict: "Fail on a route whose evidence is a skip (implies bundle).",
73
+ hydration: "Also check that every page hydrates without errors (implies bundle).",
74
+ interact: "Also click through each page in a browser (implies bundle).",
75
+ out: "Write the assurance bundle to this project-relative file (implies bundle).",
76
+ json: JSON_RESULT,
77
+ dir: DIR,
78
+ },
79
+ },
80
+ nifra_levels: {
81
+ annotations: EXECUTE,
82
+ fields: {
83
+ config: CONFIG,
84
+ seed: "Deterministic seed for the L4 invariant run. Default 1.",
85
+ min: "Fail when the project is below this level (0 to 4).",
86
+ json: JSON_RESULT,
87
+ dir: DIR,
88
+ },
89
+ },
90
+ nifra_capabilities: {
91
+ annotations: WRITE,
92
+ fields: {
93
+ action:
94
+ "snapshot writes the capability lockfile, check compares the project with it, explain describes one route.",
95
+ config: CONFIG,
96
+ out: "snapshot: the project-relative lockfile to write.",
97
+ lockfile: "check: the project-relative lockfile to compare against.",
98
+ method: "explain: the route's HTTP method.",
99
+ path: "explain: the route's path.",
100
+ json: JSON_RESULT,
101
+ dir: DIR,
102
+ },
103
+ },
104
+ nifra_manifest: {
105
+ annotations: WRITE,
106
+ fields: {
107
+ action: "emit writes the route trust manifest, diff compares two manifests.",
108
+ config: CONFIG,
109
+ out: "emit: the project-relative file to write.",
110
+ before: "diff: the project-relative manifest to compare from.",
111
+ after: "diff: the project-relative manifest to compare to.",
112
+ json: JSON_RESULT,
113
+ dir: DIR,
114
+ },
115
+ },
116
+ nifra_routes: {
117
+ annotations: EXECUTE,
118
+ fields: {
119
+ json: JSON_RESULT,
120
+ graph: "Render the public route surface as a Mermaid graph.",
121
+ modes: "Show each page route's render mode (static, isr, ssr), hydration and cache policy.",
122
+ hooks: "List the hooks each backend route and each prefix's unmatched paths run.",
123
+ since: "hooks: a project-relative saved hooks report to diff against.",
124
+ target: `modes: ${TARGET}`,
125
+ dir: DIR,
126
+ },
127
+ },
128
+ nifra_context: {
129
+ annotations: EXECUTE,
130
+ fields: {
131
+ path: "Only the routes whose path starts with this.",
132
+ kind: "Only the API routes or only the page routes.",
133
+ dir: DIR,
134
+ },
135
+ },
136
+ nifra_doctor: {
137
+ annotations: WRITE,
138
+ fields: {
139
+ json: JSON_RESULT,
140
+ autoFix: "Write the safe local-version dependency fixes to package.json.",
141
+ strict: "Fail when an applicable production-readiness guarantee is absent.",
142
+ target: TARGET,
143
+ dir: DIR,
144
+ },
145
+ },
146
+ nifra_fix: {
147
+ annotations: WRITE,
148
+ fields: {
149
+ code: "Apply only the recipe for this diagnostic code (for example NF-C007).",
150
+ json: JSON_RESULT,
151
+ dir: DIR,
152
+ },
153
+ },
154
+ nifra_snapshot: {
155
+ annotations: WRITE,
156
+ fields: {
157
+ out: "The project-relative file to write. Default api-snapshot.json.",
158
+ json: JSON_RESULT,
159
+ dir: DIR,
160
+ },
161
+ },
162
+ nifra_diff: {
163
+ annotations: EXECUTE,
164
+ fields: {
165
+ baseline: "The project-relative snapshot to compare with. Default api-snapshot.json.",
166
+ json: JSON_RESULT,
167
+ dir: DIR,
168
+ },
169
+ },
170
+ nifra_contracts: {
171
+ annotations: WRITE,
172
+ fields: {
173
+ action: "snapshot writes contracts.lock.json, check compares the routes with it.",
174
+ out: "snapshot: the project-relative lock file to write.",
175
+ json: JSON_RESULT,
176
+ dir: DIR,
177
+ },
178
+ },
179
+ nifra_sync_manifest: { annotations: WRITE, fields: { json: JSON_RESULT, dir: DIR } },
180
+ nifra_sync_routes: { annotations: WRITE, fields: { json: JSON_RESULT, dir: DIR } },
181
+ nifra_prove: {
182
+ annotations: EXECUTE,
183
+ fields: {
184
+ files: "The changed files to plan proofs for, project-relative.",
185
+ minLevel: "The verification level (0 to 4) the stop condition requires.",
186
+ json: JSON_RESULT,
187
+ dir: DIR,
188
+ },
189
+ },
190
+ nifra_replay: {
191
+ annotations: EXECUTE,
192
+ fields: { file: "The project-relative verification metadata file to replay.", dir: DIR },
193
+ },
194
+ nifra_smoke: {
195
+ annotations: EXECUTE,
196
+ fields: {
197
+ fixture: "The project-relative smoke fixture. Default nifra.smoke.ts.",
198
+ inProcess: "Run against the app in this process instead of a started production server.",
199
+ json: JSON_RESULT,
200
+ dir: DIR,
201
+ },
202
+ },
203
+ nifra_port: {
204
+ annotations: READ,
205
+ fields: {
206
+ target: `${TARGET} Fails when a used feature is unsupported there.`,
207
+ json: JSON_RESULT,
208
+ ci: "Fail when a used feature is unsupported on the target.",
209
+ strict: "Also fail on a feature the target supports only with a caveat.",
210
+ dir: DIR,
211
+ },
212
+ },
213
+ nifra_errors: { annotations: READ, fields: { json: JSON_RESULT } },
214
+ nifra_logs: {
215
+ annotations: READ,
216
+ fields: {
217
+ json: JSON_RESULT,
218
+ level: "Only lines at these levels.",
219
+ source: "Only the server's or only the browser's lines.",
220
+ },
221
+ },
222
+ nifra_db_schema: { annotations: EXECUTE, fields: { json: JSON_RESULT } },
223
+ nifra_db_query: { annotations: EXECUTE, fields: { json: JSON_RESULT } },
224
+ nifra_db_role: { annotations: EXECUTE, fields: { json: JSON_RESULT } },
225
+ nifra_verify: { annotations: EXECUTE },
226
+ nifra_contract_proof: { annotations: READ },
227
+ nifra_explain: { annotations: READ },
228
+ nifra_inspect: { annotations: READ },
229
+ nifra_openapi: { annotations: EXECUTE },
230
+ nifra_run: {
231
+ annotations: EXECUTE,
232
+ fields: {
233
+ requests:
234
+ "The requests to run, in order: each a path, with an optional method, headers and JSON body.",
235
+ },
236
+ },
237
+ nifra_render: {
238
+ annotations: EXECUTE,
239
+ fields: { requests: "The pages to render, in order: each a path, with optional headers." },
240
+ },
241
+ nifra_ws: { annotations: EXECUTE },
242
+ nifra_test: { annotations: EXECUTE },
243
+ nifra_scaffold: { annotations: WRITE },
244
+ nifra_hydrate: { annotations: EXECUTE },
245
+ }
246
+
247
+ /** `tool` with its annotations and field descriptions from {@link PROJECT_TOOL_META}. A tool that
248
+ * sets annotations itself keeps them, and so does a field that has a description. */
249
+ export function withToolMeta(tool: McpTool): McpTool {
250
+ const meta = PROJECT_TOOL_META[tool.name]
251
+ if (meta === undefined) return tool
252
+ const annotated = { ...tool, annotations: tool.annotations ?? meta.annotations }
253
+ const fields = meta.fields
254
+ const properties = tool.inputSchema.properties
255
+ if (fields === undefined || !isRecord(properties)) return annotated
256
+ const described = Object.fromEntries(
257
+ Object.entries(properties).map(([name, property]) => {
258
+ const description = fields[name]
259
+ return description === undefined || !isRecord(property) || "description" in property
260
+ ? [name, property]
261
+ : [name, { ...property, description }]
262
+ }),
263
+ )
264
+ return { ...annotated, inputSchema: { ...tool.inputSchema, properties: described } }
265
+ }
266
+
267
+ const isRecord = (value: unknown): value is Readonly<Record<string, unknown>> =>
268
+ typeof value === "object" && value !== null
package/src/mcp.ts CHANGED
@@ -40,8 +40,9 @@
40
40
  * handed to that CLI; when that is impossible the version-sensitive tools refuse rather than answer
41
41
  * for the wrong release (see `./mcp-delegate.ts`). The protocol is hand-rolled (newline-delimited JSON-RPC 2.0 over stdio), including
42
42
  * standard MCP progress notifications and request cancellation - no SDK dependency, the same
43
- * minimal-surface choice as the rest of nifra. The pure dispatch lives in `./mcp-protocol.ts`; this
44
- * module is the I/O shell (stdin loop, tool wiring, the run subprocess).
43
+ * minimal-surface choice as the rest of nifra. The pure dispatch lives in `./mcp-protocol.ts` and the
44
+ * stdio framing in `@nifrajs/mcp/stdio`; this module is the dispatch shell (roots, tool wiring, the run
45
+ * subprocess).
45
46
  *
46
47
  * This process runs no project code and holds none of the project's `.env`: the config, the backend
47
48
  * and everything they import run in a fresh subprocess per call (`./mcp-isolate.ts`), and a session
@@ -50,6 +51,7 @@
50
51
 
51
52
  import { stat } from "node:fs/promises"
52
53
  import { resolve } from "node:path"
54
+ import { runStdioTransport, type StdioConnection } from "@nifrajs/mcp/stdio"
53
55
  import { loadDocsCorpus } from "./docs-search.ts"
54
56
  import { loadExamplesCorpus } from "./examples.ts"
55
57
  import type { AppLoader } from "./load.ts"
@@ -59,9 +61,6 @@ import { docsTools } from "./mcp-docs-tools.ts"
59
61
  import {
60
62
  createMcpProtocolState,
61
63
  handleRpc,
62
- isJsonRpcRequest,
63
- isJsonRpcResponse,
64
- type JsonRpcNotification,
65
64
  type JsonRpcRequest,
66
65
  type JsonRpcResponse,
67
66
  type McpPrompt,
@@ -188,8 +187,6 @@ const ANSWERED_WITHOUT_THE_APP: ReadonlySet<string> = new Set([
188
187
  "notifications/initialized",
189
188
  "notifications/roots/list_changed",
190
189
  ])
191
- const MAX_STDIO_MESSAGE_BYTES = 8 * 1024 * 1024
192
- const STDIO_ENCODER = new TextEncoder()
193
190
 
194
191
  interface ProjectApp {
195
192
  readonly name: string
@@ -268,29 +265,12 @@ export async function runMcpServer(
268
265
  let drift: ToolingDrift | undefined = await detectToolingDrift(rootState.root, version)
269
266
  const serverInfo = { name: "nifra", version }
270
267
  const state = createMcpProtocolState()
271
- const send = (message: JsonRpcResponse | JsonRpcNotification): void => {
272
- let encoded: string
273
- try {
274
- encoded = JSON.stringify(message)
275
- } catch {
276
- encoded = JSON.stringify(
277
- rpcError(responseIdOf(message), -32603, "MCP response is not serializable"),
278
- )
279
- }
280
- if (STDIO_ENCODER.encode(encoded).byteLength > MAX_STDIO_MESSAGE_BYTES)
281
- encoded = JSON.stringify(
282
- rpcError(responseIdOf(message), -32603, "MCP response exceeded the size limit"),
283
- )
284
- process.stdout.write(`${encoded}\n`)
285
- }
286
268
  let rootsSupported = false
287
269
  let rootsRequestPending = false
288
- const requestRoots = (): void => {
270
+ const requestRoots = (connection: StdioConnection): void => {
289
271
  if (!rootsSupported || rootsRequestPending) return
290
272
  rootsRequestPending = true
291
- process.stdout.write(
292
- `${JSON.stringify({ jsonrpc: "2.0", id: ROOTS_REQUEST_ID, method: "roots/list" })}\n`,
293
- )
273
+ connection.send({ jsonrpc: "2.0", id: ROOTS_REQUEST_ID, method: "roots/list" })
294
274
  }
295
275
  const onRootsAnswer = async (message: JsonRpcResponse): Promise<void> => {
296
276
  const result = "result" in message ? message.result : undefined
@@ -310,15 +290,20 @@ export async function runMcpServer(
310
290
  // must see the adopted root, even though dispatches themselves run concurrently.
311
291
  let rootsUpdate: Promise<void> = Promise.resolve()
312
292
 
313
- const dispatchRootsAnswer = (message: JsonRpcResponse): void => {
293
+ const dispatchRootsAnswer = (message: JsonRpcResponse): boolean => {
314
294
  // The roots answer is a response to a request initiated by this server, not a client RPC request.
315
295
  // Serialize adoption with normal dispatch so a following request cannot observe a half-updated root.
316
- if (!rootsRequestPending) return
296
+ if (message.id !== ROOTS_REQUEST_ID) return false
297
+ if (!rootsRequestPending) return true
317
298
  rootsRequestPending = false
318
299
  rootsUpdate = onRootsAnswer(message).catch(() => {})
300
+ return true
319
301
  }
320
302
 
321
- const dispatch = async (message: JsonRpcRequest): Promise<void> => {
303
+ const dispatch = async (
304
+ message: JsonRpcRequest,
305
+ connection: StdioConnection,
306
+ ): Promise<JsonRpcResponse | null> => {
322
307
  await rootsUpdate
323
308
  if (message.method === "initialize") {
324
309
  rootsSupported = clientSupportsRoots(message.params)
@@ -338,13 +323,12 @@ export async function runMcpServer(
338
323
  prompts: projectPrompts(),
339
324
  instructions: rootInstructions(rootState, drift),
340
325
  },
341
- { state, sendNotification: send, exposeToolErrors: true },
326
+ { state, sendNotification: connection.send, exposeToolErrors: true },
342
327
  )
343
- if (response) send(response)
344
328
  // Ask for the client's workspace roots once the handshake completes, and again whenever the
345
- // client says they changed. The answer comes back through the interception above.
346
- if (method.startsWith("notifications/")) requestRoots()
347
- return
329
+ // client says they changed. The answer comes back through `dispatchRootsAnswer`.
330
+ if (method.startsWith("notifications/")) requestRoots(connection)
331
+ return response
348
332
  }
349
333
  const project = await ctx
350
334
  let activeTools: McpTool[]
@@ -386,76 +370,28 @@ export async function runMcpServer(
386
370
  ...project.features,
387
371
  instructions: rootInstructions(rootState, drift),
388
372
  }
389
- const response = await handleRpc(message, activeTools, serverInfo, features, {
373
+ return handleRpc(message, activeTools, serverInfo, features, {
390
374
  state,
391
- sendNotification: send,
375
+ sendNotification: connection.send,
392
376
  // The stdio caller is the developer's own agent: a failure it cannot read it cannot fix.
393
377
  exposeToolErrors: true,
394
378
  })
395
- if (response) send(response)
396
379
  }
397
380
 
398
- const decoder = new TextDecoder()
399
- let buffer = ""
400
- let bufferBytes = 0
401
- let discardingOversized = false
402
- const processLine = (rawLine: string): void => {
403
- const line = rawLine.trim()
404
- if (line === "") return
405
- if (STDIO_ENCODER.encode(rawLine).byteLength > MAX_STDIO_MESSAGE_BYTES) {
406
- send(rpcError(null, -32600, "MCP message exceeded the size limit"))
407
- return
408
- }
409
- let parsed: unknown
410
- try {
411
- parsed = JSON.parse(line) as unknown
412
- } catch {
413
- send(rpcError(null, -32700, "parse error"))
414
- return
415
- }
416
- if (isJsonRpcRequest(parsed)) {
417
- void dispatch(parsed).catch((err) => {
418
- const msg = err instanceof Error ? err.message : String(err)
419
- send(rpcError(parsed.id ?? null, -32603, msg))
420
- })
421
- } else if (isJsonRpcResponse(parsed) && parsed.id === ROOTS_REQUEST_ID) {
422
- dispatchRootsAnswer(parsed)
423
- } else {
424
- // Do not let null, arrays, scalars, responses for unknown ids, or malformed envelopes reach the
425
- // dispatch shell. In particular, reading `.id` from a hostile `null` must never crash the loop.
426
- send(rpcError(null, -32600, "Invalid Request"))
427
- }
428
- }
429
- for await (const chunk of Bun.stdin.stream()) {
430
- let text = decoder.decode(chunk as Uint8Array, { stream: true })
431
- if (discardingOversized) {
432
- const newline = text.indexOf("\n")
433
- if (newline === -1) continue
434
- text = text.slice(newline + 1)
435
- discardingOversized = false
436
- }
437
- buffer += text
438
- bufferBytes += STDIO_ENCODER.encode(text).byteLength
439
- let nl = buffer.indexOf("\n")
440
- while (nl !== -1) {
441
- const line = buffer.slice(0, nl)
442
- buffer = buffer.slice(nl + 1)
443
- bufferBytes = Math.max(0, bufferBytes - STDIO_ENCODER.encode(line).byteLength - 1)
444
- nl = buffer.indexOf("\n")
445
- processLine(line)
446
- }
447
- if (bufferBytes > MAX_STDIO_MESSAGE_BYTES) {
448
- buffer = ""
449
- bufferBytes = 0
450
- discardingOversized = true
451
- send(rpcError(null, -32600, "MCP message exceeded the size limit"))
452
- }
381
+ try {
382
+ await runStdioTransport({
383
+ onRequest: async (message, connection) => {
384
+ try {
385
+ return await dispatch(message, connection)
386
+ } catch (err) {
387
+ // Same audience as `exposeToolErrors`: a project that fails to load says why.
388
+ if (message.id === undefined) return null
389
+ return rpcError(message.id, -32603, err instanceof Error ? err.message : String(err))
390
+ }
391
+ },
392
+ onResponse: dispatchRootsAnswer,
393
+ })
394
+ } finally {
395
+ closeWarmWorkers()
453
396
  }
454
- closeWarmWorkers()
455
- }
456
-
457
- function responseIdOf(message: JsonRpcResponse | JsonRpcNotification): string | number | null {
458
- if (!("id" in message)) return null
459
- const id = message.id
460
- return id === null || typeof id === "string" || typeof id === "number" ? id : null
461
397
  }