@nifrajs/cli 2.3.0 → 2.4.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 (45) hide show
  1. package/dist/check.d.ts.map +1 -1
  2. package/dist/check.js +4 -1
  3. package/dist/check.js.map +1 -1
  4. package/dist/cli.d.ts.map +1 -1
  5. package/dist/cli.js +17 -4
  6. package/dist/cli.js.map +1 -1
  7. package/dist/doctor.d.ts.map +1 -1
  8. package/dist/doctor.js +4 -0
  9. package/dist/doctor.js.map +1 -1
  10. package/dist/learn.d.ts +32 -0
  11. package/dist/learn.d.ts.map +1 -0
  12. package/dist/learn.js +127 -0
  13. package/dist/learn.js.map +1 -0
  14. package/dist/mcp-app-tool.d.ts +14 -0
  15. package/dist/mcp-app-tool.d.ts.map +1 -0
  16. package/dist/mcp-app-tool.js +80 -0
  17. package/dist/mcp-app-tool.js.map +1 -0
  18. package/dist/mcp-docs-tools.d.ts +1 -1
  19. package/dist/mcp-docs-tools.d.ts.map +1 -1
  20. package/dist/mcp-docs-tools.js +17 -1
  21. package/dist/mcp-docs-tools.js.map +1 -1
  22. package/dist/mcp-http.d.ts +10 -6
  23. package/dist/mcp-http.d.ts.map +1 -1
  24. package/dist/mcp-http.js +26 -12
  25. package/dist/mcp-http.js.map +1 -1
  26. package/dist/mcp.d.ts +14 -0
  27. package/dist/mcp.d.ts.map +1 -1
  28. package/dist/mcp.js +188 -0
  29. package/dist/mcp.js.map +1 -1
  30. package/dist/upgrade.d.ts +13 -2
  31. package/dist/upgrade.d.ts.map +1 -1
  32. package/dist/upgrade.js +105 -7
  33. package/dist/upgrade.js.map +1 -1
  34. package/docs/llms-full.txt +75 -1
  35. package/docs/types.json +162 -11
  36. package/package.json +9 -9
  37. package/src/check.ts +5 -1
  38. package/src/cli.ts +21 -4
  39. package/src/doctor.ts +8 -0
  40. package/src/learn.ts +152 -0
  41. package/src/mcp-app-tool.ts +86 -0
  42. package/src/mcp-docs-tools.ts +18 -1
  43. package/src/mcp-http.ts +27 -14
  44. package/src/mcp.ts +237 -0
  45. package/src/upgrade.ts +125 -7
@@ -0,0 +1,86 @@
1
+ /**
2
+ * The `nifra_examples_app` MCP tool: nifra's verified code examples as an MCP Apps widget. It returns the
3
+ * examples as `structuredContent`, rendered by the {@link examplesWidget} `ui://` widget in MCP Apps hosts
4
+ * (ChatGPT Apps, MCPJam, Goose); text-only hosts still get the example names as plain text. Part of the
5
+ * public docs-MCP tool set (served by `handleMcpHttp`), so every self-host gets it from one definition.
6
+ * `loadExamples` is injected, so the same tool reads the corpus from disk (CLI) or a cached fetch (edge).
7
+ */
8
+ import { defineMcpTool, defineMcpWidget, type McpTool } from "@nifrajs/mcp"
9
+ import type { Example } from "./examples.ts"
10
+
11
+ /** The widget: renders `structuredContent.examples` as a filterable list of example cards. */
12
+ export const examplesWidget = defineMcpWidget({
13
+ uri: "ui://nifra/examples",
14
+ name: "nifra examples",
15
+ description: "Interactive browser of verified, copy-pasteable nifra code examples.",
16
+ head: `<style>
17
+ :root { color-scheme: light dark; font: 14px/1.5 system-ui, sans-serif; }
18
+ body { margin: 0; padding: 16px; }
19
+ h1 { font-size: 16px; margin: 0 0 4px; }
20
+ #q { width: 100%; box-sizing: border-box; padding: 6px 10px; margin: 8px 0 14px; border-radius: 6px; border: 1px solid color-mix(in srgb, currentColor 25%, transparent); background: transparent; color: inherit; font: inherit; }
21
+ .card { border: 1px solid color-mix(in srgb, currentColor 15%, transparent); border-radius: 10px; padding: 10px 12px; margin-bottom: 10px; }
22
+ .topic { font-size: 12px; opacity: .6; }
23
+ .name { font-weight: 600; margin: 2px 0 6px; }
24
+ pre { margin: 0; padding: 8px 10px; border-radius: 6px; background: color-mix(in srgb, currentColor 8%, transparent); overflow-x: auto; font: 12px/1.5 ui-monospace, monospace; }
25
+ </style>`,
26
+ html: `
27
+ <h1>nifra examples</h1>
28
+ <input id="q" placeholder="Filter examples…" />
29
+ <div id="list"></div>
30
+ <script>
31
+ var ALL = [];
32
+ function esc(s){ return String(s).replace(/[&<>]/g, function(c){ return c==="&"?"&amp;":c==="<"?"&lt;":"&gt;"; }); }
33
+ function paint(items){
34
+ document.getElementById("list").innerHTML = items.map(function(e){
35
+ var code = e.code.length > 600 ? e.code.slice(0, 600) + "\\n…" : e.code;
36
+ return "<div class='card'><div class='topic'>" + esc(e.topic) + "</div><div class='name'>" + esc(e.name) +
37
+ "</div><pre>" + esc(code) + "</pre></div>";
38
+ }).join("") || "<p style='opacity:.6'>No matching examples.</p>";
39
+ }
40
+ function render(data){ ALL = (data && data.examples) || []; paint(ALL); }
41
+ mcpApp.onData(render);
42
+ document.getElementById("q").addEventListener("input", function(ev){
43
+ var q = ev.target.value.toLowerCase();
44
+ paint(ALL.filter(function(e){ return (e.topic + e.name + e.slug).toLowerCase().indexOf(q) !== -1; }));
45
+ });
46
+ </script>
47
+ `,
48
+ })
49
+
50
+ /** The widget-backed tool. `loadExamples` is injected (disk on the CLI, cached fetch on the edge). */
51
+ export function examplesAppTool(loadExamples: () => Promise<Example[] | undefined>): McpTool {
52
+ return defineMcpTool({
53
+ name: "nifra_examples_app",
54
+ description:
55
+ "Browse nifra's verified code examples as an interactive, filterable list (MCP Apps widget). Pass query to pre-filter; the widget also filters client-side.",
56
+ inputSchema: {
57
+ type: "object",
58
+ properties: { query: { type: "string", description: "Pre-filter examples by keyword." } },
59
+ additionalProperties: false,
60
+ },
61
+ widget: examplesWidget,
62
+ handler: async (args) => {
63
+ const all = (await loadExamples()) ?? []
64
+ const q = ((args.query as string) ?? "").toLowerCase()
65
+ const matched = (
66
+ q
67
+ ? all.filter((e) => `${e.topic} ${e.name} ${e.slug} ${e.code}`.toLowerCase().includes(q))
68
+ : all
69
+ ).slice(0, 30)
70
+ return {
71
+ text:
72
+ matched.length === 0
73
+ ? "No matching examples."
74
+ : `${matched.length} example(s): ${matched.map((e) => e.name).join(", ")}.`,
75
+ structuredContent: {
76
+ examples: matched.map((e) => ({
77
+ name: e.name,
78
+ topic: e.topic,
79
+ slug: e.slug,
80
+ code: e.code,
81
+ })),
82
+ },
83
+ }
84
+ },
85
+ })
86
+ }
@@ -1,5 +1,5 @@
1
1
  /**
2
- * The two project-INDEPENDENT MCP tools - `nifra_docs` + `nifra_example` - as a single factory shared
2
+ * The project-INDEPENDENT MCP tools - `nifra_docs`, `nifra_example`, `nifra_types`, `nifra_learn` - as a single factory shared
3
3
  * by every transport: the project stdio server ({@link projectTools}), the CLI HTTP server
4
4
  * (`nifra docs-mcp`), and the site's Cloudflare-Pages worker (`/mcp`). The corpus source is injected as
5
5
  * loaders, so the SAME tool definitions work whether the corpus comes from disk (`Bun.file`, on the
@@ -9,6 +9,7 @@
9
9
 
10
10
  import { renderDocsResult } from "./docs-search.ts"
11
11
  import { type Example, renderExamplesResult } from "./examples.ts"
12
+ import { renderLearnResult } from "./learn.ts"
12
13
  import type { McpTool } from "./mcp-protocol.ts"
13
14
  import { renderTypesResult, type TypeEntry } from "./types-search.ts"
14
15
 
@@ -113,5 +114,21 @@ export function docsTools(
113
114
  return renderTypesResult(corpus, name, query, clamp(limit, 1, 8, 5), full === true)
114
115
  },
115
116
  },
117
+ {
118
+ name: "nifra_learn",
119
+ description:
120
+ "Walk the guided path to build a nifra app end to end - an ORDERED sequence (create → page route → loader → typed API → typed client → auth → background jobs → deploy), not the random-access search of nifra_docs/nifra_example. Call with no args for the step index; pass `step: N` for that step's goal, how to do it (which tool emits the correct artifact), and how to verify it. Use it when scaffolding a new app or learning nifra's flow - each step composes the other nifra_* tools.",
121
+ inputSchema: {
122
+ type: "object",
123
+ properties: {
124
+ step: {
125
+ type: "number",
126
+ description: "1-based step number to expand (omit for the index).",
127
+ },
128
+ },
129
+ additionalProperties: false,
130
+ },
131
+ handler: async (args) => renderLearnResult((args as { step?: number }).step),
132
+ },
116
133
  ]
117
134
  }
package/src/mcp-http.ts CHANGED
@@ -1,8 +1,9 @@
1
1
  /**
2
2
  * The PUBLIC nifra docs MCP - Streamable-HTTP transport exposing the project-INDEPENDENT tools
3
- * (`nifra_docs` + `nifra_example`) so any remote AI agent can learn nifra without a local checkout.
4
- * Both tools read the bundled corpus (llms-full.txt / examples.json shipped in this package) and ignore
5
- * `cwd`, so they reuse the exact definitions from {@link projectTools} - one source, no drift.
3
+ * (`nifra_docs`, `nifra_example`, `nifra_types`, `nifra_learn` + the `nifra_examples_app` MCP Apps widget)
4
+ * so any remote AI agent can learn nifra without a local checkout. They read the bundled corpus
5
+ * (llms-full.txt / examples.json / types.json shipped in this package) and ignore `cwd`, so they reuse the
6
+ * exact definitions from {@link projectTools} - one source, no drift.
6
7
  *
7
8
  * The transport itself (body cap, CORS, JSON-RPC dispatch) lives in `@nifrajs/mcp/http`; this module is
8
9
  * the docs-specific layer over it: it supplies the bundled corpus tools and the `nifra-docs` server info.
@@ -12,28 +13,37 @@
12
13
  */
13
14
 
14
15
  import { type McpHttpOptions, respondMcpHttp as respondMcpHttpCore } from "@nifrajs/mcp/http"
15
- import type { McpTool } from "@nifrajs/mcp/protocol"
16
+ import { type McpTool, UI_MIME } from "@nifrajs/mcp/protocol"
16
17
  import { loadDocsCorpus } from "./docs-search.ts"
17
18
  import { loadExamplesCorpus } from "./examples.ts"
19
+ import { examplesAppTool, examplesWidget } from "./mcp-app-tool.ts"
18
20
  import { docsTools } from "./mcp-docs-tools.ts"
19
21
  import { loadTypesCorpus } from "./types-search.ts"
20
22
 
21
23
  export type { McpHttpOptions } from "@nifrajs/mcp/http"
22
24
  export type { Example } from "./examples.ts"
23
- // Re-exported so a self-host (e.g. a Cloudflare-Pages `/mcp` worker route) gets the corpus-injectable
24
- // tool factory + the transport core from one entry: `import { respondMcpHttp, docsTools } from "@nifrajs/cli/mcp"`.
25
+ // Re-exported so a self-host gets the corpus-injectable tool factories + the transport core from one
26
+ // entry: `import { respondMcpHttp, docsTools, examplesAppTool } from "@nifrajs/cli/mcp"`.
27
+ export { examplesAppTool, examplesWidget } from "./mcp-app-tool.ts"
25
28
  export { docsTools } from "./mcp-docs-tools.ts"
26
29
  export type { TypeEntry } from "./types-search.ts"
27
30
 
28
31
  // Kept in lockstep with packages/cli/package.json by check:publish's version-consistency gate.
29
- const VERSION = "2.3.0"
32
+ const VERSION = "2.4.0"
30
33
  const SERVER_INFO = { name: "nifra-docs", version: VERSION }
31
- const DOCS_HEALTH =
32
- "nifra docs MCP - POST JSON-RPC 2.0 here (methods: initialize, tools/list, tools/call). Tools: nifra_docs, nifra_example."
34
+ // Derive the GET/health tool list from the tools actually served, so the line can never drift from them.
35
+ const docsHealth = (tools: McpTool[]): string =>
36
+ `nifra docs MCP - POST JSON-RPC 2.0 here (methods: initialize, tools/list, tools/call). Tools: ${tools
37
+ .map((tool) => tool.name)
38
+ .join(", ")}.`
33
39
 
34
- /** The two project-independent tools, reading the package's bundled corpus from disk (CLI use). */
40
+ /** The project-independent tools, reading the package's bundled corpus from disk (CLI use): the text
41
+ * docs tools plus the `nifra_examples_app` MCP Apps widget tool. */
35
42
  export function publicDocsTools(): McpTool[] {
36
- return docsTools(loadDocsCorpus, loadExamplesCorpus, loadTypesCorpus)
43
+ return [
44
+ ...docsTools(loadDocsCorpus, loadExamplesCorpus, loadTypesCorpus),
45
+ examplesAppTool(loadExamplesCorpus),
46
+ ]
37
47
  }
38
48
 
39
49
  /**
@@ -46,12 +56,15 @@ export function respondMcpHttp(
46
56
  tools: McpTool[],
47
57
  options: McpHttpOptions = {},
48
58
  ): Promise<Response> {
49
- return respondMcpHttpCore(request, tools, SERVER_INFO, { health: DOCS_HEALTH, ...options })
59
+ return respondMcpHttpCore(request, tools, SERVER_INFO, { health: docsHealth(tools), ...options })
50
60
  }
51
61
 
52
- /** The CLI HTTP handler: serves the disk-backed corpus tools. (`nifra docs-mcp` / `bun run` this file.) */
62
+ /** The CLI HTTP handler: serves the disk-backed corpus tools + registers the examples widget's `ui://`
63
+ * resource so MCP Apps hosts can render `nifra_examples_app`. (`nifra docs-mcp` / `bun run` this file.) */
53
64
  export function handleMcpHttp(request: Request): Promise<Response> {
54
- return respondMcpHttp(request, publicDocsTools())
65
+ return respondMcpHttp(request, publicDocsTools(), {
66
+ features: { resources: [examplesWidget.resource], ui: { mimeTypes: [UI_MIME] } },
67
+ })
55
68
  }
56
69
 
57
70
  /**
package/src/mcp.ts CHANGED
@@ -12,12 +12,18 @@
12
12
  * - `nifra_docs` - keyword-search the framework docs; returns only the matching sections.
13
13
  * - `nifra_example` - a verified, copy-pasteable snippet for a task (typechecked against the live API,
14
14
  * so it can't hallucinate a drifted nifra API).
15
+ * - `nifra_learn` - the guided, ordered path to build a nifra app end to end (create → deploy), each
16
+ * step naming the tool that emits the correct artifact and how to verify it.
15
17
  * - `nifra_scaffold`- map a URL path to the correct `routes/` file + a contract-correct page stub.
16
18
  * - `nifra_check` - the drift gate (typecheck + lints, each with a structured fix), for an agent to fix against.
17
19
  * - `nifra_assure` - route classification + enforcement-evidence gate.
18
20
  * - `nifra_levels` - the cumulative verification ladder (L0 contract → L4 invariants): what the
19
21
  * project actually proves, and why each level it misses does not hold.
20
22
  * - `nifra_doctor` - package.json dependency drift detector, with safe local-version auto-fix.
23
+ * - `nifra_explain` - resolve an error (pasted, or the dev server's last) into a structured
24
+ * diagnostic: stable code, a codeframe in the user's source, and the recognised cause + fix.
25
+ * - `nifra_inspect` - read the running dev server's recent request traces (method/path/status/
26
+ * duration/ISR) from the DevTools plugin: what your requests ACTUALLY did, not a guess.
21
27
  *
22
28
  * Wire it into a client (e.g. Claude Desktop / Cursor) as: command `nifra`, args `["mcp"]`, run in the
23
29
  * project root. The protocol is hand-rolled (newline-delimited JSON-RPC 2.0 over stdio), including
@@ -75,6 +81,67 @@ function childPath(name: "mcp-run" | "mcp-render" | "mcp-ws"): string {
75
81
  */
76
82
  const CHILD_TIMEOUT_MS = 30_000
77
83
 
84
+ /** Local dev-tool reads are intentionally bounded: MCP runs in an agent process and must not hang on or
85
+ * buffer an unrelated loopback service just because a caller supplied its port. */
86
+ export const LOCAL_TOOL_FETCH_TIMEOUT_MS = 2_000
87
+ export const LOCAL_TOOL_MAX_RESPONSE_BYTES = 1_048_576
88
+
89
+ /** Accept only a concrete TCP port. Port 0 (bind-any-free-port) is not a valid read target. */
90
+ export function validateLocalPort(port: unknown): number | undefined {
91
+ return typeof port === "number" && Number.isInteger(port) && port >= 1 && port <= 65_535
92
+ ? port
93
+ : undefined
94
+ }
95
+
96
+ /** Read a dev-tool response without allowing an untrusted localhost service to allocate unbounded memory. */
97
+ export async function readBoundedResponse(
98
+ response: Response,
99
+ maxBytes = LOCAL_TOOL_MAX_RESPONSE_BYTES,
100
+ ): Promise<string> {
101
+ const declared = response.headers.get("content-length")
102
+ if (declared !== null) {
103
+ const length = Number(declared)
104
+ if (Number.isFinite(length) && length > maxBytes)
105
+ throw new Error("response exceeded the size limit")
106
+ }
107
+ if (response.body === null) return ""
108
+ const reader = response.body.getReader()
109
+ const chunks: Uint8Array[] = []
110
+ let total = 0
111
+ try {
112
+ for (;;) {
113
+ const { done, value } = await reader.read()
114
+ if (done) break
115
+ if (value === undefined) continue
116
+ total += value.byteLength
117
+ if (total > maxBytes) {
118
+ await reader.cancel()
119
+ throw new Error("response exceeded the size limit")
120
+ }
121
+ chunks.push(value)
122
+ }
123
+ } finally {
124
+ reader.releaseLock()
125
+ }
126
+ const bytes = new Uint8Array(total)
127
+ let offset = 0
128
+ for (const chunk of chunks) {
129
+ bytes.set(chunk, offset)
130
+ offset += chunk.byteLength
131
+ }
132
+ return new TextDecoder().decode(bytes)
133
+ }
134
+
135
+ const notNifraResponse = (service: string): string =>
136
+ JSON.stringify(
137
+ {
138
+ code: "NIFRA_NOT_DEV_SERVER",
139
+ message: `The service on this port is not a Nifra ${service} endpoint.`,
140
+ },
141
+ null,
142
+ 2,
143
+ )
144
+
78
145
  const timeoutMessage = (label: string, ms: number): string =>
79
146
  `${label} timed out after ${ms / 1000}s and was terminated.\n` +
80
147
  `The app was loaded but the process did not finish. Most often this is a module-level side effect ` +
@@ -668,6 +735,176 @@ export function projectTools(
668
735
  return describeProject(await loadAppCached(), filter)
669
736
  },
670
737
  },
738
+ {
739
+ name: "nifra_explain",
740
+ description:
741
+ "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.",
742
+ inputSchema: {
743
+ type: "object",
744
+ properties: {
745
+ error: {
746
+ type: "string",
747
+ description:
748
+ "The error message to explain (copy it from nifra_run/nifra_test output or a failing build).",
749
+ },
750
+ stack: {
751
+ type: "string",
752
+ description:
753
+ "The error's stack trace, if you have it - enables the source codeframe and the top user frame.",
754
+ },
755
+ name: {
756
+ type: "string",
757
+ description:
758
+ "The error's class name (e.g. TypeError, SchemaError), if known - sharpens classification.",
759
+ },
760
+ port: {
761
+ type: "number",
762
+ description:
763
+ "Instead of a pasted error, fetch the running dev server's most recent SSR failure from this port.",
764
+ },
765
+ },
766
+ additionalProperties: false,
767
+ },
768
+ handler: async (args) => {
769
+ const { error, stack, name, port } = args as {
770
+ error?: string
771
+ stack?: string
772
+ name?: string
773
+ port?: number
774
+ }
775
+ if (error !== undefined || stack !== undefined) {
776
+ const { buildDiagnostic } = await import("@nifrajs/web/diagnostic")
777
+ const e = new Error(error ?? "")
778
+ if (name !== undefined) e.name = name
779
+ if (stack !== undefined) e.stack = stack
780
+ return JSON.stringify(buildDiagnostic(e, { root: cwd }), null, 2)
781
+ }
782
+ if (port !== undefined) {
783
+ const validPort = validateLocalPort(port)
784
+ if (validPort === undefined) {
785
+ return JSON.stringify(
786
+ { code: "NIFRA_INVALID_PORT", message: "port must be an integer from 1 to 65535." },
787
+ null,
788
+ 2,
789
+ )
790
+ }
791
+ const { LAST_ERROR_PATH } = await import("@nifrajs/web/diagnostic")
792
+ try {
793
+ const res = await fetch(`http://127.0.0.1:${validPort}${LAST_ERROR_PATH}`, {
794
+ signal: AbortSignal.timeout(LOCAL_TOOL_FETCH_TIMEOUT_MS),
795
+ })
796
+ if (res.headers.get("x-nifra-diagnostic") !== "true")
797
+ return notNifraResponse("diagnostic")
798
+ if (!res.ok) {
799
+ return JSON.stringify(
800
+ {
801
+ code: "NIFRA_NONE",
802
+ message: `dev server at :${validPort} returned ${res.status}`,
803
+ },
804
+ null,
805
+ 2,
806
+ )
807
+ }
808
+ return await readBoundedResponse(res)
809
+ } catch (cause) {
810
+ return JSON.stringify(
811
+ {
812
+ code: "NIFRA_NONE",
813
+ message: `could not reach a nifra dev server at :${validPort} - ${cause instanceof Error ? cause.message : String(cause)}`,
814
+ },
815
+ null,
816
+ 2,
817
+ )
818
+ }
819
+ }
820
+ return JSON.stringify(
821
+ {
822
+ code: "NIFRA_NONE",
823
+ message:
824
+ "Pass `error` (and `stack` if available) to explain a failure, or `port` to fetch the dev server's last error.",
825
+ },
826
+ null,
827
+ 2,
828
+ )
829
+ },
830
+ },
831
+ {
832
+ name: "nifra_inspect",
833
+ description:
834
+ "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).",
835
+ inputSchema: {
836
+ type: "object",
837
+ properties: {
838
+ port: { type: "number", description: "The running dev server's port." },
839
+ path: { type: "string", description: "Only traces whose path starts with this prefix." },
840
+ limit: { type: "number", description: "Return only the most recent N traces." },
841
+ },
842
+ required: ["port"],
843
+ additionalProperties: false,
844
+ },
845
+ handler: async (args) => {
846
+ const { port, path, limit } = args as { port?: number; path?: string; limit?: number }
847
+ if (port === undefined) {
848
+ return JSON.stringify(
849
+ {
850
+ events: [],
851
+ note: "Pass `port` - the running dev server whose request traces to read.",
852
+ },
853
+ null,
854
+ 2,
855
+ )
856
+ }
857
+ try {
858
+ const validPort = validateLocalPort(port)
859
+ if (validPort === undefined) {
860
+ return JSON.stringify(
861
+ {
862
+ events: [],
863
+ code: "NIFRA_INVALID_PORT",
864
+ note: "port must be an integer from 1 to 65535.",
865
+ },
866
+ null,
867
+ 2,
868
+ )
869
+ }
870
+ const url = new URL(`http://127.0.0.1:${validPort}/_nifra/devtools/state`)
871
+ if (path !== undefined) url.searchParams.set("path", path)
872
+ if (limit !== undefined) url.searchParams.set("limit", String(limit))
873
+ const res = await fetch(url, {
874
+ signal: AbortSignal.timeout(LOCAL_TOOL_FETCH_TIMEOUT_MS),
875
+ })
876
+ if (res.headers.get("x-nifra-devtools") !== "true") return notNifraResponse("DevTools")
877
+ if (res.status === 404) {
878
+ return JSON.stringify(
879
+ {
880
+ events: [],
881
+ note: "No DevTools endpoint on that server. Mount `devtools()` from @nifrajs/web and run in development.",
882
+ },
883
+ null,
884
+ 2,
885
+ )
886
+ }
887
+ if (!res.ok) {
888
+ return JSON.stringify(
889
+ { events: [], note: `DevTools state returned ${res.status}.` },
890
+ null,
891
+ 2,
892
+ )
893
+ }
894
+ return await readBoundedResponse(res)
895
+ } catch (cause) {
896
+ const validPort = validateLocalPort(port)
897
+ return JSON.stringify(
898
+ {
899
+ events: [],
900
+ note: `Could not reach a dev server at :${validPort ?? String(port)} - ${cause instanceof Error ? cause.message : String(cause)}`,
901
+ },
902
+ null,
903
+ 2,
904
+ )
905
+ }
906
+ },
907
+ },
671
908
  {
672
909
  name: "nifra_routes",
673
910
  description: