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

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,124 @@
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
+
11
+ ```bash
12
+ npm install @pithyjs/mcp
13
+ ```
14
+
15
+ ```bash
16
+ pnpm add @pithyjs/mcp
17
+ ```
18
+
19
+ ```bash
20
+ yarn add @pithyjs/mcp
21
+ ```
22
+
23
+ <!-- @codex:end -->
24
+
25
+ You do not need to install it to use it: `npx @pithyjs/mcp` runs the server.
26
+
27
+ ## Two modes
28
+
29
+ | Mode | Command | Answers from | Covers |
30
+ | ---------------- | ---------------------------------------- | -------------------------------------------------------------------- | ------------------------------------ |
31
+ | Public (default) | `pithy-mcp` | `dist/snapshot.json`, built from the repo when this package is built | Published packages only |
32
+ | Repo | `pithy-mcp --source=repo [--root <dir>]` | A PithyJS checkout, read when the server starts | Every package, private ones included |
33
+
34
+ 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.
35
+
36
+ ### `.mcp.json`, public mode
37
+
38
+ ```json
39
+ {
40
+ "mcpServers": {
41
+ "pithyjs": {
42
+ "command": "npx",
43
+ "args": ["-y", "@pithyjs/mcp@beta"]
44
+ }
45
+ }
46
+ }
47
+ ```
48
+
49
+ ### `.mcp.json`, repo mode (inside a PithyJS checkout)
50
+
51
+ ```json
52
+ {
53
+ "mcpServers": {
54
+ "pithyjs": {
55
+ "command": "node",
56
+ "args": ["packages/mcp/dist/cli.js", "--source=repo"]
57
+ }
58
+ }
59
+ }
60
+ ```
61
+
62
+ 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.
63
+
64
+ ## Tools
65
+
66
+ | Group | Tool | Input | Returns |
67
+ | -------- | -------------------- | ------------------------------------------------------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
68
+ | Know | `search` | `query`, `limit?` (1–50, default 10) | Ranked entries, APIs and components, each with citations |
69
+ | 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 |
70
+ | Know | `get_component` | `name`: `Button`, `button`, `cta-section` or `ui.button` | The component's PIDL spec and its file |
71
+ | Know | `get_tokens` | `category?`: `color`, `space`, `radius`… | Token names from the design system's generated manifest |
72
+ | 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 |
73
+ | 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` |
74
+ | 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 |
75
+ | Fix | `explain_error` | `message` | The catalog's explanation and the file that emits the message, or `found: false` with related search hits |
76
+ | 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 |
77
+ | 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 |
78
+
79
+ 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.
80
+
81
+ `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`.
82
+
83
+ ## Resources
84
+
85
+ | URI | Content |
86
+ | -------------------------- | ------------------------------------------ |
87
+ | `pithy://entry/{id}` | An entry, as `get_api` returns it |
88
+ | `pithy://component/{name}` | A PIDL spec, as `get_component` returns it |
89
+ | `pithy://tokens` | Every token name |
90
+
91
+ ## Input guard
92
+
93
+ 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.
94
+
95
+ ## Programmatic use
96
+
97
+ ```ts
98
+ import { connectPithyServer, createPithyServer, loadSnapshot } from '@pithyjs/mcp';
99
+ import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
100
+
101
+ await connectPithyServer(createPithyServer(loadSnapshot()), new StdioServerTransport());
102
+ ```
103
+
104
+ Importing the package starts nothing. `buildKnowledge(root, 'public' | 'all')` builds the knowledge from a checkout.
105
+
106
+ ## API
107
+
108
+ <!-- @codex:auto api="pithy.mcp.*" -->
109
+ <!-- @codex:end -->
110
+
111
+ ## Examples
112
+
113
+ <!-- @codex:auto examples="pithy.mcp.*" limit="3" -->
114
+ <!-- @codex:end -->
115
+
116
+ ## Testing
117
+
118
+ <!-- @codex:auto testing="pithy.mcp.server" -->
119
+ <!-- @codex:end -->
120
+
121
+ ```bash
122
+ pnpm --filter @pithyjs/mcp build # the bin test spawns dist/cli.js
123
+ cd packages/mcp && pnpm vitest run
124
+ ```
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
+ }
@@ -0,0 +1,41 @@
1
+ /** @codex { "id": "pithy.mcp.guard", "title": "MCP Input Guard", "category": "feature", "risk": "high" } */
2
+ import type { Transport } from '@modelcontextprotocol/sdk/shared/transport.js';
3
+ /** @codexApi {"parent":"pithy.mcp.guard","name":"GuardLimits","stability":"experimental","signature":"interface GuardLimits { maxDepth: number; maxValues: number; maxChars: number }"} */
4
+ /** The bounds {@link guardInput} enforces. */
5
+ export interface GuardLimits {
6
+ /** Deepest nesting of objects and arrays. */
7
+ maxDepth: number;
8
+ /** Most values, counting every object, array and primitive. */
9
+ maxValues: number;
10
+ /** Most characters, summed over every string and key. */
11
+ maxChars: number;
12
+ }
13
+ /** @codexApi {"parent":"pithy.mcp.guard","name":"GuardError","stability":"experimental","signature":"class GuardError extends Error"} */
14
+ /** Thrown by {@link guardInput}; the message names the offending path. */
15
+ export declare class GuardError extends Error {
16
+ name: string;
17
+ }
18
+ /**
19
+ * Rejects a value that is not plain JSON data, before any schema parses it.
20
+ *
21
+ * Forbids own keys `__proto__`, `constructor` and `prototype` at any depth,
22
+ * symbol keys and values, functions, and objects other than plain objects and
23
+ * arrays, and caps depth, value count and total characters.
24
+ *
25
+ * @param value - Raw tool arguments.
26
+ * @param limits - The bounds to hold `value` to.
27
+ * @throws {GuardError} On the first violation found.
28
+ */
29
+ /** @codexApi {"parent":"pithy.mcp.guard","name":"guardInput","stability":"experimental","signature":"(value: unknown, limits?: GuardLimits) => void"} */
30
+ export declare function guardInput(value: unknown, limits?: GuardLimits): void;
31
+ /**
32
+ * Wraps a transport so that every `tools/call` (and `resources/read`) is run
33
+ * through {@link guardInput} as it arrives, before the SDK's schemas parse
34
+ * it. A rejected request is answered with JSON-RPC error -32602 and is never
35
+ * passed on.
36
+ *
37
+ * @param inner - The transport to read from.
38
+ * @returns A transport to hand to `McpServer.connect`.
39
+ */
40
+ /** @codexApi {"parent":"pithy.mcp.guard","name":"guardTransport","stability":"experimental","signature":"(inner: Transport) => Transport"} */
41
+ export declare function guardTransport(inner: Transport): Transport;