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