@pithyjs/mcp 0.0.0-stage → 0.1.0-beta.2

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 PithyJS
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,224 @@
1
- # Temporary Holding Version
1
+ # @pithyjs/mcp
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ An [MCP](https://modelcontextprotocol.io) server that gives coding agents grounded knowledge of PithyJS: API and component lookup, template, token and PIDL checks, error explanations, and route and component scaffolds. It speaks stdio.
4
+
5
+ Every lookup answer carries `citations` (`{ entryId?, file, line? }`) taken from the annotated source, and a lookup that finds nothing returns `found: false` instead of a guess. Code examples come only from tests marked `// @codex:example`; none are made up.
6
+
7
+ ## Installation
8
+
9
+ <!-- @codex:auto install="@pithyjs/mcp" -->
10
+ ```bash
11
+ npm install @pithyjs/mcp
12
+ ```
13
+
14
+ ```bash
15
+ pnpm add @pithyjs/mcp
16
+ ```
17
+
18
+ ```bash
19
+ yarn add @pithyjs/mcp
20
+ ```
21
+ <!-- @codex:end -->
22
+
23
+ You do not need to install it to use it: `npx @pithyjs/mcp` runs the server.
24
+
25
+ ## Two modes
26
+
27
+ | Mode | Command | Answers from | Covers |
28
+ | ---------------- | ---------------------------------------- | -------------------------------------------------------------------- | ------------------------------------ |
29
+ | Public (default) | `pithy-mcp` | `dist/snapshot.json`, built from the repo when this package is built | Published packages only |
30
+ | Repo | `pithy-mcp --source=repo [--root <dir>]` | A PithyJS checkout, read when the server starts | Every package, private ones included |
31
+
32
+ Both modes build the same `Knowledge` object, and the tools only ever read that object. In repo mode `--root` defaults to the nearest directory at or above the working directory that holds `codex.index.json`. Repo mode needs `@pithyjs/codex` (an optional peer dependency), which a PithyJS checkout already has. Public mode never loads it.
33
+
34
+ ### `.mcp.json`, public mode
35
+
36
+ ```json
37
+ {
38
+ "mcpServers": {
39
+ "pithyjs": {
40
+ "command": "npx",
41
+ "args": ["-y", "@pithyjs/mcp@beta"]
42
+ }
43
+ }
44
+ }
45
+ ```
46
+
47
+ ### `.mcp.json`, repo mode (inside a PithyJS checkout)
48
+
49
+ ```json
50
+ {
51
+ "mcpServers": {
52
+ "pithyjs": {
53
+ "command": "node",
54
+ "args": ["packages/mcp/dist/cli.js", "--source=repo"]
55
+ }
56
+ }
57
+ }
58
+ ```
59
+
60
+ Run `pnpm --filter @pithyjs/mcp build` once first. Repo mode reads the checkout when the server starts, so restart the server to pick up edits.
61
+
62
+ ## Tools
63
+
64
+ | Group | Tool | Input | Returns |
65
+ | -------- | -------------------- | ------------------------------------------------------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
66
+ | Know | `search` | `query`, `limit?` (1–50, default 10) | Ranked entries, APIs and components, each with citations |
67
+ | Know | `get_api` | `query`: an entry id (`pithy.babel.validate-template`) or an API name (`validateTemplate`) | Entries with signatures, docs, `@codex:example` examples and citations |
68
+ | Know | `get_component` | `name`: `Button`, `button`, `cta-section` or `ui.button` | The component's PIDL spec and its file |
69
+ | Know | `get_tokens` | `category?`: `color`, `space`, `radius`… | Token names from the design system's generated manifest |
70
+ | Check | `validate_template` | `code`, `filename?` (default `component.ts`) | The Vite plugin's component-attribute findings, run with ui-kit's `componentScopes` and no `tsconfig.json` lookup; a parse error comes back as `error`, and a `.pithy` result carries a `note` on what the check cannot see there |
71
+ | Check | `check_tokens` | `css` | Unknown tokens (with a did-you-mean); raw hex, rgb(), hsl(), oklch()… colors in values, custom props, Sass variables and at-rule arguments (named colors pass); physical margin, padding, border, corner-radius, inset, width/height properties and left/right in `text-align`, `float`, `clear`. Lists the first 200 of `total`, with `truncated` |
72
+ | Check | `validate_pidl` | `spec`: an object or JSON text | Errors and warnings by JSON path. A spec is valid only if the registry's own `extractPublic` also accepts it |
73
+ | Fix | `explain_error` | `message` | The catalog's explanation and the file that emits the message, or `found: false` with related search hits |
74
+ | Scaffold | `scaffold_route` | `path`, `options?: { loader?, layout? }` | `{ files: [{ path, contents }] }` for `src/routes/<path>/page.ts` (plus `loader.ts`, `layout.ts`). A catch-all must be the last URL segment |
75
+ | Scaffold | `scaffold_component` | `name` (PascalCase), `kind?` (`atom`, `molecule`, `organism`, `section`) | `{ files }`: a `.ts` component returning the `html` handle (`{ el, destroy }`), token-only SCSS and a `.pidl.json`; refuses a name ui-kit already exports |
76
+
77
+ The scaffold tools write nothing; the agent writes the files it gets back. Their output parses as TypeScript and passes this server's own `validate_template`, `check_tokens` and `validate_pidl`. Every tool is annotated read-only.
78
+
79
+ `explain_error` gives a router error's recovery as the taxonomy recommends it (`getRecoveryStrategy()`). The router acts on only one of them itself: the outlet renders no error UI for `silent-fail`.
80
+
81
+ ## Resources
82
+
83
+ | URI | Content |
84
+ | -------------------------- | ------------------------------------------ |
85
+ | `pithy://entry/{id}` | An entry, as `get_api` returns it |
86
+ | `pithy://component/{name}` | A PIDL spec, as `get_component` returns it |
87
+ | `pithy://tokens` | Every token name |
88
+
89
+ ## Input guard
90
+
91
+ Every `tools/call` (and `resources/read`) is checked as it arrives, before any schema parses it. A request is answered with JSON-RPC error `-32602` and never reaches a tool when its arguments hold an own key `__proto__`, `constructor` or `prototype` at any depth, a symbol, a function or an object that is not plain, are nested deeper than 32, or hold more than 20,000 values or 2,000,000 characters.
92
+
93
+ ## Programmatic use
94
+
95
+ ```ts
96
+ import { connectPithyServer, createPithyServer, loadSnapshot } from '@pithyjs/mcp';
97
+ import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
98
+
99
+ await connectPithyServer(createPithyServer(loadSnapshot()), new StdioServerTransport());
100
+ ```
101
+
102
+ Importing the package starts nothing. `buildKnowledge(root, 'public' | 'all')` builds the knowledge from a checkout.
103
+
104
+ ## API
105
+
106
+ <!-- @codex:auto api="pithy.mcp.*" -->
107
+ | API | Component | Signature | Stability | Description |
108
+ | --- | --- | --- | --- | --- |
109
+ | GuardLimits | guard | `interface GuardLimits { maxDepth: number; maxValues: number; maxChars: number }` | experimental | The bounds {@link guardInput} enforces. |
110
+ | GuardError | guard | `class GuardError extends Error` | experimental | Thrown by {@link guardInput}; the message names the offending path. |
111
+ | guardInput | guard | `(value: unknown, limits?: GuardLimits) => void` | experimental | - |
112
+ | guardTransport | guard | `(inner: Transport) => Transport` | experimental | - |
113
+ | KnowledgeScope | knowledge | `type KnowledgeScope = 'public' | 'all'` | experimental | `public`: published packages only. `all`: every package in the checkout. |
114
+ | Citation | knowledge | `interface Citation { entryId?: string; file: string; line?: number }` | experimental | Where an answer comes from: a repo-relative file, and the line when known. |
115
+ | SourcePlace | knowledge | `interface SourcePlace { pkg: string; file: string; line: number }` | experimental | An annotation's package, repo-relative file and line. |
116
+ | KnowledgeApi | knowledge | `interface KnowledgeApi` | experimental | One `@codexApi`, joined with the declaration it annotates. |
117
+ | KnowledgeExample | knowledge | `interface KnowledgeExample { name: string; file: string; line: number; code: string }` | experimental | A test marked `// @codex:example <entry id>`. |
118
+ | KnowledgeEntry | knowledge | `interface KnowledgeEntry` | experimental | A Codex entry with its APIs, places and examples. |
119
+ | KnowledgeComponent | knowledge | `interface KnowledgeComponent { name: string; id: string; file: string; spec: Record<string, unknown> }` | experimental | A PIDL spec and the file it was read from. |
120
+ | Knowledge | knowledge | `interface Knowledge` | experimental | Everything the tools answer from. Serialised as `dist/snapshot.json`. |
121
+ | CodexDataLike | knowledge | `interface CodexDataLike` | experimental | The shape `readCodex` from `@pithyjs/codex/reader` returns. |
122
+ | assembleKnowledge | knowledge | `(codex: CodexDataLike, scope: KnowledgeScope, components: KnowledgeComponent[], tokens: Knowledge['tokens']) => Knowledge` | experimental | - |
123
+ | buildKnowledge | knowledge | `(root: string, scope: KnowledgeScope) => Promise<Knowledge>` | experimental | - |
124
+ | loadSnapshot | knowledge | `(file?: string | URL) => Knowledge` | experimental | - |
125
+ | findRepoRoot | knowledge | `(from: string) => string | null` | experimental | - |
126
+ | entryCitations | knowledge | `(entry: KnowledgeEntry) => Citation[]` | experimental | - |
127
+ | NotFound | lookup | `interface NotFound { found: false; query: string; message: string; suggestions: SearchHit[] }` | experimental | What a lookup returns instead of a guess. |
128
+ | ApiResult | lookup | `type ApiResult = { found: true; query: string; entries: KnowledgeEntry[]; citations: Citation[] } | NotFound` | experimental | The entries an id or API name resolves to, with their citations. |
129
+ | ComponentResult | lookup | `type ComponentResult = { found: true; component: KnowledgeComponent; citations: Citation[] } | NotFound` | experimental | A PIDL spec and its citation. |
130
+ | getApi | lookup | `(k: Knowledge, query: string) => ApiResult` | experimental | - |
131
+ | getComponent | lookup | `(k: Knowledge, name: string) => ComponentResult` | experimental | - |
132
+ | PidlIssue | pidl | `interface PidlIssue { path: string; message: string }` | experimental | A problem at a JSON path such as `props[2].enum`; `''` is the whole spec. |
133
+ | PidlResult | pidl | `interface PidlResult { valid: boolean; errors: PidlIssue[]; warnings: PidlIssue[]; citations: Citation[] }` | experimental | `valid` when there are no errors; warnings do not fail a spec. |
134
+ | validatePidl | pidl | `(input: unknown) => PidlResult` | experimental | - |
135
+ | ScaffoldFile | scaffold | `interface ScaffoldFile { path: string; contents: string }` | experimental | A file to create, at a path relative to the app root. |
136
+ | Scaffold | scaffold | `interface Scaffold { files: ScaffoldFile[] }` | experimental | Files for the caller to write; nothing is written here. |
137
+ | ComponentKind | scaffold | `type ComponentKind = 'atom' | 'molecule' | 'organism' | 'section'` | experimental | The PIDL level of a scaffolded component. |
138
+ | scaffoldRoute | scaffold | `(path: string, options?: { loader?: boolean; layout?: boolean }) => Scaffold` | experimental | - |
139
+ | takenComponentNames | scaffold | `(k: Knowledge) => string[]` | experimental | - |
140
+ | scaffoldComponent | scaffold | `(name: string, kind?: ComponentKind, existing?: readonly string[]) => Scaffold` | experimental | - |
141
+ | SearchHit | search | `interface SearchHit` | experimental | One ranked result. `id` is an entry id, `"<entry id> <api>"`, or a component name. |
142
+ | MAX_SEARCH_LIMIT | search | `50` | experimental | The most hits one search returns. |
143
+ | tokenize | search | `(text: string) => string[]` | experimental | - |
144
+ | search | search | `(k: Knowledge, query: string, limit?: number) => SearchHit[]` | experimental | - |
145
+ | TOOL_NAMES | server | `readonly string[]` | experimental | Every tool the server registers. |
146
+ | createPithyServer | server | `(knowledge: Knowledge) => McpServer` | experimental | - |
147
+ | connectPithyServer | server | `(server: McpServer, transport: Transport) => Promise<void>` | experimental | - |
148
+ | TemplateCheck | template | `interface TemplateCheck { filename: string; checked: boolean; ok: boolean; findings: TemplateFinding[]; error?: string; note?: string }` | experimental | `checked` is false when the file type is one the plugin never reads. `ok` is true only for a checked module with no findings and no error. |
149
+ | checkTemplate | template | `(code: string, filename?: string) => Promise<TemplateCheck>` | experimental | - |
150
+ | suggestToken | tokens | `(token: string, known: ReadonlySet<string>) => string | null` | experimental | - |
151
+ | TokenIssue | tokens | `interface TokenIssue` | experimental | One problem `check_tokens` found. |
152
+ | TokenCheck | tokens | `interface TokenCheck { ok: boolean; issues: TokenIssue[]; total: number; truncated: boolean }` | experimental | `ok` when there are no issues; `issues` lists the first 200 of `total`. |
153
+ | checkTokens | tokens | `(css: string, names: readonly string[]) => TokenCheck` | experimental | - |
154
+ | TokensResult | tokens | `type TokensResult` | experimental | Token names with their citation, or the families when `category` is unknown. |
155
+ | getTokens | tokens | `(k: Knowledge, category?: string) => TokensResult` | experimental | - |
156
+ | CatalogEntry | errors | `interface CatalogEntry` | experimental | A framework message, where it is emitted, and what it means. |
157
+ | ERROR_CATALOG | errors | `readonly CatalogEntry[]` | experimental | Framework messages `explain_error` knows, each citing the file that emits it. |
158
+ | ExplainResult | errors | `type ExplainResult` | experimental | A catalog explanation with its citation, or a plain "not known". |
159
+ | explainError | errors | `(k: Knowledge, message: string) => ExplainResult` | experimental | - |
160
+ <!-- @codex:end -->
161
+
162
+ ## Examples
163
+
164
+ <!-- @codex:auto examples="pithy.mcp.*" limit="3" -->
165
+ **initializes over stdio and lists tools from the bundled snapshot**
166
+
167
+ ```typescript
168
+ const [tools, privateEntry] = await withClient(
169
+ [],
170
+ async c =>
171
+ [
172
+ (await c.listTools()).tools,
173
+ JSON.parse(
174
+ (
175
+ (await c.callTool({
176
+ name: 'get_api',
177
+ arguments: { query: 'pithy.server.middleware' },
178
+ })) as {
179
+ content: Array<{ text: string }>;
180
+ }
181
+ ).content[0].text
182
+ ),
183
+ ] as const
184
+ );
185
+ tools.map(t => t.name); // contains 'get_api'
186
+ tools; // has length 10
187
+ privateEntry.found; // → false
188
+ ```
189
+
190
+ **rejects an own \_\_proto\_\_ key, as JSON.parse creates one**
191
+
192
+ ```typescript
193
+ const value = JSON.parse('{"__proto__":{"x":1}}');
194
+ Object.getOwnPropertyNames(value); // → ['__proto__']
195
+ rejects(value, /__proto__/);
196
+ expect(() => guardInput(value)).toThrow(GuardError);
197
+ ```
198
+
199
+ **builds public knowledge from published packages only**
200
+
201
+ ```typescript
202
+ const k = await repoKnowledge('public');
203
+ k.format; // → 1
204
+ k.scope; // → 'public'
205
+ const places = placesOf(k);
206
+ expect(places.length).toBeGreaterThan(100);
207
+ places.filter(p => isPrivate(p.file)); // → []
208
+ ```
209
+ <!-- @codex:end -->
210
+
211
+ ## Testing
212
+
213
+ <!-- @codex:auto testing="pithy.mcp.server" -->
214
+ | Feature | Unit | Integration | E2E | Status |
215
+ | --- | --- | --- | --- | --- |
216
+ | TOOL_NAMES | ✓ | - | - | Missing integration |
217
+ | createPithyServer | ✓ | - | - | Missing integration |
218
+ | connectPithyServer | ✓ | - | - | Missing integration |
219
+ <!-- @codex:end -->
220
+
221
+ ```bash
222
+ pnpm --filter @pithyjs/mcp build # the bin test spawns dist/cli.js
223
+ cd packages/mcp && pnpm vitest run
224
+ ```
package/dist/cli.d.ts ADDED
@@ -0,0 +1,3 @@
1
+ #!/usr/bin/env node
2
+ /** @codex { "id": "pithy.mcp.cli", "title": "pithy-mcp CLI", "category": "feature", "risk": "medium" } */
3
+ export {};
package/dist/cli.js ADDED
@@ -0,0 +1,74 @@
1
+ #!/usr/bin/env node
2
+ /** @codex { "id": "pithy.mcp.cli", "title": "pithy-mcp CLI", "category": "feature", "risk": "medium" } */
3
+ import { Console } from 'node:console';
4
+ import { resolve } from 'node:path';
5
+ import { parseArgs } from 'node:util';
6
+ import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
7
+ import { buildKnowledge, findRepoRoot, loadSnapshot } from './knowledge.js';
8
+ import { connectPithyServer, createPithyServer } from './server.js';
9
+ const USAGE = `Usage: pithy-mcp [--source=snapshot|repo] [--root <dir>]
10
+
11
+ --source=snapshot Answer from the bundled snapshot of the published packages (default).
12
+ --source=repo Read a PithyJS checkout live, every package included.
13
+ --root <dir> The checkout for --source=repo; default: the nearest
14
+ directory above the working directory with codex.index.json.`;
15
+ // stdout carries JSON-RPC only; anything a dependency logs goes to stderr.
16
+ globalThis.console = new Console({
17
+ stdout: process.stderr,
18
+ stderr: process.stderr,
19
+ });
20
+ async function main() {
21
+ let values;
22
+ try {
23
+ ({ values } = parseArgs({
24
+ options: {
25
+ source: { type: 'string', default: 'snapshot' },
26
+ root: { type: 'string' },
27
+ help: { type: 'boolean', short: 'h' },
28
+ },
29
+ strict: true,
30
+ }));
31
+ }
32
+ catch (e) {
33
+ console.error(`${e.message}\n\n${USAGE}`);
34
+ return 2;
35
+ }
36
+ if (values.help) {
37
+ console.error(USAGE);
38
+ return 0;
39
+ }
40
+ if (values.source !== 'snapshot' && values.source !== 'repo') {
41
+ console.error(`Unknown --source "${values.source}".\n\n${USAGE}`);
42
+ return 2;
43
+ }
44
+ let knowledge;
45
+ if (values.source === 'repo') {
46
+ const root = values.root
47
+ ? resolve(values.root)
48
+ : findRepoRoot(process.cwd());
49
+ if (!root) {
50
+ console.error('pithy-mcp: no codex.index.json at or above the working directory; pass --root <checkout>.');
51
+ return 1;
52
+ }
53
+ try {
54
+ knowledge = await buildKnowledge(root, 'all');
55
+ }
56
+ catch (e) {
57
+ console.error(`pithy-mcp: cannot read ${root}: ${e.message}`);
58
+ return 1;
59
+ }
60
+ }
61
+ else {
62
+ knowledge = loadSnapshot();
63
+ }
64
+ await connectPithyServer(createPithyServer(knowledge), new StdioServerTransport());
65
+ console.error(`pithy-mcp ready (${knowledge.scope === 'all' ? 'repo' : 'snapshot'}: ${knowledge.entries.length} entries, ${knowledge.components.length} components)`);
66
+ return -1;
67
+ }
68
+ main().then(code => {
69
+ if (code >= 0)
70
+ process.exit(code);
71
+ }, e => {
72
+ console.error(e);
73
+ process.exit(1);
74
+ });
@@ -0,0 +1,48 @@
1
+ /** @codex { "id": "pithy.mcp.errors", "title": "MCP Error Catalog", "category": "feature", "risk": "medium" } */
2
+ import type { Citation, Knowledge } from '../knowledge.js';
3
+ import { type SearchHit } from '../search.js';
4
+ /** @codexApi {"parent":"pithy.mcp.errors","name":"CatalogEntry","stability":"experimental","signature":"interface CatalogEntry"} */
5
+ /** A framework message, where it is emitted, and what it means. */
6
+ export interface CatalogEntry {
7
+ id: string;
8
+ title: string;
9
+ pattern: RegExp;
10
+ /** A message as the framework prints it; tests match `pattern` against it. */
11
+ sample: string;
12
+ /** `text` appears verbatim in `file` and in `sample`. */
13
+ source: {
14
+ file: string;
15
+ text: string;
16
+ };
17
+ explanation: string;
18
+ fix: string;
19
+ facts?: Record<string, unknown>;
20
+ }
21
+ /** @codexApi {"parent":"pithy.mcp.errors","name":"ERROR_CATALOG","stability":"experimental","signature":"readonly CatalogEntry[]"} */
22
+ /** Framework messages `explain_error` knows, each citing the file that emits it. */
23
+ export declare const ERROR_CATALOG: readonly CatalogEntry[];
24
+ /** @codexApi {"parent":"pithy.mcp.errors","name":"ExplainResult","stability":"experimental","signature":"type ExplainResult"} */
25
+ /** A catalog explanation with its citation, or a plain "not known". */
26
+ export type ExplainResult = {
27
+ found: true;
28
+ id: string;
29
+ title: string;
30
+ explanation: string;
31
+ fix: string;
32
+ facts?: Record<string, unknown>;
33
+ citations: Citation[];
34
+ } | {
35
+ found: false;
36
+ message: string;
37
+ related: SearchHit[];
38
+ };
39
+ /**
40
+ * Explains a framework error or warning from the curated catalog. A message
41
+ * the catalog does not hold gets no explanation, only related search hits.
42
+ *
43
+ * @param k - The knowledge to search for related entries.
44
+ * @param message - The message as printed.
45
+ * @returns The entry's explanation and source, or `found: false`.
46
+ */
47
+ /** @codexApi {"parent":"pithy.mcp.errors","name":"explainError","stability":"experimental","signature":"(k: Knowledge, message: string) => ExplainResult"} */
48
+ export declare function explainError(k: Knowledge, message: string): ExplainResult;
@@ -0,0 +1,252 @@
1
+ /** @codex { "id": "pithy.mcp.errors", "title": "MCP Error Catalog", "category": "feature", "risk": "medium" } */
2
+ import { search } from '../search.js';
3
+ const ROUTER_FILE = 'packages/router/src/router/features/errors/error-codes.ts';
4
+ // [code, what the enum's doc comment says, severity, recovery, retryable, userMessage]
5
+ const ROUTER = [
6
+ [
7
+ 'LOADER_EXECUTION_ERROR',
8
+ 'Loader function threw an error',
9
+ 'error',
10
+ 'show-error-ui',
11
+ true,
12
+ 'Failed to load data for this page',
13
+ ],
14
+ [
15
+ 'LOADER_TIMEOUT',
16
+ 'Loader timed out',
17
+ 'error',
18
+ 'show-error-ui',
19
+ true,
20
+ 'Loading data took too long',
21
+ ],
22
+ [
23
+ 'LOADER_ABORTED',
24
+ 'Loader was aborted/cancelled',
25
+ 'info',
26
+ 'silent-fail',
27
+ false,
28
+ 'Loading was cancelled',
29
+ ],
30
+ [
31
+ 'LOADER_FAILED_SENTINEL',
32
+ 'Loader returned LOADER_FAILED sentinel',
33
+ 'error',
34
+ 'show-error-ui',
35
+ true,
36
+ 'Failed to load data',
37
+ ],
38
+ [
39
+ 'GUARD_EXECUTION_ERROR',
40
+ 'Guard function threw an error',
41
+ 'critical',
42
+ 'redirect-fallback',
43
+ false,
44
+ 'Navigation check failed',
45
+ ],
46
+ [
47
+ 'GUARD_TIMEOUT',
48
+ 'Guard timed out',
49
+ 'error',
50
+ 'redirect-fallback',
51
+ true,
52
+ 'Navigation check took too long',
53
+ ],
54
+ [
55
+ 'GUARD_ABORTED',
56
+ 'Guard was aborted/cancelled',
57
+ 'info',
58
+ 'silent-fail',
59
+ false,
60
+ 'Navigation was cancelled',
61
+ ],
62
+ [
63
+ 'GUARD_DENIED',
64
+ 'Guard denied navigation (returned false)',
65
+ 'warning',
66
+ 'silent-fail',
67
+ false,
68
+ "You don't have permission to access this page",
69
+ ],
70
+ [
71
+ 'COMPONENT_FACTORY_ERROR',
72
+ 'Component factory function threw error',
73
+ 'error',
74
+ 'show-error-ui',
75
+ true,
76
+ 'Failed to initialize page component',
77
+ ],
78
+ [
79
+ 'COMPONENT_RENDER_ERROR',
80
+ 'Component render threw error',
81
+ 'error',
82
+ 'show-error-ui',
83
+ true,
84
+ 'Failed to render page',
85
+ ],
86
+ [
87
+ 'COMPONENT_LOAD_ERROR',
88
+ 'Component module failed to load',
89
+ 'error',
90
+ 'show-error-ui',
91
+ true,
92
+ 'Failed to load page component',
93
+ ],
94
+ [
95
+ 'COMPONENT_LIFECYCLE_ERROR',
96
+ 'Component lifecycle hook threw error',
97
+ 'error',
98
+ 'show-error-ui',
99
+ true,
100
+ 'Page component error',
101
+ ],
102
+ [
103
+ 'ROUTE_NOT_FOUND',
104
+ 'Route not found for path',
105
+ 'error',
106
+ 'redirect-fallback',
107
+ false,
108
+ 'Page not found',
109
+ ],
110
+ [
111
+ 'NAVIGATION_ABORTED',
112
+ 'Navigation was aborted',
113
+ 'info',
114
+ 'silent-fail',
115
+ false,
116
+ 'Navigation was cancelled',
117
+ ],
118
+ [
119
+ 'NAVIGATION_SUPERSEDED',
120
+ 'Navigation was superseded by another navigation',
121
+ 'info',
122
+ 'silent-fail',
123
+ false,
124
+ 'Navigation was replaced by a newer navigation',
125
+ ],
126
+ [
127
+ 'CIRCULAR_REDIRECT',
128
+ 'Circular redirect detected',
129
+ 'critical',
130
+ 'show-error-ui',
131
+ false,
132
+ 'Circular redirect detected',
133
+ ],
134
+ [
135
+ 'ERROR_BOUNDARY_LOAD_ERROR',
136
+ 'Error boundary component failed to load',
137
+ 'critical',
138
+ 'bubble-up',
139
+ false,
140
+ 'Failed to load error page',
141
+ ],
142
+ [
143
+ 'ERROR_BOUNDARY_RENDER_ERROR',
144
+ 'Error boundary component threw error during render',
145
+ 'critical',
146
+ 'bubble-up',
147
+ false,
148
+ 'Error page failed to render',
149
+ ],
150
+ [
151
+ 'UNKNOWN_ERROR',
152
+ 'Unknown error with no specific categorization',
153
+ 'error',
154
+ 'show-error-ui',
155
+ true,
156
+ 'An unexpected error occurred',
157
+ ],
158
+ ];
159
+ const RECOVERY = {
160
+ 'show-error-ui': 'showing error UI with a retry',
161
+ 'redirect-fallback': 'redirecting to a fallback route',
162
+ 'silent-fail': 'logging it and showing no UI',
163
+ 'auto-retry': 'retrying automatically',
164
+ 'bubble-up': 'passing it to the parent error boundary',
165
+ };
166
+ // The only recommendation the router acts on itself (outlet/errors.ts).
167
+ const ACTED_ON = 'silent-fail';
168
+ const escape = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
169
+ // A user message matches only as the whole message, and a message shared by
170
+ // two codes matches neither; otherwise the code name decides.
171
+ const shared = new Set(ROUTER.map(r => r[5]).filter((m, i, all) => all.indexOf(m) !== i));
172
+ const routerEntries = ROUTER.map(([code, what, severity, recovery, retryable, userMessage]) => ({
173
+ id: code,
174
+ title: `Router error ${code}`,
175
+ pattern: shared.has(userMessage)
176
+ ? new RegExp(`\\b${code}\\b`)
177
+ : new RegExp(`\\b${code}\\b|^\\s*${escape(userMessage)}\\s*$`),
178
+ sample: `RouterError [${code}]: ${userMessage}`,
179
+ source: { file: ROUTER_FILE, text: code },
180
+ explanation: `${what}. The router's error taxonomy rates it ${severity} and recommends ${RECOVERY[recovery]} (\`getRecoveryStrategy()\`); it is ${retryable ? '' : 'not '}retryable. ${recovery === ACTED_ON ? 'The route outlet acts on this one and renders no error UI.' : 'The router does not perform this recovery itself; your error.ts or app code decides.'} Users see "${userMessage}".`,
181
+ fix: "Read the error's cause (`RouterError.cause`) for the underlying failure.",
182
+ facts: { severity, recommendedRecovery: recovery, retryable, userMessage },
183
+ }));
184
+ /** @codexApi {"parent":"pithy.mcp.errors","name":"ERROR_CATALOG","stability":"experimental","signature":"readonly CatalogEntry[]"} */
185
+ /** Framework messages `explain_error` knows, each citing the file that emits it. */
186
+ export const ERROR_CATALOG = [
187
+ {
188
+ id: 'component-attribute-expression',
189
+ title: 'Component attribute read as JavaScript',
190
+ pattern: /a component attribute is a JavaScript expression/,
191
+ sample: '[pithy] <Text as="strong">: a component attribute is a JavaScript expression, and this one reads `strong`, which has no entry in the html() context, so unless an SSR or parent component context supplies it, it throws or reads a browser global at runtime. To pass a string, quote it: as="\'strong\'".',
192
+ source: {
193
+ file: 'packages/vitePlugins/src/babelPlugin/babelPlugin.ts',
194
+ text: 'a component attribute is a JavaScript expression',
195
+ },
196
+ explanation: 'Every attribute on a component tag except data-* and class is parsed as a JavaScript expression. A bare word reads a variable of that name (a ReferenceError, or a browser global such as window.status); a value that does not parse, such as a multi-word aria-label, is dropped.',
197
+ fix: 'Quote a string (as="\'strong\'"); leave numbers and booleans unquoted (level="3", disabled="true"). The message ends with the quoted fix when there is one.',
198
+ },
199
+ {
200
+ id: 'heading-invalid-level',
201
+ title: 'Heading level out of range',
202
+ pattern: /\[<Heading>\] Invalid level:/,
203
+ sample: '[<Heading>] Invalid level: "3". Expected an integer between 1 and 6. Falling back to 2.',
204
+ source: {
205
+ file: 'packages/ui-kit/src/atoms/content/heading/Heading.ts',
206
+ text: 'Expected an integer between 1 and 6.',
207
+ },
208
+ explanation: '<Heading> got a level that is not an integer from 1 to 6. A non-number (often a quoted level="\'3\'", which is the string "3") falls back to 2; a number is rounded and clamped.',
209
+ fix: 'Pass the level as an unquoted number: level="3".',
210
+ },
211
+ {
212
+ id: 'render-children-outside-render',
213
+ title: 'renderChildren outside a component render',
214
+ pattern: /\[renderChildren\] Called outside component render context/,
215
+ sample: '[renderChildren] Called outside component render context',
216
+ source: {
217
+ file: 'packages/core/src/compile/renderChildren.ts',
218
+ text: '[renderChildren] Called outside component render context',
219
+ },
220
+ explanation: 'renderChildren() was called when no component was rendering, so there is no projected content to render; it renders nothing. Development builds only.',
221
+ fix: 'Call renderChildren() synchronously in the component function, while it renders, not in an effect, a timer or an event handler.',
222
+ },
223
+ ...routerEntries,
224
+ ];
225
+ /**
226
+ * Explains a framework error or warning from the curated catalog. A message
227
+ * the catalog does not hold gets no explanation, only related search hits.
228
+ *
229
+ * @param k - The knowledge to search for related entries.
230
+ * @param message - The message as printed.
231
+ * @returns The entry's explanation and source, or `found: false`.
232
+ */
233
+ /** @codexApi {"parent":"pithy.mcp.errors","name":"explainError","stability":"experimental","signature":"(k: Knowledge, message: string) => ExplainResult"} */
234
+ export function explainError(k, message) {
235
+ const e = ERROR_CATALOG.find(c => c.pattern.test(message));
236
+ if (!e) {
237
+ return {
238
+ found: false,
239
+ message: 'No known explanation for this message in the @pithyjs/mcp catalog.',
240
+ related: search(k, message, 5),
241
+ };
242
+ }
243
+ return {
244
+ found: true,
245
+ id: e.id,
246
+ title: e.title,
247
+ explanation: e.explanation,
248
+ fix: e.fix,
249
+ ...(e.facts ? { facts: e.facts } : {}),
250
+ citations: [{ file: e.source.file }],
251
+ };
252
+ }