@storybook/mcp 0.7.0 → 10.6.0-alpha.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,845 +1,1101 @@
1
- import { t as instructions_default } from "./instructions-Cl0vcW2j.js";
1
+ import CJS_COMPAT_NODE_URL_zxd3nd567le from 'node:url';
2
+ import CJS_COMPAT_NODE_PATH_zxd3nd567le from 'node:path';
3
+ import CJS_COMPAT_NODE_MODULE_zxd3nd567le from "node:module";
4
+
5
+ var __filename = CJS_COMPAT_NODE_URL_zxd3nd567le.fileURLToPath(import.meta.url);
6
+ var __dirname = CJS_COMPAT_NODE_PATH_zxd3nd567le.dirname(__filename);
7
+ var require = CJS_COMPAT_NODE_MODULE_zxd3nd567le.createRequire(import.meta.url);
8
+
9
+ // ------------------------------------------------------------
10
+ // end of CJS compatibility banner, injected by Storybook's esbuild configuration
11
+ // ------------------------------------------------------------
12
+
13
+ // src/index.ts
2
14
  import { McpServer } from "tmcp";
3
15
  import { ValibotJsonSchemaAdapter } from "@tmcp/adapter-valibot";
4
16
  import { HttpTransport } from "@tmcp/transport-http";
5
- import * as v from "valibot";
6
17
 
7
- //#region package.json
8
- var name = "@storybook/mcp";
9
- var version = "0.7.0";
10
- var description = "MCP server that serves knowledge about your components based on your Storybook stories and documentation";
18
+ // package.json
19
+ var package_default = {
20
+ name: "@storybook/mcp",
21
+ version: "10.6.0-alpha.4",
22
+ description: "MCP server that serves knowledge about your components based on your Storybook stories and documentation",
23
+ keywords: [
24
+ "mcp",
25
+ "storybook"
26
+ ],
27
+ homepage: "https://github.com/storybookjs/storybook/tree/next/code/lib/mcp",
28
+ bugs: {
29
+ url: "https://github.com/storybookjs/storybook/issues"
30
+ },
31
+ repository: {
32
+ type: "git",
33
+ url: "https://github.com/storybookjs/storybook.git",
34
+ directory: "code/lib/mcp"
35
+ },
36
+ funding: {
37
+ type: "opencollective",
38
+ url: "https://opencollective.com/storybook"
39
+ },
40
+ license: "MIT",
41
+ author: "Storybook Core Team",
42
+ type: "module",
43
+ exports: {
44
+ ".": {
45
+ types: "./dist/index.d.ts",
46
+ code: "./src/index.ts",
47
+ default: "./dist/index.js"
48
+ },
49
+ "./package.json": "./package.json"
50
+ },
51
+ files: [
52
+ "dist/**/*",
53
+ "README.md",
54
+ "*.js",
55
+ "*.d.ts",
56
+ "!src/**/*"
57
+ ],
58
+ dependencies: {
59
+ "@tmcp/adapter-valibot": "^0.1.5",
60
+ "@tmcp/transport-http": "^0.8.5",
61
+ tmcp: "^1.19.4",
62
+ valibot: "^1.4.0"
63
+ },
64
+ devDependencies: {
65
+ "@modelcontextprotocol/sdk": "^1.22.0",
66
+ "@tmcp/transport-stdio": "^0.4.3",
67
+ "react-docgen": "^8.0.2",
68
+ "react-docgen-typescript": "^2.4.0",
69
+ srvx: "^0.8.16",
70
+ tinyexec: "^1.0.2",
71
+ typescript: "^6.0.3"
72
+ },
73
+ publishConfig: {
74
+ access: "public"
75
+ }
76
+ };
11
77
 
12
- //#endregion
13
- //#region src/types.ts
14
- const JSDocTag = v.record(v.string(), v.array(v.string()));
15
- const Error$1 = v.object({
16
- name: v.string(),
17
- message: v.string()
18
- });
19
- const BaseManifest = v.object({
20
- name: v.string(),
21
- description: v.optional(v.string()),
22
- jsDocTags: v.optional(JSDocTag),
23
- error: v.optional(Error$1)
24
- });
25
- const Story = v.object({
26
- ...BaseManifest.entries,
27
- id: v.optional(v.string()),
28
- snippet: v.optional(v.string()),
29
- summary: v.optional(v.string())
30
- });
31
- /**
32
- * A docs entry represents MDX documentation that can be attached to a component
33
- * or standalone (unattached).
34
- */
35
- const Doc = v.object({
36
- id: v.string(),
37
- name: v.string(),
38
- title: v.string(),
39
- path: v.string(),
40
- content: v.string(),
41
- summary: v.optional(v.string()),
42
- error: v.optional(Error$1)
43
- });
44
- const BaseComponentProperties = v.object({
45
- ...BaseManifest.entries,
46
- path: v.string(),
47
- summary: v.optional(v.string()),
48
- import: v.optional(v.string()),
49
- reactDocgen: v.optional(v.any()),
50
- reactDocgenTypescript: v.optional(v.any()),
51
- reactComponentMeta: v.optional(v.any())
52
- });
53
- const SubcomponentManifest = v.object({ ...BaseComponentProperties.entries });
54
- const ComponentManifest = v.object({
55
- ...BaseComponentProperties.entries,
56
- id: v.string(),
57
- stories: v.optional(v.array(Story)),
58
- subcomponents: v.optional(v.record(v.string(), SubcomponentManifest)),
59
- docs: v.optional(v.record(v.string(), Doc))
60
- });
61
- const ComponentManifestMap = v.object({
62
- v: v.number(),
63
- components: v.record(v.string(), ComponentManifest)
64
- });
65
- /**
66
- * Manifest for unattached/standalone documentation entries.
67
- * Served at /manifests/docs.json
68
- */
69
- const DocsManifestMap = v.object({
70
- v: v.number(),
71
- docs: v.record(v.string(), Doc)
72
- });
73
- /**
74
- * Shared Valibot field for the storybookId input, used in multi-source mode.
75
- * Reused across tools that support source selection.
76
- */
77
- const StorybookIdField = { storybookId: v.pipe(v.string(), v.description("The Storybook source ID (e.g., \"local\", \"tetra\"). Required when multiple Storybooks are composed. See list-all-documentation for available sources.")) };
78
+ // src/tools/list-all-documentation.ts
79
+ import * as v3 from "valibot";
78
80
 
79
- //#endregion
80
- //#region src/utils/get-manifest.ts
81
- /**
82
- * The paths to the manifest files relative to the Storybook build
83
- */
84
- const COMPONENT_MANIFEST_PATH = "./manifests/components.json";
85
- const DOCS_MANIFEST_PATH = "./manifests/docs.json";
86
- /**
87
- * Error thrown when getting or parsing a manifest fails
88
- */
89
- var ManifestGetError = class extends Error {
90
- url;
91
- cause;
92
- constructor(message, url, cause) {
93
- super(message);
94
- this.name = "ManifestGetError";
95
- this.url = url ?? "No source URL provided";
96
- this.cause = cause;
97
- }
81
+ // src/types.ts
82
+ import * as v from "valibot";
83
+ var JSDocTag = v.record(v.string(), v.array(v.string())), ManifestError = v.object({
84
+ name: v.string(),
85
+ message: v.string()
86
+ }), BaseManifest = v.object({
87
+ name: v.string(),
88
+ description: v.optional(v.string()),
89
+ jsDocTags: v.optional(JSDocTag),
90
+ error: v.optional(ManifestError)
91
+ }), Story = v.object({
92
+ ...BaseManifest.entries,
93
+ id: v.optional(v.string()),
94
+ snippet: v.optional(v.string()),
95
+ summary: v.optional(v.string())
96
+ }), JsonRef = v.object({
97
+ $ref: v.string()
98
+ }), DocV0 = v.object({
99
+ id: v.string(),
100
+ name: v.string(),
101
+ title: v.optional(v.string()),
102
+ path: v.optional(v.string()),
103
+ content: v.optional(v.string()),
104
+ summary: v.optional(v.string()),
105
+ error: v.optional(ManifestError)
106
+ }), BaseInlineComponentProperties = v.object({
107
+ ...BaseManifest.entries,
108
+ path: v.optional(v.string()),
109
+ summary: v.optional(v.string()),
110
+ import: v.optional(v.string()),
111
+ reactDocgen: v.optional(v.any()),
112
+ reactDocgenTypescript: v.optional(v.any()),
113
+ reactComponentMeta: v.optional(v.any())
114
+ }), SubcomponentManifest = v.object({
115
+ ...BaseInlineComponentProperties.entries
116
+ }), ComponentManifestV0 = v.object({
117
+ ...BaseInlineComponentProperties.entries,
118
+ id: v.string(),
119
+ stories: v.optional(v.array(Story)),
120
+ subcomponents: v.optional(v.record(v.string(), SubcomponentManifest)),
121
+ docs: v.optional(v.record(v.string(), DocV0))
122
+ }), ComponentManifestMapV0 = v.object({
123
+ v: v.literal(0),
124
+ components: v.record(v.string(), ComponentManifestV0)
125
+ }), DocsManifestMapV0 = v.object({
126
+ v: v.literal(0),
127
+ docs: v.record(v.string(), DocV0)
128
+ }), DocV1 = v.object({
129
+ id: v.string(),
130
+ name: v.string(),
131
+ summary: v.optional(v.string()),
132
+ mdx: v.optional(JsonRef),
133
+ error: v.optional(ManifestError)
134
+ }), ComponentManifestV1 = v.object({
135
+ id: v.string(),
136
+ name: v.string(),
137
+ description: v.optional(v.string()),
138
+ summary: v.optional(v.string()),
139
+ error: v.optional(ManifestError),
140
+ docgen: v.optional(JsonRef),
141
+ stories: v.optional(JsonRef),
142
+ docs: v.optional(v.record(v.string(), DocV1))
143
+ }), ComponentManifestMapV1 = v.object({
144
+ v: v.literal(1),
145
+ components: v.record(v.string(), ComponentManifestV1)
146
+ }), DocsManifestMapV1 = v.object({
147
+ v: v.literal(1),
148
+ docs: v.record(v.string(), DocV1)
149
+ }), ComponentManifestMap = v.variant("v", [
150
+ ComponentManifestMapV0,
151
+ ComponentManifestMapV1
152
+ ]), DocsManifestMap = v.variant("v", [DocsManifestMapV0, DocsManifestMapV1]), StorybookIdField = {
153
+ storybookId: v.pipe(
154
+ v.string(),
155
+ v.description(
156
+ 'The Storybook source ID (e.g., "local", "tetra"). Required when multiple Storybooks are composed. See list-all-documentation for available sources.'
157
+ )
158
+ )
98
159
  };
99
- /**
100
- * Converts an error to MCP-compatible content format
101
- *
102
- * @param error - The error to convert (can be any type)
103
- * @returns A tool result with error content and isError flag
104
- */
105
- const errorToMCPContent = (error) => {
106
- let fullMessage = `${error instanceof ManifestGetError ? "Error getting manifest" : "Unexpected error"}: ${error instanceof Error ? error.message : String(error)}`;
107
- if (error instanceof ManifestGetError && error.cause) {
108
- const causeMessage = error.cause instanceof Error ? error.cause.message : String(error.cause);
109
- fullMessage += `\nCaused by: ${causeMessage}`;
110
- }
111
- return {
112
- content: [{
113
- type: "text",
114
- text: fullMessage
115
- }],
116
- isError: true
117
- };
160
+
161
+ // src/utils/get-manifest.ts
162
+ import * as v2 from "valibot";
163
+
164
+ // src/utils/adapt-core-manifest.ts
165
+ var ARG_TYPES_KEY = "argTypes";
166
+ function adaptCoreStories(stories) {
167
+ if (stories)
168
+ return Array.isArray(stories) ? stories : Object.values(stories);
169
+ }
170
+ function adaptCoreDoc(doc) {
171
+ return { ...doc };
172
+ }
173
+ function adaptCoreComponent(core) {
174
+ let { stories, docs, [ARG_TYPES_KEY]: _argTypes, ...rest } = core, component = { ...rest }, adaptedStories = adaptCoreStories(stories);
175
+ return adaptedStories && (component.stories = adaptedStories), docs && (component.docs = Object.fromEntries(
176
+ Object.entries(docs).map(([id, doc]) => [id, adaptCoreDoc(doc)])
177
+ )), component;
178
+ }
179
+
180
+ // src/utils/requires-own-mcp.ts
181
+ function getSourceMcpEndpoint(source) {
182
+ let base = new URL(source.url);
183
+ return base.pathname = `${base.pathname.replace(/\/$/, "")}/`, new URL("mcp", base).toString();
184
+ }
185
+ function formatRequiresOwnMcpNotice(source, endpoint, options = {}) {
186
+ let parts = [];
187
+ return (options.includeHeader ?? !0) && (parts.push(`# ${source.title}`), parts.push(`id: ${source.id}`), parts.push("")), parts.push(
188
+ "This composed Storybook is private and cannot be read through the local Storybook MCP proxy."
189
+ ), parts.push(""), parts.push("Use this source's own MCP endpoint instead:"), parts.push(endpoint), parts.join(`
190
+ `);
191
+ }
192
+
193
+ // src/utils/get-manifest.ts
194
+ var COMPONENT_MANIFEST_PATH = "./manifests/components.json", DOCS_MANIFEST_PATH = "./manifests/docs.json", EMPTY_COMPONENT_MANIFEST = { v: 1, components: {} }, ManifestGetError = class extends Error {
195
+ constructor(message, url, cause) {
196
+ super(message), this.name = "ManifestGetError", this.url = url ?? "No source URL provided", this.cause = cause;
197
+ }
198
+ }, RequiresOwnMcpError = class extends Error {
199
+ constructor(source) {
200
+ let endpoint = getSourceMcpEndpoint(source);
201
+ super(`Composed Storybook "${source.title}" requires its own MCP endpoint: ${endpoint}`), this.name = "RequiresOwnMcpError", this.source = source, this.endpoint = endpoint;
202
+ }
203
+ }, errorToMCPContent = (error) => {
204
+ if (error instanceof RequiresOwnMcpError)
205
+ return {
206
+ content: [
207
+ {
208
+ type: "text",
209
+ text: formatRequiresOwnMcpNotice(error.source, error.endpoint)
210
+ }
211
+ ]
212
+ };
213
+ let errorPrefix = error instanceof ManifestGetError ? "Error getting manifest" : "Unexpected error", errorMessage = error instanceof Error ? error.message : String(error), fullMessage = `${errorPrefix}: ${errorMessage}`;
214
+ if (error instanceof ManifestGetError && error.cause) {
215
+ let causeMessage = error.cause instanceof Error ? error.cause.message : String(error.cause);
216
+ fullMessage += `
217
+ Caused by: ${causeMessage}`;
218
+ }
219
+ return {
220
+ content: [
221
+ {
222
+ type: "text",
223
+ text: fullMessage
224
+ }
225
+ ],
226
+ isError: !0
227
+ };
118
228
  };
119
- /**
120
- * Parses a JSON string and validates it against a Valibot schema
121
- */
122
- function parseManifest({ jsonString, schema, name, url }) {
123
- try {
124
- return v.parse(v.pipe(v.string(), v.parseJson(), schema), jsonString);
125
- } catch (error) {
126
- throw new ManifestGetError(`Failed to parse ${name} manifest:
127
- ${error instanceof v.ValiError ? error.issues.map((i) => i.message).join("\n") : String(error)}`, url);
128
- }
129
- }
130
- /**
131
- * Gets component and docs manifest from a request or using a custom provider
132
- *
133
- * @param request - The HTTP request to get the manifest for (optional when using custom manifestProvider)
134
- * @param manifestProvider - Optional custom function to get the manifest
135
- * @param source - Optional source for multi-source mode
136
- * @returns A promise that resolves to the parsed ComponentManifestMap
137
- * @throws {ManifestGetError} If getting the manifest fails or the response is invalid
138
- */
229
+ function parseManifest({
230
+ jsonString,
231
+ schema,
232
+ name,
233
+ url
234
+ }) {
235
+ try {
236
+ return v2.parse(v2.pipe(v2.string(), v2.parseJson(), schema), jsonString);
237
+ } catch (error) {
238
+ throw new ManifestGetError(
239
+ `Failed to parse ${name} manifest:
240
+ ${error instanceof v2.ValiError ? error.issues.map((i) => i.message).join(`
241
+ `) : String(error)}`,
242
+ url
243
+ );
244
+ }
245
+ }
139
246
  async function getManifests(request, manifestProvider, source) {
140
- const provider = manifestProvider ?? defaultManifestProvider;
141
- const [componentResult, docsResult] = await Promise.allSettled([provider(request, COMPONENT_MANIFEST_PATH, source), provider(request, DOCS_MANIFEST_PATH, source)]);
142
- const getUrl = (path) => request ? getManifestUrlFromRequest(request, path) : "Unknown manifest source";
143
- if (componentResult.status === "rejected") {
144
- const reason = componentResult.reason;
145
- const hint = reason instanceof ManifestGetError && reason.message.includes("404") ? `\nHint: The Storybook at this URL may not have the component manifest enabled. Add \`features: { componentsManifest: true }\` (or \`features: { experimentalComponentsManifest: true }\` for older Storybook versions) to its main.ts config.` : "";
146
- throw new ManifestGetError(`Failed to get component manifest: ${reason instanceof Error ? reason.message : String(reason)}${hint}`, getUrl(COMPONENT_MANIFEST_PATH), reason instanceof Error ? reason : void 0);
147
- }
148
- const componentManifest = parseManifest({
149
- jsonString: componentResult.value,
150
- schema: ComponentManifestMap,
151
- name: "component",
152
- url: getUrl(COMPONENT_MANIFEST_PATH)
153
- });
154
- if (Object.keys(componentManifest.components).length === 0) throw new ManifestGetError(`No components found in the manifest`, getUrl(COMPONENT_MANIFEST_PATH));
155
- if (docsResult.status === "rejected") return { componentManifest };
156
- return {
157
- componentManifest,
158
- docsManifest: parseManifest({
159
- jsonString: docsResult.value,
160
- schema: DocsManifestMap,
161
- name: "docs",
162
- url: getUrl(DOCS_MANIFEST_PATH)
163
- })
164
- };
165
- }
166
- /**
167
- * Constructs the manifest URL from a request by replacing /mcp with the provided path
168
- */
247
+ let provider = manifestProvider ?? defaultManifestProvider, [componentResult, docsResult] = await Promise.allSettled([
248
+ provider(request, COMPONENT_MANIFEST_PATH, source),
249
+ provider(request, DOCS_MANIFEST_PATH, source)
250
+ ]), getUrl = (path) => request ? getManifestUrlFromRequest(request, path) : "Unknown manifest source";
251
+ if (componentResult.status === "rejected") {
252
+ let reason = componentResult.reason;
253
+ if (reason instanceof RequiresOwnMcpError)
254
+ throw reason;
255
+ let hint = reason instanceof ManifestGetError && reason.message.includes("404") ? "\nHint: The Storybook at this URL may not have the component manifest enabled. Add `features: { componentsManifest: true }` (or `features: { experimentalComponentsManifest: true }` for older Storybook versions) to its main.ts config." : "";
256
+ throw new ManifestGetError(
257
+ `Failed to get component manifest: ${reason instanceof Error ? reason.message : String(reason)}${hint}`,
258
+ getUrl(COMPONENT_MANIFEST_PATH),
259
+ reason instanceof Error ? reason : void 0
260
+ );
261
+ }
262
+ let componentManifest = parseManifest({
263
+ jsonString: componentResult.value,
264
+ schema: ComponentManifestMap,
265
+ name: "component",
266
+ url: getUrl(COMPONENT_MANIFEST_PATH)
267
+ });
268
+ if (Object.keys(componentManifest.components).length === 0)
269
+ throw new ManifestGetError(
270
+ "No components found in the manifest",
271
+ getUrl(COMPONENT_MANIFEST_PATH)
272
+ );
273
+ if (docsResult.status === "rejected")
274
+ return { componentManifest };
275
+ let docsManifest = parseManifest({
276
+ jsonString: docsResult.value,
277
+ schema: DocsManifestMap,
278
+ name: "docs",
279
+ url: getUrl(DOCS_MANIFEST_PATH)
280
+ });
281
+ return { componentManifest, docsManifest };
282
+ }
283
+ function parseManifestRef(ref) {
284
+ let [filePath = "", hash = ""] = ref.split("#"), manifestDir = COMPONENT_MANIFEST_PATH.replace(/^\.\//, "").replace(/[^/]+$/, ""), resolved = new URL(filePath, `https://localhost/${manifestDir}`).pathname.replace(
285
+ /^\//,
286
+ ""
287
+ ), pointer = hash.split("/").filter(Boolean).map((segment) => segment.replace(/~1/g, "/").replace(/~0/g, "~"));
288
+ return { path: `./${resolved}`, pointer };
289
+ }
290
+ async function fetchRefValue(ref, request, provider, source) {
291
+ let { path, pointer } = parseManifestRef(ref), jsonString = await provider(request, path, source), target;
292
+ try {
293
+ target = JSON.parse(jsonString);
294
+ } catch (error) {
295
+ throw new ManifestGetError(
296
+ `Failed to parse externalized payload referenced by "${ref}"`,
297
+ path,
298
+ error instanceof Error ? error : void 0
299
+ );
300
+ }
301
+ for (let key of pointer)
302
+ if (target && typeof target == "object" && key in target)
303
+ target = target[key];
304
+ else
305
+ throw new ManifestGetError(
306
+ `Reference "${ref}" could not be resolved: missing "${key}".`,
307
+ path
308
+ );
309
+ return target;
310
+ }
311
+ async function resolveComponentEntry(component, request, manifestProvider, source) {
312
+ let docgenRef = "docgen" in component ? component.docgen?.$ref : void 0, storiesRef = component.stories && !Array.isArray(component.stories) ? component.stories.$ref : void 0, docEntries = component.docs ? Object.entries(component.docs) : [], docRefs = docEntries.filter(([, doc]) => "mdx" in doc && !!doc.mdx?.$ref);
313
+ if (!docgenRef && !storiesRef && docRefs.length === 0)
314
+ return component;
315
+ let provider = manifestProvider ?? defaultManifestProvider, core = {
316
+ id: component.id,
317
+ name: component.name,
318
+ ...component.description !== void 0 ? { description: component.description } : {},
319
+ ...component.summary !== void 0 ? { summary: component.summary } : {},
320
+ ...component.error !== void 0 ? { error: component.error } : {}
321
+ };
322
+ if (docgenRef) {
323
+ let payload = await fetchRefValue(docgenRef, request, provider, source);
324
+ core = {
325
+ ...core,
326
+ ...payload,
327
+ id: component.id,
328
+ name: component.name,
329
+ ...component.description !== void 0 ? { description: component.description } : {},
330
+ ...component.summary !== void 0 ? { summary: component.summary } : {},
331
+ ...component.error !== void 0 ? { error: component.error } : {}
332
+ };
333
+ }
334
+ if (Array.isArray(component.stories) && (core.stories = component.stories), storiesRef) {
335
+ let storyDocs = await fetchRefValue(
336
+ storiesRef,
337
+ request,
338
+ provider,
339
+ source
340
+ );
341
+ storyDocs?.stories && (core.stories = storyDocs.stories), storyDocs?.import && (core.import = storyDocs.import);
342
+ }
343
+ if (docEntries.length > 0) {
344
+ let docs = {};
345
+ for (let [docId, doc] of docEntries) {
346
+ let mdxRef = "mdx" in doc ? doc.mdx?.$ref : void 0;
347
+ docs[docId] = mdxRef ? await fetchRefValue(mdxRef, request, provider, source) : doc;
348
+ }
349
+ core.docs = docs;
350
+ }
351
+ return adaptCoreComponent(core);
352
+ }
353
+ async function resolveComponentStories(component, request, manifestProvider, source) {
354
+ if (!component.stories || Array.isArray(component.stories))
355
+ return component;
356
+ let provider = manifestProvider ?? defaultManifestProvider, storyDocs = await fetchRefValue(
357
+ component.stories.$ref,
358
+ request,
359
+ provider,
360
+ source
361
+ );
362
+ return {
363
+ ...component,
364
+ stories: storyDocs?.stories ? adaptCoreStories(storyDocs.stories) : []
365
+ };
366
+ }
367
+ async function resolveDoc(doc, request, manifestProvider, source) {
368
+ let ref = "mdx" in doc ? doc.mdx?.$ref : void 0;
369
+ if (!ref)
370
+ return doc;
371
+ let payload = await fetchRefValue(ref, request, manifestProvider ?? defaultManifestProvider, source);
372
+ return adaptCoreDoc({
373
+ ...payload,
374
+ id: payload.id ?? doc.id,
375
+ name: payload.name ?? doc.name
376
+ });
377
+ }
169
378
  function getManifestUrlFromRequest(request, path) {
170
- const url = new URL(request.url);
171
- const normalizedPath = path.replace(/^\.\//, "");
172
- url.pathname = url.pathname.replace(/\/mcp\/?$/, `/${normalizedPath}`);
173
- return url.toString();
174
- }
175
- /**
176
- * Default manifest provider that fetches from the same origin as the request,
177
- * replacing /mcp with the provided path
178
- */
379
+ let normalizedPath = path.replace(/^\.\//, "");
380
+ return new URL(`/${normalizedPath}`, request.url).toString();
381
+ }
179
382
  async function defaultManifestProvider(request, path) {
180
- if (!request) throw new ManifestGetError("Request is required when using the default manifest provider. You must either pass the original request forward to the server context, or set a custom manifestProvider that doesn't need the request.");
181
- const manifestUrl = getManifestUrlFromRequest(request, path);
182
- const response = await fetch(manifestUrl);
183
- if (!response.ok) throw new ManifestGetError(`Failed to fetch manifest: ${response.status} ${response.statusText}`, manifestUrl);
184
- const contentType = response.headers.get("content-type");
185
- if (!contentType?.includes("application/json")) throw new ManifestGetError(`Invalid content type: expected application/json, got ${contentType}`, manifestUrl);
186
- return response.text();
187
- }
188
- /**
189
- * Gets manifests from multiple sources.
190
- * Returns an array of source manifests, each containing the source info and its manifests.
191
- * Failures for individual sources are captured as errors rather than failing the entire request.
192
- *
193
- * @param sources - Array of source configurations
194
- * @param request - The HTTP request (used for local source)
195
- * @param manifestProvider - Function to fetch manifests, receives source as third parameter
196
- * @returns Promise resolving to array of source manifests
197
- * @throws {ManifestGetError} If no sources could be fetched successfully
198
- */
383
+ if (!request)
384
+ throw new ManifestGetError(
385
+ "Request is required when using the default manifest provider. You must either pass the original request forward to the server context, or set a custom manifestProvider that doesn't need the request."
386
+ );
387
+ let manifestUrl = getManifestUrlFromRequest(request, path), response = await fetch(manifestUrl);
388
+ if (!response.ok)
389
+ throw new ManifestGetError(
390
+ `Failed to fetch manifest: ${response.status} ${response.statusText}`,
391
+ manifestUrl
392
+ );
393
+ let contentType = response.headers.get("content-type");
394
+ if (!contentType?.includes("application/json"))
395
+ throw new ManifestGetError(
396
+ `Invalid content type: expected application/json, got ${contentType}`,
397
+ manifestUrl
398
+ );
399
+ return response.text();
400
+ }
199
401
  async function getMultiSourceManifests(sources, request, manifestProvider) {
200
- const results = await Promise.all(sources.map(async (source) => {
201
- try {
202
- const manifests = await getManifests(request, manifestProvider, source);
203
- return {
204
- source,
205
- componentManifest: manifests.componentManifest,
206
- docsManifest: manifests.docsManifest
207
- };
208
- } catch (error) {
209
- return {
210
- source,
211
- componentManifest: {
212
- v: 1,
213
- components: {}
214
- },
215
- error: error instanceof Error ? error.message : String(error)
216
- };
217
- }
218
- }));
219
- if (results.filter((r) => !r.error).length === 0) throw new ManifestGetError(`Failed to fetch manifests from any source. Errors:\n${results.map((r) => `- ${r.source.title}: ${r.error}`).join("\n")}`);
220
- return results;
402
+ let results = await Promise.all(
403
+ sources.map(async (source) => {
404
+ try {
405
+ let manifests = await getManifests(request, manifestProvider, source);
406
+ return {
407
+ source,
408
+ componentManifest: manifests.componentManifest,
409
+ docsManifest: manifests.docsManifest
410
+ };
411
+ } catch (error) {
412
+ if (error instanceof RequiresOwnMcpError)
413
+ return {
414
+ source,
415
+ componentManifest: EMPTY_COMPONENT_MANIFEST,
416
+ notice: {
417
+ kind: "requires-own-mcp",
418
+ endpoint: error.endpoint
419
+ }
420
+ };
421
+ let errorMessage = error instanceof Error ? error.message : String(error);
422
+ return {
423
+ source,
424
+ componentManifest: EMPTY_COMPONENT_MANIFEST,
425
+ error: errorMessage
426
+ };
427
+ }
428
+ })
429
+ ), successCount = results.filter((r) => !r.error && !r.notice).length, noticeCount = results.filter((r) => r.notice).length;
430
+ if (successCount === 0 && noticeCount === 0)
431
+ throw new ManifestGetError(
432
+ `Failed to fetch manifests from any source. Errors:
433
+ ${results.map((r) => `- ${r.source.title}: ${r.error}`).join(`
434
+ `)}`
435
+ );
436
+ return results;
437
+ }
438
+
439
+ // src/utils/map-with-concurrency.ts
440
+ async function mapWithConcurrency(items, limit, fn) {
441
+ if (items.length === 0)
442
+ return [];
443
+ let safeLimit = Number.isFinite(limit) ? limit : items.length, concurrency = Math.max(1, Math.min(safeLimit, items.length)), results = Array(items.length), nextIndex = 0;
444
+ async function worker() {
445
+ for (; nextIndex < items.length; ) {
446
+ let index = nextIndex++;
447
+ results[index] = await fn(items[index], index);
448
+ }
449
+ }
450
+ return await Promise.all(Array.from({ length: concurrency }, () => worker())), results;
221
451
  }
222
452
 
223
- //#endregion
224
- //#region src/utils/parse-react-docgen.ts
453
+ // src/utils/parse-react-docgen.ts
225
454
  function serializeTsType(tsType) {
226
- if (!tsType) return void 0;
227
- if ("raw" in tsType && typeof tsType.raw === "string" && tsType.raw.trim().length > 0) return tsType.raw;
228
- if (!tsType.name) return void 0;
229
- if ("elements" in tsType) {
230
- const serializeElements = () => (tsType.elements ?? []).map((el) => serializeTsType(el) ?? "unknown");
231
- switch (tsType.name) {
232
- case "union": return serializeElements().join(" | ");
233
- case "intersection": return serializeElements().join(" & ");
234
- case "Array": return `${serializeTsType((tsType.elements ?? [])[0]) ?? "unknown"}[]`;
235
- case "tuple": return `[${serializeElements().join(", ")}]`;
236
- }
237
- }
238
- if ("value" in tsType && tsType.name === "literal") return tsType.value;
239
- if ("signature" in tsType && tsType.name === "signature") {
240
- if (tsType.type === "function") {
241
- const args = (tsType.signature?.arguments ?? []).map((a) => {
242
- const argType = serializeTsType(a.type) ?? "any";
243
- return `${a.name}: ${argType}`;
244
- });
245
- const ret = serializeTsType(tsType.signature?.return) ?? "void";
246
- return `(${args.join(", ")}) => ${ret}`;
247
- }
248
- if (tsType.type === "object") return `{ ${(tsType.signature?.properties ?? []).map((p) => {
249
- const req = Boolean(p.value?.required);
250
- const propType = serializeTsType(p.value) ?? "any";
251
- return `${p.key}${req ? "" : "?"}: ${propType}`;
252
- }).join("; ")} }`;
253
- return "unknown";
254
- }
255
- if ("elements" in tsType) {
256
- const inner = (tsType.elements ?? []).map((el) => serializeTsType(el) ?? "unknown");
257
- if (inner.length > 0) return `${tsType.name}<${inner.join(", ")}>`;
258
- }
259
- return tsType.name;
260
- }
261
- const parseReactDocgen = (reactDocgen) => {
262
- const props = reactDocgen?.props ?? {};
263
- return { props: Object.fromEntries(Object.entries(props).map(([propName, prop]) => [propName, {
264
- description: prop.description,
265
- type: serializeTsType(prop.tsType ?? prop.type),
266
- defaultValue: prop.defaultValue?.value,
267
- required: prop.required
268
- }])) };
269
- };
270
- /**
271
- * Parse react-docgen-typescript output into the same simplified ParsedDocgen format.
272
- * RDT uses flat type strings (prop.type.name / prop.type.raw) instead of react-docgen's
273
- * nested tsType structure, so no serialization is needed.
274
- */
275
- const parseComponentDocLike = (componentDoc) => {
276
- const props = componentDoc.props ?? {};
277
- return { props: Object.fromEntries(Object.entries(props).map(([propName, prop]) => [propName, {
278
- description: prop.description || void 0,
279
- type: prop.type?.raw ?? prop.type?.name,
280
- defaultValue: prop.defaultValue?.value,
281
- required: prop.required
282
- }])) };
283
- };
284
- const parseReactDocgenTypescript = (reactDocgenTypescript) => parseComponentDocLike(reactDocgenTypescript);
285
- const parseReactComponentMeta = (reactComponentMeta) => parseComponentDocLike(reactComponentMeta);
455
+ if (tsType) {
456
+ if ("raw" in tsType && typeof tsType.raw == "string" && tsType.raw.trim().length > 0)
457
+ return tsType.raw;
458
+ if (tsType.name) {
459
+ if ("elements" in tsType) {
460
+ let serializeElements = () => (tsType.elements ?? []).map((el) => serializeTsType(el) ?? "unknown");
461
+ switch (tsType.name) {
462
+ case "union":
463
+ return serializeElements().join(" | ");
464
+ case "intersection":
465
+ return serializeElements().join(" & ");
466
+ case "Array":
467
+ return `${serializeTsType((tsType.elements ?? [])[0]) ?? "unknown"}[]`;
468
+ case "tuple":
469
+ return `[${serializeElements().join(", ")}]`;
470
+ }
471
+ }
472
+ if ("value" in tsType && tsType.name === "literal")
473
+ return tsType.value;
474
+ if ("signature" in tsType && tsType.name === "signature") {
475
+ if (tsType.type === "function") {
476
+ let args = (tsType.signature?.arguments ?? []).map((a) => {
477
+ let argType = serializeTsType(a.type) ?? "any";
478
+ return `${a.name}: ${argType}`;
479
+ }), ret = serializeTsType(tsType.signature?.return) ?? "void";
480
+ return `(${args.join(", ")}) => ${ret}`;
481
+ }
482
+ return tsType.type === "object" ? `{ ${(tsType.signature?.properties ?? []).map((p) => {
483
+ let req = !!p.value?.required, propType = serializeTsType(p.value) ?? "any";
484
+ return `${p.key}${req ? "" : "?"}: ${propType}`;
485
+ }).join("; ")} }` : "unknown";
486
+ }
487
+ if ("elements" in tsType) {
488
+ let inner = (tsType.elements ?? []).map((el) => serializeTsType(el) ?? "unknown");
489
+ if (inner.length > 0) return `${tsType.name}<${inner.join(", ")}>`;
490
+ }
491
+ return tsType.name;
492
+ }
493
+ }
494
+ }
495
+ var parseReactDocgen = (reactDocgen) => {
496
+ let props = reactDocgen?.props ?? {};
497
+ return {
498
+ props: Object.fromEntries(
499
+ Object.entries(props).map(([propName, prop]) => [
500
+ propName,
501
+ {
502
+ description: prop.description,
503
+ type: serializeTsType(prop.tsType ?? prop.type),
504
+ defaultValue: prop.defaultValue?.value,
505
+ required: prop.required
506
+ }
507
+ ])
508
+ )
509
+ };
510
+ }, parseComponentDocLike = (componentDoc) => {
511
+ let props = componentDoc.props ?? {};
512
+ return {
513
+ props: Object.fromEntries(
514
+ Object.entries(props).map(([propName, prop]) => [
515
+ propName,
516
+ {
517
+ description: prop.description || void 0,
518
+ // RDT uses prop.type.name as a flat string (e.g. "() => void", "{ id: string }")
519
+ // For enums, prefer prop.type.raw which has the full union
520
+ type: prop.type?.raw ?? prop.type?.name,
521
+ defaultValue: prop.defaultValue?.value,
522
+ required: prop.required
523
+ }
524
+ ])
525
+ )
526
+ };
527
+ }, parseReactDocgenTypescript = (reactDocgenTypescript) => parseComponentDocLike(reactDocgenTypescript), parseReactComponentMeta = (reactComponentMeta) => parseComponentDocLike(reactComponentMeta);
286
528
 
287
- //#endregion
288
- //#region src/utils/dedent.ts
289
- /**
290
- * Copied from https://github.com/tamino-martinius/node-ts-dedent/blob/18c4736c79806d7fe78bdaaaf5ae307b79f9574a/src/index.ts
291
- *
292
- * Rationale for vendoring instead of using the ts-dedent package:
293
- * 1. The package has a broken ESM distribution - the IDE auto-imports as
294
- * `import dedent from 'ts-dedent'` but that breaks at runtime, requiring
295
- * manual changes to named imports. See:
296
- * - https://github.com/tamino-martinius/node-ts-dedent/issues/42
297
- * - https://github.com/tamino-martinius/node-ts-dedent/pull/41
298
- * 2. Keeps bundle size smaller for such a simple utility (avoid "is-even" syndrome)
299
- */
529
+ // src/utils/dedent.ts
300
530
  function dedent(templ, ...values) {
301
- let strings = Array.from(typeof templ === "string" ? [templ] : templ);
302
- strings[strings.length - 1] = strings.at(-1).replace(/\r?\n([\t ]*)$/, "");
303
- const indentLengths = strings.reduce((arr, str) => {
304
- const matches = str.match(/\n([\t ]+|(?!\s).)/g);
305
- if (matches) return arr.concat(matches.map((match) => match.match(/[\t ]/g)?.length ?? 0));
306
- return arr;
307
- }, []);
308
- if (indentLengths.length) {
309
- const pattern = new RegExp(`\n[\t ]{${Math.min(...indentLengths)}}`, "g");
310
- strings = strings.map((str) => str.replace(pattern, "\n"));
311
- }
312
- strings[0] = strings[0].replace(/^\r?\n/, "");
313
- let string = strings[0];
314
- values.forEach((value, i) => {
315
- const endentations = string.match(/(?:^|\n)( *)$/);
316
- const endentation = endentations ? endentations[1] : "";
317
- let indentedValue = value;
318
- if (typeof value === "string" && value.includes("\n")) indentedValue = String(value).split("\n").map((str, i) => {
319
- return i === 0 ? str : `${endentation}${str}`;
320
- }).join("\n");
321
- string += `${String(indentedValue)}${strings[i + 1]}`;
322
- });
323
- return string;
531
+ let strings = Array.from(typeof templ == "string" ? [templ] : templ);
532
+ strings[strings.length - 1] = strings.at(-1).replace(/\r?\n([\t ]*)$/, "");
533
+ let indentLengths = strings.reduce((arr, str) => {
534
+ let matches = str.match(/\n([\t ]+|(?!\s).)/g);
535
+ return matches ? arr.concat(matches.map((match) => match.match(/[\t ]/g)?.length ?? 0)) : arr;
536
+ }, []);
537
+ if (indentLengths.length) {
538
+ let pattern = new RegExp(`
539
+ [ ]{${Math.min(...indentLengths)}}`, "g");
540
+ strings = strings.map((str) => str.replace(pattern, `
541
+ `));
542
+ }
543
+ strings[0] = strings[0].replace(/^\r?\n/, "");
544
+ let string5 = strings[0];
545
+ return values.forEach((value, i) => {
546
+ let endentations = string5.match(/(?:^|\n)( *)$/), endentation = endentations ? endentations[1] : "", indentedValue = value;
547
+ typeof value == "string" && value.includes(`
548
+ `) && (indentedValue = String(value).split(`
549
+ `).map((str, i2) => i2 === 0 ? str : `${endentation}${str}`).join(`
550
+ `)), string5 += `${String(indentedValue)}${strings[i + 1]}`;
551
+ }), string5;
324
552
  }
325
553
 
326
- //#endregion
327
- //#region src/utils/manifest-formatter/extract-docs-summary.ts
328
- /**
329
- * Maximum length for a summary before truncation.
330
- */
331
- const MAX_SUMMARY_LENGTH = 90;
332
- /**
333
- * Extracts a summary from MDX content.
334
- * The summary is created by:
335
- * 1. Removing import statements
336
- * 2. Removing JSX/MDX expressions
337
- * 3. Extracting only text content from JSX/HTML elements
338
- * 4. Truncating to MAX_SUMMARY_LENGTH characters if needed
339
- *
340
- * @param content - The MDX content string
341
- * @returns A summary string, or undefined if no meaningful text content is found
342
- */
554
+ // src/utils/manifest-formatter/extract-docs-summary.ts
343
555
  function extractDocsSummary(content) {
344
- let result = content;
345
- result = result.replace(/^\s*import\s+(?:[\s\S]*?from\s+)?['"][^'"]+['"];?\s*$/gm, "");
346
- let prevResult = "";
347
- while (prevResult !== result) {
348
- prevResult = result;
349
- result = result.replace(/\{[^{}]*\}/g, "");
350
- }
351
- result = result.replace(/<[^>]+\/>/g, "");
352
- prevResult = "";
353
- while (prevResult !== result) {
354
- prevResult = result;
355
- result = result.replace(/<(\w+)[^>]*>([\s\S]*?)<\/\1>/g, "$2");
356
- }
357
- result = result.replace(/<[^>]+>/g, "");
358
- result = result.replace(/\s+/g, " ").trim();
359
- if (!result) return;
360
- if (result.length > MAX_SUMMARY_LENGTH) return `${result.slice(0, MAX_SUMMARY_LENGTH)}...`;
361
- return result;
556
+ let result = content;
557
+ result = result.replace(/^\s*import\s+(?:[\s\S]*?from\s+)?['"][^'"]+['"];?\s*$/gm, "");
558
+ let prevResult = "";
559
+ for (; prevResult !== result; )
560
+ prevResult = result, result = result.replace(/\{[^{}]*\}/g, "");
561
+ for (result = result.replace(/<[^>]+\/>/g, ""), prevResult = ""; prevResult !== result; )
562
+ prevResult = result, result = result.replace(/<(\w+)[^>]*>([\s\S]*?)<\/\1>/g, "$2");
563
+ if (result = result.replace(/<[^>]+>/g, ""), result = result.replace(/\s+/g, " ").trim(), !!result)
564
+ return result.length > 90 ? `${result.slice(0, 90)}...` : result;
362
565
  }
363
566
 
364
- //#endregion
365
- //#region src/utils/manifest-formatter/markdown.ts
366
- /**
367
- * Maximum number of stories to show in full detail in component manifests.
368
- * Remaining stories will be shown as names only.
369
- */
370
- const MAX_STORIES_TO_SHOW = 3;
567
+ // src/utils/manifest-formatter/markdown.ts
568
+ var MAX_STORIES_TO_SHOW = 3;
371
569
  function formatComponentLine(component) {
372
- const summary = component.summary ?? (component.description ? component.description.length > MAX_SUMMARY_LENGTH ? `${component.description.slice(0, MAX_SUMMARY_LENGTH)}...` : component.description : void 0);
373
- if (summary) return `- ${component.name} (${component.id}): ${summary}`;
374
- return `- ${component.name} (${component.id})`;
570
+ let summary = component.summary ?? (component.description ? component.description.length > 90 ? `${component.description.slice(0, 90)}...` : component.description : void 0);
571
+ return summary ? `- ${component.name} (${component.id}): ${summary}` : `- ${component.name} (${component.id})`;
375
572
  }
376
573
  function formatDocLine(doc) {
377
- const summary = doc.summary ?? extractDocsSummary(doc.content);
378
- return `- ${doc.title} (${doc.id})${summary ? `: ${summary}` : ""}`;
574
+ let title = "title" in doc ? doc.title : void 0, content = "content" in doc ? doc.content : void 0, summary = doc.summary ?? extractDocsSummary(content ?? "");
575
+ return `- ${title ?? doc.name} (${doc.id})${summary ? `: ${summary}` : ""}`;
379
576
  }
380
577
  function formatStorySubLine(story) {
381
- return ` - ${story.name}` + (story.id ? ` (${story.id})` : "");
382
- }
383
- /**
384
- * Extracts a summary from an object with optional summary and description fields.
385
- * Prefers summary if available, otherwise truncates description to maxLength.
386
- */
387
- function extractSummary(item, maxLength = MAX_SUMMARY_LENGTH) {
388
- if (item.summary) return item.summary;
389
- if (item.description) return item.description.length > maxLength ? `${item.description.slice(0, maxLength)}...` : item.description;
390
- }
391
- /**
392
- * Extract parsed docgen from a component manifest, preferring reactDocgen over
393
- * reactDocgenTypescript over reactComponentMeta.
394
- */
578
+ return ` - ${story.name}` + (story.id ? ` (${story.id})` : "");
579
+ }
580
+ function extractSummary(item, maxLength = 90) {
581
+ if (item.summary)
582
+ return item.summary;
583
+ if (item.description)
584
+ return item.description.length > maxLength ? `${item.description.slice(0, maxLength)}...` : item.description;
585
+ }
395
586
  function getParsedDocgen(componentManifest) {
396
- if (componentManifest.reactDocgen) return parseReactDocgen(componentManifest.reactDocgen);
397
- if (componentManifest.reactDocgenTypescript) return parseReactDocgenTypescript(componentManifest.reactDocgenTypescript);
398
- if (componentManifest.reactComponentMeta) return parseReactComponentMeta(componentManifest.reactComponentMeta);
399
- }
400
- /**
401
- * Formats a story's content (description + code snippet) into markdown.
402
- * Reusable helper for both formatComponentManifest and formatStoryDocumentation.
403
- */
587
+ if (componentManifest.reactDocgen)
588
+ return parseReactDocgen(componentManifest.reactDocgen);
589
+ if (componentManifest.reactDocgenTypescript)
590
+ return parseReactDocgenTypescript(componentManifest.reactDocgenTypescript);
591
+ if (componentManifest.reactComponentMeta)
592
+ return parseReactComponentMeta(componentManifest.reactComponentMeta);
593
+ }
404
594
  function formatStoryContent(story, importStatement) {
405
- const parts = [];
406
- if (story.description) {
407
- parts.push(story.description);
408
- parts.push("");
409
- }
410
- parts.push("```");
411
- if (importStatement) {
412
- parts.push(importStatement);
413
- parts.push("");
414
- }
415
- parts.push(story.snippet ?? "");
416
- parts.push("```");
417
- return parts;
595
+ let parts = [];
596
+ return story.description && (parts.push(story.description), parts.push("")), parts.push("```"), importStatement && (parts.push(importStatement), parts.push("")), parts.push(story.snippet ?? ""), parts.push("```"), parts;
418
597
  }
419
598
  function formatPropsSection(parsedDocgen, options = {}) {
420
- const propEntries = parsedDocgen ? Object.entries(parsedDocgen.props) : [];
421
- if (propEntries.length === 0) return [];
422
- const title = options.title ?? "## Props";
423
- const typeName = options.typeName ?? "Props";
424
- const parts = [];
425
- parts.push(title);
426
- parts.push("");
427
- parts.push("```");
428
- parts.push(`export type ${typeName} = {`);
429
- for (const [propName, propInfo] of propEntries) {
430
- const type = propInfo.type ?? "any";
431
- const isRequired = propInfo.required ?? true;
432
- const hasDefault = propInfo.defaultValue !== void 0;
433
- if (propInfo.description !== void 0) {
434
- parts.push(" /**");
435
- parts.push(` ${propInfo.description}`);
436
- parts.push(" */");
437
- }
438
- let propLine = ` ${propName}`;
439
- if (!isRequired) propLine += "?";
440
- propLine += `: ${type}`;
441
- if (hasDefault) propLine += ` = ${propInfo.defaultValue}`;
442
- propLine += ";";
443
- parts.push(propLine);
444
- }
445
- parts.push("}");
446
- parts.push("```");
447
- parts.push("");
448
- return parts;
599
+ let propEntries = parsedDocgen ? Object.entries(parsedDocgen.props) : [];
600
+ if (propEntries.length === 0)
601
+ return [];
602
+ let title = options.title ?? "## Props", typeName = options.typeName ?? "Props", parts = [];
603
+ parts.push(title), parts.push(""), parts.push("```"), parts.push(`export type ${typeName} = {`);
604
+ for (let [propName, propInfo] of propEntries) {
605
+ let type = propInfo.type ?? "any", isRequired = propInfo.required ?? !0, hasDefault = propInfo.defaultValue !== void 0;
606
+ propInfo.description !== void 0 && (parts.push(" /**"), parts.push(` ${propInfo.description}`), parts.push(" */"));
607
+ let propLine = ` ${propName}`;
608
+ isRequired || (propLine += "?"), propLine += `: ${type}`, hasDefault && (propLine += ` = ${propInfo.defaultValue}`), propLine += ";", parts.push(propLine);
609
+ }
610
+ return parts.push("}"), parts.push("```"), parts.push(""), parts;
449
611
  }
450
612
  function formatSubcomponentsSection(subcomponents) {
451
- if (!subcomponents || Object.keys(subcomponents).length === 0) return [];
452
- const parts = [];
453
- parts.push("## Subcomponents");
454
- parts.push("");
455
- for (const [key, subcomponent] of Object.entries(subcomponents)) {
456
- parts.push(`### ${subcomponent.name || key}`);
457
- parts.push("");
458
- if (subcomponent.summary) {
459
- parts.push(subcomponent.summary);
460
- parts.push("");
461
- }
462
- if (subcomponent.description) {
463
- parts.push(subcomponent.description);
464
- parts.push("");
465
- }
466
- if (subcomponent.import) {
467
- parts.push("```");
468
- parts.push(subcomponent.import);
469
- parts.push("```");
470
- parts.push("");
471
- }
472
- if (subcomponent.error) {
473
- parts.push(`Error: ${subcomponent.error.name}`);
474
- parts.push("");
475
- parts.push("```");
476
- parts.push(subcomponent.error.message);
477
- parts.push("```");
478
- parts.push("");
479
- continue;
480
- }
481
- const parsedDocgen = getParsedDocgen(subcomponent);
482
- const typeName = `${(subcomponent.name || key).replace(/\W+/g, "")}Props`;
483
- parts.push(...formatPropsSection(parsedDocgen, {
484
- title: "#### Props",
485
- typeName
486
- }));
487
- }
488
- return parts;
489
- }
490
- /**
491
- * Format a single component manifest into markdown.
492
- */
613
+ if (!subcomponents || Object.keys(subcomponents).length === 0)
614
+ return [];
615
+ let parts = [];
616
+ parts.push("## Subcomponents"), parts.push("");
617
+ for (let [key, subcomponent] of Object.entries(subcomponents)) {
618
+ if (parts.push(`### ${subcomponent.name || key}`), parts.push(""), subcomponent.summary && (parts.push(subcomponent.summary), parts.push("")), subcomponent.description && (parts.push(subcomponent.description), parts.push("")), subcomponent.import && (parts.push("```"), parts.push(subcomponent.import), parts.push("```"), parts.push("")), subcomponent.error) {
619
+ parts.push(`Error: ${subcomponent.error.name}`), parts.push(""), parts.push("```"), parts.push(subcomponent.error.message), parts.push("```"), parts.push("");
620
+ continue;
621
+ }
622
+ let parsedDocgen = getParsedDocgen(subcomponent), typeName = `${(subcomponent.name || key).replace(/\W+/g, "")}Props`;
623
+ parts.push(...formatPropsSection(parsedDocgen, { title: "#### Props", typeName }));
624
+ }
625
+ return parts;
626
+ }
493
627
  function formatComponentManifest(componentManifest) {
494
- const parts = [];
495
- parts.push(`# ${componentManifest.name}`);
496
- parts.push("");
497
- parts.push(`ID: ${componentManifest.id}`);
498
- parts.push("");
499
- if (componentManifest.description) {
500
- parts.push(componentManifest.description);
501
- parts.push("");
502
- }
503
- parts.push(...formatSubcomponentsSection(componentManifest.subcomponents));
504
- const parsedDocgen = getParsedDocgen(componentManifest);
505
- if (componentManifest.stories && componentManifest.stories.length > 0) {
506
- parts.push("## Stories");
507
- parts.push("");
508
- const storiesWithSnippets = componentManifest.stories.filter((s) => s.snippet);
509
- const hasProps = parsedDocgen && Object.keys(parsedDocgen.props).length > 0;
510
- const storiesToShow = hasProps ? storiesWithSnippets.slice(0, MAX_STORIES_TO_SHOW) : storiesWithSnippets;
511
- const remainingStories = hasProps ? storiesWithSnippets.slice(MAX_STORIES_TO_SHOW) : [];
512
- for (const story of storiesToShow) {
513
- parts.push(`### ${story.name}`);
514
- parts.push("");
515
- if (story.id) {
516
- parts.push(`Story ID: ${story.id}`);
517
- parts.push("");
518
- }
519
- parts.push(...formatStoryContent(story, componentManifest.import));
520
- parts.push("");
521
- }
522
- if (remainingStories.length > 0) {
523
- if (storiesToShow.length > 0) parts.push("### Other Stories");
524
- parts.push("");
525
- for (const story of remainingStories) {
526
- const summary = extractSummary(story);
527
- const summaryPart = summary ? `: ${summary}` : "";
528
- const storyLabel = story.id ? `${story.name} (${story.id})` : story.name;
529
- parts.push(`- ${storyLabel}${summaryPart}`);
530
- }
531
- parts.push("");
532
- }
533
- }
534
- parts.push(...formatPropsSection(parsedDocgen));
535
- if (componentManifest.docs && Object.keys(componentManifest.docs).length > 0) {
536
- const docsWithContent = Object.values(componentManifest.docs).filter((doc) => doc.content.trim().length > 0);
537
- if (docsWithContent.length > 0) {
538
- parts.push("## Docs");
539
- parts.push("");
540
- for (const doc of docsWithContent) {
541
- parts.push(`### ${doc.name}`);
542
- parts.push("");
543
- parts.push(doc.content);
544
- parts.push("");
545
- }
546
- }
547
- }
548
- return parts.join("\n").trim();
549
- }
550
- /**
551
- * Format a single doc manifest into markdown.
552
- */
628
+ let parts = [];
629
+ parts.push(`# ${componentManifest.name}`), parts.push(""), parts.push(`ID: ${componentManifest.id}`), parts.push(""), componentManifest.description && (parts.push(componentManifest.description), parts.push("")), parts.push(...formatSubcomponentsSection(componentManifest.subcomponents));
630
+ let parsedDocgen = getParsedDocgen(componentManifest), stories = Array.isArray(componentManifest.stories) ? componentManifest.stories : [];
631
+ if (stories.length > 0) {
632
+ parts.push("## Stories"), parts.push("");
633
+ let storiesWithSnippets = stories.filter((s) => s.snippet), hasProps = parsedDocgen && Object.keys(parsedDocgen.props).length > 0, storiesToShow = hasProps ? storiesWithSnippets.slice(0, MAX_STORIES_TO_SHOW) : storiesWithSnippets, remainingStories = hasProps ? storiesWithSnippets.slice(MAX_STORIES_TO_SHOW) : [];
634
+ for (let story of storiesToShow)
635
+ parts.push(`### ${story.name}`), parts.push(""), story.id && (parts.push(`Story ID: ${story.id}`), parts.push("")), parts.push(...formatStoryContent(story, componentManifest.import)), parts.push("");
636
+ if (remainingStories.length > 0) {
637
+ storiesToShow.length > 0 && parts.push("### Other Stories"), parts.push("");
638
+ for (let story of remainingStories) {
639
+ let summary = extractSummary(story), summaryPart = summary ? `: ${summary}` : "", storyLabel = story.id ? `${story.name} (${story.id})` : story.name;
640
+ parts.push(`- ${storyLabel}${summaryPart}`);
641
+ }
642
+ parts.push("");
643
+ }
644
+ }
645
+ if (parts.push(...formatPropsSection(parsedDocgen)), componentManifest.docs && Object.keys(componentManifest.docs).length > 0) {
646
+ let docsWithContent = Object.values(componentManifest.docs).filter(
647
+ (doc) => (doc.content ?? "").trim().length > 0
648
+ );
649
+ if (docsWithContent.length > 0) {
650
+ parts.push("## Docs"), parts.push("");
651
+ for (let doc of docsWithContent)
652
+ parts.push(`### ${doc.name}`), parts.push(""), parts.push(doc.content ?? ""), parts.push("");
653
+ }
654
+ }
655
+ return parts.join(`
656
+ `).trim();
657
+ }
553
658
  function formatDocsManifest(doc) {
554
- return dedent`# ${doc.title}
659
+ return dedent`# ${doc.title ?? doc.name}
555
660
 
556
- ${doc.content}`;
661
+ ${doc.content ?? ""}`;
557
662
  }
558
- /**
559
- * Format a component manifest map into a markdown list.
560
- * @param manifest - The component manifest map to format
561
- * @returns Formatted string representation of the component list
562
- */
563
663
  function formatManifestsToLists(manifests, options = {}) {
564
- const parts = [];
565
- parts.push("# Components");
566
- parts.push("");
567
- for (const component of Object.values(manifests.componentManifest.components)) {
568
- parts.push(formatComponentLine(component));
569
- if (options.withStoryIds) for (const story of component.stories ?? []) parts.push(formatStorySubLine(story));
570
- }
571
- parts.push("");
572
- if (!manifests.docsManifest) return parts.join("\n").trim();
573
- parts.push("# Docs");
574
- parts.push("");
575
- for (const doc of Object.values(manifests.docsManifest.docs)) parts.push(formatDocLine(doc));
576
- return parts.join("\n").trim();
664
+ let parts = [];
665
+ parts.push("# Components"), parts.push("");
666
+ for (let component of Object.values(manifests.componentManifest.components))
667
+ if (parts.push(formatComponentLine(component)), options.withStoryIds && Array.isArray(component.stories))
668
+ for (let story of component.stories)
669
+ parts.push(formatStorySubLine(story));
670
+ if (parts.push(""), !manifests.docsManifest)
671
+ return parts.join(`
672
+ `).trim();
673
+ parts.push("# Docs"), parts.push("");
674
+ for (let doc of Object.values(manifests.docsManifest.docs))
675
+ parts.push(formatDocLine(doc));
676
+ return parts.join(`
677
+ `).trim();
577
678
  }
578
679
  function formatMultiSourceManifestsToLists(manifests, options = {}) {
579
- const parts = [];
580
- for (const { source, componentManifest, docsManifest, error } of manifests) {
581
- parts.push(`# ${source.title}`);
582
- parts.push(`id: ${source.id}`);
583
- parts.push("");
584
- if (error) {
585
- parts.push(`error: ${error}`);
586
- parts.push("");
587
- continue;
588
- }
589
- const components = Object.values(componentManifest.components);
590
- if (components.length > 0) {
591
- parts.push("## Components");
592
- parts.push("");
593
- for (const component of components) {
594
- parts.push(formatComponentLine(component));
595
- if (options.withStoryIds) for (const story of component.stories ?? []) parts.push(formatStorySubLine(story));
596
- }
597
- parts.push("");
598
- }
599
- if (docsManifest && Object.keys(docsManifest.docs).length > 0) {
600
- parts.push("## Docs");
601
- parts.push("");
602
- for (const doc of Object.values(docsManifest.docs)) parts.push(formatDocLine(doc));
603
- parts.push("");
604
- }
605
- }
606
- return parts.join("\n").trim();
607
- }
608
- /**
609
- * Format a single story's documentation.
610
- */
680
+ let parts = [];
681
+ for (let { source, componentManifest, docsManifest, error, notice } of manifests) {
682
+ if (parts.push(`# ${source.title}`), parts.push(`id: ${source.id}`), parts.push(""), error) {
683
+ parts.push(`error: ${error}`), parts.push("");
684
+ continue;
685
+ }
686
+ if (notice) {
687
+ parts.push(formatRequiresOwnMcpNotice(source, notice.endpoint, { includeHeader: !1 })), parts.push("");
688
+ continue;
689
+ }
690
+ let components = Object.values(componentManifest.components);
691
+ if (components.length > 0) {
692
+ parts.push("## Components"), parts.push("");
693
+ for (let component of components)
694
+ if (parts.push(formatComponentLine(component)), options.withStoryIds && Array.isArray(component.stories))
695
+ for (let story of component.stories)
696
+ parts.push(formatStorySubLine(story));
697
+ parts.push("");
698
+ }
699
+ if (docsManifest && Object.keys(docsManifest.docs).length > 0) {
700
+ parts.push("## Docs"), parts.push("");
701
+ for (let doc of Object.values(docsManifest.docs))
702
+ parts.push(formatDocLine(doc));
703
+ parts.push("");
704
+ }
705
+ }
706
+ return parts.join(`
707
+ `).trim();
708
+ }
611
709
  function formatStoryDocumentation(componentManifest, storyName) {
612
- const story = componentManifest.stories?.find((s) => s.name === storyName);
613
- if (!story || !story.snippet) return "";
614
- const parts = [];
615
- parts.push(`# ${componentManifest.name} - ${story.name}`);
616
- parts.push("");
617
- parts.push(...formatStoryContent(story, componentManifest.import));
618
- return parts.join("\n").trim();
710
+ let story = Array.isArray(componentManifest.stories) ? componentManifest.stories.find((s) => s.name === storyName) : void 0;
711
+ if (!story || !story.snippet)
712
+ return "";
713
+ let parts = [];
714
+ return parts.push(`# ${componentManifest.name} - ${story.name}`), parts.push(""), parts.push(...formatStoryContent(story, componentManifest.import)), parts.join(`
715
+ `).trim();
619
716
  }
620
717
 
621
- //#endregion
622
- //#region src/tools/list-all-documentation.ts
623
- const LIST_TOOL_NAME = "list-all-documentation";
624
- const ListAllDocumentationInput = v.object({ withStoryIds: v.optional(v.pipe(v.boolean(), v.description("When true, includes story sub-bullets under each component with story name and story ID. Use this to discover IDs for downstream story-focused workflows without filesystem lookup.")), false) });
718
+ // src/tools/list-all-documentation.ts
719
+ var LIST_TOOL_NAME = "list-all-documentation", ListAllDocumentationInput = v3.object({
720
+ withStoryIds: v3.optional(
721
+ v3.pipe(
722
+ v3.boolean(),
723
+ v3.description(
724
+ "When true, includes story sub-bullets under each component with story name and story ID. Use this to discover IDs for downstream story-focused workflows without filesystem lookup."
725
+ )
726
+ ),
727
+ !1
728
+ )
729
+ });
730
+ function getListAllDocumentationToolMetadata() {
731
+ return {
732
+ name: LIST_TOOL_NAME,
733
+ title: "List All Documentation",
734
+ description: "List all available UI components and documentation entries from the Storybook, returning the IDs the other documentation tools take as input. Call this first for any UI task \u2014 before writing a new component, check what the design system already provides and build on it instead of hand-rolling a duplicate; before answering any question about props, API, or usage, discover the relevant IDs here rather than reading component source. Then fetch the entries with get-documentation, referencing only IDs returned here \u2014 never guess IDs. When multiple Storybook sources are configured, entries from every source are included; scope follow-up calls to one source via their `storybookId` input. Pass `withStoryIds: true` when you need story IDs for other tools.",
735
+ schema: ListAllDocumentationInput
736
+ };
737
+ }
625
738
  async function addListAllDocumentationTool(server, enabled) {
626
- server.tool({
627
- name: LIST_TOOL_NAME,
628
- title: "List All Documentation",
629
- description: "List all available UI components and documentation entries from the Storybook",
630
- schema: ListAllDocumentationInput,
631
- enabled
632
- }, async (input) => {
633
- try {
634
- const ctx = server.ctx.custom;
635
- const withStoryIds = input.withStoryIds ?? false;
636
- if (ctx?.sources?.some((s) => s.url)) {
637
- const multiSourceManifests = await getMultiSourceManifests(ctx.sources, ctx.request, ctx.manifestProvider);
638
- const lists = formatMultiSourceManifestsToLists(multiSourceManifests, { withStoryIds });
639
- const firstSuccess = multiSourceManifests.find((m) => !m.error);
640
- if (firstSuccess) await ctx.onListAllDocumentation?.({
641
- context: ctx,
642
- manifests: {
643
- componentManifest: firstSuccess.componentManifest,
644
- docsManifest: firstSuccess.docsManifest
645
- },
646
- resultText: lists,
647
- sources: multiSourceManifests
648
- });
649
- return { content: [{
650
- type: "text",
651
- text: lists
652
- }] };
653
- }
654
- const manifests = await getManifests(ctx?.request, ctx?.manifestProvider);
655
- const lists = formatManifestsToLists(manifests, { withStoryIds });
656
- await ctx?.onListAllDocumentation?.({
657
- context: ctx,
658
- manifests,
659
- resultText: lists
660
- });
661
- return { content: [{
662
- type: "text",
663
- text: lists
664
- }] };
665
- } catch (error) {
666
- return errorToMCPContent(error);
667
- }
668
- });
739
+ server.tool(
740
+ {
741
+ ...getListAllDocumentationToolMetadata(),
742
+ enabled
743
+ },
744
+ async (input) => {
745
+ try {
746
+ let ctx = server.ctx.custom, withStoryIds = input.withStoryIds ?? !1;
747
+ if (ctx?.sources?.some((s) => s.url)) {
748
+ let multiSourceManifests = await getMultiSourceManifests(
749
+ ctx.sources,
750
+ ctx.request,
751
+ ctx.manifestProvider
752
+ );
753
+ withStoryIds && await Promise.all(
754
+ multiSourceManifests.map(async (sourceManifest) => {
755
+ if (!(sourceManifest.error || sourceManifest.notice))
756
+ try {
757
+ let components = sourceManifest.componentManifest.components, entries = Object.entries(components), resolved = await mapWithConcurrency(
758
+ entries,
759
+ 16,
760
+ async ([id, component]) => {
761
+ let storiesResolved = await resolveComponentStories(
762
+ component,
763
+ ctx.request,
764
+ ctx.manifestProvider,
765
+ sourceManifest.source
766
+ );
767
+ return [id, storiesResolved];
768
+ }
769
+ );
770
+ for (let [id, component] of resolved)
771
+ components[id] = component;
772
+ } catch {
773
+ }
774
+ })
775
+ );
776
+ let lists2 = formatMultiSourceManifestsToLists(multiSourceManifests, {
777
+ withStoryIds
778
+ }), firstSuccess = multiSourceManifests.find((m) => !m.error && !m.notice);
779
+ return firstSuccess && await ctx.onListAllDocumentation?.({
780
+ context: ctx,
781
+ manifests: {
782
+ componentManifest: firstSuccess.componentManifest,
783
+ docsManifest: firstSuccess.docsManifest
784
+ },
785
+ resultText: lists2,
786
+ sources: multiSourceManifests
787
+ }), {
788
+ content: [
789
+ {
790
+ type: "text",
791
+ text: lists2
792
+ }
793
+ ]
794
+ };
795
+ }
796
+ let manifests = await getManifests(ctx?.request, ctx?.manifestProvider);
797
+ if (withStoryIds) {
798
+ let components = manifests.componentManifest.components, entries = Object.entries(components), resolved = await mapWithConcurrency(entries, 16, async ([id, component]) => {
799
+ let storiesResolved = await resolveComponentStories(
800
+ component,
801
+ ctx?.request,
802
+ ctx?.manifestProvider
803
+ );
804
+ return [id, storiesResolved];
805
+ });
806
+ for (let [id, component] of resolved)
807
+ components[id] = component;
808
+ }
809
+ let lists = formatManifestsToLists(manifests, {
810
+ withStoryIds
811
+ });
812
+ return await ctx?.onListAllDocumentation?.({
813
+ context: ctx,
814
+ manifests,
815
+ resultText: lists
816
+ }), {
817
+ content: [
818
+ {
819
+ type: "text",
820
+ text: lists
821
+ }
822
+ ]
823
+ };
824
+ } catch (error) {
825
+ return errorToMCPContent(error);
826
+ }
827
+ }
828
+ );
669
829
  }
670
830
 
671
- //#endregion
672
- //#region src/tools/get-documentation-for-story.ts
673
- const GET_STORY_TOOL_NAME = "get-documentation-for-story";
674
- const BaseInput$1 = {
675
- componentId: v.string(),
676
- storyName: v.string()
831
+ // src/tools/get-documentation-for-story.ts
832
+ import * as v4 from "valibot";
833
+ var GET_STORY_TOOL_NAME = "get-documentation-for-story", GET_STORY_DOCUMENTATION_TOOL_DESCRIPTION = "Get detailed documentation for a specific story variant of a UI component. Use this when you need to see more usage examples of a component, via the stories written for it.", BaseInput = {
834
+ componentId: v4.string(),
835
+ storyName: v4.string()
677
836
  };
837
+ function getStoryDocumentationToolSchema(options) {
838
+ return options?.multiSource ? v4.object({ ...BaseInput, ...StorybookIdField }) : v4.object(BaseInput);
839
+ }
840
+ function getStoryDocumentationToolMetadata(options) {
841
+ return {
842
+ name: GET_STORY_TOOL_NAME,
843
+ title: "Get Documentation for Story",
844
+ description: GET_STORY_DOCUMENTATION_TOOL_DESCRIPTION,
845
+ schema: getStoryDocumentationToolSchema(options)
846
+ };
847
+ }
678
848
  async function addGetStoryDocumentationTool(server, enabled, options) {
679
- const schema = options?.multiSource ? v.object({
680
- ...BaseInput$1,
681
- ...StorybookIdField
682
- }) : v.object(BaseInput$1);
683
- server.tool({
684
- name: GET_STORY_TOOL_NAME,
685
- title: "Get Documentation for Story",
686
- description: "Get detailed documentation for a specific story variant of a UI component. Use this when you need to see more usage examples of a component, via the stories written for it.",
687
- schema,
688
- enabled
689
- }, async (input) => {
690
- try {
691
- const ctx = server.ctx.custom;
692
- const { componentId, storyName, storybookId } = input;
693
- const sources = ctx?.sources;
694
- const isMultiSource = sources && sources.some((s) => s.url);
695
- let source;
696
- if (isMultiSource) {
697
- if (!storybookId) return {
698
- content: [{
699
- type: "text",
700
- text: `storybookId is required. Available sources: ${sources.map((s) => s.id).join(", ")}. Use the ${LIST_TOOL_NAME} tool to see available sources.`
701
- }],
702
- isError: true
703
- };
704
- source = sources.find((s) => s.id === storybookId);
705
- if (!source) return {
706
- content: [{
707
- type: "text",
708
- text: `Storybook source not found: "${storybookId}". Available sources: ${sources.map((s) => s.id).join(", ")}. Use the ${LIST_TOOL_NAME} tool to see available sources.`
709
- }],
710
- isError: true
711
- };
712
- }
713
- const component = (await getManifests(ctx?.request, ctx?.manifestProvider, source)).componentManifest?.components[componentId];
714
- if (!component) return {
715
- content: [{
716
- type: "text",
717
- text: `Component not found: "${componentId}". Use the list-all-documentation tool to see available components.`
718
- }],
719
- isError: true
720
- };
721
- if (!component.stories?.find((s) => s.name === storyName)) return {
722
- content: [{
723
- type: "text",
724
- text: `Story "${storyName}" not found for component "${componentId}". Available stories: ${component.stories?.map((s) => s.name).join(", ") ?? "none"}`
725
- }],
726
- isError: true
727
- };
728
- return { content: [{
729
- type: "text",
730
- text: formatStoryDocumentation(component, storyName)
731
- }] };
732
- } catch (error) {
733
- return errorToMCPContent(error);
734
- }
735
- });
849
+ server.tool(
850
+ {
851
+ ...getStoryDocumentationToolMetadata(options),
852
+ enabled
853
+ },
854
+ async (input) => {
855
+ try {
856
+ let ctx = server.ctx.custom, { componentId, storyName, storybookId } = input, sources = ctx?.sources, isMultiSource = sources && sources.some((s) => s.url), source;
857
+ if (isMultiSource) {
858
+ if (!storybookId)
859
+ return {
860
+ content: [
861
+ {
862
+ type: "text",
863
+ text: `storybookId is required. Available sources: ${sources.map((s) => s.id).join(", ")}. Use the ${LIST_TOOL_NAME} tool to see available sources.`
864
+ }
865
+ ],
866
+ isError: !0
867
+ };
868
+ if (source = sources.find((s) => s.id === storybookId), !source) {
869
+ let availableSources = sources.map((s) => s.id).join(", ");
870
+ return {
871
+ content: [
872
+ {
873
+ type: "text",
874
+ text: `Storybook source not found: "${storybookId}". Available sources: ${availableSources}. Use the ${LIST_TOOL_NAME} tool to see available sources.`
875
+ }
876
+ ],
877
+ isError: !0
878
+ };
879
+ }
880
+ }
881
+ let component;
882
+ if (ctx?.resolveEntry && !source?.url) {
883
+ let resolved = await ctx.resolveEntry(componentId, source);
884
+ resolved?.kind === "component" && (component = resolved.component);
885
+ } else {
886
+ let componentEntry = (await getManifests(ctx?.request, ctx?.manifestProvider, source)).componentManifest?.components[componentId];
887
+ componentEntry && (component = await resolveComponentEntry(
888
+ componentEntry,
889
+ ctx?.request,
890
+ ctx?.manifestProvider,
891
+ source
892
+ ));
893
+ }
894
+ if (!component)
895
+ return {
896
+ content: [
897
+ {
898
+ type: "text",
899
+ text: `Component not found: "${componentId}". Use the list-all-documentation tool to see available components.`
900
+ }
901
+ ],
902
+ isError: !0
903
+ };
904
+ if (!(Array.isArray(component.stories) ? component.stories.find((s) => s.name === storyName) : void 0)) {
905
+ let availableStories = Array.isArray(component.stories) ? component.stories.map((s) => s.name).join(", ") : "none";
906
+ return {
907
+ content: [
908
+ {
909
+ type: "text",
910
+ text: `Story "${storyName}" not found for component "${componentId}". Available stories: ${availableStories}`
911
+ }
912
+ ],
913
+ isError: !0
914
+ };
915
+ }
916
+ return {
917
+ content: [
918
+ {
919
+ type: "text",
920
+ text: formatStoryDocumentation(component, storyName)
921
+ }
922
+ ]
923
+ };
924
+ } catch (error) {
925
+ return errorToMCPContent(error);
926
+ }
927
+ }
928
+ );
736
929
  }
737
930
 
738
- //#endregion
739
- //#region src/tools/get-documentation.ts
740
- const GET_TOOL_NAME = "get-documentation";
741
- const BaseInput = { id: v.pipe(v.string(), v.description("The component or docs entry ID (e.g., \"button\")")) };
742
- async function addGetDocumentationTool(server, enabled, options) {
743
- const schema = options?.multiSource ? v.object({
744
- ...BaseInput,
745
- ...StorybookIdField
746
- }) : v.object(BaseInput);
747
- server.tool({
748
- name: GET_TOOL_NAME,
749
- title: "Get Documentation",
750
- description: `Get documentation for a UI component or docs entry.
931
+ // src/tools/get-documentation.ts
932
+ import * as v5 from "valibot";
933
+ var GET_TOOL_NAME = "get-documentation", BaseInput2 = {
934
+ id: v5.pipe(v5.string(), v5.description('The component or docs entry ID (e.g., "button")'))
935
+ }, GET_DOCUMENTATION_TOOL_DESCRIPTION = `Get documentation for a UI component or docs entry.
751
936
 
752
- Returns the first ${MAX_STORIES_TO_SHOW} stories (including story IDs) with code snippets showing how props are used, plus TypeScript prop definitions. Call this before using a component to avoid hallucinating prop names, types, or valid combinations. Stories reveal real prop usage patterns, interactions, and edge cases that type definitions alone don't show. If the example stories don't show the prop you need, use the ${GET_STORY_TOOL_NAME} tool to fetch the story documentation for the specific story variant you need.
937
+ Returns the first ${MAX_STORIES_TO_SHOW} stories (including story IDs) with code snippets showing how props are used, plus TypeScript prop definitions. Call this before using a component to avoid hallucinating prop names, types, or valid combinations, and to answer any question about a component's props, API, or usage \u2014 reading or grepping the component source is not a substitute. Stories reveal real prop usage patterns, interactions, and edge cases that type definitions alone don't show. If the example stories don't show the prop you need, use the ${GET_STORY_TOOL_NAME} tool to fetch the story documentation for the specific story variant you need.
753
938
 
754
- Example: id="button" returns Primary, Secondary, Large stories with code like <Button variant="primary" size="large"> showing actual prop combinations.`,
755
- schema,
756
- enabled
757
- }, async (input) => {
758
- try {
759
- const ctx = server.ctx.custom;
760
- const { id, storybookId } = input;
761
- const sources = ctx?.sources;
762
- const isMultiSource = sources && sources.some((s) => s.url);
763
- let source;
764
- if (isMultiSource) {
765
- if (!storybookId) return {
766
- content: [{
767
- type: "text",
768
- text: `storybookId is required. Available sources: ${sources.map((s) => s.id).join(", ")}. Use the ${LIST_TOOL_NAME} tool to see available sources.`
769
- }],
770
- isError: true
771
- };
772
- source = sources.find((s) => s.id === storybookId);
773
- if (!source) return {
774
- content: [{
775
- type: "text",
776
- text: `Storybook source not found: "${storybookId}". Available sources: ${sources.map((s) => s.id).join(", ")}. Use the ${LIST_TOOL_NAME} tool to see available sources.`
777
- }],
778
- isError: true
779
- };
780
- }
781
- const { componentManifest, docsManifest } = await getManifests(ctx?.request, ctx?.manifestProvider, source);
782
- const component = componentManifest.components[id];
783
- const docsEntry = docsManifest?.docs[id];
784
- if (!component && !docsEntry) {
785
- const suffix = storybookId ? ` in source "${storybookId}"` : "";
786
- await ctx?.onGetDocumentation?.({
787
- context: ctx,
788
- input
789
- });
790
- return {
791
- content: [{
792
- type: "text",
793
- text: `Component or Docs Entry not found: "${id}"${suffix}. Use the ${LIST_TOOL_NAME} tool to see available components and documentation entries.`
794
- }],
795
- isError: true
796
- };
797
- }
798
- const documentation = component ?? docsEntry;
799
- const text = component ? formatComponentManifest(documentation) : formatDocsManifest(documentation);
800
- await ctx?.onGetDocumentation?.({
801
- context: ctx,
802
- input,
803
- foundDocumentation: documentation,
804
- resultText: text
805
- });
806
- return { content: [{
807
- type: "text",
808
- text
809
- }] };
810
- } catch (error) {
811
- return errorToMCPContent(error);
812
- }
813
- });
939
+ Example: id="button" returns Primary, Secondary, Large stories with code like <Button variant="primary" size="large"> showing actual prop combinations.`;
940
+ function getDocumentationToolSchema(options) {
941
+ return options?.multiSource ? v5.object({ ...BaseInput2, ...StorybookIdField }) : v5.object(BaseInput2);
942
+ }
943
+ function getDocumentationToolMetadata(options) {
944
+ return {
945
+ name: GET_TOOL_NAME,
946
+ title: "Get Documentation",
947
+ description: GET_DOCUMENTATION_TOOL_DESCRIPTION,
948
+ schema: getDocumentationToolSchema(options)
949
+ };
950
+ }
951
+ async function addGetDocumentationTool(server, enabled, options) {
952
+ server.tool(
953
+ {
954
+ ...getDocumentationToolMetadata(options),
955
+ enabled
956
+ },
957
+ async (input) => {
958
+ try {
959
+ let ctx = server.ctx.custom, { id, storybookId } = input, sources = ctx?.sources, isMultiSource = sources && sources.some((s) => s.url), source;
960
+ if (isMultiSource) {
961
+ if (!storybookId)
962
+ return {
963
+ content: [
964
+ {
965
+ type: "text",
966
+ text: `storybookId is required. Available sources: ${sources.map((s) => s.id).join(", ")}. Use the ${LIST_TOOL_NAME} tool to see available sources.`
967
+ }
968
+ ],
969
+ isError: !0
970
+ };
971
+ if (source = sources.find((s) => s.id === storybookId), !source) {
972
+ let availableSources = sources.map((s) => s.id).join(", ");
973
+ return {
974
+ content: [
975
+ {
976
+ type: "text",
977
+ text: `Storybook source not found: "${storybookId}". Available sources: ${availableSources}. Use the ${LIST_TOOL_NAME} tool to see available sources.`
978
+ }
979
+ ],
980
+ isError: !0
981
+ };
982
+ }
983
+ }
984
+ let component, docsEntry;
985
+ if (ctx?.resolveEntry && !source?.url) {
986
+ let resolved = await ctx.resolveEntry(id, source);
987
+ resolved?.kind === "component" ? component = resolved.component : resolved?.kind === "doc" && (docsEntry = resolved.doc);
988
+ } else {
989
+ let { componentManifest, docsManifest } = await getManifests(
990
+ ctx?.request,
991
+ ctx?.manifestProvider,
992
+ source
993
+ ), componentEntry = componentManifest.components[id], docEntry = docsManifest?.docs[id];
994
+ componentEntry ? component = await resolveComponentEntry(
995
+ componentEntry,
996
+ ctx?.request,
997
+ ctx?.manifestProvider,
998
+ source
999
+ ) : docEntry && (docsEntry = await resolveDoc(docEntry, ctx?.request, ctx?.manifestProvider, source));
1000
+ }
1001
+ if (!component && !docsEntry) {
1002
+ let suffix = storybookId ? ` in source "${storybookId}"` : "";
1003
+ return await ctx?.onGetDocumentation?.({
1004
+ context: ctx,
1005
+ input
1006
+ }), {
1007
+ content: [
1008
+ {
1009
+ type: "text",
1010
+ text: `Component or Docs Entry not found: "${id}"${suffix}. Use the ${LIST_TOOL_NAME} tool to see available components and documentation entries.`
1011
+ }
1012
+ ],
1013
+ isError: !0
1014
+ };
1015
+ }
1016
+ let documentation = component ?? docsEntry, text = component ? formatComponentManifest(documentation) : formatDocsManifest(documentation);
1017
+ return await ctx?.onGetDocumentation?.({
1018
+ context: ctx,
1019
+ input,
1020
+ foundDocumentation: documentation,
1021
+ resultText: text
1022
+ }), {
1023
+ content: [
1024
+ {
1025
+ type: "text",
1026
+ text
1027
+ }
1028
+ ]
1029
+ };
1030
+ } catch (error) {
1031
+ return errorToMCPContent(error);
1032
+ }
1033
+ }
1034
+ );
814
1035
  }
815
1036
 
816
- //#endregion
817
- //#region src/index.ts
818
- const createStorybookMcpHandler = async (options = {}) => {
819
- const { onSessionInitialize, ...defaultContext } = options;
820
- const adapter = new ValibotJsonSchemaAdapter();
821
- const server = new McpServer({
822
- name,
823
- version,
824
- description
825
- }, {
826
- adapter,
827
- instructions: instructions_default,
828
- capabilities: { tools: { listChanged: true } }
829
- }).withContext();
830
- if (onSessionInitialize) server.on("initialize", onSessionInitialize);
831
- await addListAllDocumentationTool(server);
832
- await addGetStoryDocumentationTool(server);
833
- await addGetDocumentationTool(server);
834
- const transport = new HttpTransport(server, { path: null });
835
- return (async (req, context) => {
836
- return await transport.respond(req, {
837
- ...defaultContext,
838
- ...context,
839
- request: req
840
- });
841
- });
842
- };
1037
+ // src/instructions.md
1038
+ var instructions_default = `## Documentation Workflow
843
1039
 
844
- //#endregion
845
- export { COMPONENT_MANIFEST_PATH, ComponentManifestMap, DOCS_MANIFEST_PATH, DocsManifestMap, GET_STORY_TOOL_NAME, GET_TOOL_NAME, LIST_TOOL_NAME, instructions_default as STORYBOOK_MCP_INSTRUCTIONS, addGetDocumentationTool, addGetStoryDocumentationTool, addListAllDocumentationTool, createStorybookMcpHandler, getMultiSourceManifests };
1040
+ **CRITICAL: Never hallucinate component properties!** Before using ANY property on a component (even common-sounding ones like \`shadow\`), you MUST verify it is documented via these tools. If it is not documented, it does not exist \u2014 never assume props from naming conventions or other libraries; report it to the user instead.
1041
+
1042
+ 1. Call **list-all-documentation** once at the start of the task to discover available component and docs IDs.
1043
+ 2. Call **get-documentation** with an \`id\` from that list to retrieve full component docs, props, usage examples, and stories.
1044
+ 3. Call **get-documentation-for-story** for extra docs on a story variant not covered by the component docs.
1045
+
1046
+ Only use properties explicitly documented or shown in example stories. Only reference IDs returned by these tools; never guess IDs.
1047
+
1048
+ ## Multi-Source Requests
1049
+
1050
+ - With multiple sources configured, **list-all-documentation** returns entries from every source; pass \`storybookId\` to **get-documentation** to scope one.
1051
+ `;
1052
+
1053
+ // src/index.ts
1054
+ var createStorybookMcpHandler = async (options = {}) => {
1055
+ let { onSessionInitialize, ...defaultContext } = options, adapter = new ValibotJsonSchemaAdapter(), server = new McpServer(
1056
+ {
1057
+ name: package_default.name,
1058
+ version: package_default.version,
1059
+ description: package_default.description
1060
+ },
1061
+ {
1062
+ adapter,
1063
+ instructions: instructions_default,
1064
+ capabilities: {
1065
+ tools: { listChanged: !0 }
1066
+ }
1067
+ }
1068
+ ).withContext();
1069
+ onSessionInitialize && server.on("initialize", onSessionInitialize), await addListAllDocumentationTool(server), await addGetStoryDocumentationTool(server), await addGetDocumentationTool(server);
1070
+ let transport = new HttpTransport(server, { path: null });
1071
+ return (async (req, context) => await transport.respond(req, {
1072
+ ...defaultContext,
1073
+ ...context,
1074
+ request: req
1075
+ }));
1076
+ };
1077
+ export {
1078
+ COMPONENT_MANIFEST_PATH,
1079
+ ComponentManifestMap,
1080
+ DOCS_MANIFEST_PATH,
1081
+ DocsManifestMap,
1082
+ GET_STORY_TOOL_NAME,
1083
+ GET_TOOL_NAME,
1084
+ LIST_TOOL_NAME,
1085
+ RequiresOwnMcpError,
1086
+ instructions_default as STORYBOOK_MCP_INSTRUCTIONS,
1087
+ adaptCoreComponent,
1088
+ adaptCoreDoc,
1089
+ adaptCoreStories,
1090
+ addGetDocumentationTool,
1091
+ addGetStoryDocumentationTool,
1092
+ addListAllDocumentationTool,
1093
+ createStorybookMcpHandler,
1094
+ getDocumentationToolMetadata,
1095
+ getListAllDocumentationToolMetadata,
1096
+ getMultiSourceManifests,
1097
+ getStoryDocumentationToolMetadata,
1098
+ resolveComponentEntry,
1099
+ resolveComponentStories,
1100
+ resolveDoc
1101
+ };