@storybook/mcp 0.6.2 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- import { t as instructions_default } from "./instructions-Cl0vcW2j.js";
1
+ import { t as instructions_default } from "./instructions-CiOmp0JI.js";
2
2
  import { McpServer } from "tmcp";
3
3
  import { ValibotJsonSchemaAdapter } from "@tmcp/adapter-valibot";
4
4
  import { HttpTransport } from "@tmcp/transport-http";
@@ -6,13 +6,13 @@ import * as v from "valibot";
6
6
 
7
7
  //#region package.json
8
8
  var name = "@storybook/mcp";
9
- var version = "0.6.2";
9
+ var version = "0.8.0";
10
10
  var description = "MCP server that serves knowledge about your components based on your Storybook stories and documentation";
11
11
 
12
12
  //#endregion
13
13
  //#region src/types.ts
14
14
  const JSDocTag = v.record(v.string(), v.array(v.string()));
15
- const Error$1 = v.object({
15
+ const ManifestError = v.object({
16
16
  name: v.string(),
17
17
  message: v.string()
18
18
  });
@@ -20,7 +20,7 @@ const BaseManifest = v.object({
20
20
  name: v.string(),
21
21
  description: v.optional(v.string()),
22
22
  jsDocTags: v.optional(JSDocTag),
23
- error: v.optional(Error$1)
23
+ error: v.optional(ManifestError)
24
24
  });
25
25
  const Story = v.object({
26
26
  ...BaseManifest.entries,
@@ -29,48 +29,149 @@ const Story = v.object({
29
29
  summary: v.optional(v.string())
30
30
  });
31
31
  /**
32
- * A docs entry represents MDX documentation that can be attached to a component
33
- * or standalone (unattached).
32
+ * A JSON Reference (`{ $ref }`) pointing at a value in another manifest document.
33
+ * Used by the v1 (split/ref) manifest format for docgen, story-docs and MDX payloads.
34
34
  */
35
- const Doc = v.object({
35
+ const JsonRef = v.object({ $ref: v.string() });
36
+ /** Inline (v0) docs entry: the full MDX `content` is embedded. */
37
+ const DocV0 = v.object({
36
38
  id: v.string(),
37
39
  name: v.string(),
38
- title: v.string(),
39
- path: v.string(),
40
- content: v.string(),
40
+ title: v.optional(v.string()),
41
+ path: v.optional(v.string()),
42
+ content: v.optional(v.string()),
41
43
  summary: v.optional(v.string()),
42
- error: v.optional(Error$1)
44
+ error: v.optional(ManifestError)
43
45
  });
44
- const ComponentManifest = v.object({
46
+ const BaseInlineComponentProperties = v.object({
45
47
  ...BaseManifest.entries,
46
- id: v.string(),
47
- path: v.string(),
48
+ path: v.optional(v.string()),
48
49
  summary: v.optional(v.string()),
49
50
  import: v.optional(v.string()),
50
- stories: v.optional(v.array(Story)),
51
51
  reactDocgen: v.optional(v.any()),
52
52
  reactDocgenTypescript: v.optional(v.any()),
53
- reactComponentMeta: v.optional(v.any()),
54
- docs: v.optional(v.record(v.string(), Doc))
53
+ reactComponentMeta: v.optional(v.any())
54
+ });
55
+ const SubcomponentManifest = v.object({ ...BaseInlineComponentProperties.entries });
56
+ /** Inline (v0) component: docgen, stories and attached docs are all embedded. */
57
+ const ComponentManifestV0 = v.object({
58
+ ...BaseInlineComponentProperties.entries,
59
+ id: v.string(),
60
+ stories: v.optional(v.array(Story)),
61
+ subcomponents: v.optional(v.record(v.string(), SubcomponentManifest)),
62
+ docs: v.optional(v.record(v.string(), DocV0))
55
63
  });
56
- const ComponentManifestMap = v.object({
57
- v: v.number(),
58
- components: v.record(v.string(), ComponentManifest)
64
+ const ComponentManifestMapV0 = v.object({
65
+ v: v.literal(0),
66
+ components: v.record(v.string(), ComponentManifestV0)
67
+ });
68
+ const DocsManifestMapV0 = v.object({
69
+ v: v.literal(0),
70
+ docs: v.record(v.string(), DocV0)
71
+ });
72
+ /**
73
+ * Shallow (v1) docs entry. The full MDX payload (title/path/content) lives behind
74
+ * `mdx.$ref`; `mdx` is optional because Storybook's in-process dev index omits it
75
+ * (those entries are resolved in-process via {@link StorybookContext.resolveEntry}).
76
+ */
77
+ const DocV1 = v.object({
78
+ id: v.string(),
79
+ name: v.string(),
80
+ summary: v.optional(v.string()),
81
+ mdx: v.optional(JsonRef),
82
+ error: v.optional(ManifestError)
59
83
  });
60
84
  /**
61
- * Manifest for unattached/standalone documentation entries.
62
- * Served at /manifests/docs.json
85
+ * Shallow (v1) component index row. Identity + summary are inlined for cheap
86
+ * listing; docgen and story-docs live behind `$ref`s, attached docs behind nested
87
+ * `mdx.$ref`s. `docgen`/`stories` are optional (the in-process dev index omits
88
+ * `docgen`, and docs-only components have neither).
63
89
  */
64
- const DocsManifestMap = v.object({
65
- v: v.number(),
66
- docs: v.record(v.string(), Doc)
90
+ const ComponentManifestV1 = v.object({
91
+ id: v.string(),
92
+ name: v.string(),
93
+ description: v.optional(v.string()),
94
+ summary: v.optional(v.string()),
95
+ error: v.optional(ManifestError),
96
+ docgen: v.optional(JsonRef),
97
+ stories: v.optional(JsonRef),
98
+ docs: v.optional(v.record(v.string(), DocV1))
99
+ });
100
+ const ComponentManifestMapV1 = v.object({
101
+ v: v.literal(1),
102
+ components: v.record(v.string(), ComponentManifestV1)
103
+ });
104
+ const DocsManifestMapV1 = v.object({
105
+ v: v.literal(1),
106
+ docs: v.record(v.string(), DocV1)
67
107
  });
108
+ /** `components.json`, discriminated on `v` (0 = inline, 1 = split/ref). */
109
+ const ComponentManifestMap = v.variant("v", [ComponentManifestMapV0, ComponentManifestMapV1]);
110
+ /**
111
+ * `docs.json` for unattached/standalone documentation entries (served at
112
+ * `/manifests/docs.json`), discriminated on `v`.
113
+ */
114
+ const DocsManifestMap = v.variant("v", [DocsManifestMapV0, DocsManifestMapV1]);
68
115
  /**
69
116
  * Shared Valibot field for the storybookId input, used in multi-source mode.
70
117
  * Reused across tools that support source selection.
71
118
  */
72
119
  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.")) };
73
120
 
121
+ //#endregion
122
+ //#region src/utils/adapt-core-manifest.ts
123
+ /**
124
+ * Adapts Storybook's `experimentalDocgenServer` open-service payloads (the "core
125
+ * format") into `@storybook/mcp`'s internal {@link ComponentManifest}/{@link Doc}
126
+ * shapes. This is the single place that bridges the two formats, used by both the
127
+ * ref-resolution path (built/static/remote manifests) and the addon's in-process
128
+ * `resolveEntry` hook (dev).
129
+ *
130
+ * Only `argTypes` is dropped: prop types still come from `reactComponentMeta` and
131
+ * the `react*` docgen-engine fields, which are passed through unchanged.
132
+ */
133
+ const ARG_TYPES_KEY = "argTypes";
134
+ /** Converts the story-docs `stories` record (or an already-resolved array) into `Story[]`. */
135
+ function adaptCoreStories(stories) {
136
+ if (!stories) return;
137
+ if (Array.isArray(stories)) return stories;
138
+ return Object.values(stories);
139
+ }
140
+ /** Adapts one MDX service payload into a {@link Doc}. */
141
+ function adaptCoreDoc(doc) {
142
+ return { ...doc };
143
+ }
144
+ /** Adapts a core-format component (docgen + story-docs + attached MDX) into a {@link ComponentManifest}. */
145
+ function adaptCoreComponent(core) {
146
+ const { stories, docs, [ARG_TYPES_KEY]: _argTypes, ...rest } = core;
147
+ const component = { ...rest };
148
+ const adaptedStories = adaptCoreStories(stories);
149
+ if (adaptedStories) component.stories = adaptedStories;
150
+ if (docs) component.docs = Object.fromEntries(Object.entries(docs).map(([id, doc]) => [id, adaptCoreDoc(doc)]));
151
+ return component;
152
+ }
153
+
154
+ //#endregion
155
+ //#region src/utils/requires-own-mcp.ts
156
+ function getSourceMcpEndpoint(source) {
157
+ const base = new URL(source.url);
158
+ base.pathname = `${base.pathname.replace(/\/$/, "")}/`;
159
+ return new URL("mcp", base).toString();
160
+ }
161
+ function formatRequiresOwnMcpNotice(source, endpoint, options = {}) {
162
+ const parts = [];
163
+ if (options.includeHeader ?? true) {
164
+ parts.push(`# ${source.title}`);
165
+ parts.push(`id: ${source.id}`);
166
+ parts.push("");
167
+ }
168
+ parts.push("This composed Storybook is private and cannot be read through the local Storybook MCP proxy.");
169
+ parts.push("");
170
+ parts.push("Use this source's own MCP endpoint instead:");
171
+ parts.push(endpoint);
172
+ return parts.join("\n");
173
+ }
174
+
74
175
  //#endregion
75
176
  //#region src/utils/get-manifest.ts
76
177
  /**
@@ -78,6 +179,11 @@ const StorybookIdField = { storybookId: v.pipe(v.string(), v.description("The St
78
179
  */
79
180
  const COMPONENT_MANIFEST_PATH = "./manifests/components.json";
80
181
  const DOCS_MANIFEST_PATH = "./manifests/docs.json";
182
+ /** Empty placeholder manifest used for sources that errored or need their own MCP endpoint. */
183
+ const EMPTY_COMPONENT_MANIFEST = {
184
+ v: 1,
185
+ components: {}
186
+ };
81
187
  /**
82
188
  * Error thrown when getting or parsing a manifest fails
83
189
  */
@@ -91,6 +197,17 @@ var ManifestGetError = class extends Error {
91
197
  this.cause = cause;
92
198
  }
93
199
  };
200
+ var RequiresOwnMcpError = class extends Error {
201
+ source;
202
+ endpoint;
203
+ constructor(source) {
204
+ const endpoint = getSourceMcpEndpoint(source);
205
+ super(`Composed Storybook "${source.title}" requires its own MCP endpoint: ${endpoint}`);
206
+ this.name = "RequiresOwnMcpError";
207
+ this.source = source;
208
+ this.endpoint = endpoint;
209
+ }
210
+ };
94
211
  /**
95
212
  * Converts an error to MCP-compatible content format
96
213
  *
@@ -98,6 +215,10 @@ var ManifestGetError = class extends Error {
98
215
  * @returns A tool result with error content and isError flag
99
216
  */
100
217
  const errorToMCPContent = (error) => {
218
+ if (error instanceof RequiresOwnMcpError) return { content: [{
219
+ type: "text",
220
+ text: formatRequiresOwnMcpNotice(error.source, error.endpoint)
221
+ }] };
101
222
  let fullMessage = `${error instanceof ManifestGetError ? "Error getting manifest" : "Unexpected error"}: ${error instanceof Error ? error.message : String(error)}`;
102
223
  if (error instanceof ManifestGetError && error.cause) {
103
224
  const causeMessage = error.cause instanceof Error ? error.cause.message : String(error.cause);
@@ -137,6 +258,7 @@ async function getManifests(request, manifestProvider, source) {
137
258
  const getUrl = (path) => request ? getManifestUrlFromRequest(request, path) : "Unknown manifest source";
138
259
  if (componentResult.status === "rejected") {
139
260
  const reason = componentResult.reason;
261
+ if (reason instanceof RequiresOwnMcpError) throw reason;
140
262
  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.` : "";
141
263
  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);
142
264
  }
@@ -159,17 +281,132 @@ async function getManifests(request, manifestProvider, source) {
159
281
  };
160
282
  }
161
283
  /**
162
- * Constructs the manifest URL from a request by replacing /mcp with the provided path
284
+ * Resolves a `$ref` into the provider path of the referenced file and the
285
+ * JSON-pointer segments into it.
286
+ *
287
+ * The `$ref` file path is relative to the component manifest's location, e.g.
288
+ * `"../services/core/docgen/button.json#/components/button"` from
289
+ * `./manifests/components.json` resolves to `./services/core/docgen/button.json`
290
+ * with pointer `["components", "button"]`. The same base (`manifests/`) applies to
291
+ * docgen, story-docs and MDX refs.
292
+ */
293
+ function parseManifestRef(ref) {
294
+ const [filePath = "", hash = ""] = ref.split("#");
295
+ const manifestDir = COMPONENT_MANIFEST_PATH.replace(/^\.\//, "").replace(/[^/]+$/, "");
296
+ const resolved = new URL(filePath, `https://localhost/${manifestDir}`).pathname.replace(/^\//, "");
297
+ const pointer = hash.split("/").filter(Boolean).map((segment) => segment.replace(/~1/g, "/").replace(/~0/g, "~"));
298
+ return {
299
+ path: `./${resolved}`,
300
+ pointer
301
+ };
302
+ }
303
+ /**
304
+ * Fetches the file a `$ref` points at (verbatim — never a fabricated path) and
305
+ * walks its JSON pointer, returning the pointed-to value.
306
+ */
307
+ async function fetchRefValue(ref, request, provider, source) {
308
+ const { path, pointer } = parseManifestRef(ref);
309
+ const jsonString = await provider(request, path, source);
310
+ let target;
311
+ try {
312
+ target = JSON.parse(jsonString);
313
+ } catch (error) {
314
+ throw new ManifestGetError(`Failed to parse externalized payload referenced by "${ref}"`, path, error instanceof Error ? error : void 0);
315
+ }
316
+ for (const key of pointer) if (target && typeof target === "object" && key in target) target = target[key];
317
+ else throw new ManifestGetError(`Reference "${ref}" could not be resolved: missing "${key}".`, path);
318
+ return target;
319
+ }
320
+ /**
321
+ * Resolves a component index entry into a full component manifest by following any
322
+ * `$ref`s it carries (docgen, story-docs, attached MDX docs), then adapting the
323
+ * core-format payloads into `@storybook/mcp`'s internal shape.
324
+ *
325
+ * Refs are read verbatim from the entry — never fabricated from an id — so a
326
+ * provider is only ever asked for top-level manifest paths or paths a manifest
327
+ * already pointed at. Components without any `$ref` (inline/v0 format, or entries
328
+ * already resolved in-process) are returned unchanged.
329
+ */
330
+ async function resolveComponentEntry(component, request, manifestProvider, source) {
331
+ const docgenRef = "docgen" in component ? component.docgen?.$ref : void 0;
332
+ const storiesRef = component.stories && !Array.isArray(component.stories) ? component.stories.$ref : void 0;
333
+ const docEntries = component.docs ? Object.entries(component.docs) : [];
334
+ const docRefs = docEntries.filter(([, doc]) => "mdx" in doc && !!doc.mdx?.$ref);
335
+ if (!docgenRef && !storiesRef && docRefs.length === 0) return component;
336
+ const provider = manifestProvider ?? defaultManifestProvider;
337
+ let core = {
338
+ id: component.id,
339
+ name: component.name,
340
+ ...component.description !== void 0 ? { description: component.description } : {},
341
+ ...component.summary !== void 0 ? { summary: component.summary } : {},
342
+ ...component.error !== void 0 ? { error: component.error } : {}
343
+ };
344
+ if (docgenRef) {
345
+ const payload = await fetchRefValue(docgenRef, request, provider, source);
346
+ core = {
347
+ ...core,
348
+ ...payload,
349
+ id: component.id,
350
+ name: component.name,
351
+ ...component.description !== void 0 ? { description: component.description } : {},
352
+ ...component.summary !== void 0 ? { summary: component.summary } : {},
353
+ ...component.error !== void 0 ? { error: component.error } : {}
354
+ };
355
+ }
356
+ if (Array.isArray(component.stories)) core.stories = component.stories;
357
+ if (storiesRef) {
358
+ const storyDocs = await fetchRefValue(storiesRef, request, provider, source);
359
+ if (storyDocs?.stories) core.stories = storyDocs.stories;
360
+ if (storyDocs?.import) core.import = storyDocs.import;
361
+ }
362
+ if (docEntries.length > 0) {
363
+ const docs = {};
364
+ for (const [docId, doc] of docEntries) {
365
+ const mdxRef = "mdx" in doc ? doc.mdx?.$ref : void 0;
366
+ docs[docId] = mdxRef ? await fetchRefValue(mdxRef, request, provider, source) : doc;
367
+ }
368
+ core.docs = docs;
369
+ }
370
+ return adaptCoreComponent(core);
371
+ }
372
+ /**
373
+ * Resolves only a component's stories `$ref` (story-docs payload) into a `Story[]`,
374
+ * leaving docgen/docs refs untouched. Used by `list-all-documentation` when story
375
+ * ids are requested, so listing doesn't pay for docgen/MDX resolution it won't show.
376
+ */
377
+ async function resolveComponentStories(component, request, manifestProvider, source) {
378
+ if (!component.stories || Array.isArray(component.stories)) return component;
379
+ const provider = manifestProvider ?? defaultManifestProvider;
380
+ const storyDocs = await fetchRefValue(component.stories.$ref, request, provider, source);
381
+ return {
382
+ ...component,
383
+ stories: storyDocs?.stories ? adaptCoreStories(storyDocs.stories) : []
384
+ };
385
+ }
386
+ /**
387
+ * Resolves a standalone docs entry, following its `mdx.$ref` when present.
388
+ * Inline docs (v0) are returned unchanged.
389
+ */
390
+ async function resolveDoc(doc, request, manifestProvider, source) {
391
+ const ref = "mdx" in doc ? doc.mdx?.$ref : void 0;
392
+ if (!ref) return doc;
393
+ const payload = await fetchRefValue(ref, request, manifestProvider ?? defaultManifestProvider, source);
394
+ return adaptCoreDoc({
395
+ ...payload,
396
+ id: payload.id ?? doc.id,
397
+ name: payload.name ?? doc.name
398
+ });
399
+ }
400
+ /**
401
+ * Constructs the manifest URL from the request origin and the top-level manifest path.
163
402
  */
164
403
  function getManifestUrlFromRequest(request, path) {
165
- const url = new URL(request.url);
166
404
  const normalizedPath = path.replace(/^\.\//, "");
167
- url.pathname = url.pathname.replace(/\/mcp\/?$/, `/${normalizedPath}`);
168
- return url.toString();
405
+ return new URL(`/${normalizedPath}`, request.url).toString();
169
406
  }
170
407
  /**
171
408
  * Default manifest provider that fetches from the same origin as the request,
172
- * replacing /mcp with the provided path
409
+ * using Storybook's top-level manifest path.
173
410
  */
174
411
  async function defaultManifestProvider(request, path) {
175
412
  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.");
@@ -201,17 +438,45 @@ async function getMultiSourceManifests(sources, request, manifestProvider) {
201
438
  docsManifest: manifests.docsManifest
202
439
  };
203
440
  } catch (error) {
441
+ if (error instanceof RequiresOwnMcpError) return {
442
+ source,
443
+ componentManifest: EMPTY_COMPONENT_MANIFEST,
444
+ notice: {
445
+ kind: "requires-own-mcp",
446
+ endpoint: error.endpoint
447
+ }
448
+ };
204
449
  return {
205
450
  source,
206
- componentManifest: {
207
- v: 1,
208
- components: {}
209
- },
451
+ componentManifest: EMPTY_COMPONENT_MANIFEST,
210
452
  error: error instanceof Error ? error.message : String(error)
211
453
  };
212
454
  }
213
455
  }));
214
- 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")}`);
456
+ const successCount = results.filter((r) => !r.error && !r.notice).length;
457
+ const noticeCount = results.filter((r) => r.notice).length;
458
+ if (successCount === 0 && noticeCount === 0) throw new ManifestGetError(`Failed to fetch manifests from any source. Errors:\n${results.map((r) => `- ${r.source.title}: ${r.error}`).join("\n")}`);
459
+ return results;
460
+ }
461
+
462
+ //#endregion
463
+ //#region src/utils/map-with-concurrency.ts
464
+ /**
465
+ * Maps `items` with at most `limit` concurrent in-flight `fn` calls.
466
+ */
467
+ async function mapWithConcurrency(items, limit, fn) {
468
+ if (items.length === 0) return [];
469
+ const safeLimit = Number.isFinite(limit) ? limit : items.length;
470
+ const concurrency = Math.max(1, Math.min(safeLimit, items.length));
471
+ const results = Array(items.length);
472
+ let nextIndex = 0;
473
+ async function worker() {
474
+ while (nextIndex < items.length) {
475
+ const index = nextIndex++;
476
+ results[index] = await fn(items[index], index);
477
+ }
478
+ }
479
+ await Promise.all(Array.from({ length: concurrency }, () => worker()));
215
480
  return results;
216
481
  }
217
482
 
@@ -369,8 +634,10 @@ function formatComponentLine(component) {
369
634
  return `- ${component.name} (${component.id})`;
370
635
  }
371
636
  function formatDocLine(doc) {
372
- const summary = doc.summary ?? extractDocsSummary(doc.content);
373
- return `- ${doc.title} (${doc.id})${summary ? `: ${summary}` : ""}`;
637
+ const title = "title" in doc ? doc.title : void 0;
638
+ const content = "content" in doc ? doc.content : void 0;
639
+ const summary = doc.summary ?? extractDocsSummary(content ?? "");
640
+ return `- ${title ?? doc.name} (${doc.id})${summary ? `: ${summary}` : ""}`;
374
641
  }
375
642
  function formatStorySubLine(story) {
376
643
  return ` - ${story.name}` + (story.id ? ` (${story.id})` : "");
@@ -411,6 +678,77 @@ function formatStoryContent(story, importStatement) {
411
678
  parts.push("```");
412
679
  return parts;
413
680
  }
681
+ function formatPropsSection(parsedDocgen, options = {}) {
682
+ const propEntries = parsedDocgen ? Object.entries(parsedDocgen.props) : [];
683
+ if (propEntries.length === 0) return [];
684
+ const title = options.title ?? "## Props";
685
+ const typeName = options.typeName ?? "Props";
686
+ const parts = [];
687
+ parts.push(title);
688
+ parts.push("");
689
+ parts.push("```");
690
+ parts.push(`export type ${typeName} = {`);
691
+ for (const [propName, propInfo] of propEntries) {
692
+ const type = propInfo.type ?? "any";
693
+ const isRequired = propInfo.required ?? true;
694
+ const hasDefault = propInfo.defaultValue !== void 0;
695
+ if (propInfo.description !== void 0) {
696
+ parts.push(" /**");
697
+ parts.push(` ${propInfo.description}`);
698
+ parts.push(" */");
699
+ }
700
+ let propLine = ` ${propName}`;
701
+ if (!isRequired) propLine += "?";
702
+ propLine += `: ${type}`;
703
+ if (hasDefault) propLine += ` = ${propInfo.defaultValue}`;
704
+ propLine += ";";
705
+ parts.push(propLine);
706
+ }
707
+ parts.push("}");
708
+ parts.push("```");
709
+ parts.push("");
710
+ return parts;
711
+ }
712
+ function formatSubcomponentsSection(subcomponents) {
713
+ if (!subcomponents || Object.keys(subcomponents).length === 0) return [];
714
+ const parts = [];
715
+ parts.push("## Subcomponents");
716
+ parts.push("");
717
+ for (const [key, subcomponent] of Object.entries(subcomponents)) {
718
+ parts.push(`### ${subcomponent.name || key}`);
719
+ parts.push("");
720
+ if (subcomponent.summary) {
721
+ parts.push(subcomponent.summary);
722
+ parts.push("");
723
+ }
724
+ if (subcomponent.description) {
725
+ parts.push(subcomponent.description);
726
+ parts.push("");
727
+ }
728
+ if (subcomponent.import) {
729
+ parts.push("```");
730
+ parts.push(subcomponent.import);
731
+ parts.push("```");
732
+ parts.push("");
733
+ }
734
+ if (subcomponent.error) {
735
+ parts.push(`Error: ${subcomponent.error.name}`);
736
+ parts.push("");
737
+ parts.push("```");
738
+ parts.push(subcomponent.error.message);
739
+ parts.push("```");
740
+ parts.push("");
741
+ continue;
742
+ }
743
+ const parsedDocgen = getParsedDocgen(subcomponent);
744
+ const typeName = `${(subcomponent.name || key).replace(/\W+/g, "")}Props`;
745
+ parts.push(...formatPropsSection(parsedDocgen, {
746
+ title: "#### Props",
747
+ typeName
748
+ }));
749
+ }
750
+ return parts;
751
+ }
414
752
  /**
415
753
  * Format a single component manifest into markdown.
416
754
  */
@@ -424,11 +762,13 @@ function formatComponentManifest(componentManifest) {
424
762
  parts.push(componentManifest.description);
425
763
  parts.push("");
426
764
  }
765
+ parts.push(...formatSubcomponentsSection(componentManifest.subcomponents));
427
766
  const parsedDocgen = getParsedDocgen(componentManifest);
428
- if (componentManifest.stories && componentManifest.stories.length > 0) {
767
+ const stories = Array.isArray(componentManifest.stories) ? componentManifest.stories : [];
768
+ if (stories.length > 0) {
429
769
  parts.push("## Stories");
430
770
  parts.push("");
431
- const storiesWithSnippets = componentManifest.stories.filter((s) => s.snippet);
771
+ const storiesWithSnippets = stories.filter((s) => s.snippet);
432
772
  const hasProps = parsedDocgen && Object.keys(parsedDocgen.props).length > 0;
433
773
  const storiesToShow = hasProps ? storiesWithSnippets.slice(0, MAX_STORIES_TO_SHOW) : storiesWithSnippets;
434
774
  const remainingStories = hasProps ? storiesWithSnippets.slice(MAX_STORIES_TO_SHOW) : [];
@@ -454,43 +794,16 @@ function formatComponentManifest(componentManifest) {
454
794
  parts.push("");
455
795
  }
456
796
  }
457
- if (parsedDocgen) {
458
- const propEntries = Object.entries(parsedDocgen.props);
459
- if (propEntries.length > 0) {
460
- parts.push("## Props");
461
- parts.push("");
462
- parts.push("```");
463
- parts.push("export type Props = {");
464
- for (const [propName, propInfo] of propEntries) {
465
- const type = propInfo.type ?? "any";
466
- const isRequired = propInfo.required ?? true;
467
- const hasDefault = propInfo.defaultValue !== void 0;
468
- if (propInfo.description !== void 0) {
469
- parts.push(" /**");
470
- parts.push(` ${propInfo.description}`);
471
- parts.push(" */");
472
- }
473
- let propLine = ` ${propName}`;
474
- if (!isRequired) propLine += "?";
475
- propLine += `: ${type}`;
476
- if (hasDefault) propLine += ` = ${propInfo.defaultValue}`;
477
- propLine += ";";
478
- parts.push(propLine);
479
- }
480
- parts.push("}");
481
- parts.push("```");
482
- parts.push("");
483
- }
484
- }
797
+ parts.push(...formatPropsSection(parsedDocgen));
485
798
  if (componentManifest.docs && Object.keys(componentManifest.docs).length > 0) {
486
- const docsWithContent = Object.values(componentManifest.docs).filter((doc) => doc.content.trim().length > 0);
799
+ const docsWithContent = Object.values(componentManifest.docs).filter((doc) => (doc.content ?? "").trim().length > 0);
487
800
  if (docsWithContent.length > 0) {
488
801
  parts.push("## Docs");
489
802
  parts.push("");
490
803
  for (const doc of docsWithContent) {
491
804
  parts.push(`### ${doc.name}`);
492
805
  parts.push("");
493
- parts.push(doc.content);
806
+ parts.push(doc.content ?? "");
494
807
  parts.push("");
495
808
  }
496
809
  }
@@ -501,9 +814,9 @@ function formatComponentManifest(componentManifest) {
501
814
  * Format a single doc manifest into markdown.
502
815
  */
503
816
  function formatDocsManifest(doc) {
504
- return dedent`# ${doc.title}
817
+ return dedent`# ${doc.title ?? doc.name}
505
818
 
506
- ${doc.content}`;
819
+ ${doc.content ?? ""}`;
507
820
  }
508
821
  /**
509
822
  * Format a component manifest map into a markdown list.
@@ -516,7 +829,7 @@ function formatManifestsToLists(manifests, options = {}) {
516
829
  parts.push("");
517
830
  for (const component of Object.values(manifests.componentManifest.components)) {
518
831
  parts.push(formatComponentLine(component));
519
- if (options.withStoryIds) for (const story of component.stories ?? []) parts.push(formatStorySubLine(story));
832
+ if (options.withStoryIds && Array.isArray(component.stories)) for (const story of component.stories) parts.push(formatStorySubLine(story));
520
833
  }
521
834
  parts.push("");
522
835
  if (!manifests.docsManifest) return parts.join("\n").trim();
@@ -527,7 +840,7 @@ function formatManifestsToLists(manifests, options = {}) {
527
840
  }
528
841
  function formatMultiSourceManifestsToLists(manifests, options = {}) {
529
842
  const parts = [];
530
- for (const { source, componentManifest, docsManifest, error } of manifests) {
843
+ for (const { source, componentManifest, docsManifest, error, notice } of manifests) {
531
844
  parts.push(`# ${source.title}`);
532
845
  parts.push(`id: ${source.id}`);
533
846
  parts.push("");
@@ -536,13 +849,18 @@ function formatMultiSourceManifestsToLists(manifests, options = {}) {
536
849
  parts.push("");
537
850
  continue;
538
851
  }
852
+ if (notice) {
853
+ parts.push(formatRequiresOwnMcpNotice(source, notice.endpoint, { includeHeader: false }));
854
+ parts.push("");
855
+ continue;
856
+ }
539
857
  const components = Object.values(componentManifest.components);
540
858
  if (components.length > 0) {
541
859
  parts.push("## Components");
542
860
  parts.push("");
543
861
  for (const component of components) {
544
862
  parts.push(formatComponentLine(component));
545
- if (options.withStoryIds) for (const story of component.stories ?? []) parts.push(formatStorySubLine(story));
863
+ if (options.withStoryIds && Array.isArray(component.stories)) for (const story of component.stories) parts.push(formatStorySubLine(story));
546
864
  }
547
865
  parts.push("");
548
866
  }
@@ -559,7 +877,7 @@ function formatMultiSourceManifestsToLists(manifests, options = {}) {
559
877
  * Format a single story's documentation.
560
878
  */
561
879
  function formatStoryDocumentation(componentManifest, storyName) {
562
- const story = componentManifest.stories?.find((s) => s.name === storyName);
880
+ const story = Array.isArray(componentManifest.stories) ? componentManifest.stories.find((s) => s.name === storyName) : void 0;
563
881
  if (!story || !story.snippet) return "";
564
882
  const parts = [];
565
883
  parts.push(`# ${componentManifest.name} - ${story.name}`);
@@ -572,12 +890,17 @@ function formatStoryDocumentation(componentManifest, storyName) {
572
890
  //#region src/tools/list-all-documentation.ts
573
891
  const LIST_TOOL_NAME = "list-all-documentation";
574
892
  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) });
575
- async function addListAllDocumentationTool(server, enabled) {
576
- server.tool({
893
+ function getListAllDocumentationToolMetadata() {
894
+ return {
577
895
  name: LIST_TOOL_NAME,
578
896
  title: "List All Documentation",
579
- description: "List all available UI components and documentation entries from the Storybook",
580
- schema: ListAllDocumentationInput,
897
+ 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 — 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 — 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.",
898
+ schema: ListAllDocumentationInput
899
+ };
900
+ }
901
+ async function addListAllDocumentationTool(server, enabled) {
902
+ server.tool({
903
+ ...getListAllDocumentationToolMetadata(),
581
904
  enabled
582
905
  }, async (input) => {
583
906
  try {
@@ -585,8 +908,18 @@ async function addListAllDocumentationTool(server, enabled) {
585
908
  const withStoryIds = input.withStoryIds ?? false;
586
909
  if (ctx?.sources?.some((s) => s.url)) {
587
910
  const multiSourceManifests = await getMultiSourceManifests(ctx.sources, ctx.request, ctx.manifestProvider);
911
+ if (withStoryIds) await Promise.all(multiSourceManifests.map(async (sourceManifest) => {
912
+ if (sourceManifest.error || sourceManifest.notice) return;
913
+ try {
914
+ const components = sourceManifest.componentManifest.components;
915
+ const resolved = await mapWithConcurrency(Object.entries(components), 16, async ([id, component]) => {
916
+ return [id, await resolveComponentStories(component, ctx.request, ctx.manifestProvider, sourceManifest.source)];
917
+ });
918
+ for (const [id, component] of resolved) components[id] = component;
919
+ } catch {}
920
+ }));
588
921
  const lists = formatMultiSourceManifestsToLists(multiSourceManifests, { withStoryIds });
589
- const firstSuccess = multiSourceManifests.find((m) => !m.error);
922
+ const firstSuccess = multiSourceManifests.find((m) => !m.error && !m.notice);
590
923
  if (firstSuccess) await ctx.onListAllDocumentation?.({
591
924
  context: ctx,
592
925
  manifests: {
@@ -602,6 +935,13 @@ async function addListAllDocumentationTool(server, enabled) {
602
935
  }] };
603
936
  }
604
937
  const manifests = await getManifests(ctx?.request, ctx?.manifestProvider);
938
+ if (withStoryIds) {
939
+ const components = manifests.componentManifest.components;
940
+ const resolved = await mapWithConcurrency(Object.entries(components), 16, async ([id, component]) => {
941
+ return [id, await resolveComponentStories(component, ctx?.request, ctx?.manifestProvider)];
942
+ });
943
+ for (const [id, component] of resolved) components[id] = component;
944
+ }
605
945
  const lists = formatManifestsToLists(manifests, { withStoryIds });
606
946
  await ctx?.onListAllDocumentation?.({
607
947
  context: ctx,
@@ -621,20 +961,28 @@ async function addListAllDocumentationTool(server, enabled) {
621
961
  //#endregion
622
962
  //#region src/tools/get-documentation-for-story.ts
623
963
  const GET_STORY_TOOL_NAME = "get-documentation-for-story";
964
+ const 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.";
624
965
  const BaseInput$1 = {
625
966
  componentId: v.string(),
626
967
  storyName: v.string()
627
968
  };
628
- async function addGetStoryDocumentationTool(server, enabled, options) {
629
- const schema = options?.multiSource ? v.object({
969
+ function getStoryDocumentationToolSchema(options) {
970
+ return options?.multiSource ? v.object({
630
971
  ...BaseInput$1,
631
972
  ...StorybookIdField
632
973
  }) : v.object(BaseInput$1);
633
- server.tool({
974
+ }
975
+ function getStoryDocumentationToolMetadata(options) {
976
+ return {
634
977
  name: GET_STORY_TOOL_NAME,
635
978
  title: "Get Documentation for Story",
636
- 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.",
637
- schema,
979
+ description: GET_STORY_DOCUMENTATION_TOOL_DESCRIPTION,
980
+ schema: getStoryDocumentationToolSchema(options)
981
+ };
982
+ }
983
+ async function addGetStoryDocumentationTool(server, enabled, options) {
984
+ server.tool({
985
+ ...getStoryDocumentationToolMetadata(options),
638
986
  enabled
639
987
  }, async (input) => {
640
988
  try {
@@ -660,7 +1008,14 @@ async function addGetStoryDocumentationTool(server, enabled, options) {
660
1008
  isError: true
661
1009
  };
662
1010
  }
663
- const component = (await getManifests(ctx?.request, ctx?.manifestProvider, source)).componentManifest?.components[componentId];
1011
+ let component;
1012
+ if (ctx?.resolveEntry && !source?.url) {
1013
+ const resolved = await ctx.resolveEntry(componentId, source);
1014
+ if (resolved?.kind === "component") component = resolved.component;
1015
+ } else {
1016
+ const componentEntry = (await getManifests(ctx?.request, ctx?.manifestProvider, source)).componentManifest?.components[componentId];
1017
+ if (componentEntry) component = await resolveComponentEntry(componentEntry, ctx?.request, ctx?.manifestProvider, source);
1018
+ }
664
1019
  if (!component) return {
665
1020
  content: [{
666
1021
  type: "text",
@@ -668,10 +1023,10 @@ async function addGetStoryDocumentationTool(server, enabled, options) {
668
1023
  }],
669
1024
  isError: true
670
1025
  };
671
- if (!component.stories?.find((s) => s.name === storyName)) return {
1026
+ if (!(Array.isArray(component.stories) ? component.stories.find((s) => s.name === storyName) : void 0)) return {
672
1027
  content: [{
673
1028
  type: "text",
674
- text: `Story "${storyName}" not found for component "${componentId}". Available stories: ${component.stories?.map((s) => s.name).join(", ") ?? "none"}`
1029
+ text: `Story "${storyName}" not found for component "${componentId}". Available stories: ${Array.isArray(component.stories) ? component.stories.map((s) => s.name).join(", ") : "none"}`
675
1030
  }],
676
1031
  isError: true
677
1032
  };
@@ -689,20 +1044,28 @@ async function addGetStoryDocumentationTool(server, enabled, options) {
689
1044
  //#region src/tools/get-documentation.ts
690
1045
  const GET_TOOL_NAME = "get-documentation";
691
1046
  const BaseInput = { id: v.pipe(v.string(), v.description("The component or docs entry ID (e.g., \"button\")")) };
692
- async function addGetDocumentationTool(server, enabled, options) {
693
- const schema = options?.multiSource ? v.object({
1047
+ const GET_DOCUMENTATION_TOOL_DESCRIPTION = `Get documentation for a UI component or docs entry.
1048
+
1049
+ 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 — 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.
1050
+
1051
+ Example: id="button" returns Primary, Secondary, Large stories with code like <Button variant="primary" size="large"> showing actual prop combinations.`;
1052
+ function getDocumentationToolSchema(options) {
1053
+ return options?.multiSource ? v.object({
694
1054
  ...BaseInput,
695
1055
  ...StorybookIdField
696
1056
  }) : v.object(BaseInput);
697
- server.tool({
1057
+ }
1058
+ function getDocumentationToolMetadata(options) {
1059
+ return {
698
1060
  name: GET_TOOL_NAME,
699
1061
  title: "Get Documentation",
700
- description: `Get documentation for a UI component or docs entry.
701
-
702
- 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.
703
-
704
- Example: id="button" returns Primary, Secondary, Large stories with code like <Button variant="primary" size="large"> showing actual prop combinations.`,
705
- schema,
1062
+ description: GET_DOCUMENTATION_TOOL_DESCRIPTION,
1063
+ schema: getDocumentationToolSchema(options)
1064
+ };
1065
+ }
1066
+ async function addGetDocumentationTool(server, enabled, options) {
1067
+ server.tool({
1068
+ ...getDocumentationToolMetadata(options),
706
1069
  enabled
707
1070
  }, async (input) => {
708
1071
  try {
@@ -728,9 +1091,19 @@ Example: id="button" returns Primary, Secondary, Large stories with code like <B
728
1091
  isError: true
729
1092
  };
730
1093
  }
731
- const { componentManifest, docsManifest } = await getManifests(ctx?.request, ctx?.manifestProvider, source);
732
- const component = componentManifest.components[id];
733
- const docsEntry = docsManifest?.docs[id];
1094
+ let component;
1095
+ let docsEntry;
1096
+ if (ctx?.resolveEntry && !source?.url) {
1097
+ const resolved = await ctx.resolveEntry(id, source);
1098
+ if (resolved?.kind === "component") component = resolved.component;
1099
+ else if (resolved?.kind === "doc") docsEntry = resolved.doc;
1100
+ } else {
1101
+ const { componentManifest, docsManifest } = await getManifests(ctx?.request, ctx?.manifestProvider, source);
1102
+ const componentEntry = componentManifest.components[id];
1103
+ const docEntry = docsManifest?.docs[id];
1104
+ if (componentEntry) component = await resolveComponentEntry(componentEntry, ctx?.request, ctx?.manifestProvider, source);
1105
+ else if (docEntry) docsEntry = await resolveDoc(docEntry, ctx?.request, ctx?.manifestProvider, source);
1106
+ }
734
1107
  if (!component && !docsEntry) {
735
1108
  const suffix = storybookId ? ` in source "${storybookId}"` : "";
736
1109
  await ctx?.onGetDocumentation?.({
@@ -792,4 +1165,4 @@ const createStorybookMcpHandler = async (options = {}) => {
792
1165
  };
793
1166
 
794
1167
  //#endregion
795
- 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 };
1168
+ export { COMPONENT_MANIFEST_PATH, ComponentManifestMap, DOCS_MANIFEST_PATH, DocsManifestMap, GET_STORY_TOOL_NAME, GET_TOOL_NAME, LIST_TOOL_NAME, RequiresOwnMcpError, instructions_default as STORYBOOK_MCP_INSTRUCTIONS, adaptCoreComponent, adaptCoreDoc, adaptCoreStories, addGetDocumentationTool, addGetStoryDocumentationTool, addListAllDocumentationTool, createStorybookMcpHandler, getDocumentationToolMetadata, getListAllDocumentationToolMetadata, getMultiSourceManifests, getStoryDocumentationToolMetadata, resolveComponentEntry, resolveComponentStories, resolveDoc };