@exhaustive-ui/mcp 0.0.0-stage → 3.0.0-alpha.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.
Files changed (121) hide show
  1. package/LICENSE +23 -0
  2. package/README.md +167 -2
  3. package/data/components/accordion.md +421 -0
  4. package/data/components/animateonscroll.md +163 -0
  5. package/data/components/autocomplete.md +1077 -0
  6. package/data/components/autofocus.md +38 -0
  7. package/data/components/avatar.md +417 -0
  8. package/data/components/badge.md +234 -0
  9. package/data/components/blockui.md +108 -0
  10. package/data/components/breadcrumb.md +178 -0
  11. package/data/components/button.md +774 -0
  12. package/data/components/card.md +138 -0
  13. package/data/components/carousel.md +440 -0
  14. package/data/components/cascadeselect.md +1387 -0
  15. package/data/components/chart.md +1178 -0
  16. package/data/components/checkbox.md +529 -0
  17. package/data/components/chip.md +180 -0
  18. package/data/components/colorpicker.md +301 -0
  19. package/data/components/confirmdialog.md +287 -0
  20. package/data/components/confirmpopup.md +417 -0
  21. package/data/components/contextmenu.md +491 -0
  22. package/data/components/dataview.md +600 -0
  23. package/data/components/datepicker.md +1262 -0
  24. package/data/components/dialog.md +622 -0
  25. package/data/components/divider.md +250 -0
  26. package/data/components/dock.md +500 -0
  27. package/data/components/dragdrop.md +285 -0
  28. package/data/components/drawer.md +510 -0
  29. package/data/components/dynamicdialog.md +109 -0
  30. package/data/components/editor.md +291 -0
  31. package/data/components/fieldset.md +182 -0
  32. package/data/components/fileupload.md +430 -0
  33. package/data/components/floatlabel.md +155 -0
  34. package/data/components/fluid.md +72 -0
  35. package/data/components/focustrap.md +65 -0
  36. package/data/components/galleria.md +627 -0
  37. package/data/components/iconfield.md +246 -0
  38. package/data/components/iftalabel.md +105 -0
  39. package/data/components/imagecompare.md +97 -0
  40. package/data/components/inplace.md +233 -0
  41. package/data/components/inputgroup.md +306 -0
  42. package/data/components/inputmask.md +518 -0
  43. package/data/components/inputnumber.md +675 -0
  44. package/data/components/inputotp.md +336 -0
  45. package/data/components/inputtext.md +488 -0
  46. package/data/components/keyfilter.md +85 -0
  47. package/data/components/knob.md +462 -0
  48. package/data/components/listbox.md +798 -0
  49. package/data/components/llms.md +28 -0
  50. package/data/components/megamenu.md +587 -0
  51. package/data/components/menu.md +483 -0
  52. package/data/components/menubar.md +462 -0
  53. package/data/components/message.md +449 -0
  54. package/data/components/metergroup.md +241 -0
  55. package/data/components/multiselect.md +1047 -0
  56. package/data/components/orderlist.md +342 -0
  57. package/data/components/organizationchart.md +197 -0
  58. package/data/components/overlay.md +217 -0
  59. package/data/components/paginator.md +314 -0
  60. package/data/components/panel.md +214 -0
  61. package/data/components/panelmenu.md +699 -0
  62. package/data/components/password.md +570 -0
  63. package/data/components/picklist.md +420 -0
  64. package/data/components/popover.md +378 -0
  65. package/data/components/progressbar.md +181 -0
  66. package/data/components/progressspinner.md +91 -0
  67. package/data/components/radiobutton.md +377 -0
  68. package/data/components/rating.md +312 -0
  69. package/data/components/ripple.md +89 -0
  70. package/data/components/scroller.md +122 -0
  71. package/data/components/scrollpanel.md +149 -0
  72. package/data/components/scrolltop.md +105 -0
  73. package/data/components/select.md +1206 -0
  74. package/data/components/selectbutton.md +356 -0
  75. package/data/components/skeleton.md +242 -0
  76. package/data/components/slider.md +337 -0
  77. package/data/components/speeddial.md +589 -0
  78. package/data/components/splitbutton.md +945 -0
  79. package/data/components/splitter.md +196 -0
  80. package/data/components/stepper.md +411 -0
  81. package/data/components/styleclass.md +126 -0
  82. package/data/components/table.md +4557 -0
  83. package/data/components/tabs.md +467 -0
  84. package/data/components/tag.md +200 -0
  85. package/data/components/terminal.md +118 -0
  86. package/data/components/textarea.md +416 -0
  87. package/data/components/tieredmenu.md +578 -0
  88. package/data/components/timeline.md +310 -0
  89. package/data/components/toast.md +596 -0
  90. package/data/components/togglebutton.md +356 -0
  91. package/data/components/toggleswitch.md +285 -0
  92. package/data/components/toolbar.md +182 -0
  93. package/data/components/tooltip.md +211 -0
  94. package/data/components/tree.md +746 -0
  95. package/data/components/treeselect.md +912 -0
  96. package/data/components/treetable.md +2814 -0
  97. package/data/components.json +43751 -0
  98. package/data/llms-full.txt +47433 -0
  99. package/data/llms.txt +121 -0
  100. package/data/manifest.json +46513 -0
  101. package/data/pages/accessibility.md +28 -0
  102. package/data/pages/animations.md +28 -0
  103. package/data/pages/configuration.md +210 -0
  104. package/data/pages/contribution.md +20 -0
  105. package/data/pages/customicons.md +20 -0
  106. package/data/pages/faq.md +20 -0
  107. package/data/pages/icons.md +66 -0
  108. package/data/pages/installation.md +71 -0
  109. package/data/pages/llms.md +61 -0
  110. package/data/pages/passthrough.md +32 -0
  111. package/data/pages/philosophy.md +28 -0
  112. package/data/pages/primeflex.md +20 -0
  113. package/data/pages/rtl.md +12 -0
  114. package/data/pages/styled.md +132 -0
  115. package/data/pages/tailwind.md +40 -0
  116. package/data/pages/unstyled.md +39 -0
  117. package/data/snapshot.json +9 -0
  118. package/dist/index.d.mts +448 -0
  119. package/dist/index.mjs +2501 -0
  120. package/dist/index.mjs.map +1 -0
  121. package/package.json +67 -3
package/dist/index.mjs ADDED
@@ -0,0 +1,2501 @@
1
+ #!/usr/bin/env node
2
+ import { readFileSync, realpathSync } from "node:fs";
3
+ import { fileURLToPath } from "node:url";
4
+ import { McpServer, ResourceTemplate } from "@modelcontextprotocol/sdk/server/mcp.js";
5
+ import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
6
+ import { z } from "zod";
7
+ import { readFile } from "node:fs/promises";
8
+ import path from "node:path";
9
+
10
+ //#region src/config.ts
11
+ const DEFAULT_DOCS_URL = "https://exhaustive-ui.e-xiste.com";
12
+ const DEFAULT_CACHE_TTL_SECONDS = 900;
13
+ const DEFAULT_FETCH_TIMEOUT_MS = 1e4;
14
+ const RESOURCE_BASE_URI = "exhaustive-ui://docs";
15
+ /** Package-relative path of the offline snapshot written by scripts/prebuild.mjs (works from src/ and from dist/). */
16
+ const DEFAULT_SNAPSHOT_DIR = fileURLToPath(new URL("../data", import.meta.url));
17
+ function resolveConfig(env = process.env, overrides = {}) {
18
+ return {
19
+ docsUrl: (overrides.docsUrl ?? env.EXHAUSTIVE_UI_DOCS_URL ?? "https://exhaustive-ui.e-xiste.com").replace(/\/+$/, ""),
20
+ cacheTtlMs: overrides.cacheTtlMs ?? parseNumber(env.EXHAUSTIVE_UI_MCP_CACHE_TTL, 900) * 1e3,
21
+ fetchTimeoutMs: overrides.fetchTimeoutMs ?? parseNumber(env.EXHAUSTIVE_UI_MCP_FETCH_TIMEOUT, 1e4),
22
+ offline: overrides.offline ?? parseBoolean(env.EXHAUSTIVE_UI_MCP_OFFLINE),
23
+ snapshotDir: "snapshotDir" in overrides ? overrides.snapshotDir : env.EXHAUSTIVE_UI_MCP_SNAPSHOT_DIR ?? DEFAULT_SNAPSHOT_DIR
24
+ };
25
+ }
26
+ function parseNumber(value, fallback) {
27
+ if (value === void 0 || value.trim() === "") return fallback;
28
+ const parsed = Number(value);
29
+ return Number.isFinite(parsed) && parsed >= 0 ? parsed : fallback;
30
+ }
31
+ function parseBoolean(value) {
32
+ return value !== void 0 && [
33
+ "1",
34
+ "true",
35
+ "yes",
36
+ "on"
37
+ ].includes(value.trim().toLowerCase());
38
+ }
39
+
40
+ //#endregion
41
+ //#region src/errors.ts
42
+ /** A tool request that cannot be fulfilled; the structured content is returned to the client next to the message. */
43
+ var ToolError = class extends Error {
44
+ structuredContent;
45
+ constructor(message, structuredContent = {}) {
46
+ super(message);
47
+ this.structuredContent = structuredContent;
48
+ this.name = "ToolError";
49
+ }
50
+ };
51
+ /** The docs source has no such document (HTTP 404, SPA fallback page, or missing snapshot file). */
52
+ var DocsNotFoundError = class extends Error {
53
+ path;
54
+ constructor(path, message = `Document "${path}" not found`) {
55
+ super(message);
56
+ this.path = path;
57
+ this.name = "DocsNotFoundError";
58
+ }
59
+ };
60
+ /** The docs source could not be reached or answered with an error. */
61
+ var DocsFetchError = class extends Error {
62
+ path;
63
+ constructor(path, message, options) {
64
+ super(message, options);
65
+ this.path = path;
66
+ this.name = "DocsFetchError";
67
+ }
68
+ };
69
+ /** First line of an error message, with local filesystem paths redacted. */
70
+ function describeError(error) {
71
+ return (error instanceof Error ? error.message : String(error)).split(/\r?\n/, 1)[0].trim().replace(/(?:[A-Za-z]:\\|\/(?:Users|private|tmp|var|home|root)\/)[^\s]+/g, "[redacted path]") || "Tool request failed unexpectedly.";
72
+ }
73
+
74
+ //#endregion
75
+ //#region src/text.ts
76
+ /** Lower-case, dash-separated form of a name, route or title ("Angular Button Component" -> "angular-button-component"). */
77
+ function slugify(value) {
78
+ return value.trim().toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "");
79
+ }
80
+ /** Letters and digits only ("Angular CLI" -> "angularcli"); used to compare environment names and selectors loosely. */
81
+ function compact(value) {
82
+ return value.trim().toLowerCase().replace(/[^a-z0-9]+/g, "");
83
+ }
84
+ function unique(values) {
85
+ return [...new Set(values)];
86
+ }
87
+ const STOP_WORDS = /* @__PURE__ */ new Set([
88
+ "a",
89
+ "an",
90
+ "and",
91
+ "as",
92
+ "by",
93
+ "for",
94
+ "from",
95
+ "how",
96
+ "i",
97
+ "in",
98
+ "is",
99
+ "of",
100
+ "on",
101
+ "or",
102
+ "the",
103
+ "to",
104
+ "use",
105
+ "with"
106
+ ]);
107
+ /** Significant search terms of a query. */
108
+ function tokenize(value) {
109
+ return unique(slugify(value).split("-").filter((term) => term.length > 1 && !STOP_WORDS.has(term)));
110
+ }
111
+ const SYNONYMS = {
112
+ busy: ["loading", "spinner"],
113
+ calendar: ["datepicker", "date"],
114
+ chips: ["autocomplete", "multiple"],
115
+ danger: ["severity", "error"],
116
+ date: ["datepicker", "calendar"],
117
+ datatable: ["table"],
118
+ dialog: ["modal", "popup"],
119
+ dropdown: ["select"],
120
+ error: [
121
+ "danger",
122
+ "severity",
123
+ "invalid"
124
+ ],
125
+ filter: [
126
+ "filtering",
127
+ "filters",
128
+ "filtered",
129
+ "search"
130
+ ],
131
+ filtering: ["filter"],
132
+ filters: ["filter"],
133
+ form: [
134
+ "forms",
135
+ "ngmodel",
136
+ "reactive"
137
+ ],
138
+ forms: ["form"],
139
+ icon: ["icons"],
140
+ icons: ["icon"],
141
+ inputswitch: ["toggleswitch"],
142
+ lazy: [
143
+ "virtual",
144
+ "scroller",
145
+ "loading"
146
+ ],
147
+ load: ["loading"],
148
+ loading: [
149
+ "load",
150
+ "spinner",
151
+ "busy"
152
+ ],
153
+ menu: [
154
+ "menubar",
155
+ "tieredmenu",
156
+ "contextmenu",
157
+ "panelmenu"
158
+ ],
159
+ modal: ["dialog"],
160
+ notification: ["toast", "message"],
161
+ overlaypanel: ["popover"],
162
+ page: [
163
+ "paginator",
164
+ "pagination",
165
+ "pages"
166
+ ],
167
+ pages: ["paginator", "pagination"],
168
+ paginate: ["paginator", "pagination"],
169
+ pagination: ["paginator", "page"],
170
+ paginator: ["pagination", "page"],
171
+ popup: [
172
+ "popover",
173
+ "dialog",
174
+ "overlay"
175
+ ],
176
+ pt: ["passthrough", "pass"],
177
+ passthrough: ["pt"],
178
+ select: [
179
+ "selection",
180
+ "selected",
181
+ "dropdown"
182
+ ],
183
+ selected: ["selection", "select"],
184
+ selection: ["select", "selected"],
185
+ severity: [
186
+ "danger",
187
+ "error",
188
+ "success",
189
+ "warn",
190
+ "info"
191
+ ],
192
+ sidebar: ["drawer"],
193
+ sort: [
194
+ "sorting",
195
+ "sortable",
196
+ "sorted"
197
+ ],
198
+ sortable: ["sort"],
199
+ sorting: ["sort"],
200
+ spinner: ["loading", "progressspinner"],
201
+ switch: ["toggleswitch"],
202
+ tab: ["tabs"],
203
+ tabview: ["tabs"],
204
+ template: [
205
+ "templates",
206
+ "templating",
207
+ "ng-template"
208
+ ],
209
+ templates: ["template"],
210
+ templating: ["template"],
211
+ theme: [
212
+ "theming",
213
+ "themes",
214
+ "tokens",
215
+ "preset"
216
+ ],
217
+ themes: ["theme"],
218
+ theming: ["theme"],
219
+ toggle: ["togglebutton", "toggleswitch"],
220
+ token: ["tokens", "theming"],
221
+ tokens: ["token", "theming"],
222
+ tooltip: ["tooltips"],
223
+ validation: ["invalid", "forms"],
224
+ virtual: [
225
+ "scroller",
226
+ "virtualscroll",
227
+ "lazy"
228
+ ]
229
+ };
230
+ /** Crude English stemmer, good enough to match "sorting" against "sortable". */
231
+ function stem(term) {
232
+ return term.replace(/(?:ing|ers|er|ed|es|s)$/i, "").replace(/(?:tion|ions)$/i, "t").replace(/(?:able)$/i, "");
233
+ }
234
+ /** A term together with its synonyms and stem; every entry is at least two characters long. */
235
+ function expandTerm(term) {
236
+ const base = slugify(term);
237
+ const variants = /* @__PURE__ */ new Set([base]);
238
+ for (const synonym of SYNONYMS[base] ?? []) variants.add(synonym);
239
+ const stemmed = stem(base);
240
+ if (stemmed !== base) variants.add(stemmed);
241
+ return [...variants].filter((variant) => variant.length > 1);
242
+ }
243
+ /** Whether one of the (expanded) terms occurs in the text; prefix matches count for terms longer than three characters. */
244
+ function matchesTerm(term, lowerText, textTerms) {
245
+ return expandTerm(term).some((variant) => lowerText.includes(variant) || textTerms.includes(variant) || textTerms.some((textTerm) => variant.length > 3 && textTerm.length > 3 && (textTerm.startsWith(variant) || variant.startsWith(textTerm))));
246
+ }
247
+ /** Up to five short excerpts around the occurrences of the needle. */
248
+ function snippets(text, needle, limit = 5) {
249
+ const lower = text.toLowerCase();
250
+ const target = needle.toLowerCase();
251
+ const results = [];
252
+ let index = lower.indexOf(target);
253
+ while (index !== -1 && results.length < limit) {
254
+ const start = Math.max(0, index - 45);
255
+ const end = Math.min(text.length, index + target.length + 45);
256
+ results.push(text.slice(start, end).replace(/\s+/g, " ").trim());
257
+ index = lower.indexOf(target, index + target.length);
258
+ }
259
+ return results;
260
+ }
261
+ /** The best snippets for a term, trying its synonyms when the term itself does not occur. */
262
+ function snippetsForTerm(text, term) {
263
+ for (const variant of expandTerm(term)) {
264
+ const found = snippets(text, variant);
265
+ if (found.length > 0) return found;
266
+ }
267
+ return [];
268
+ }
269
+ /** Human readable title without the "Angular ... Component" wrapper of the generated docs ("Angular Button Component" -> "Button"). */
270
+ function shortTitle(title) {
271
+ return title.replace(/^Angular\s+/i, "").replace(/\s+(Component|Directive|API)$/i, "");
272
+ }
273
+
274
+ //#endregion
275
+ //#region src/catalog.ts
276
+ /** Names PrimeNG users (and older ExhaustiveUI versions) may still use for a component. */
277
+ const COMPONENT_ALIASES = {
278
+ calendar: "datepicker",
279
+ chips: "autocomplete",
280
+ "data-table": "table",
281
+ datatable: "table",
282
+ dropdown: "select",
283
+ "inplace-editor": "inplace",
284
+ inputswitch: "toggleswitch",
285
+ overlaypanel: "popover",
286
+ sidebar: "drawer",
287
+ tabview: "tabs",
288
+ virtualscroller: "scroller"
289
+ };
290
+ /** Normalize the two generated indexes into one catalog. */
291
+ function buildCatalog(componentsJson, manifest, options = {}) {
292
+ const base = (options.resourceBaseUri ?? "exhaustive-ui://docs").replace(/\/+$/, "");
293
+ const site = manifest.site.replace(/\/+$/, "");
294
+ const entryPoints = new Map(manifest.entryPoints.map((entryPoint) => [entryPoint.name, entryPoint]));
295
+ const guideNames = new Set(componentsJson.pages.map((page) => page.name));
296
+ const guides = componentsJson.pages.map((page) => ({
297
+ kind: "guide",
298
+ name: page.name,
299
+ title: page.title,
300
+ description: page.description ?? "",
301
+ route: `/${page.path}`,
302
+ publicUrl: `${site}/${page.path}`,
303
+ markdownUrl: `${site}/llms/pages/${page.name}.md`,
304
+ docPath: `pages/${page.name}.md`,
305
+ resourceUri: `${base}/pages/${page.name}.md`,
306
+ sections: page.sections.map(normalizeSection)
307
+ }));
308
+ const components = componentsJson.components.filter((component) => entryPoints.has(component.name) || !guideNames.has(component.name) && component.sections.some((section) => section.examples?.typescript || section.examples?.html)).map((component) => {
309
+ const entryPoint = entryPoints.get(component.name);
310
+ const declarations = entryPoint?.declarations ?? [];
311
+ return {
312
+ kind: "component",
313
+ name: component.name,
314
+ title: component.title,
315
+ description: component.description ?? "",
316
+ route: `/${component.name}`,
317
+ publicUrl: `${site}/${component.name}`,
318
+ markdownUrl: `${site}/llms/components/${component.name}.md`,
319
+ docPath: `components/${component.name}.md`,
320
+ resourceUri: `${base}/components/${component.name}.md`,
321
+ apiResourceUri: `${base}/components/${component.name}/api.json`,
322
+ import: entryPoint?.import,
323
+ modules: entryPoint?.modules ?? [],
324
+ selectors: unique(declarations.flatMap((declaration) => splitSelectors(declaration.selector))),
325
+ declarations,
326
+ sections: component.sections.map(normalizeSection),
327
+ api: component.api ?? {}
328
+ };
329
+ });
330
+ const componentNames = new Set(components.map((component) => component.name));
331
+ const directives = manifest.entryPoints.flatMap((entryPoint) => (entryPoint.declarations ?? []).filter((declaration) => declaration.kind === "directive" && declaration.selector).map((declaration) => ({
332
+ className: declaration.className,
333
+ selector: declaration.selector,
334
+ entryPoint: entryPoint.name,
335
+ import: entryPoint.import,
336
+ description: declaration.description,
337
+ component: componentNames.has(entryPoint.name) ? entryPoint.name : void 0
338
+ })));
339
+ return {
340
+ libraryVersion: manifest.version,
341
+ docsVersion: componentsJson.version,
342
+ generatedAt: componentsJson.generatedAt,
343
+ site,
344
+ components,
345
+ guides,
346
+ directives
347
+ };
348
+ }
349
+ function normalizeSection(section) {
350
+ const [code, codeLanguage] = pickCode(section.examples ?? void 0);
351
+ return {
352
+ id: section.id,
353
+ label: section.label,
354
+ description: section.description || void 0,
355
+ hasCode: code !== void 0,
356
+ codeLanguage,
357
+ code
358
+ };
359
+ }
360
+ function pickCode(examples) {
361
+ if (examples?.typescript?.trim()) return [examples.typescript, "typescript"];
362
+ if (examples?.html?.trim()) return [examples.html, "html"];
363
+ if (examples?.command?.trim()) return [examples.command, "bash"];
364
+ return [void 0, void 0];
365
+ }
366
+ /** "p-autoComplete, p-autocomplete, p-auto-complete" -> three selectors. */
367
+ function splitSelectors(selector) {
368
+ return (selector ?? "").split(",").map((part) => part.trim()).filter(Boolean);
369
+ }
370
+ /** Attribute name of an attribute selector ("[pTooltip]" -> "pTooltip"), or undefined for element selectors. */
371
+ function attributeSelectorName(selector) {
372
+ return /^\[([^\]=]+)(?:=[^\]]*)?\]$/.exec(selector.trim())?.[1];
373
+ }
374
+ /** Every spelling under which a component can be requested. */
375
+ function componentKeys(component) {
376
+ const keys = [
377
+ component.name,
378
+ shortTitle(component.title),
379
+ component.import?.split("/").pop() ?? ""
380
+ ];
381
+ for (const selector of component.selectors) {
382
+ const attribute = attributeSelectorName(selector);
383
+ keys.push(attribute ?? selector, (attribute ?? selector).replace(/^p-?/i, ""));
384
+ }
385
+ for (const declaration of component.declarations) keys.push(declaration.className);
386
+ return unique(keys.map(compact).filter(Boolean));
387
+ }
388
+ /** Resolve a component by name, title, selector, class name, alias, route or URL. */
389
+ function findComponent(catalog, query) {
390
+ const raw = query.trim();
391
+ const candidates = unique([raw, raw.replace(/^https?:\/\/[^/]+/, "").replace(/^exhaustive-ui:\/\/docs/, "").replace(/\.md$/, "").replace(/\/api\.json$/, "").split("/").filter(Boolean).pop() ?? raw].map(compact).filter(Boolean));
392
+ const aliased = candidates.map((candidate) => COMPONENT_ALIASES[candidate]).filter((name) => !!name);
393
+ for (const candidate of [...candidates, ...aliased.map(compact)]) {
394
+ const exact = catalog.components.find((component) => component.name === candidate) ?? catalog.components.find((component) => componentKeys(component).includes(candidate));
395
+ if (exact) return exact;
396
+ }
397
+ const suggestions = suggestComponents(catalog, raw);
398
+ throw new ToolError(`Component "${query}" not found.${suggestions.length ? ` Did you mean: ${suggestions.join(", ")}?` : ""}`, {
399
+ component: query,
400
+ suggestions,
401
+ nextCall: {
402
+ tool: "list",
403
+ arguments: { kind: "components" }
404
+ }
405
+ });
406
+ }
407
+ function suggestComponents(catalog, query, limit = 5) {
408
+ const needle = compact(query);
409
+ const terms = expandTerm(query).map(compact);
410
+ return catalog.components.map((component) => {
411
+ const keys = componentKeys(component);
412
+ let score = 0;
413
+ if (needle && keys.some((key) => key.startsWith(needle) || needle.startsWith(key))) score += 10;
414
+ if (needle && keys.some((key) => editDistance(key, needle) <= Math.max(1, Math.floor(needle.length / 4)))) score += 8;
415
+ if (needle && keys.some((key) => key.includes(needle) || needle.includes(key))) score += 5;
416
+ if (needle.length >= 4 && keys.some((key) => key.slice(0, 4) === needle.slice(0, 4))) score += 3;
417
+ if (terms.some((term) => keys.some((key) => key.includes(term)))) score += 2;
418
+ return {
419
+ name: component.name,
420
+ score
421
+ };
422
+ }).filter((entry) => entry.score > 0).sort((a, b) => b.score - a.score || a.name.localeCompare(b.name)).slice(0, limit).map((entry) => entry.name);
423
+ }
424
+ /** Levenshtein distance, for "did you mean" suggestions on short names. */
425
+ function editDistance(a, b) {
426
+ if (a === b) return 0;
427
+ let previous = Array.from({ length: b.length + 1 }, (_, index) => index);
428
+ for (let i = 1; i <= a.length; i++) {
429
+ const current = [i];
430
+ for (let j = 1; j <= b.length; j++) current[j] = Math.min(previous[j] + 1, current[j - 1] + 1, previous[j - 1] + (a[i - 1] === b[j - 1] ? 0 : 1));
431
+ previous = current;
432
+ }
433
+ return previous[b.length];
434
+ }
435
+ /** Resolve a guide by name ("installation"), route ("theming/styled"), title, markdown path or URL. */
436
+ function findGuide(catalog, query) {
437
+ const normalized = normalizeGuidePath(query);
438
+ const last = normalized.split("/").pop() ?? normalized;
439
+ const byPath = catalog.guides.filter((guide) => guideKeys(guide).includes(normalized));
440
+ if (byPath.length === 1) return byPath[0];
441
+ const byName = catalog.guides.filter((guide) => [
442
+ guide.name,
443
+ slugify(guide.title),
444
+ compact(guide.title)
445
+ ].includes(last) || compact(guide.name) === compact(last));
446
+ if (byName.length === 1) return byName[0];
447
+ const candidates = byPath.length > 1 ? byPath : byName;
448
+ if (candidates.length > 1) throw new ToolError(`Guide "${query}" is ambiguous. Use the full route of one of the candidates.`, {
449
+ guide: query,
450
+ candidates: candidates.map((guide) => ({
451
+ name: guide.name,
452
+ title: guide.title,
453
+ route: guide.route,
454
+ resourceUri: guide.resourceUri
455
+ }))
456
+ });
457
+ throw new ToolError(`Guide "${query}" not found.`, {
458
+ guide: query,
459
+ availableGuides: catalog.guides.map((guide) => guide.route.slice(1)),
460
+ nextCall: {
461
+ tool: "list",
462
+ arguments: { kind: "guides" }
463
+ }
464
+ });
465
+ }
466
+ function guideKeys(guide) {
467
+ return unique([
468
+ guide.name,
469
+ guide.route.slice(1),
470
+ guide.docPath.replace(/\.md$/, ""),
471
+ slugify(guide.title)
472
+ ].map(normalizeGuidePath));
473
+ }
474
+ function normalizeGuidePath(value) {
475
+ return value.trim().toLowerCase().replace(/^exhaustive-ui:\/\/docs\//, "").replace(/^https?:\/\/[^/]+\//, "").replace(/^llms\/pages\//, "").replace(/^pages\//, "").replace(/\.md$/, "").split("/").map(slugify).filter(Boolean).join("/");
476
+ }
477
+ /** Resolve a section of a component or guide by id or label; undefined when nothing matches. */
478
+ function findSection(sections, query) {
479
+ const needle = compact(query);
480
+ return sections.find((section) => compact(section.id) === needle || compact(section.label) === needle) ?? sections.find((section) => slugify(section.label).includes(slugify(query)));
481
+ }
482
+ function requireSection(sections, query) {
483
+ const section = findSection(sections, query);
484
+ if (!section) throw new ToolError(`Section "${query}" not found.`, {
485
+ section: query,
486
+ availableSections: sections.map((entry) => entry.id)
487
+ });
488
+ return section;
489
+ }
490
+ /** Loads and caches the catalog; a rebuild only happens when the source hands back different index documents. */
491
+ var CatalogLoader = class {
492
+ source;
493
+ options;
494
+ cached;
495
+ constructor(source, options = {}) {
496
+ this.source = source;
497
+ this.options = options;
498
+ }
499
+ async load() {
500
+ const [components, manifest] = await Promise.all([this.source.readText("components.json"), this.source.readText("manifest.json")]);
501
+ if (this.cached && this.cached.components === components && this.cached.manifest === manifest) return this.cached.catalog;
502
+ const catalog = buildCatalog(parseJson(components, "components.json"), parseJson(manifest, "manifest.json"), this.options);
503
+ this.cached = {
504
+ components,
505
+ manifest,
506
+ catalog
507
+ };
508
+ return catalog;
509
+ }
510
+ };
511
+ function parseJson(text, name) {
512
+ try {
513
+ return JSON.parse(text);
514
+ } catch (error) {
515
+ throw new Error(`${name} is not valid JSON: ${error.message}`);
516
+ }
517
+ }
518
+
519
+ //#endregion
520
+ //#region src/source.ts
521
+ const DOCS_PATH_PATTERN = /^(?:components\.json|manifest\.json|llms\.txt|llms-full\.txt|(?:components|pages)\/[a-z0-9][a-z0-9._-]*\.md)$/;
522
+ /** Reject anything that is not one of the generated docs files, so a crafted resource URI cannot read elsewhere. */
523
+ function assertDocsPath(docsPath) {
524
+ if (!DOCS_PATH_PATTERN.test(docsPath)) throw new DocsNotFoundError(docsPath, `"${docsPath}" is not a generated docs file`);
525
+ return docsPath;
526
+ }
527
+ /** In-memory documents, for tests and embedding. */
528
+ var MemorySource = class {
529
+ documents;
530
+ kind = "memory";
531
+ constructor(documents = /* @__PURE__ */ new Map()) {
532
+ this.documents = documents;
533
+ }
534
+ async readText(docsPath) {
535
+ const text = this.documents.get(assertDocsPath(docsPath));
536
+ if (text === void 0) throw new DocsNotFoundError(docsPath);
537
+ return text;
538
+ }
539
+ };
540
+ /** The offline snapshot produced at build time by scripts/prebuild.mjs. */
541
+ var SnapshotSource = class {
542
+ directory;
543
+ kind = "snapshot";
544
+ constructor(directory) {
545
+ this.directory = directory;
546
+ }
547
+ async readText(docsPath) {
548
+ const file = path.join(this.directory, assertDocsPath(docsPath));
549
+ try {
550
+ return await readFile(file, "utf8");
551
+ } catch (error) {
552
+ if (error.code === "ENOENT") throw new DocsNotFoundError(docsPath, `Document "${docsPath}" is not in the offline snapshot`);
553
+ throw new DocsFetchError(docsPath, `Cannot read "${docsPath}" from the offline snapshot: ${describeError(error)}`, { cause: error });
554
+ }
555
+ }
556
+ };
557
+ /** The live docs site. A not-found path is served as the SPA shell with HTTP 200, so HTML answers are treated as misses. */
558
+ var RemoteSource = class {
559
+ options;
560
+ kind = "remote";
561
+ fetchImpl;
562
+ constructor(options) {
563
+ this.options = options;
564
+ this.fetchImpl = options.fetchImpl ?? globalThis.fetch;
565
+ }
566
+ urlFor(docsPath) {
567
+ return `${this.options.baseUrl.replace(/\/+$/, "")}/llms/${assertDocsPath(docsPath)}`;
568
+ }
569
+ async readText(docsPath) {
570
+ const url = this.urlFor(docsPath);
571
+ let response;
572
+ try {
573
+ response = await this.fetchImpl(url, {
574
+ signal: AbortSignal.timeout(this.options.timeoutMs),
575
+ headers: {
576
+ accept: "text/markdown, text/plain, application/json;q=0.9, */*;q=0.1",
577
+ "user-agent": this.options.userAgent ?? "@exhaustive-ui/mcp"
578
+ }
579
+ });
580
+ } catch (error) {
581
+ throw new DocsFetchError(docsPath, `Cannot reach ${url}: ${describeError(error)}`, { cause: error });
582
+ }
583
+ if (response.status === 404) throw new DocsNotFoundError(docsPath, `${url} answered HTTP 404`);
584
+ if (!response.ok) throw new DocsFetchError(docsPath, `${url} answered HTTP ${response.status}`);
585
+ const text = await response.text();
586
+ if (/text\/html/i.test(response.headers.get("content-type") ?? "") || /^\s*<(?:!doctype|html)/i.test(text)) throw new DocsNotFoundError(docsPath, `${url} is not published (the site answered with its HTML shell)`);
587
+ return text;
588
+ }
589
+ };
590
+ /** Remembers documents for a TTL, dedupes concurrent reads, and serves a stale copy when a refresh fails. */
591
+ var CachedSource = class {
592
+ inner;
593
+ options;
594
+ kind;
595
+ entries = /* @__PURE__ */ new Map();
596
+ pending = /* @__PURE__ */ new Map();
597
+ now;
598
+ hits = 0;
599
+ misses = 0;
600
+ constructor(inner, options) {
601
+ this.inner = inner;
602
+ this.options = options;
603
+ this.kind = inner.kind;
604
+ this.now = options.now ?? Date.now;
605
+ }
606
+ async readText(docsPath) {
607
+ const cached = this.entries.get(docsPath);
608
+ if (cached && cached.expiresAt > this.now()) {
609
+ this.hits++;
610
+ return cached.value;
611
+ }
612
+ const inFlight = this.pending.get(docsPath);
613
+ if (inFlight) return inFlight;
614
+ this.misses++;
615
+ const request = this.inner.readText(docsPath).then((value) => {
616
+ this.entries.set(docsPath, {
617
+ value,
618
+ expiresAt: this.now() + this.options.ttlMs
619
+ });
620
+ return value;
621
+ }).catch((error) => {
622
+ if (cached) {
623
+ this.entries.set(docsPath, {
624
+ value: cached.value,
625
+ expiresAt: this.now() + this.options.ttlMs
626
+ });
627
+ return cached.value;
628
+ }
629
+ throw error;
630
+ }).finally(() => {
631
+ this.pending.delete(docsPath);
632
+ });
633
+ this.pending.set(docsPath, request);
634
+ return request;
635
+ }
636
+ invalidate() {
637
+ this.entries.clear();
638
+ }
639
+ stats() {
640
+ return {
641
+ entries: this.entries.size,
642
+ hits: this.hits,
643
+ misses: this.misses,
644
+ ttlMs: this.options.ttlMs
645
+ };
646
+ }
647
+ };
648
+ const DEFAULT_FALLBACK_COOLDOWN_MS = 6e4;
649
+ /** Reads from the primary source and falls back to the secondary one when the primary fails for any reason. */
650
+ var FallbackSource = class {
651
+ primary;
652
+ fallback;
653
+ kind;
654
+ cooldownMs;
655
+ now;
656
+ fallbackReads = 0;
657
+ lastFallbackAt;
658
+ lastFallbackReason;
659
+ primarySkippedUntil = 0;
660
+ constructor(primary, fallback, options = {}) {
661
+ this.primary = primary;
662
+ this.fallback = fallback;
663
+ this.kind = `${primary.kind}+${fallback.kind}`;
664
+ this.cooldownMs = options.cooldownMs ?? 6e4;
665
+ this.now = options.now ?? Date.now;
666
+ }
667
+ async readText(docsPath) {
668
+ if (this.primarySkippedUntil > this.now()) try {
669
+ return await this.readFallback(docsPath, void 0);
670
+ } catch {}
671
+ try {
672
+ return await this.primary.readText(docsPath);
673
+ } catch (primaryError) {
674
+ if (primaryError instanceof DocsFetchError) this.primarySkippedUntil = this.now() + this.cooldownMs;
675
+ try {
676
+ return await this.readFallback(docsPath, primaryError);
677
+ } catch (fallbackError) {
678
+ throw primaryError instanceof DocsNotFoundError && fallbackError instanceof DocsNotFoundError ? fallbackError : primaryError;
679
+ }
680
+ }
681
+ }
682
+ async readFallback(docsPath, primaryError) {
683
+ const text = await this.fallback.readText(docsPath);
684
+ this.fallbackReads++;
685
+ this.lastFallbackAt = (/* @__PURE__ */ new Date()).toISOString();
686
+ if (primaryError !== void 0) this.lastFallbackReason = describeError(primaryError);
687
+ return text;
688
+ }
689
+ status() {
690
+ return {
691
+ primary: this.primary.kind,
692
+ fallback: this.fallback.kind,
693
+ fallbackReads: this.fallbackReads,
694
+ lastFallbackAt: this.lastFallbackAt,
695
+ lastFallbackReason: this.lastFallbackReason,
696
+ primarySkippedUntil: this.primarySkippedUntil > this.now() ? new Date(this.primarySkippedUntil).toISOString() : void 0
697
+ };
698
+ }
699
+ };
700
+ /** The runtime source: the live site behind a TTL cache, falling back to the offline snapshot (or the snapshot alone when offline). */
701
+ function createDocsSource(config, fetchImpl) {
702
+ const snapshot = config.snapshotDir ? new SnapshotSource(config.snapshotDir) : void 0;
703
+ if (config.offline) {
704
+ if (!snapshot) throw new Error("Offline mode needs an offline snapshot directory (EXHAUSTIVE_UI_MCP_SNAPSHOT_DIR).");
705
+ return {
706
+ source: snapshot,
707
+ status: () => ({
708
+ mode: "offline",
709
+ docsUrl: config.docsUrl,
710
+ cacheTtlSeconds: 0,
711
+ snapshotDir: snapshot.directory
712
+ })
713
+ };
714
+ }
715
+ const remote = new CachedSource(new RemoteSource({
716
+ baseUrl: config.docsUrl,
717
+ timeoutMs: config.fetchTimeoutMs,
718
+ fetchImpl
719
+ }), { ttlMs: config.cacheTtlMs });
720
+ const fallback = snapshot ? new FallbackSource(remote, snapshot) : void 0;
721
+ return {
722
+ source: fallback ?? remote,
723
+ status: () => ({
724
+ mode: "remote",
725
+ docsUrl: config.docsUrl,
726
+ cacheTtlSeconds: Math.round(config.cacheTtlMs / 1e3),
727
+ snapshotDir: snapshot?.directory,
728
+ fallback: fallback?.status(),
729
+ cache: remote.stats()
730
+ })
731
+ };
732
+ }
733
+
734
+ //#endregion
735
+ //#region src/search.ts
736
+ const indexes = /* @__PURE__ */ new WeakMap();
737
+ /** Search components, guides, API members and examples of the catalog. Results are sorted by relevance. */
738
+ function searchCatalog(catalog, query, scope = "all") {
739
+ const phrase = query.trim().toLowerCase();
740
+ const terms = tokenize(query);
741
+ const entries = indexFor(catalog).filter((entry) => scope === "all" ? entry.scope === "components" || entry.scope === "guides" : entry.scope === scope);
742
+ const hits = [];
743
+ for (const entry of entries) {
744
+ const match = scoreEntry(entry.fields, phrase, terms);
745
+ if (match) hits.push({
746
+ ...entry.result,
747
+ type: String(entry.result.type),
748
+ score: match.score,
749
+ matchedTerms: match.matchedTerms,
750
+ matches: match.matches
751
+ });
752
+ }
753
+ return hits.sort((a, b) => b.score - a.score || b.matchedTerms.length - a.matchedTerms.length || String(a.title ?? a.name).localeCompare(String(b.title ?? b.name)));
754
+ }
755
+ function scoreEntry(fields, phrase, terms) {
756
+ const matchedTerms = /* @__PURE__ */ new Set();
757
+ const matches = [];
758
+ let score = 0;
759
+ let phraseMatched = false;
760
+ for (const field of fields) {
761
+ if (!field.text) continue;
762
+ if (phrase && field.lower.includes(phrase)) {
763
+ phraseMatched = true;
764
+ score += 100 * field.weight;
765
+ matches.push(...snippets(field.text, phrase));
766
+ }
767
+ for (const term of terms) if (matchesTerm(term, field.lower, field.terms)) {
768
+ matchedTerms.add(term);
769
+ score += field.weight;
770
+ matches.push(...snippetsForTerm(field.text, term));
771
+ }
772
+ }
773
+ const required = terms.length <= 2 ? 1 : Math.max(2, Math.ceil(terms.length * .4));
774
+ if (!phraseMatched && matchedTerms.size < required) return;
775
+ return {
776
+ score,
777
+ matchedTerms: [...matchedTerms],
778
+ matches: unique(matches).slice(0, 5)
779
+ };
780
+ }
781
+ function indexFor(catalog) {
782
+ let index = indexes.get(catalog);
783
+ if (!index) {
784
+ index = buildIndex(catalog);
785
+ indexes.set(catalog, index);
786
+ }
787
+ return index;
788
+ }
789
+ function buildIndex(catalog) {
790
+ const entries = [];
791
+ for (const component of catalog.components) {
792
+ entries.push(componentEntry(component));
793
+ entries.push(...apiEntries(component));
794
+ entries.push(...exampleEntries(component));
795
+ }
796
+ for (const guide of catalog.guides) entries.push(guideEntry(guide));
797
+ return entries;
798
+ }
799
+ function componentEntry(component) {
800
+ const api = component.api;
801
+ const apiText = [
802
+ ...api.props ?? [],
803
+ ...api.emits ?? [],
804
+ ...api.templates ?? [],
805
+ ...api.methods ?? [],
806
+ ...api.pt ?? []
807
+ ].map((member) => `${member.name} ${member.description ?? ""}`).join(" ");
808
+ const sectionsText = component.sections.map((section) => `${section.label} ${section.description ?? ""}`).join(" ");
809
+ const codeText = component.sections.map((section) => section.code ?? "").join("\n");
810
+ return {
811
+ scope: "components",
812
+ result: {
813
+ type: "component",
814
+ name: component.name,
815
+ title: component.title,
816
+ description: component.description,
817
+ selectors: component.selectors,
818
+ import: component.import,
819
+ resourceUri: component.resourceUri,
820
+ publicUrl: component.publicUrl,
821
+ nextCall: {
822
+ tool: "get_component",
823
+ arguments: { component: component.name }
824
+ }
825
+ },
826
+ fields: [
827
+ field([
828
+ component.name,
829
+ shortTitle(component.title),
830
+ ...component.selectors,
831
+ component.import ?? "",
832
+ ...component.declarations.map((declaration) => declaration.className)
833
+ ].join(" "), 8),
834
+ field(component.description, 4),
835
+ field(sectionsText, 3),
836
+ field(apiText, 3),
837
+ field(codeText, 1)
838
+ ]
839
+ };
840
+ }
841
+ function guideEntry(guide) {
842
+ return {
843
+ scope: "guides",
844
+ result: {
845
+ type: "guide",
846
+ name: guide.name,
847
+ title: guide.title,
848
+ description: guide.description,
849
+ route: guide.route,
850
+ resourceUri: guide.resourceUri,
851
+ publicUrl: guide.publicUrl,
852
+ nextCall: {
853
+ tool: "get_guide",
854
+ arguments: { guide: guide.name }
855
+ }
856
+ },
857
+ fields: [
858
+ field([
859
+ guide.name,
860
+ guide.route,
861
+ guide.title
862
+ ].join(" "), 8),
863
+ field(guide.description, 4),
864
+ field(guide.sections.map((section) => `${section.label} ${section.description ?? ""}`).join(" "), 3),
865
+ field(guide.sections.map((section) => section.code ?? "").join("\n"), 1)
866
+ ]
867
+ };
868
+ }
869
+ function apiEntries(component) {
870
+ const api = component.api;
871
+ return [
872
+ ...(api.props ?? []).map((prop) => ({
873
+ member: "prop",
874
+ name: prop.name,
875
+ type: prop.type,
876
+ description: prop.description
877
+ })),
878
+ ...(api.emits ?? []).map((emit) => ({
879
+ member: "emit",
880
+ name: emit.name,
881
+ type: emit.parameters?.map((parameter) => `${parameter.name}: ${parameter.type ?? "unknown"}`).join(", "),
882
+ description: emit.description
883
+ })),
884
+ ...(api.templates ?? []).map((template) => ({
885
+ member: "template",
886
+ name: template.name,
887
+ type: template.type,
888
+ description: template.description
889
+ })),
890
+ ...(api.methods ?? []).map((method) => ({
891
+ member: "method",
892
+ name: method.name,
893
+ type: method.returnType,
894
+ description: method.description
895
+ })),
896
+ ...(api.pt ?? []).map((pt) => ({
897
+ member: "pt",
898
+ name: pt.name,
899
+ type: pt.type,
900
+ description: pt.description
901
+ })),
902
+ ...(api.styles ?? []).map((style) => ({
903
+ member: "style",
904
+ name: style.class,
905
+ description: style.description
906
+ })),
907
+ ...(api.tokens ?? []).map((token) => ({
908
+ member: "token",
909
+ name: token.token,
910
+ type: token.variable,
911
+ description: token.description
912
+ }))
913
+ ].map((member) => ({
914
+ scope: "api",
915
+ result: {
916
+ type: "api",
917
+ component: component.name,
918
+ member: member.member,
919
+ name: member.name,
920
+ memberType: member.type,
921
+ description: member.description,
922
+ apiResourceUri: component.apiResourceUri,
923
+ nextCall: {
924
+ tool: "get_component",
925
+ arguments: {
926
+ component: component.name,
927
+ includeApi: true
928
+ }
929
+ }
930
+ },
931
+ fields: [field(`${component.name} ${member.name} ${slugify(member.name).replace(/-/g, " ")}`, 8), field(`${member.type ?? ""} ${member.description ?? ""}`, 3)]
932
+ }));
933
+ }
934
+ function exampleEntries(component) {
935
+ return component.sections.filter((section) => section.hasCode).map((section) => ({
936
+ scope: "examples",
937
+ result: {
938
+ type: "example",
939
+ component: component.name,
940
+ section: section.id,
941
+ title: section.label,
942
+ description: section.description,
943
+ codeLanguage: section.codeLanguage,
944
+ resourceUri: component.resourceUri,
945
+ nextCall: {
946
+ tool: "get_example",
947
+ arguments: {
948
+ component: component.name,
949
+ section: section.id
950
+ }
951
+ }
952
+ },
953
+ fields: [
954
+ field(`${component.name} ${section.label} ${section.id}`, 8),
955
+ field(section.description ?? "", 3),
956
+ field(section.code ?? "", 1)
957
+ ]
958
+ }));
959
+ }
960
+ function field(text, weight) {
961
+ const value = text ?? "";
962
+ return {
963
+ text: value,
964
+ lower: value.toLowerCase(),
965
+ terms: tokenize(value),
966
+ weight
967
+ };
968
+ }
969
+
970
+ //#endregion
971
+ //#region src/template.ts
972
+ const TAG_PATTERN = /<([A-Za-z][\w.-]*)((?:\s+(?:[^\s<>"'=/]+(?:\s*=\s*(?:"[^"]*"|'[^']*'|[^\s"'<>]+))?))*)\s*\/?>/g;
973
+ const ATTRIBUTE_PATTERN = /([^\s"'=<>/]+)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'<>]+)))?/g;
974
+ const IMPORT_PATTERN = /import\s+(?:type\s+)?(?:([\w$]+)\s*,?\s*)?(?:\{([^}]*)\}|\*\s+as\s+([\w$]+))?\s*from\s*['"]([^'"]+)['"]/g;
975
+ /** Every opening element of the template with its attributes. */
976
+ function scanElements(code) {
977
+ const elements = [];
978
+ for (const match of code.matchAll(TAG_PATTERN)) {
979
+ const attributes = [];
980
+ for (const attribute of (match[2] ?? "").matchAll(ATTRIBUTE_PATTERN)) {
981
+ const raw = attribute[1];
982
+ const value = attribute[2] ?? attribute[3] ?? attribute[4];
983
+ attributes.push({
984
+ raw,
985
+ value,
986
+ ...classifyAttribute(raw)
987
+ });
988
+ }
989
+ elements.push({
990
+ name: match[1],
991
+ attributes,
992
+ raw: match[0]
993
+ });
994
+ }
995
+ return elements;
996
+ }
997
+ function classifyAttribute(raw) {
998
+ let match = /^\[\((.+)\)\]$/.exec(raw);
999
+ if (match) return {
1000
+ kind: "twoWay",
1001
+ name: match[1]
1002
+ };
1003
+ match = /^bindon-(.+)$/.exec(raw);
1004
+ if (match) return {
1005
+ kind: "twoWay",
1006
+ name: match[1]
1007
+ };
1008
+ match = /^\[(.+)\]$/.exec(raw) ?? /^bind-(.+)$/.exec(raw);
1009
+ if (match) {
1010
+ const target = match[1];
1011
+ return /^(?:attr|class|style)\./.test(target) ? {
1012
+ kind: "other",
1013
+ name: target
1014
+ } : {
1015
+ kind: "property",
1016
+ name: target
1017
+ };
1018
+ }
1019
+ match = /^\((.+)\)$/.exec(raw) ?? /^on-(.+)$/.exec(raw);
1020
+ if (match) return {
1021
+ kind: "event",
1022
+ name: match[1]
1023
+ };
1024
+ if (raw.startsWith("*")) return {
1025
+ kind: "structural",
1026
+ name: raw.slice(1)
1027
+ };
1028
+ if (raw.startsWith("#") || raw.startsWith("ref-")) return {
1029
+ kind: "reference",
1030
+ name: raw.replace(/^#|^ref-/, "")
1031
+ };
1032
+ if (raw.startsWith("@") || raw.startsWith("i18n") || raw.includes(".")) return {
1033
+ kind: "other",
1034
+ name: raw
1035
+ };
1036
+ return {
1037
+ kind: "static",
1038
+ name: raw
1039
+ };
1040
+ }
1041
+ /** ES import statements of a component source. */
1042
+ function scanImports(code) {
1043
+ const imports = [];
1044
+ for (const match of code.matchAll(IMPORT_PATTERN)) {
1045
+ const names = [
1046
+ match[1],
1047
+ match[3],
1048
+ ...(match[2] ?? "").split(",").map((name) => name.trim().split(/\s+as\s+/).pop() ?? "")
1049
+ ].filter((name) => !!name);
1050
+ imports.push({
1051
+ source: match[4],
1052
+ names
1053
+ });
1054
+ }
1055
+ return imports;
1056
+ }
1057
+ /** Whether an attribute value is a template expression rather than a literal. */
1058
+ function isInterpolated(value) {
1059
+ return value !== void 0 && value.includes("{{");
1060
+ }
1061
+ /** The string literal a property binding assigns (`[severity]="'danger'"` -> `danger`), or undefined when it is an expression. */
1062
+ function literalOfBinding(value) {
1063
+ const match = value === void 0 ? null : /^\s*(?:'([^']*)'|"([^"]*)")\s*$/.exec(value);
1064
+ return match ? match[1] ?? match[2] : void 0;
1065
+ }
1066
+
1067
+ //#endregion
1068
+ //#region src/validate.ts
1069
+ /** Attributes any element may carry; never reported as unknown inputs. */
1070
+ const GLOBAL_ATTRIBUTES = /* @__PURE__ */ new Set([
1071
+ "id",
1072
+ "class",
1073
+ "style",
1074
+ "title",
1075
+ "hidden",
1076
+ "tabindex",
1077
+ "role",
1078
+ "lang",
1079
+ "dir",
1080
+ "slot",
1081
+ "part",
1082
+ "autofocus",
1083
+ "draggable",
1084
+ "contenteditable",
1085
+ "spellcheck",
1086
+ "translate",
1087
+ "accesskey",
1088
+ "inert",
1089
+ "popover",
1090
+ "ngmodel",
1091
+ "ngclass",
1092
+ "ngstyle",
1093
+ "ngmodeloptions",
1094
+ "formcontrol",
1095
+ "formcontrolname",
1096
+ "formgroup",
1097
+ "formgroupname",
1098
+ "formarrayname",
1099
+ "ngmodelgroup",
1100
+ "ngform",
1101
+ "ngnativevalidate",
1102
+ "ngnonbindable",
1103
+ "ngtemplateoutlet",
1104
+ "ngtemplateoutletcontext",
1105
+ "ngcomponentoutlet",
1106
+ "ngprojectas",
1107
+ "routerlink",
1108
+ "routerlinkactive",
1109
+ "routerlinkactiveoptions",
1110
+ "queryparams",
1111
+ "cdkdrag",
1112
+ "cdkdroplist",
1113
+ "ptooltip"
1114
+ ]);
1115
+ /** Attributes and properties of native elements a directive like pButton or pInputText is applied to. */
1116
+ const NATIVE_ATTRIBUTES = /* @__PURE__ */ new Set([
1117
+ "type",
1118
+ "name",
1119
+ "value",
1120
+ "placeholder",
1121
+ "disabled",
1122
+ "readonly",
1123
+ "required",
1124
+ "checked",
1125
+ "selected",
1126
+ "multiple",
1127
+ "min",
1128
+ "max",
1129
+ "step",
1130
+ "minlength",
1131
+ "maxlength",
1132
+ "pattern",
1133
+ "size",
1134
+ "rows",
1135
+ "cols",
1136
+ "wrap",
1137
+ "autocomplete",
1138
+ "inputmode",
1139
+ "enterkeyhint",
1140
+ "src",
1141
+ "srcset",
1142
+ "alt",
1143
+ "href",
1144
+ "target",
1145
+ "rel",
1146
+ "download",
1147
+ "for",
1148
+ "form",
1149
+ "list",
1150
+ "label",
1151
+ "width",
1152
+ "height",
1153
+ "loading",
1154
+ "innerhtml",
1155
+ "innertext",
1156
+ "textcontent",
1157
+ "scrolltop",
1158
+ "scrollleft"
1159
+ ]);
1160
+ const LEGACY_IMPORT_PATTERN = /^(?:primeng(?:\/.*)?|@primeng\/.*|@openng\/optimus-ui(?:\/.*)?|optimus-ui(?:\/.*)?)$/;
1161
+ const selectorIndexes = /* @__PURE__ */ new WeakMap();
1162
+ function selectorIndex(catalog) {
1163
+ let index = selectorIndexes.get(catalog);
1164
+ if (!index) {
1165
+ index = {
1166
+ elements: /* @__PURE__ */ new Map(),
1167
+ attributes: /* @__PURE__ */ new Map()
1168
+ };
1169
+ for (const component of catalog.components) for (const declaration of component.declarations) for (const selector of splitSelectors(declaration.selector)) {
1170
+ const attribute = attributeSelectorName(selector);
1171
+ if (attribute) index.attributes.set(attribute.toLowerCase(), {
1172
+ component,
1173
+ declaration
1174
+ });
1175
+ else if (/^[a-z][\w-]*$/i.test(selector)) index.elements.set(selector.toLowerCase(), {
1176
+ component,
1177
+ declaration
1178
+ });
1179
+ }
1180
+ selectorIndexes.set(catalog, index);
1181
+ }
1182
+ return index;
1183
+ }
1184
+ /** Validate a template or component source against the generated API of one component. */
1185
+ function validateComponentUsage(catalog, component, code) {
1186
+ const issues = [...checkImports(component, code)];
1187
+ if (component.declarations.length === 0) {
1188
+ issues.push({
1189
+ kind: "api-unavailable",
1190
+ severity: "warning",
1191
+ name: component.name,
1192
+ message: `No compiled API metadata is available for ${component.title}; bindings could not be checked.`
1193
+ });
1194
+ return issues;
1195
+ }
1196
+ const index = selectorIndex(catalog);
1197
+ const ownSelectors = new Set(component.selectors.map((selector) => (attributeSelectorName(selector) ?? selector).toLowerCase()));
1198
+ const elements = scanElements(code);
1199
+ const usages = elements.map((element) => ({
1200
+ element,
1201
+ matches: declarationsOn(element, index)
1202
+ })).filter(({ matches }) => matches.some((ref) => ref.component === component));
1203
+ if (usages.length === 0) {
1204
+ issues.push(...checkSelectorMismatch(component, elements, index));
1205
+ if (!issues.some((issue) => issue.kind === "selector-mismatch" || issue.kind === "unknown-selector")) issues.push({
1206
+ kind: "selector-not-found",
1207
+ severity: "warning",
1208
+ name: component.name,
1209
+ message: `The code does not use ${component.title}: none of its selectors (${component.selectors.join(", ")}) appear in it.`
1210
+ });
1211
+ return issues;
1212
+ }
1213
+ for (const { element, matches } of usages) issues.push(...checkElement(component, element, matches, ownSelectors.has(element.name.toLowerCase())));
1214
+ return dedupe(issues);
1215
+ }
1216
+ function checkImports(component, code) {
1217
+ const issues = [];
1218
+ for (const statement of scanImports(code)) if (LEGACY_IMPORT_PATTERN.test(statement.source)) {
1219
+ const target = statement.source.split("/").slice(1).join("/");
1220
+ const suggestion = target && target === component.name ? component.import : target ? `@exhaustive-ui/core/${target}` : "@exhaustive-ui/core";
1221
+ issues.push({
1222
+ kind: "import-mismatch",
1223
+ severity: "error",
1224
+ name: statement.source,
1225
+ message: `"${statement.source}" is a PrimeNG / Optimus UI import; ExhaustiveUI components are imported from @exhaustive-ui/core.`,
1226
+ suggestion: suggestion ? `import { ${statement.names.join(", ") || component.modules[0] || component.declarations[0]?.className || ""} } from '${suggestion}';` : void 0
1227
+ });
1228
+ }
1229
+ return issues;
1230
+ }
1231
+ function declarationsOn(element, index) {
1232
+ const refs = [];
1233
+ const byElement = index.elements.get(element.name.toLowerCase());
1234
+ if (byElement) refs.push(byElement);
1235
+ for (const attribute of element.attributes) {
1236
+ if (attribute.kind !== "static" && attribute.kind !== "property") continue;
1237
+ const byAttribute = index.attributes.get(attribute.name.toLowerCase());
1238
+ if (byAttribute && !refs.includes(byAttribute)) refs.push(byAttribute);
1239
+ }
1240
+ return refs;
1241
+ }
1242
+ function checkSelectorMismatch(component, elements, index) {
1243
+ const issues = [];
1244
+ const names = /* @__PURE__ */ new Set([component.name, ...component.declarations.map((declaration) => compact(declaration.className))]);
1245
+ for (const element of elements) {
1246
+ const tag = element.name;
1247
+ const key = compact(tag.replace(/^p-/i, ""));
1248
+ const aliasTarget = COMPONENT_ALIASES[slugify(tag.replace(/^p-/i, ""))];
1249
+ if (/^[A-Z]/.test(tag) && names.has(compact(tag))) issues.push({
1250
+ kind: "selector-mismatch",
1251
+ severity: "error",
1252
+ name: tag,
1253
+ message: `ExhaustiveUI ${component.title} is used through its selector (${component.selectors.join(", ")}), not the PascalCase <${tag}> tag.`,
1254
+ suggestion: component.selectors[0]
1255
+ });
1256
+ else if (/^p-/i.test(tag) && !index.elements.has(tag.toLowerCase())) {
1257
+ const renamed = aliasTarget === component.name;
1258
+ const related = renamed || names.has(key) || slugify(tag).startsWith(`p-${component.name}`);
1259
+ issues.push({
1260
+ kind: "unknown-selector",
1261
+ severity: "error",
1262
+ name: tag,
1263
+ message: renamed ? `<${tag}> is the PrimeNG name of this component; in ExhaustiveUI ${component.title} uses ${component.selectors.join(" or ")}.` : `<${tag}> is not a selector of any ExhaustiveUI component${related ? "" : ` (expected ${component.title} here)`}; use ${component.selectors.join(" or ")}.`,
1264
+ suggestion: component.selectors[0]
1265
+ });
1266
+ }
1267
+ }
1268
+ return issues;
1269
+ }
1270
+ function checkElement(component, element, matches, isOwnElement) {
1271
+ const issues = [];
1272
+ const own = matches.filter((ref) => ref.component === component).map((ref) => ref.declaration);
1273
+ const inputs = /* @__PURE__ */ new Map();
1274
+ const outputs = /* @__PURE__ */ new Set();
1275
+ const everyInput = /* @__PURE__ */ new Set();
1276
+ for (const ref of matches) {
1277
+ for (const selector of splitSelectors(ref.declaration.selector)) {
1278
+ const attribute = attributeSelectorName(selector);
1279
+ if (attribute) everyInput.add(attribute.toLowerCase());
1280
+ }
1281
+ for (const input of ref.declaration.inputs ?? []) {
1282
+ everyInput.add(input.name.toLowerCase());
1283
+ if (ref.component === component) inputs.set(input.name.toLowerCase(), input);
1284
+ }
1285
+ for (const output of ref.declaration.outputs ?? []) outputs.add(output.name);
1286
+ }
1287
+ const allowedProps = [...inputs.keys()].sort().join(", ");
1288
+ const allowedEvents = [...outputs].sort().join(", ");
1289
+ const supportsForms = own.some((declaration) => declaration.forms);
1290
+ const label = own[0]?.className ?? component.title;
1291
+ for (const attribute of element.attributes) {
1292
+ const lowerName = attribute.name.toLowerCase();
1293
+ switch (attribute.kind) {
1294
+ case "static":
1295
+ case "property": {
1296
+ if (everyInput.has(lowerName) && !inputs.has(lowerName)) break;
1297
+ const input = inputs.get(lowerName);
1298
+ if (!input) {
1299
+ if (GLOBAL_ATTRIBUTES.has(lowerName) || lowerName.startsWith("aria-") || lowerName.startsWith("data-") || lowerName.startsWith("ng") || !isOwnElement && NATIVE_ATTRIBUTES.has(lowerName)) break;
1300
+ issues.push({
1301
+ kind: "unknown-prop",
1302
+ severity: "error",
1303
+ name: attribute.name,
1304
+ message: `"${attribute.name}" is not an input of ${label}.`,
1305
+ allowedProps
1306
+ });
1307
+ break;
1308
+ }
1309
+ if (input.deprecated) issues.push({
1310
+ kind: "deprecated-prop",
1311
+ severity: "warning",
1312
+ name: input.name,
1313
+ message: `Input "${input.name}" of ${label} is deprecated: ${input.deprecated}`
1314
+ });
1315
+ const literal = attribute.kind === "static" ? isInterpolated(attribute.value) ? void 0 : attribute.value : literalOfBinding(attribute.value);
1316
+ if (literal !== void 0 && input.values && input.values.length > 0 && !input.values.includes(literal)) issues.push({
1317
+ kind: "invalid-enum-value",
1318
+ severity: "error",
1319
+ name: input.name,
1320
+ message: `"${literal}" is not an allowed value of ${label} input "${input.name}".`,
1321
+ allowedValues: input.values.join(", ")
1322
+ });
1323
+ break;
1324
+ }
1325
+ case "event":
1326
+ if (outputs.has(attribute.name)) break;
1327
+ if (inputs.get(lowerName.replace(/change$/, ""))?.twoWay && /change$/i.test(attribute.name)) break;
1328
+ if (/^on[A-Z]/.test(attribute.name)) issues.push({
1329
+ kind: "unknown-output",
1330
+ severity: "error",
1331
+ name: attribute.name,
1332
+ message: `"${attribute.name}" is not an output of ${label}.`,
1333
+ allowedEvents
1334
+ });
1335
+ break;
1336
+ case "twoWay": {
1337
+ if (lowerName === "ngmodel") {
1338
+ if (isOwnElement && !supportsForms && !inputs.has("ngmodel")) issues.push({
1339
+ kind: "forms-unsupported",
1340
+ severity: "warning",
1341
+ name: "ngModel",
1342
+ message: `${label} does not implement ControlValueAccessor, so [(ngModel)] has no effect on it.`
1343
+ });
1344
+ break;
1345
+ }
1346
+ const input = inputs.get(lowerName);
1347
+ if (!input) {
1348
+ if (everyInput.has(lowerName) || GLOBAL_ATTRIBUTES.has(lowerName)) break;
1349
+ issues.push({
1350
+ kind: "unknown-prop",
1351
+ severity: "error",
1352
+ name: attribute.name,
1353
+ message: `"${attribute.name}" is not an input of ${label}, so it cannot be bound two-way.`,
1354
+ allowedProps
1355
+ });
1356
+ } else if (!input.twoWay && !outputs.has(`${input.name}Change`)) issues.push({
1357
+ kind: "two-way-binding-unsupported",
1358
+ severity: "error",
1359
+ name: input.name,
1360
+ message: `Input "${input.name}" of ${label} has no "${input.name}Change" output; bind it one-way with [${input.name}].`
1361
+ });
1362
+ break;
1363
+ }
1364
+ default: break;
1365
+ }
1366
+ }
1367
+ return issues;
1368
+ }
1369
+ function dedupe(issues) {
1370
+ const seen = /* @__PURE__ */ new Set();
1371
+ return issues.filter((issue) => {
1372
+ const key = `${issue.kind}:${issue.name ?? ""}:${issue.message}`;
1373
+ if (seen.has(key)) return false;
1374
+ seen.add(key);
1375
+ return true;
1376
+ });
1377
+ }
1378
+ function formatIssues(componentTitle, issues) {
1379
+ const lines = issues.map((issue) => {
1380
+ const extras = [
1381
+ issue.allowedProps ? ` Allowed inputs: ${issue.allowedProps}.` : "",
1382
+ issue.allowedValues ? ` Allowed values: ${issue.allowedValues}.` : "",
1383
+ issue.allowedEvents ? ` Allowed outputs: ${issue.allowedEvents}.` : "",
1384
+ issue.suggestion ? ` Suggestion: ${issue.suggestion}` : ""
1385
+ ].join("");
1386
+ return `- [${issue.severity}] ${issue.kind}${issue.name ? ` ${issue.name}` : ""}: ${issue.message}${extras}`;
1387
+ });
1388
+ return [`Usage has ${issues.length} validation issue${issues.length === 1 ? "" : "s"} for ${componentTitle}.`, ...lines].join("\n");
1389
+ }
1390
+
1391
+ //#endregion
1392
+ //#region src/tools.ts
1393
+ /**
1394
+ * Every tool answers with structured content plus its JSON serialization as text, so clients that only forward text
1395
+ * content still see the whole answer. `summary` is a one-line description of the result.
1396
+ */
1397
+ function ok(structured, summary) {
1398
+ const structuredContent = {
1399
+ summary,
1400
+ ...structured
1401
+ };
1402
+ return {
1403
+ content: [{
1404
+ type: "text",
1405
+ text: JSON.stringify(structuredContent, null, 2)
1406
+ }],
1407
+ structuredContent
1408
+ };
1409
+ }
1410
+ function fail(message, structured = {}) {
1411
+ const structuredContent = {
1412
+ summary: message,
1413
+ error: message,
1414
+ ...structured
1415
+ };
1416
+ return {
1417
+ content: [{
1418
+ type: "text",
1419
+ text: JSON.stringify(structuredContent, null, 2)
1420
+ }],
1421
+ structuredContent,
1422
+ isError: true
1423
+ };
1424
+ }
1425
+ /** Turn thrown errors into error results instead of protocol failures. */
1426
+ async function guard(run) {
1427
+ try {
1428
+ return await run();
1429
+ } catch (error) {
1430
+ return error instanceof ToolError ? fail(error.message, error.structuredContent) : fail(describeError(error));
1431
+ }
1432
+ }
1433
+ const TOOL_NAMES = [
1434
+ "list",
1435
+ "search",
1436
+ "get_component",
1437
+ "get_guide",
1438
+ "get_example",
1439
+ "get_setup",
1440
+ "validate_usage",
1441
+ "version"
1442
+ ];
1443
+ const STATIC_RESOURCE_URIS = [
1444
+ `${RESOURCE_BASE_URI}/llms.txt`,
1445
+ `${RESOURCE_BASE_URI}/llms-full.txt`,
1446
+ `${RESOURCE_BASE_URI}/manifest.json`,
1447
+ `${RESOURCE_BASE_URI}/components.json`
1448
+ ];
1449
+ const RESOURCE_TEMPLATE_NAMES = [
1450
+ "component-docs",
1451
+ "component-api",
1452
+ "guide-docs",
1453
+ "example-docs"
1454
+ ];
1455
+ const PROMPT_NAMES = [
1456
+ "use_component",
1457
+ "build_form",
1458
+ "theme_component",
1459
+ "migrate_from_primeng",
1460
+ "audit_component_usage"
1461
+ ];
1462
+ const listInput = {
1463
+ kind: z.enum([
1464
+ "components",
1465
+ "directives",
1466
+ "guides",
1467
+ "examples",
1468
+ "resources"
1469
+ ]).default("components").describe("What to list."),
1470
+ limit: z.number().int().min(1).max(200).default(50),
1471
+ offset: z.number().int().min(0).default(0)
1472
+ };
1473
+ const searchInput = {
1474
+ query: z.string().min(1).describe("Free text: component names, features (\"lazy loading\"), API members (\"onRowSelect\"), guide topics."),
1475
+ scope: z.enum([
1476
+ "all",
1477
+ "components",
1478
+ "guides",
1479
+ "api",
1480
+ "examples"
1481
+ ]).default("all").describe("\"all\" searches components and guides; \"api\" searches inputs, outputs, templates, methods, PT keys, CSS classes and tokens; \"examples\" searches code examples."),
1482
+ limit: z.number().int().min(1).max(50).default(10),
1483
+ offset: z.number().int().min(0).default(0)
1484
+ };
1485
+ const componentRequest = z.object({
1486
+ component: z.string().min(1).describe("Component name, selector, class name or docs URL (e.g. \"button\", \"p-button\", \"Table\", \"dropdown\")."),
1487
+ sections: z.array(z.string()).optional().describe("Restrict to these section ids or labels."),
1488
+ includeApi: z.boolean().default(false).describe("Include the API (inputs, outputs, templates, methods, PT keys, CSS classes, tokens) and compiled declarations."),
1489
+ includeExamples: z.boolean().default(false).describe("Include the code of every example section."),
1490
+ detail: z.enum(["compact", "full"]).default("compact").describe("\"full\" also returns the complete Markdown document.")
1491
+ });
1492
+ const getComponentInput = {
1493
+ ...componentRequest.shape,
1494
+ component: componentRequest.shape.component.optional(),
1495
+ components: z.array(z.unknown()).max(10).optional().describe("Batch form: up to 10 single-component requests.")
1496
+ };
1497
+ const getGuideInput = {
1498
+ guide: z.string().min(1).describe("Guide name or route: \"installation\", \"configuration\", \"theming/styled\", \"tailwind\", \"guides/accessibility\"..."),
1499
+ section: z.string().optional().describe("Section id or label to focus on."),
1500
+ detail: z.enum(["compact", "full"]).default("compact").describe("\"full\" also returns the complete Markdown document.")
1501
+ };
1502
+ const getExampleInput = {
1503
+ component: z.string().min(1),
1504
+ section: z.string().optional().describe("Section id or label (\"basic\", \"lazy\", \"Template\"...). Defaults to the first section with code."),
1505
+ variant: z.string().optional().describe("Feature hint used when no section matches (\"outlined\", \"severity\", \"icons\"...).")
1506
+ };
1507
+ const getSetupInput = { environment: z.string().optional().describe("What to set up: \"angular-cli\" (default), \"configuration\", \"styled\", \"unstyled\", \"tailwind\", \"icons\", \"custom-icons\", \"passthrough\".") };
1508
+ const usageRequest = z.object({
1509
+ component: z.string().min(1),
1510
+ code: z.string().min(1).describe("Angular template or component source using the component.")
1511
+ });
1512
+ const validateUsageInput = {
1513
+ component: usageRequest.shape.component.optional(),
1514
+ code: usageRequest.shape.code.optional(),
1515
+ usages: z.array(z.unknown()).max(10).optional().describe("Batch form: up to 10 { component, code } items.")
1516
+ };
1517
+ const versionInput = {};
1518
+ function componentSummary(component) {
1519
+ return {
1520
+ name: component.name,
1521
+ title: component.title,
1522
+ description: component.description,
1523
+ selectors: component.selectors,
1524
+ import: component.import,
1525
+ modules: component.modules,
1526
+ resourceUri: component.resourceUri,
1527
+ apiResourceUri: component.apiResourceUri,
1528
+ publicUrl: component.publicUrl,
1529
+ markdownUrl: component.markdownUrl
1530
+ };
1531
+ }
1532
+ function guideSummary(guide) {
1533
+ return {
1534
+ name: guide.name,
1535
+ title: guide.title,
1536
+ description: guide.description,
1537
+ route: guide.route,
1538
+ resourceUri: guide.resourceUri,
1539
+ publicUrl: guide.publicUrl,
1540
+ markdownUrl: guide.markdownUrl
1541
+ };
1542
+ }
1543
+ function sectionSummary(section) {
1544
+ return {
1545
+ id: section.id,
1546
+ label: section.label,
1547
+ description: section.description,
1548
+ hasCode: section.hasCode,
1549
+ codeLanguage: section.codeLanguage
1550
+ };
1551
+ }
1552
+ function exampleCall(component, section) {
1553
+ return {
1554
+ tool: "get_example",
1555
+ arguments: {
1556
+ component: component.name,
1557
+ section: section.id
1558
+ }
1559
+ };
1560
+ }
1561
+ function resourceEntries(catalog) {
1562
+ const base = RESOURCE_BASE_URI;
1563
+ const entries = [
1564
+ {
1565
+ uri: `${base}/llms.txt`,
1566
+ type: "index",
1567
+ name: "llms.txt",
1568
+ title: "ExhaustiveUI llms.txt",
1569
+ mimeType: "text/plain",
1570
+ publicUrl: `${catalog.site}/llms/llms.txt`
1571
+ },
1572
+ {
1573
+ uri: `${base}/llms-full.txt`,
1574
+ type: "index",
1575
+ name: "llms-full.txt",
1576
+ title: "ExhaustiveUI llms-full.txt",
1577
+ mimeType: "text/plain",
1578
+ publicUrl: `${catalog.site}/llms/llms-full.txt`
1579
+ },
1580
+ {
1581
+ uri: `${base}/manifest.json`,
1582
+ type: "manifest",
1583
+ name: "manifest.json",
1584
+ title: "ExhaustiveUI API manifest",
1585
+ mimeType: "application/json",
1586
+ publicUrl: `${catalog.site}/llms/manifest.json`
1587
+ },
1588
+ {
1589
+ uri: `${base}/components.json`,
1590
+ type: "index",
1591
+ name: "components.json",
1592
+ title: "ExhaustiveUI components index",
1593
+ mimeType: "application/json",
1594
+ publicUrl: `${catalog.site}/llms/components.json`
1595
+ }
1596
+ ];
1597
+ for (const component of catalog.components) {
1598
+ entries.push({
1599
+ uri: component.resourceUri,
1600
+ type: "component",
1601
+ name: component.name,
1602
+ title: component.title,
1603
+ mimeType: "text/markdown",
1604
+ publicUrl: component.markdownUrl
1605
+ });
1606
+ entries.push({
1607
+ uri: component.apiResourceUri,
1608
+ type: "component-api",
1609
+ name: component.name,
1610
+ title: `${component.title} API`,
1611
+ mimeType: "application/json"
1612
+ });
1613
+ }
1614
+ for (const guide of catalog.guides) entries.push({
1615
+ uri: guide.resourceUri,
1616
+ type: "guide",
1617
+ name: guide.name,
1618
+ title: guide.title,
1619
+ mimeType: "text/markdown",
1620
+ publicUrl: guide.markdownUrl
1621
+ });
1622
+ return entries;
1623
+ }
1624
+ async function listTool(ctx, input) {
1625
+ const catalog = await ctx.catalog();
1626
+ let items;
1627
+ switch (input.kind) {
1628
+ case "components":
1629
+ items = catalog.components.map(componentSummary);
1630
+ break;
1631
+ case "directives":
1632
+ items = catalog.directives.map((directive) => ({ ...directive }));
1633
+ break;
1634
+ case "guides":
1635
+ items = catalog.guides.map(guideSummary);
1636
+ break;
1637
+ case "examples":
1638
+ items = catalog.components.flatMap((component) => component.sections.filter((section) => section.hasCode).map((section) => ({
1639
+ component: component.name,
1640
+ section: section.id,
1641
+ title: section.label,
1642
+ codeLanguage: section.codeLanguage,
1643
+ nextCall: exampleCall(component, section)
1644
+ })));
1645
+ break;
1646
+ case "resources":
1647
+ items = resourceEntries(catalog);
1648
+ break;
1649
+ }
1650
+ const page = items.slice(input.offset, input.offset + input.limit);
1651
+ return ok({
1652
+ kind: input.kind,
1653
+ total: items.length,
1654
+ limit: input.limit,
1655
+ offset: input.offset,
1656
+ items: page
1657
+ }, `${page.length} of ${items.length} ${input.kind} returned.`);
1658
+ }
1659
+ async function searchTool(ctx, input) {
1660
+ const hits = searchCatalog(await ctx.catalog(), input.query, input.scope);
1661
+ const page = hits.slice(input.offset, input.offset + input.limit);
1662
+ return ok({
1663
+ query: input.query,
1664
+ scope: input.scope,
1665
+ total: hits.length,
1666
+ limit: input.limit,
1667
+ offset: input.offset,
1668
+ results: page
1669
+ }, `${page.length} of ${hits.length} result${hits.length === 1 ? "" : "s"} for "${input.query}".`);
1670
+ }
1671
+ async function getComponentTool(ctx, input) {
1672
+ if (input.components !== void 0) {
1673
+ if (input.component !== void 0 || input.sections !== void 0 || input.includeApi || input.includeExamples || input.detail !== "compact") throw new ToolError("Use either the single-component fields or \"components\", not both.");
1674
+ return batch(input.components, componentRequest, "component", (item) => getSingleComponent(ctx, item));
1675
+ }
1676
+ if (!input.component) throw new ToolError("\"component\" is required.");
1677
+ return getSingleComponent(ctx, {
1678
+ ...input,
1679
+ component: input.component
1680
+ });
1681
+ }
1682
+ async function getSingleComponent(ctx, input) {
1683
+ const component = findComponent(await ctx.catalog(), input.component);
1684
+ const sections = input.sections?.length ? input.sections.map((query) => requireSection(component.sections, query)) : component.sections;
1685
+ const withCode = sections.filter((section) => section.hasCode);
1686
+ const document = input.detail === "full" ? await ctx.source.readText(component.docPath) : void 0;
1687
+ const result = {
1688
+ ...componentSummary(component),
1689
+ route: component.route,
1690
+ declarations: component.declarations.map((declaration) => ({
1691
+ kind: declaration.kind,
1692
+ className: declaration.className,
1693
+ selector: declaration.selector,
1694
+ forms: declaration.forms,
1695
+ standalone: declaration.standalone
1696
+ })),
1697
+ sections: sections.map(sectionSummary),
1698
+ examplesAvailable: withCode.map((section) => ({
1699
+ section: section.id,
1700
+ title: section.label,
1701
+ codeLanguage: section.codeLanguage,
1702
+ nextCall: exampleCall(component, section)
1703
+ }))
1704
+ };
1705
+ if (input.includeExamples) result.examples = withCode.map((section) => ({
1706
+ section: section.id,
1707
+ title: section.label,
1708
+ description: section.description,
1709
+ codeLanguage: section.codeLanguage,
1710
+ code: section.code
1711
+ }));
1712
+ if (input.includeApi) {
1713
+ result.api = component.api;
1714
+ result.compiled = component.declarations;
1715
+ }
1716
+ if (document !== void 0) result.document = document;
1717
+ const next = withCode[0] ? ` Next: get_example ${JSON.stringify({
1718
+ component: component.name,
1719
+ section: withCode[0].id
1720
+ })}.` : "";
1721
+ return ok({ component: result }, `${component.title}: ${sections.length} section${sections.length === 1 ? "" : "s"}, ${withCode.length} with code; source ${component.resourceUri}.${next}`);
1722
+ }
1723
+ async function getGuideTool(ctx, input) {
1724
+ const guide = findGuide(await ctx.catalog(), input.guide);
1725
+ const section = input.section ? requireSection(guide.sections, input.section) : void 0;
1726
+ const document = input.detail === "full" ? await ctx.source.readText(guide.docPath) : void 0;
1727
+ return ok({ guide: {
1728
+ ...guideSummary(guide),
1729
+ section: section ? {
1730
+ ...sectionSummary(section),
1731
+ code: section.code
1732
+ } : void 0,
1733
+ sections: guide.sections.map(sectionSummary),
1734
+ document
1735
+ } }, `${guide.title} guide: ${guide.sections.length} section${guide.sections.length === 1 ? "" : "s"}; source ${guide.resourceUri}.`);
1736
+ }
1737
+ /** Section ids the usual feature words map to. */
1738
+ const VARIANT_SECTIONS = {
1739
+ basic: ["basic"],
1740
+ default: ["basic"],
1741
+ primary: ["basic"],
1742
+ danger: ["severity"],
1743
+ error: ["severity", "invalid"],
1744
+ warning: ["severity"],
1745
+ success: ["severity"],
1746
+ busy: ["loading"],
1747
+ spinner: ["loading"],
1748
+ outline: ["outlined"],
1749
+ icon: ["icons", "icon"],
1750
+ size: ["sizes"],
1751
+ small: ["sizes"],
1752
+ large: ["sizes"],
1753
+ pagination: ["paginator", "page"],
1754
+ page: ["paginator"],
1755
+ paging: ["paginator"],
1756
+ sorting: [
1757
+ "sort",
1758
+ "singlecolumnsort",
1759
+ "multiplecolumnssort"
1760
+ ],
1761
+ sortable: ["sort", "singlecolumnsort"],
1762
+ filtering: [
1763
+ "filter",
1764
+ "filterbasic",
1765
+ "filteradvanced"
1766
+ ],
1767
+ filters: ["filter", "filterbasic"],
1768
+ select: [
1769
+ "selection",
1770
+ "singleselection",
1771
+ "multipleselection",
1772
+ "checkboxselection",
1773
+ "radiobuttonselection"
1774
+ ],
1775
+ selected: ["selection"],
1776
+ checkbox: ["checkboxselection", "checkbox"],
1777
+ form: [
1778
+ "reactiveforms",
1779
+ "forms",
1780
+ "templatedrivenforms"
1781
+ ],
1782
+ forms: [
1783
+ "reactiveforms",
1784
+ "forms",
1785
+ "templatedrivenforms"
1786
+ ],
1787
+ reactive: ["reactiveforms"],
1788
+ ngmodel: ["templatedrivenforms", "forms"],
1789
+ lazy: [
1790
+ "lazy",
1791
+ "lazyload",
1792
+ "virtualscroll"
1793
+ ],
1794
+ virtual: ["virtualscroll", "lazy"],
1795
+ template: [
1796
+ "template",
1797
+ "templates",
1798
+ "customtemplate"
1799
+ ],
1800
+ templating: ["template"],
1801
+ disabled: ["disabled"],
1802
+ invalid: ["invalid"],
1803
+ accessible: ["accessibility"]
1804
+ };
1805
+ async function getExampleTool(ctx, input) {
1806
+ const component = findComponent(await ctx.catalog(), input.component);
1807
+ const withCode = component.sections.filter((section) => section.hasCode);
1808
+ if (withCode.length === 0) throw new ToolError(`No code example is available for ${component.title}.`, exampleFailure(component, input, void 0));
1809
+ const query = input.section ?? input.variant;
1810
+ let section;
1811
+ if (query) section = findSection(component.sections, query) ?? bestSection(component.sections, [input.section, input.variant]);
1812
+ else section = withCode.find((entry) => compact(entry.id) === "basic") ?? withCode[0];
1813
+ if (!section) throw new ToolError(`No section of ${component.title} matches ${describeRequest(input)}.`, exampleFailure(component, input, void 0));
1814
+ if (!section.hasCode) {
1815
+ const alternative = input.variant ? bestSection(withCode, [input.variant]) : void 0;
1816
+ if (alternative) section = alternative;
1817
+ else throw new ToolError(`Section "${section.id}" of ${component.title} has no code example.`, exampleFailure(component, input, section));
1818
+ }
1819
+ return ok({
1820
+ component: component.name,
1821
+ title: component.title,
1822
+ section: section.id,
1823
+ sectionTitle: section.label,
1824
+ requestedSection: input.section,
1825
+ requestedVariant: input.variant,
1826
+ description: section.description,
1827
+ codeLanguage: section.codeLanguage,
1828
+ code: section.code,
1829
+ import: component.import,
1830
+ resourceUri: component.resourceUri,
1831
+ publicUrl: component.publicUrl
1832
+ }, `${component.title} "${section.label}" example (${section.codeLanguage}).`);
1833
+ }
1834
+ function describeRequest(input) {
1835
+ return [input.section ? `section "${input.section}"` : "", input.variant ? `variant "${input.variant}"` : ""].filter(Boolean).join(" and ") || "the request";
1836
+ }
1837
+ function bestSection(sections, hints) {
1838
+ const terms = unique(hints.filter((hint) => !!hint).flatMap((hint) => {
1839
+ const slug = slugify(hint);
1840
+ return [
1841
+ slug,
1842
+ ...VARIANT_SECTIONS[slug] ?? [],
1843
+ ...slug.split("-").flatMap((part) => [
1844
+ part,
1845
+ ...VARIANT_SECTIONS[part] ?? [],
1846
+ ...expandTerm(part)
1847
+ ])
1848
+ ];
1849
+ }).map(compact).filter((term) => term.length > 1));
1850
+ return sections.map((section, index) => {
1851
+ const keys = [compact(section.id), compact(section.label)];
1852
+ const text = `${section.label} ${section.description ?? ""}`.toLowerCase();
1853
+ let score = 0;
1854
+ if (keys.some((key) => terms.includes(key))) score += 100;
1855
+ if (keys.some((key) => terms.some((term) => term.length > 3 && (key.includes(term) || term.includes(key))))) score += 60;
1856
+ if (terms.some((term) => term.length > 3 && text.includes(term))) score += 30;
1857
+ if (score > 0 && section.hasCode) score += 10;
1858
+ return {
1859
+ section,
1860
+ index,
1861
+ score
1862
+ };
1863
+ }).filter((entry) => entry.score > 0).sort((a, b) => b.score - a.score || a.index - b.index)[0]?.section;
1864
+ }
1865
+ function exampleFailure(component, input, selected) {
1866
+ const withCode = component.sections.filter((section) => section.hasCode);
1867
+ const suggested = bestSection(withCode, [input.section, input.variant]);
1868
+ const props = (component.api.props ?? []).filter((prop) => !/^aria/i.test(prop.name));
1869
+ const hints = unique([input.section, input.variant].filter((hint) => !!hint).flatMap((hint) => expandTerm(hint)));
1870
+ return {
1871
+ component: component.name,
1872
+ requestedSection: input.section ?? selected?.id,
1873
+ requestedVariant: input.variant,
1874
+ availableSections: component.sections.map((section) => section.id),
1875
+ sectionsWithCode: withCode.map((section) => section.id),
1876
+ suggestedSections: unique([suggested?.id, ...withCode.slice(0, 5).map((section) => section.id)].filter((id) => !!id)),
1877
+ suggestedApiProps: props.filter((prop) => hints.some((hint) => slugify(prop.name).includes(hint) || (prop.description ?? "").toLowerCase().includes(hint))).slice(0, 8).map((prop) => ({
1878
+ name: prop.name,
1879
+ type: prop.type,
1880
+ description: prop.description
1881
+ })),
1882
+ apiAvailable: props.length > 0,
1883
+ sourceBackedCodeAvailable: withCode.length > 0,
1884
+ componentResourceUri: component.resourceUri,
1885
+ apiResourceUri: component.apiResourceUri,
1886
+ nextCall: suggested ? exampleCall(component, suggested) : {
1887
+ tool: "get_component",
1888
+ arguments: {
1889
+ component: component.name,
1890
+ includeApi: true
1891
+ }
1892
+ }
1893
+ };
1894
+ }
1895
+ const SETUP_ENVIRONMENTS = [
1896
+ {
1897
+ environment: "angular-cli",
1898
+ guide: "installation",
1899
+ aliases: [
1900
+ "angular",
1901
+ "cli",
1902
+ "ng",
1903
+ "npm",
1904
+ "pnpm",
1905
+ "yarn",
1906
+ "install",
1907
+ "installation",
1908
+ "setup",
1909
+ "getting-started",
1910
+ "quickstart",
1911
+ "start",
1912
+ "default"
1913
+ ]
1914
+ },
1915
+ {
1916
+ environment: "configuration",
1917
+ guide: "configuration",
1918
+ aliases: [
1919
+ "config",
1920
+ "configure",
1921
+ "provideexhaustiveui",
1922
+ "providers",
1923
+ "app-config",
1924
+ "ripple",
1925
+ "zindex",
1926
+ "locale",
1927
+ "translation"
1928
+ ]
1929
+ },
1930
+ {
1931
+ environment: "styled",
1932
+ guide: "theming/styled",
1933
+ aliases: [
1934
+ "theme",
1935
+ "themes",
1936
+ "theming",
1937
+ "preset",
1938
+ "presets",
1939
+ "aura",
1940
+ "lara",
1941
+ "nora",
1942
+ "material",
1943
+ "design-tokens",
1944
+ "tokens",
1945
+ "dark-mode",
1946
+ "css-variables"
1947
+ ]
1948
+ },
1949
+ {
1950
+ environment: "unstyled",
1951
+ guide: "theming/unstyled",
1952
+ aliases: ["headless", "no-theme"]
1953
+ },
1954
+ {
1955
+ environment: "tailwind",
1956
+ guide: "tailwind",
1957
+ aliases: [
1958
+ "tailwindcss",
1959
+ "tailwind-css",
1960
+ "tw"
1961
+ ]
1962
+ },
1963
+ {
1964
+ environment: "icons",
1965
+ guide: "icons",
1966
+ aliases: [
1967
+ "icon",
1968
+ "openng-icons",
1969
+ "primeicons"
1970
+ ]
1971
+ },
1972
+ {
1973
+ environment: "custom-icons",
1974
+ guide: "customicons",
1975
+ aliases: [
1976
+ "customicons",
1977
+ "custom-icon",
1978
+ "font-awesome",
1979
+ "material-icons",
1980
+ "svg-icons"
1981
+ ]
1982
+ },
1983
+ {
1984
+ environment: "passthrough",
1985
+ guide: "passthrough",
1986
+ aliases: ["pass-through", "pt"]
1987
+ }
1988
+ ];
1989
+ async function getSetupTool(ctx, input) {
1990
+ const catalog = await ctx.catalog();
1991
+ const requested = input.environment?.trim();
1992
+ const key = compact(requested ?? "angular-cli");
1993
+ const match = SETUP_ENVIRONMENTS.find((entry) => compact(entry.environment) === key || entry.aliases.some((alias) => compact(alias) === key));
1994
+ let guide;
1995
+ if (match) guide = findGuide(catalog, match.guide);
1996
+ else if (requested) try {
1997
+ guide = findGuide(catalog, requested);
1998
+ } catch {
1999
+ guide = void 0;
2000
+ }
2001
+ if (!guide) throw new ToolError(`Setup environment "${requested}" is unsupported. Valid environments: ${SETUP_ENVIRONMENTS.map((entry) => entry.environment).join(", ")}.`, {
2002
+ environment: requested,
2003
+ validEnvironments: SETUP_ENVIRONMENTS.map((entry) => entry.environment),
2004
+ candidates: SETUP_ENVIRONMENTS.map((entry) => ({
2005
+ environment: entry.environment,
2006
+ guide: entry.guide,
2007
+ aliases: entry.aliases
2008
+ }))
2009
+ });
2010
+ const document = await ctx.source.readText(guide.docPath);
2011
+ return ok({
2012
+ environment: match?.environment ?? guide.name,
2013
+ guide: {
2014
+ ...guideSummary(guide),
2015
+ sections: guide.sections.map(sectionSummary),
2016
+ document
2017
+ },
2018
+ relatedGuides: SETUP_ENVIRONMENTS.filter((entry) => entry.guide !== match?.guide).map((entry) => ({
2019
+ environment: entry.environment,
2020
+ nextCall: {
2021
+ tool: "get_setup",
2022
+ arguments: { environment: entry.environment }
2023
+ }
2024
+ }))
2025
+ }, `${guide.title} setup docs returned (${match?.environment ?? guide.name}).`);
2026
+ }
2027
+ async function validateUsageTool(ctx, input) {
2028
+ if (input.usages !== void 0) {
2029
+ if (input.component !== void 0 || input.code !== void 0) throw new ToolError("Use either the single usage fields or \"usages\", not both.");
2030
+ return batch(input.usages, usageRequest, "usage", (item) => validateSingleUsage(ctx, item));
2031
+ }
2032
+ if (!input.component || !input.code) throw new ToolError("\"component\" and \"code\" are required.");
2033
+ return validateSingleUsage(ctx, {
2034
+ component: input.component,
2035
+ code: input.code
2036
+ });
2037
+ }
2038
+ async function validateSingleUsage(ctx, input) {
2039
+ const catalog = await ctx.catalog();
2040
+ const component = findComponent(catalog, input.component);
2041
+ const issues = validateComponentUsage(catalog, component, input.code);
2042
+ const errors = issues.filter((issue) => issue.severity === "error");
2043
+ const structured = {
2044
+ component: component.name,
2045
+ title: component.title,
2046
+ selectors: component.selectors,
2047
+ valid: errors.length === 0,
2048
+ issues,
2049
+ apiResourceUri: component.apiResourceUri
2050
+ };
2051
+ if (errors.length > 0) return fail(formatIssues(component.title, issues), structured);
2052
+ return ok(structured, issues.length > 0 ? `${component.title} usage is valid, with ${issues.length} warning${issues.length === 1 ? "" : "s"}.` : `${component.title} usage is valid against the compiled API.`);
2053
+ }
2054
+ async function versionTool(ctx) {
2055
+ const status = ctx.sourceStatus();
2056
+ let data;
2057
+ try {
2058
+ const catalog = await ctx.catalog();
2059
+ data = {
2060
+ libraryVersion: catalog.libraryVersion,
2061
+ docsVersion: catalog.docsVersion,
2062
+ generatedAt: catalog.generatedAt,
2063
+ site: catalog.site,
2064
+ counts: {
2065
+ components: catalog.components.length,
2066
+ directives: catalog.directives.length,
2067
+ guides: catalog.guides.length,
2068
+ examples: catalog.components.reduce((sum, component) => sum + component.sections.filter((section) => section.hasCode).length, 0)
2069
+ }
2070
+ };
2071
+ } catch (error) {
2072
+ data = { error: describeError(error) };
2073
+ }
2074
+ return ok({
2075
+ server: {
2076
+ name: ctx.serverName,
2077
+ version: ctx.serverVersion
2078
+ },
2079
+ data,
2080
+ source: status,
2081
+ tools: [...TOOL_NAMES],
2082
+ resources: {
2083
+ static: STATIC_RESOURCE_URIS,
2084
+ templates: RESOURCE_TEMPLATE_NAMES
2085
+ },
2086
+ prompts: [...PROMPT_NAMES]
2087
+ }, `${ctx.serverName} ${ctx.serverVersion}; ${TOOL_NAMES.length} tools; docs from ${status.mode === "offline" ? "the offline snapshot" : status.docsUrl}.`);
2088
+ }
2089
+ async function batch(items, schema, label, run) {
2090
+ if (items.length === 0) throw new ToolError(`"${label}s" must contain at least one item.`);
2091
+ const results = [];
2092
+ for (const [index, item] of items.entries()) {
2093
+ const parsed = schema.safeParse(item);
2094
+ if (!parsed.success) {
2095
+ results.push({
2096
+ index,
2097
+ status: "error",
2098
+ error: `Invalid ${label} item: ${parsed.error.issues.map((issue) => `${issue.path.join(".") || label}: ${issue.message}`).join("; ")}.`
2099
+ });
2100
+ continue;
2101
+ }
2102
+ const result = await guard(() => run(parsed.data));
2103
+ results.push({
2104
+ index,
2105
+ status: result.isError ? "error" : "success",
2106
+ ...result.structuredContent
2107
+ });
2108
+ }
2109
+ const succeeded = results.filter((result) => result.status === "success").length;
2110
+ return ok({
2111
+ total: results.length,
2112
+ succeeded,
2113
+ failed: results.length - succeeded,
2114
+ results
2115
+ }, `${succeeded} of ${results.length} ${label} request${results.length === 1 ? "" : "s"} succeeded.`);
2116
+ }
2117
+
2118
+ //#endregion
2119
+ //#region src/server.ts
2120
+ const SERVER_NAME = "@exhaustive-ui/mcp";
2121
+ const readOnly = {
2122
+ readOnlyHint: true,
2123
+ destructiveHint: false,
2124
+ idempotentHint: true,
2125
+ openWorldHint: false
2126
+ };
2127
+ function readPackageVersion() {
2128
+ try {
2129
+ return JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8")).version ?? "0.0.0";
2130
+ } catch {
2131
+ return "0.0.0";
2132
+ }
2133
+ }
2134
+ /** Build the tool context: configured docs source, catalog loader and status reporting. */
2135
+ function createToolContext(options = {}) {
2136
+ const config = resolveConfig(options.env ?? process.env, options.config);
2137
+ const configured = options.source ? {
2138
+ source: options.source,
2139
+ status: () => ({
2140
+ mode: "offline",
2141
+ docsUrl: config.docsUrl,
2142
+ cacheTtlSeconds: 0
2143
+ })
2144
+ } : createDocsSource(config, options.fetchImpl);
2145
+ const loader = new CatalogLoader(configured.source);
2146
+ return {
2147
+ serverName: SERVER_NAME,
2148
+ serverVersion: options.version ?? readPackageVersion(),
2149
+ source: configured.source,
2150
+ catalog: () => loader.load(),
2151
+ sourceStatus: () => configured.status()
2152
+ };
2153
+ }
2154
+ async function createExhaustiveUiMcpServer(options = {}) {
2155
+ const ctx = createToolContext(options);
2156
+ const server = new McpServer({
2157
+ name: SERVER_NAME,
2158
+ version: ctx.serverVersion,
2159
+ title: "ExhaustiveUI docs"
2160
+ }, { capabilities: {
2161
+ tools: {},
2162
+ resources: {},
2163
+ prompts: {}
2164
+ } });
2165
+ registerTools(server, ctx);
2166
+ registerResources(server, ctx);
2167
+ registerPrompts(server);
2168
+ return server;
2169
+ }
2170
+ async function runExhaustiveUiMcpServer(options = {}) {
2171
+ const server = await createExhaustiveUiMcpServer(options);
2172
+ const transport = new StdioServerTransport();
2173
+ await server.connect(transport);
2174
+ console.error(`${SERVER_NAME} running on stdio`);
2175
+ }
2176
+ function registerTools(server, ctx) {
2177
+ server.registerTool("list", {
2178
+ title: "List ExhaustiveUI docs",
2179
+ description: "List the ExhaustiveUI components, directives, guides, code examples or MCP resources.",
2180
+ inputSchema: listInput,
2181
+ annotations: readOnly
2182
+ }, (input) => guard(() => listTool(ctx, input)));
2183
+ server.registerTool("search", {
2184
+ title: "Search ExhaustiveUI docs",
2185
+ description: "Search the ExhaustiveUI component docs, guides, API members (inputs, outputs, templates, PT keys, tokens) and code examples.",
2186
+ inputSchema: searchInput,
2187
+ annotations: readOnly
2188
+ }, (input) => guard(() => searchTool(ctx, input)));
2189
+ server.registerTool("get_component", {
2190
+ title: "Get component docs",
2191
+ description: "Read the docs of an ExhaustiveUI component: sections, available examples, and optionally its API, compiled declarations and full Markdown document. Accepts a batch of up to 10 components.",
2192
+ inputSchema: getComponentInput,
2193
+ annotations: readOnly
2194
+ }, (input) => guard(() => getComponentTool(ctx, input)));
2195
+ server.registerTool("get_guide", {
2196
+ title: "Get guide docs",
2197
+ description: "Read an ExhaustiveUI guide (installation, configuration, theming, Tailwind, icons, pass through, accessibility, migration...).",
2198
+ inputSchema: getGuideInput,
2199
+ annotations: readOnly
2200
+ }, (input) => guard(() => getGuideTool(ctx, input)));
2201
+ server.registerTool("get_example", {
2202
+ title: "Get a code example",
2203
+ description: "Return one complete, source-backed code example of a component (a standalone Angular component with its template and imports).",
2204
+ inputSchema: getExampleInput,
2205
+ annotations: readOnly
2206
+ }, (input) => guard(() => getExampleTool(ctx, input)));
2207
+ server.registerTool("get_setup", {
2208
+ title: "Get setup docs",
2209
+ description: "Return the installation and setup guidance for ExhaustiveUI in an Angular project (Angular CLI by default; also configuration, styled/unstyled theming, Tailwind, icons, pass through).",
2210
+ inputSchema: getSetupInput,
2211
+ annotations: readOnly
2212
+ }, (input) => guard(() => getSetupTool(ctx, input)));
2213
+ server.registerTool("validate_usage", {
2214
+ title: "Validate component usage",
2215
+ description: "Check an Angular template or component source against the compiled API of an ExhaustiveUI component: unknown inputs and outputs, invalid literal values, unsupported two-way bindings, deprecated inputs, wrong selectors and PrimeNG imports. Accepts a batch of up to 10 usages.",
2216
+ inputSchema: validateUsageInput,
2217
+ annotations: readOnly
2218
+ }, (input) => guard(() => validateUsageTool(ctx, input)));
2219
+ server.registerTool("version", {
2220
+ title: "ExhaustiveUI MCP version",
2221
+ description: "Return the server version, the documented library version, where the docs are read from (live site or offline snapshot) and the registered tools, resources and prompts.",
2222
+ inputSchema: versionInput,
2223
+ annotations: readOnly
2224
+ }, () => guard(() => versionTool(ctx)));
2225
+ }
2226
+ const STATIC_RESOURCES = [
2227
+ {
2228
+ name: "llms-txt",
2229
+ file: "llms.txt",
2230
+ title: "ExhaustiveUI llms.txt",
2231
+ description: "Index of the ExhaustiveUI guides and components with their URLs.",
2232
+ mimeType: "text/plain"
2233
+ },
2234
+ {
2235
+ name: "llms-full-txt",
2236
+ file: "llms-full.txt",
2237
+ title: "ExhaustiveUI llms-full.txt",
2238
+ description: "The complete ExhaustiveUI documentation in one Markdown file.",
2239
+ mimeType: "text/plain"
2240
+ },
2241
+ {
2242
+ name: "manifest",
2243
+ file: "manifest.json",
2244
+ title: "ExhaustiveUI API manifest",
2245
+ description: "Compiled metadata of every entry point of @exhaustive-ui/core: selectors, inputs, outputs, templates, pass-through keys, services and types.",
2246
+ mimeType: "application/json"
2247
+ },
2248
+ {
2249
+ name: "components-index",
2250
+ file: "components.json",
2251
+ title: "ExhaustiveUI components index",
2252
+ description: "Every component with its documentation sections, examples and API, plus the guides.",
2253
+ mimeType: "application/json"
2254
+ }
2255
+ ];
2256
+ function registerResources(server, ctx) {
2257
+ for (const resource of STATIC_RESOURCES) {
2258
+ const uri = `${RESOURCE_BASE_URI}/${resource.file}`;
2259
+ server.registerResource(resource.name, uri, {
2260
+ title: resource.title,
2261
+ description: resource.description,
2262
+ mimeType: resource.mimeType
2263
+ }, async () => ({ contents: [{
2264
+ uri,
2265
+ mimeType: resource.mimeType,
2266
+ text: await ctx.source.readText(resource.file)
2267
+ }] }));
2268
+ }
2269
+ server.registerResource("component-docs", new ResourceTemplate(`${RESOURCE_BASE_URI}/components/{component}.md`, {
2270
+ list: async () => ({ resources: (await ctx.catalog()).components.map((component) => ({
2271
+ uri: component.resourceUri,
2272
+ name: component.name,
2273
+ title: component.title,
2274
+ description: component.description,
2275
+ mimeType: "text/markdown"
2276
+ })) }),
2277
+ complete: { component: completeComponent(ctx) }
2278
+ }), {
2279
+ title: "ExhaustiveUI component docs",
2280
+ description: "Generated Markdown documentation of one component (examples, API tables, pass-through options, theming).",
2281
+ mimeType: "text/markdown"
2282
+ }, async (uri, variables) => {
2283
+ const component = findComponent(await ctx.catalog(), variable(variables.component));
2284
+ return { contents: [{
2285
+ uri: uri.href,
2286
+ mimeType: "text/markdown",
2287
+ text: await ctx.source.readText(component.docPath)
2288
+ }] };
2289
+ });
2290
+ server.registerResource("component-api", new ResourceTemplate(`${RESOURCE_BASE_URI}/components/{component}/api.json`, {
2291
+ list: async () => ({ resources: (await ctx.catalog()).components.map((component) => ({
2292
+ uri: component.apiResourceUri,
2293
+ name: `${component.name}-api`,
2294
+ title: `${component.title} API`,
2295
+ mimeType: "application/json"
2296
+ })) }),
2297
+ complete: { component: completeComponent(ctx) }
2298
+ }), {
2299
+ title: "ExhaustiveUI component API",
2300
+ description: "API of one component as JSON: documented members and compiled declarations.",
2301
+ mimeType: "application/json"
2302
+ }, async (uri, variables) => {
2303
+ const component = findComponent(await ctx.catalog(), variable(variables.component));
2304
+ return { contents: [{
2305
+ uri: uri.href,
2306
+ mimeType: "application/json",
2307
+ text: JSON.stringify(componentApi(component), null, 2)
2308
+ }] };
2309
+ });
2310
+ server.registerResource("guide-docs", new ResourceTemplate(`${RESOURCE_BASE_URI}/pages/{guide}.md`, {
2311
+ list: async () => ({ resources: (await ctx.catalog()).guides.map((guide) => ({
2312
+ uri: guide.resourceUri,
2313
+ name: guide.name,
2314
+ title: guide.title,
2315
+ description: guide.description,
2316
+ mimeType: "text/markdown"
2317
+ })) }),
2318
+ complete: { guide: async (value) => {
2319
+ const prefix = value.toLowerCase();
2320
+ return (await ctx.catalog()).guides.map((guide) => guide.name).filter((name) => name.startsWith(prefix));
2321
+ } }
2322
+ }), {
2323
+ title: "ExhaustiveUI guide docs",
2324
+ description: "Generated Markdown of one guide.",
2325
+ mimeType: "text/markdown"
2326
+ }, async (uri, variables) => {
2327
+ const guide = findGuide(await ctx.catalog(), variable(variables.guide));
2328
+ return { contents: [{
2329
+ uri: uri.href,
2330
+ mimeType: "text/markdown",
2331
+ text: await ctx.source.readText(guide.docPath)
2332
+ }] };
2333
+ });
2334
+ server.registerResource("example-docs", new ResourceTemplate(`${RESOURCE_BASE_URI}/examples/{component}/{section}.md`, {
2335
+ list: void 0,
2336
+ complete: {
2337
+ component: completeComponent(ctx),
2338
+ section: async (value, context) => {
2339
+ const componentName = context?.arguments?.component;
2340
+ if (!componentName) return [];
2341
+ const component = findComponent(await ctx.catalog(), componentName);
2342
+ const prefix = value.toLowerCase();
2343
+ return component.sections.filter((section) => section.hasCode).map((section) => section.id).filter((id) => id.toLowerCase().startsWith(prefix));
2344
+ }
2345
+ }
2346
+ }), {
2347
+ title: "ExhaustiveUI examples",
2348
+ description: "One code example of a component, as Markdown.",
2349
+ mimeType: "text/markdown"
2350
+ }, async (uri, variables) => {
2351
+ const component = findComponent(await ctx.catalog(), variable(variables.component));
2352
+ const section = requireSection(component.sections, variable(variables.section));
2353
+ const text = [
2354
+ `# ${component.title}: ${section.label}`,
2355
+ "",
2356
+ section.description ?? "",
2357
+ "",
2358
+ `Source: ${component.resourceUri}`,
2359
+ "",
2360
+ section.hasCode ? `\`\`\`${section.codeLanguage}\n${section.code}\n\`\`\`` : "_This section has no code example._"
2361
+ ].join("\n");
2362
+ return { contents: [{
2363
+ uri: uri.href,
2364
+ mimeType: "text/markdown",
2365
+ text
2366
+ }] };
2367
+ });
2368
+ }
2369
+ function completeComponent(ctx) {
2370
+ return async (value) => {
2371
+ const prefix = value.toLowerCase();
2372
+ return (await ctx.catalog()).components.map((component) => component.name).filter((name) => name.startsWith(prefix)).slice(0, 50);
2373
+ };
2374
+ }
2375
+ function variable(value) {
2376
+ const single = Array.isArray(value) ? value[0] : value;
2377
+ if (!single) throw new Error("Missing resource template variable");
2378
+ return single;
2379
+ }
2380
+ function componentApi(component) {
2381
+ return {
2382
+ name: component.name,
2383
+ title: component.title,
2384
+ import: component.import,
2385
+ modules: component.modules,
2386
+ selectors: component.selectors,
2387
+ api: component.api,
2388
+ compiled: component.declarations
2389
+ };
2390
+ }
2391
+ const PROMPTS = {
2392
+ use_component: {
2393
+ title: "Use an ExhaustiveUI component",
2394
+ description: "Add an ExhaustiveUI component to an Angular app correctly, from its documented API and examples.",
2395
+ steps: [
2396
+ "Call get_component for the component (includeApi: true when you need inputs, outputs or templates).",
2397
+ "Call get_example for the closest documented example and adapt it; keep the `@exhaustive-ui/core/<name>` import.",
2398
+ "Call validate_usage on the template you wrote before answering."
2399
+ ]
2400
+ },
2401
+ build_form: {
2402
+ title: "Build a form with ExhaustiveUI",
2403
+ description: "Build an Angular form (reactive or template-driven) with ExhaustiveUI form components.",
2404
+ steps: [
2405
+ "Call search with scope \"components\" for the inputs the form needs (inputtext, select, datepicker, checkbox, ...).",
2406
+ "Call get_example with section \"reactiveforms\" or \"forms\" for each component to see the documented form integration.",
2407
+ "Call validate_usage on the final template."
2408
+ ]
2409
+ },
2410
+ theme_component: {
2411
+ title: "Theme an ExhaustiveUI component",
2412
+ description: "Customize a component with design tokens, pass-through attributes, CSS classes or Tailwind.",
2413
+ steps: [
2414
+ "Call get_setup with environment \"styled\" (or \"unstyled\", \"tailwind\", \"passthrough\") for the theming model.",
2415
+ "Call get_component with includeApi: true and read its pt keys, styles (CSS classes) and tokens.",
2416
+ "Prefer design tokens (dt input or theme preset) over overriding CSS classes."
2417
+ ]
2418
+ },
2419
+ migrate_from_primeng: {
2420
+ title: "Migrate from PrimeNG",
2421
+ description: "Plan the migration of PrimeNG (or Optimus UI) code to ExhaustiveUI.",
2422
+ steps: [
2423
+ "Call get_guide for \"faq\" (migration notes) and get_setup for \"angular-cli\".",
2424
+ "For each PrimeNG component used, call get_component with the PrimeNG name: renamed components (dropdown, calendar, sidebar, overlaypanel, inputswitch, tabview...) resolve to their ExhaustiveUI equivalent.",
2425
+ "Replace `primeng/<name>` imports with `@exhaustive-ui/core/<name>` and call validate_usage on each migrated template."
2426
+ ]
2427
+ },
2428
+ audit_component_usage: {
2429
+ title: "Audit ExhaustiveUI usage",
2430
+ description: "Review application code for ExhaustiveUI API mismatches.",
2431
+ steps: [
2432
+ "Collect every template that uses a `p-*` element or `p*` directive.",
2433
+ "Call validate_usage with \"usages\" batches of up to 10 { component, code } items.",
2434
+ "Fix errors first (unknown inputs/outputs, invalid values, PrimeNG imports), then review warnings (deprecated inputs)."
2435
+ ]
2436
+ }
2437
+ };
2438
+ function registerPrompts(server) {
2439
+ for (const name of PROMPT_NAMES) {
2440
+ const prompt = PROMPTS[name];
2441
+ server.registerPrompt(name, {
2442
+ title: prompt.title,
2443
+ description: prompt.description,
2444
+ argsSchema: {
2445
+ component: z.string().optional().describe("Component name"),
2446
+ goal: z.string().optional().describe("What the user wants to achieve")
2447
+ }
2448
+ }, ({ component, goal }) => ({ messages: [{
2449
+ role: "user",
2450
+ content: {
2451
+ type: "text",
2452
+ text: [
2453
+ `${prompt.description}${component ? ` Component: ${component}.` : ""}`,
2454
+ goal ? `Goal: ${goal}` : "",
2455
+ "",
2456
+ "Use the ExhaustiveUI MCP tools rather than memory of PrimeNG:",
2457
+ ...prompt.steps.map((step, index) => `${index + 1}. ${step}`)
2458
+ ].filter((line) => line !== void 0).join("\n")
2459
+ }
2460
+ }] }));
2461
+ }
2462
+ }
2463
+
2464
+ //#endregion
2465
+ //#region src/index.ts
2466
+ const HELP = `${SERVER_NAME}: Model Context Protocol server for the ExhaustiveUI Angular component library.
2467
+
2468
+ Usage: exhaustive-ui-mcp [--help] [--version]
2469
+
2470
+ The server speaks MCP over stdio; register it in your MCP client, for example:
2471
+ claude mcp add exhaustive-ui -- npx -y @exhaustive-ui/mcp
2472
+
2473
+ Environment variables:
2474
+ EXHAUSTIVE_UI_DOCS_URL Docs site to read from (default https://exhaustive-ui.e-xiste.com)
2475
+ EXHAUSTIVE_UI_MCP_CACHE_TTL Seconds a fetched document is reused (default 900)
2476
+ EXHAUSTIVE_UI_MCP_FETCH_TIMEOUT Milliseconds before a request to the docs site is abandoned (default 10000)
2477
+ EXHAUSTIVE_UI_MCP_OFFLINE Set to 1 to only use the offline snapshot bundled with the package
2478
+ EXHAUSTIVE_UI_MCP_SNAPSHOT_DIR Directory of the offline snapshot (default: the package's data/ directory)
2479
+ `;
2480
+ function isCliEntrypoint() {
2481
+ const entry = process.argv[1];
2482
+ if (!entry) return false;
2483
+ try {
2484
+ return realpathSync(entry) === realpathSync(fileURLToPath(import.meta.url));
2485
+ } catch {
2486
+ return false;
2487
+ }
2488
+ }
2489
+ if (isCliEntrypoint()) {
2490
+ const args = process.argv.slice(2);
2491
+ if (args.includes("--help") || args.includes("-h")) console.log(HELP);
2492
+ else if (args.includes("--version") || args.includes("-v")) console.log(readPackageVersion());
2493
+ else runExhaustiveUiMcpServer().catch((error) => {
2494
+ console.error(`Failed to start ${SERVER_NAME}:`, error);
2495
+ process.exit(1);
2496
+ });
2497
+ }
2498
+
2499
+ //#endregion
2500
+ export { CachedSource, CatalogLoader, DEFAULT_CACHE_TTL_SECONDS, DEFAULT_DOCS_URL, DEFAULT_FETCH_TIMEOUT_MS, FallbackSource, MemorySource, PROMPT_NAMES, RESOURCE_BASE_URI, RESOURCE_TEMPLATE_NAMES, RemoteSource, SERVER_NAME, STATIC_RESOURCE_URIS, SnapshotSource, TOOL_NAMES, buildCatalog, componentApi, createDocsSource, createExhaustiveUiMcpServer, createToolContext, findComponent, findGuide, findSection, readPackageVersion, resolveConfig, runExhaustiveUiMcpServer, searchCatalog, validateComponentUsage };
2501
+ //# sourceMappingURL=index.mjs.map