@storybook/mcp 0.2.2 → 0.3.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.
Files changed (3) hide show
  1. package/dist/index.d.ts +46 -12
  2. package/dist/index.js +313 -350
  3. package/package.json +1 -1
package/dist/index.d.ts CHANGED
@@ -4,9 +4,26 @@ import { Documentation } from "react-docgen";
4
4
 
5
5
  //#region src/types.d.ts
6
6
  /**
7
- * Supported output formats for component manifest formatting.
7
+ * Represents a single Storybook source (local or remote).
8
8
  */
9
- type OutputFormat = 'xml' | 'markdown';
9
+ type Source = {
10
+ /** Unique identifier for this source (e.g., 'local', 'tetra') */
11
+ id: string;
12
+ /** Human-readable title (e.g., 'Local', 'Tetra Design System') */
13
+ title: string;
14
+ /** Remote URL, undefined for local source */
15
+ url?: string;
16
+ };
17
+ /**
18
+ * All manifests for a single source.
19
+ */
20
+ type SourceManifests = {
21
+ source: Source;
22
+ componentManifest: ComponentManifestMap;
23
+ docsManifest?: DocsManifestMap;
24
+ /** Error message if fetching this source failed */
25
+ error?: string;
26
+ };
10
27
  /**
11
28
  * Custom context passed to MCP server and tools.
12
29
  * Contains the request object and optional manifest provider.
@@ -16,21 +33,21 @@ type StorybookContext = {
16
33
  * The incoming HTTP request being processed.
17
34
  */
18
35
  request?: Request;
19
- /**
20
- * Output format for component manifests.
21
- * @default 'markdown'
22
- */
23
- format?: OutputFormat;
24
36
  /**
25
37
  * Optional function to provide custom manifest retrieval logic.
26
38
  * If provided, this function will be called instead of the default fetch-based provider.
27
- * The function receives the request object and a path to the manifest file,
28
- * and should return the manifest as a string.
39
+ * The function receives the request object, a path to the manifest file, and optionally
40
+ * a source (in multi-source mode).
29
41
  * The default provider requires a request object and constructs the manifest URL from the request origin,
30
42
  * replacing /mcp with /manifests/components.json.
31
43
  * Custom providers can use the request parameter to determine the manifest source, or ignore it entirely.
32
44
  */
33
- manifestProvider?: (request: Request | undefined, path: string) => Promise<string>;
45
+ manifestProvider?: (request: Request | undefined, path: string, source?: Source) => Promise<string>;
46
+ /**
47
+ * Sources configuration for multi-source mode.
48
+ * When provided, tools will fetch and display manifests grouped by source.
49
+ */
50
+ sources?: Source[];
34
51
  /**
35
52
  * Optional handler called when list-all-documentation tool is invoked.
36
53
  * Receives the context and the component manifest.
@@ -39,6 +56,8 @@ type StorybookContext = {
39
56
  context: StorybookContext;
40
57
  manifests: AllManifests;
41
58
  resultText: string;
59
+ /** Present in multi-source mode — all source manifests including errors */
60
+ sources?: SourceManifests[];
42
61
  }) => void | Promise<void>;
43
62
  /**
44
63
  * Optional handler called when get-documentation tool is invoked.
@@ -48,6 +67,7 @@ type StorybookContext = {
48
67
  context: StorybookContext;
49
68
  input: {
50
69
  id: string;
70
+ storybookId?: string;
51
71
  };
52
72
  } & ({
53
73
  foundDocumentation: ComponentManifest | Doc;
@@ -186,7 +206,9 @@ declare function addListAllDocumentationTool(server: McpServer<any, StorybookCon
186
206
  //#endregion
187
207
  //#region src/tools/get-documentation.d.ts
188
208
  declare const GET_TOOL_NAME = "get-documentation";
189
- declare function addGetDocumentationTool(server: McpServer<any, StorybookContext>, enabled?: Parameters<McpServer<any, StorybookContext>['tool']>[0]['enabled']): Promise<void>;
209
+ declare function addGetDocumentationTool(server: McpServer<any, StorybookContext>, enabled?: Parameters<McpServer<any, StorybookContext>['tool']>[0]['enabled'], options?: {
210
+ multiSource?: boolean;
211
+ }): Promise<void>;
190
212
  //#endregion
191
213
  //#region src/tools/get-documentation-for-story.d.ts
192
214
  declare const GET_STORY_TOOL_NAME = "get-documentation-for-story";
@@ -198,6 +220,18 @@ declare function addGetStoryDocumentationTool(server: McpServer<any, StorybookCo
198
220
  */
199
221
  declare const COMPONENT_MANIFEST_PATH = "./manifests/components.json";
200
222
  declare const DOCS_MANIFEST_PATH = "./manifests/docs.json";
223
+ /**
224
+ * Gets manifests from multiple sources.
225
+ * Returns an array of source manifests, each containing the source info and its manifests.
226
+ * Failures for individual sources are captured as errors rather than failing the entire request.
227
+ *
228
+ * @param sources - Array of source configurations
229
+ * @param request - The HTTP request (used for local source)
230
+ * @param manifestProvider - Function to fetch manifests, receives source as third parameter
231
+ * @returns Promise resolving to array of source manifests
232
+ * @throws {ManifestGetError} If no sources could be fetched successfully
233
+ */
234
+ declare function getMultiSourceManifests(sources: Source[], request?: Request, manifestProvider?: (request: Request | undefined, path: string, source?: Source) => Promise<string>): Promise<SourceManifests[]>;
201
235
  //#endregion
202
236
  //#region src/index.d.ts
203
237
  type InitializeRequestParams = {
@@ -237,4 +271,4 @@ interface StorybookMcpHandlerOptions extends StorybookContext {
237
271
  type Handler = (req: Request, context?: StorybookContext) => Promise<Response>;
238
272
  declare const createStorybookMcpHandler: (options?: StorybookMcpHandlerOptions) => Promise<Handler>;
239
273
  //#endregion
240
- export { COMPONENT_MANIFEST_PATH, type ComponentManifest, type ComponentManifestMap, DOCS_MANIFEST_PATH, GET_STORY_TOOL_NAME, GET_TOOL_NAME, LIST_TOOL_NAME, type StorybookContext, StorybookMcpHandlerOptions, addGetStoryDocumentationTool as addGetComponentStoryDocumentationTool, addGetDocumentationTool, addListAllDocumentationTool, createStorybookMcpHandler };
274
+ export { COMPONENT_MANIFEST_PATH, type ComponentManifest, ComponentManifestMap, DOCS_MANIFEST_PATH, DocsManifestMap, GET_STORY_TOOL_NAME, GET_TOOL_NAME, LIST_TOOL_NAME, type Source, type SourceManifests, type StorybookContext, StorybookMcpHandlerOptions, addGetStoryDocumentationTool as addGetComponentStoryDocumentationTool, addGetDocumentationTool, addListAllDocumentationTool, createStorybookMcpHandler, getMultiSourceManifests };
package/dist/index.js CHANGED
@@ -5,7 +5,7 @@ import * as v from "valibot";
5
5
 
6
6
  //#region package.json
7
7
  var name = "@storybook/mcp";
8
- var version = "0.2.2";
8
+ var version = "0.3.0";
9
9
  var description = "MCP server that serves knowledge about your components based on your Storybook stories and documentation";
10
10
 
11
11
  //#endregion
@@ -119,14 +119,19 @@ ${error instanceof v.ValiError ? error.issues.map((i) => i.message).join("\n") :
119
119
  *
120
120
  * @param request - The HTTP request to get the manifest for (optional when using custom manifestProvider)
121
121
  * @param manifestProvider - Optional custom function to get the manifest
122
+ * @param source - Optional source for multi-source mode
122
123
  * @returns A promise that resolves to the parsed ComponentManifestMap
123
124
  * @throws {ManifestGetError} If getting the manifest fails or the response is invalid
124
125
  */
125
- async function getManifests(request, manifestProvider) {
126
+ async function getManifests(request, manifestProvider, source) {
126
127
  const provider = manifestProvider ?? defaultManifestProvider;
127
- const [componentResult, docsResult] = await Promise.allSettled([provider(request, COMPONENT_MANIFEST_PATH), provider(request, DOCS_MANIFEST_PATH)]);
128
+ const [componentResult, docsResult] = await Promise.allSettled([provider(request, COMPONENT_MANIFEST_PATH, source), provider(request, DOCS_MANIFEST_PATH, source)]);
128
129
  const getUrl = (path) => request ? getManifestUrlFromRequest(request, path) : "Unknown manifest source";
129
- if (componentResult.status === "rejected") throw new ManifestGetError(`Failed to get component manifest: ${componentResult.reason instanceof Error ? componentResult.reason.message : String(componentResult.reason)}`, getUrl(COMPONENT_MANIFEST_PATH), componentResult.reason instanceof Error ? componentResult.reason : void 0);
130
+ if (componentResult.status === "rejected") {
131
+ const reason = componentResult.reason;
132
+ const hint = reason instanceof ManifestGetError && reason.message.includes("404") ? `\nHint: The Storybook at this URL may not have the component manifest enabled. Add \`features: { experimentalComponentsManifest: true }\` to its main.ts config.` : "";
133
+ 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);
134
+ }
130
135
  const componentManifest = parseManifest({
131
136
  jsonString: componentResult.value,
132
137
  schema: ComponentManifestMap,
@@ -167,90 +172,39 @@ async function defaultManifestProvider(request, path) {
167
172
  if (!contentType?.includes("application/json")) throw new ManifestGetError(`Invalid content type: expected application/json, got ${contentType}`, manifestUrl);
168
173
  return response.text();
169
174
  }
170
-
171
- //#endregion
172
- //#region src/utils/manifest-formatter/types.ts
173
- /**
174
- * Maximum length for a summary before truncation.
175
- */
176
- const MAX_SUMMARY_LENGTH = 90;
177
- /**
178
- * Maximum number of stories to show in full detail in component manifests.
179
- * Remaining stories will be shown as names only.
180
- */
181
- const MAX_STORIES_TO_SHOW = 3;
182
-
183
- //#endregion
184
- //#region src/utils/manifest-formatter/extract-docs-summary.ts
185
- /**
186
- * Extracts a summary from MDX content.
187
- * The summary is created by:
188
- * 1. Removing import statements
189
- * 2. Removing JSX/MDX expressions
190
- * 3. Extracting only text content from JSX/HTML elements
191
- * 4. Truncating to MAX_SUMMARY_LENGTH characters if needed
192
- *
193
- * @param content - The MDX content string
194
- * @returns A summary string, or undefined if no meaningful text content is found
195
- */
196
- function extractDocsSummary(content) {
197
- let result = content;
198
- result = result.replace(/^\s*import\s+(?:[\s\S]*?from\s+)?['"][^'"]+['"];?\s*$/gm, "");
199
- let prevResult = "";
200
- while (prevResult !== result) {
201
- prevResult = result;
202
- result = result.replace(/\{[^{}]*\}/g, "");
203
- }
204
- result = result.replace(/<[^>]+\/>/g, "");
205
- prevResult = "";
206
- while (prevResult !== result) {
207
- prevResult = result;
208
- result = result.replace(/<(\w+)[^>]*>([\s\S]*?)<\/\1>/g, "$2");
209
- }
210
- result = result.replace(/<[^>]+>/g, "");
211
- result = result.replace(/\s+/g, " ").trim();
212
- if (!result) return;
213
- if (result.length > MAX_SUMMARY_LENGTH) return `${result.slice(0, MAX_SUMMARY_LENGTH)}...`;
214
- return result;
215
- }
216
-
217
- //#endregion
218
- //#region src/utils/dedent.ts
219
175
  /**
220
- * Copied from https://github.com/tamino-martinius/node-ts-dedent/blob/18c4736c79806d7fe78bdaaaf5ae307b79f9574a/src/index.ts
176
+ * Gets manifests from multiple sources.
177
+ * Returns an array of source manifests, each containing the source info and its manifests.
178
+ * Failures for individual sources are captured as errors rather than failing the entire request.
221
179
  *
222
- * Rationale for vendoring instead of using the ts-dedent package:
223
- * 1. The package has a broken ESM distribution - the IDE auto-imports as
224
- * `import dedent from 'ts-dedent'` but that breaks at runtime, requiring
225
- * manual changes to named imports. See:
226
- * - https://github.com/tamino-martinius/node-ts-dedent/issues/42
227
- * - https://github.com/tamino-martinius/node-ts-dedent/pull/41
228
- * 2. Keeps bundle size smaller for such a simple utility (avoid "is-even" syndrome)
180
+ * @param sources - Array of source configurations
181
+ * @param request - The HTTP request (used for local source)
182
+ * @param manifestProvider - Function to fetch manifests, receives source as third parameter
183
+ * @returns Promise resolving to array of source manifests
184
+ * @throws {ManifestGetError} If no sources could be fetched successfully
229
185
  */
230
- function dedent(templ, ...values) {
231
- let strings = Array.from(typeof templ === "string" ? [templ] : templ);
232
- strings[strings.length - 1] = strings.at(-1).replace(/\r?\n([\t ]*)$/, "");
233
- const indentLengths = strings.reduce((arr, str) => {
234
- const matches = str.match(/\n([\t ]+|(?!\s).)/g);
235
- if (matches) return arr.concat(matches.map((match) => match.match(/[\t ]/g)?.length ?? 0));
236
- return arr;
237
- }, []);
238
- if (indentLengths.length) {
239
- const pattern = new RegExp(`\n[\t ]{${Math.min(...indentLengths)}}`, "g");
240
- strings = strings.map((str) => str.replace(pattern, "\n"));
241
- }
242
- strings[0] = strings[0].replace(/^\r?\n/, "");
243
- let string = strings[0];
244
- values.forEach((value, i) => {
245
- const endentations = string.match(/(?:^|\n)( *)$/);
246
- const endentation = endentations ? endentations[1] : "";
247
- let indentedValue = value;
248
- if (typeof value === "string" && value.includes("\n")) indentedValue = String(value).split("\n").map((str, i$1) => {
249
- return i$1 === 0 ? str : `${endentation}${str}`;
250
- }).join("\n");
251
- string += `${String(indentedValue)}${strings[i + 1]}`;
252
- });
253
- return string;
186
+ async function getMultiSourceManifests(sources, request, manifestProvider) {
187
+ const results = await Promise.all(sources.map(async (source) => {
188
+ try {
189
+ const manifests = await getManifests(request, manifestProvider, source);
190
+ return {
191
+ source,
192
+ componentManifest: manifests.componentManifest,
193
+ docsManifest: manifests.docsManifest
194
+ };
195
+ } catch (error) {
196
+ return {
197
+ source,
198
+ componentManifest: {
199
+ v: 1,
200
+ components: {}
201
+ },
202
+ error: error instanceof Error ? error.message : String(error)
203
+ };
204
+ }
205
+ }));
206
+ 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")}`);
207
+ return results;
254
208
  }
255
209
 
256
210
  //#endregion
@@ -302,129 +256,99 @@ const parseReactDocgen = (reactDocgen) => {
302
256
  };
303
257
 
304
258
  //#endregion
305
- //#region src/utils/manifest-formatter/xml.ts
259
+ //#region src/utils/dedent.ts
306
260
  /**
307
- * XML formatter for component manifests.
308
- * Formats component data into XML structure with tags like <component>, <props>, etc.
261
+ * Copied from https://github.com/tamino-martinius/node-ts-dedent/blob/18c4736c79806d7fe78bdaaaf5ae307b79f9574a/src/index.ts
262
+ *
263
+ * Rationale for vendoring instead of using the ts-dedent package:
264
+ * 1. The package has a broken ESM distribution - the IDE auto-imports as
265
+ * `import dedent from 'ts-dedent'` but that breaks at runtime, requiring
266
+ * manual changes to named imports. See:
267
+ * - https://github.com/tamino-martinius/node-ts-dedent/issues/42
268
+ * - https://github.com/tamino-martinius/node-ts-dedent/pull/41
269
+ * 2. Keeps bundle size smaller for such a simple utility (avoid "is-even" syndrome)
309
270
  */
310
- const xmlFormatter = {
311
- formatComponentManifest(componentManifest) {
312
- const parts = [];
313
- parts.push(dedent`<component>
314
- <id>${componentManifest.id}</id>
315
- <name>${componentManifest.name}</name>`);
316
- if (componentManifest.description) parts.push(dedent`<description>
317
- ${componentManifest.description}
318
- </description>`);
319
- if (componentManifest.stories && componentManifest.stories.length > 0) {
320
- const storiesWithSnippets = componentManifest.stories.filter((s) => s.snippet);
321
- const storiesToShow = storiesWithSnippets.slice(0, MAX_STORIES_TO_SHOW);
322
- const remainingStories = storiesWithSnippets.slice(MAX_STORIES_TO_SHOW);
323
- for (const story of storiesToShow) {
324
- const storyParts = [];
325
- storyParts.push(dedent`<story>
326
- <story_name>${story.name.replace(/([A-Z])/g, " $1").trim()}</story_name>`);
327
- if (story.description) storyParts.push(dedent`<story_description>
328
- ${story.description}
329
- </story_description>`);
330
- storyParts.push("<story_code>");
331
- if (componentManifest.import) storyParts.push(`${componentManifest.import}\n`);
332
- storyParts.push(dedent`${story.snippet}
333
- </story_code>
334
- </story>`);
335
- parts.push(storyParts.join("\n"));
336
- }
337
- if (remainingStories.length > 0) {
338
- parts.push("<other_stories>");
339
- for (const story of remainingStories) {
340
- const storyName = story.name.replace(/([A-Z])/g, " $1").trim();
341
- parts.push(dedent`<story_name>${storyName}</story_name>`);
342
- }
343
- parts.push("</other_stories>");
344
- }
345
- }
346
- if (componentManifest.reactDocgen) {
347
- const parsedDocgen = parseReactDocgen(componentManifest.reactDocgen);
348
- const propEntries = Object.entries(parsedDocgen.props);
349
- if (propEntries.length > 0) {
350
- parts.push("<props>");
351
- for (const [propName, propInfo] of propEntries) {
352
- parts.push(dedent`<prop>
353
- <prop_name>${propName}</prop_name>`);
354
- if (propInfo.description !== void 0) parts.push(dedent`<prop_description>
355
- ${propInfo.description}
356
- </prop_description>`);
357
- if (propInfo.type !== void 0) parts.push(dedent`<prop_type>${propInfo.type}</prop_type>`);
358
- if (propInfo.required !== void 0) parts.push(dedent`<prop_required>${propInfo.required}</prop_required>`);
359
- if (propInfo.defaultValue !== void 0) parts.push(dedent`<prop_default>${propInfo.defaultValue}</prop_default>`);
360
- parts.push("</prop>");
361
- }
362
- parts.push("</props>");
363
- }
364
- }
365
- parts.push("</component>");
366
- return parts.join("\n");
367
- },
368
- formatDocsManifest(doc) {
369
- return dedent`<doc>
370
- <title>${doc.title}</title>
371
- <content>
372
- ${doc.content}
373
- </content>
374
- </doc>`;
375
- },
376
- formatManifestsToLists(manifests) {
377
- const parts = [];
378
- parts.push("<components>");
379
- for (const component of Object.values(manifests.componentManifest.components)) {
380
- parts.push(dedent`<component>
381
- <id>${component.id}</id>
382
- <name>${component.name}</name>`);
383
- const summary = component.summary ?? (component.description ? component.description.length > MAX_SUMMARY_LENGTH ? `${component.description.slice(0, MAX_SUMMARY_LENGTH)}...` : component.description : void 0);
384
- if (summary) parts.push(dedent`<summary>
385
- ${summary}
386
- </summary>`);
387
- parts.push("</component>");
388
- }
389
- parts.push("</components>");
390
- if (!manifests.docsManifest) return parts.join("\n");
391
- parts.push("<docs>");
392
- for (const doc of Object.values(manifests.docsManifest.docs)) {
393
- const summary = doc.summary ?? extractDocsSummary(doc.content);
394
- parts.push(dedent`<doc>
395
- <id>${doc.id}</id>
396
- <title>${doc.title}</title>`);
397
- if (summary) parts.push(dedent`<summary>
398
- ${summary}
399
- </summary>`);
400
- parts.push("</doc>");
401
- }
402
- parts.push("</docs>");
403
- return parts.join("\n");
404
- },
405
- formatStoryDocumentation(componentManifest, storyName) {
406
- const story = componentManifest.stories?.find((s) => s.name === storyName);
407
- if (!story || !story.snippet) return "";
408
- const parts = [];
409
- const displayStoryName = story.name.replace(/([A-Z])/g, " $1").trim();
410
- parts.push(dedent`<story_documentation>
411
- <component_name>${componentManifest.name}</component_name>
412
- <story_name>${displayStoryName}</story_name>`);
413
- if (story.description) parts.push(dedent`<story_description>
414
- ${story.description}
415
- </story_description>`);
416
- parts.push("<story_code>");
417
- if (componentManifest.import) parts.push(`${componentManifest.import}\n`);
418
- parts.push(dedent`${story.snippet}
419
- </story_code>
420
- </story_documentation>`);
421
- return parts.join("\n");
271
+ function dedent(templ, ...values) {
272
+ let strings = Array.from(typeof templ === "string" ? [templ] : templ);
273
+ strings[strings.length - 1] = strings.at(-1).replace(/\r?\n([\t ]*)$/, "");
274
+ const indentLengths = strings.reduce((arr, str) => {
275
+ const matches = str.match(/\n([\t ]+|(?!\s).)/g);
276
+ if (matches) return arr.concat(matches.map((match) => match.match(/[\t ]/g)?.length ?? 0));
277
+ return arr;
278
+ }, []);
279
+ if (indentLengths.length) {
280
+ const pattern = new RegExp(`\n[\t ]{${Math.min(...indentLengths)}}`, "g");
281
+ strings = strings.map((str) => str.replace(pattern, "\n"));
422
282
  }
423
- };
283
+ strings[0] = strings[0].replace(/^\r?\n/, "");
284
+ let string = strings[0];
285
+ values.forEach((value, i) => {
286
+ const endentations = string.match(/(?:^|\n)( *)$/);
287
+ const endentation = endentations ? endentations[1] : "";
288
+ let indentedValue = value;
289
+ if (typeof value === "string" && value.includes("\n")) indentedValue = String(value).split("\n").map((str, i$1) => {
290
+ return i$1 === 0 ? str : `${endentation}${str}`;
291
+ }).join("\n");
292
+ string += `${String(indentedValue)}${strings[i + 1]}`;
293
+ });
294
+ return string;
295
+ }
296
+
297
+ //#endregion
298
+ //#region src/utils/manifest-formatter/extract-docs-summary.ts
299
+ /**
300
+ * Maximum length for a summary before truncation.
301
+ */
302
+ const MAX_SUMMARY_LENGTH = 90;
303
+ /**
304
+ * Extracts a summary from MDX content.
305
+ * The summary is created by:
306
+ * 1. Removing import statements
307
+ * 2. Removing JSX/MDX expressions
308
+ * 3. Extracting only text content from JSX/HTML elements
309
+ * 4. Truncating to MAX_SUMMARY_LENGTH characters if needed
310
+ *
311
+ * @param content - The MDX content string
312
+ * @returns A summary string, or undefined if no meaningful text content is found
313
+ */
314
+ function extractDocsSummary(content) {
315
+ let result = content;
316
+ result = result.replace(/^\s*import\s+(?:[\s\S]*?from\s+)?['"][^'"]+['"];?\s*$/gm, "");
317
+ let prevResult = "";
318
+ while (prevResult !== result) {
319
+ prevResult = result;
320
+ result = result.replace(/\{[^{}]*\}/g, "");
321
+ }
322
+ result = result.replace(/<[^>]+\/>/g, "");
323
+ prevResult = "";
324
+ while (prevResult !== result) {
325
+ prevResult = result;
326
+ result = result.replace(/<(\w+)[^>]*>([\s\S]*?)<\/\1>/g, "$2");
327
+ }
328
+ result = result.replace(/<[^>]+>/g, "");
329
+ result = result.replace(/\s+/g, " ").trim();
330
+ if (!result) return;
331
+ if (result.length > MAX_SUMMARY_LENGTH) return `${result.slice(0, MAX_SUMMARY_LENGTH)}...`;
332
+ return result;
333
+ }
424
334
 
425
335
  //#endregion
426
336
  //#region src/utils/manifest-formatter/markdown.ts
427
337
  /**
338
+ * Maximum number of stories to show in full detail in component manifests.
339
+ * Remaining stories will be shown as names only.
340
+ */
341
+ const MAX_STORIES_TO_SHOW = 3;
342
+ function formatComponentLine(component) {
343
+ const summary = component.summary ?? (component.description ? component.description.length > MAX_SUMMARY_LENGTH ? `${component.description.slice(0, MAX_SUMMARY_LENGTH)}...` : component.description : void 0);
344
+ if (summary) return `- ${component.name} (${component.id}): ${summary}`;
345
+ return `- ${component.name} (${component.id})`;
346
+ }
347
+ function formatDocLine(doc) {
348
+ const summary = doc.summary ?? extractDocsSummary(doc.content);
349
+ return `- ${doc.title} (${doc.id})${summary ? `: ${summary}` : ""}`;
350
+ }
351
+ /**
428
352
  * Extracts a summary from an object with optional summary and description fields.
429
353
  * Prefers summary if available, otherwise truncates description to maxLength.
430
354
  */
@@ -452,160 +376,155 @@ function formatStoryContent(story, importStatement) {
452
376
  return parts;
453
377
  }
454
378
  /**
455
- * Markdown formatter for component manifests.
456
- * Formats component data into token-efficient markdown with headers, lists, and tables.
457
- * Uses adaptive formatting based on prop complexity to optimize token usage.
379
+ * Format a single component manifest into markdown.
458
380
  */
459
- const markdownFormatter = {
460
- formatComponentManifest(componentManifest) {
461
- const parts = [];
462
- parts.push(`# ${componentManifest.name}`);
381
+ function formatComponentManifest(componentManifest) {
382
+ const parts = [];
383
+ parts.push(`# ${componentManifest.name}`);
384
+ parts.push("");
385
+ parts.push(`ID: ${componentManifest.id}`);
386
+ parts.push("");
387
+ if (componentManifest.description) {
388
+ parts.push(componentManifest.description);
463
389
  parts.push("");
464
- parts.push(`ID: ${componentManifest.id}`);
390
+ }
391
+ if (componentManifest.stories && componentManifest.stories.length > 0) {
392
+ parts.push("## Stories");
465
393
  parts.push("");
466
- if (componentManifest.description) {
467
- parts.push(componentManifest.description);
394
+ const storiesWithSnippets = componentManifest.stories.filter((s) => s.snippet);
395
+ const hasProps = componentManifest.reactDocgen && Object.keys(componentManifest.reactDocgen.props ?? {}).length > 0;
396
+ const storiesToShow = hasProps ? storiesWithSnippets.slice(0, MAX_STORIES_TO_SHOW) : storiesWithSnippets;
397
+ const remainingStories = hasProps ? storiesWithSnippets.slice(MAX_STORIES_TO_SHOW) : [];
398
+ for (const story of storiesToShow) {
399
+ parts.push(`### ${story.name}`);
400
+ parts.push("");
401
+ parts.push(...formatStoryContent(story, componentManifest.import));
468
402
  parts.push("");
469
403
  }
470
- if (componentManifest.stories && componentManifest.stories.length > 0) {
471
- parts.push("## Stories");
404
+ if (remainingStories.length > 0) {
405
+ if (storiesToShow.length > 0) parts.push("### Other Stories");
472
406
  parts.push("");
473
- const storiesWithSnippets = componentManifest.stories.filter((s) => s.snippet);
474
- const hasProps = componentManifest.reactDocgen && Object.keys(componentManifest.reactDocgen.props ?? {}).length > 0;
475
- const storiesToShow = hasProps ? storiesWithSnippets.slice(0, MAX_STORIES_TO_SHOW) : storiesWithSnippets;
476
- const remainingStories = hasProps ? storiesWithSnippets.slice(MAX_STORIES_TO_SHOW) : [];
477
- for (const story of storiesToShow) {
478
- parts.push(`### ${story.name}`);
479
- parts.push("");
480
- parts.push(...formatStoryContent(story, componentManifest.import));
481
- parts.push("");
482
- }
483
- if (remainingStories.length > 0) {
484
- if (storiesToShow.length > 0) parts.push("### Other Stories");
485
- parts.push("");
486
- for (const story of remainingStories) {
487
- const summary = extractSummary(story);
488
- const summaryPart = summary ? `: ${summary}` : "";
489
- parts.push(`- ${story.name}${summaryPart}`);
490
- }
491
- parts.push("");
407
+ for (const story of remainingStories) {
408
+ const summary = extractSummary(story);
409
+ const summaryPart = summary ? `: ${summary}` : "";
410
+ parts.push(`- ${story.name}${summaryPart}`);
492
411
  }
412
+ parts.push("");
493
413
  }
494
- if (componentManifest.reactDocgen) {
495
- const parsedDocgen = parseReactDocgen(componentManifest.reactDocgen);
496
- const propEntries = Object.entries(parsedDocgen.props);
497
- if (propEntries.length > 0) {
498
- parts.push("## Props");
499
- parts.push("");
500
- parts.push("```");
501
- parts.push("export type Props = {");
502
- for (const [propName, propInfo] of propEntries) {
503
- const type = propInfo.type ?? "any";
504
- const isRequired = propInfo.required ?? true;
505
- const hasDefault = propInfo.defaultValue !== void 0;
506
- if (propInfo.description !== void 0) {
507
- parts.push(" /**");
508
- parts.push(` ${propInfo.description}`);
509
- parts.push(" */");
510
- }
511
- let propLine = ` ${propName}`;
512
- if (!isRequired) propLine += "?";
513
- propLine += `: ${type}`;
514
- if (hasDefault) propLine += ` = ${propInfo.defaultValue}`;
515
- propLine += ";";
516
- parts.push(propLine);
414
+ }
415
+ if (componentManifest.reactDocgen) {
416
+ const parsedDocgen = parseReactDocgen(componentManifest.reactDocgen);
417
+ const propEntries = Object.entries(parsedDocgen.props);
418
+ if (propEntries.length > 0) {
419
+ parts.push("## Props");
420
+ parts.push("");
421
+ parts.push("```");
422
+ parts.push("export type Props = {");
423
+ for (const [propName, propInfo] of propEntries) {
424
+ const type = propInfo.type ?? "any";
425
+ const isRequired = propInfo.required ?? true;
426
+ const hasDefault = propInfo.defaultValue !== void 0;
427
+ if (propInfo.description !== void 0) {
428
+ parts.push(" /**");
429
+ parts.push(` ${propInfo.description}`);
430
+ parts.push(" */");
517
431
  }
518
- parts.push("}");
519
- parts.push("```");
520
- parts.push("");
432
+ let propLine = ` ${propName}`;
433
+ if (!isRequired) propLine += "?";
434
+ propLine += `: ${type}`;
435
+ if (hasDefault) propLine += ` = ${propInfo.defaultValue}`;
436
+ propLine += ";";
437
+ parts.push(propLine);
521
438
  }
439
+ parts.push("}");
440
+ parts.push("```");
441
+ parts.push("");
522
442
  }
523
- if (componentManifest.docs && Object.keys(componentManifest.docs).length > 0) {
524
- const docsWithContent = Object.values(componentManifest.docs).filter((doc) => doc.content.trim().length > 0);
525
- if (docsWithContent.length > 0) {
526
- parts.push("## Docs");
443
+ }
444
+ if (componentManifest.docs && Object.keys(componentManifest.docs).length > 0) {
445
+ const docsWithContent = Object.values(componentManifest.docs).filter((doc) => doc.content.trim().length > 0);
446
+ if (docsWithContent.length > 0) {
447
+ parts.push("## Docs");
448
+ parts.push("");
449
+ for (const doc of docsWithContent) {
450
+ parts.push(`### ${doc.name}`);
451
+ parts.push("");
452
+ parts.push(doc.content);
527
453
  parts.push("");
528
- for (const doc of docsWithContent) {
529
- parts.push(`### ${doc.name}`);
530
- parts.push("");
531
- parts.push(doc.content);
532
- parts.push("");
533
- }
534
454
  }
535
455
  }
536
- return parts.join("\n").trim();
537
- },
538
- formatDocsManifest(doc) {
539
- return dedent`# ${doc.title}
540
-
541
- ${doc.content}`;
542
- },
543
- formatManifestsToLists(manifests) {
544
- const parts = [];
545
- parts.push("# Components");
546
- parts.push("");
547
- for (const component of Object.values(manifests.componentManifest.components)) {
548
- const summary = extractSummary(component);
549
- if (summary) parts.push(`- ${component.name} (${component.id}): ${summary}`);
550
- else parts.push(`- ${component.name} (${component.id})`);
551
- }
552
- parts.push("");
553
- if (!manifests.docsManifest) return parts.join("\n").trim();
554
- parts.push("# Docs");
555
- parts.push("");
556
- for (const doc of Object.values(manifests.docsManifest.docs)) {
557
- const summary = doc.summary ?? extractDocsSummary(doc.content);
558
- parts.push(`- ${doc.title} (${doc.id})${summary ? `: ${summary}` : ""}`);
559
- }
560
- return parts.join("\n").trim();
561
- },
562
- formatStoryDocumentation(componentManifest, storyName) {
563
- const story = componentManifest.stories?.find((s) => s.name === storyName);
564
- if (!story || !story.snippet) return "";
565
- const parts = [];
566
- parts.push(`# ${componentManifest.name} - ${story.name}`);
567
- parts.push("");
568
- parts.push(...formatStoryContent(story, componentManifest.import));
569
- return parts.join("\n").trim();
570
456
  }
571
- };
572
-
573
- //#endregion
574
- //#region src/utils/format-manifest.ts
575
- const formatters = {
576
- xml: xmlFormatter,
577
- markdown: markdownFormatter
578
- };
457
+ return parts.join("\n").trim();
458
+ }
579
459
  /**
580
- * Format a single component manifest in summary mode (optimized for token usage).
581
- * @param componentManifest - The component manifest to format
582
- * @param format - The desired output format (defaults to 'markdown')
583
- * @returns Formatted string representation of the component
460
+ * Format a single doc manifest into markdown.
584
461
  */
585
- function formatComponentManifest(componentManifest, format = "markdown") {
586
- return formatters[format].formatComponentManifest(componentManifest);
462
+ function formatDocsManifest(doc) {
463
+ return dedent`# ${doc.title}
464
+
465
+ ${doc.content}`;
587
466
  }
588
467
  /**
589
- * Format a single story's documentation.
590
- * @param componentManifest - The component manifest containing the story
591
- * @param storyName - The name of the story to format
592
- * @param format - The desired output format (defaults to 'markdown')
593
- * @returns Formatted string representation of the story
468
+ * Format a component manifest map into a markdown list.
469
+ * @param manifest - The component manifest map to format
470
+ * @returns Formatted string representation of the component list
594
471
  */
595
- function formatStoryDocumentation(componentManifest, storyName, format = "markdown") {
596
- return formatters[format].formatStoryDocumentation(componentManifest, storyName);
472
+ function formatManifestsToLists(manifests) {
473
+ const parts = [];
474
+ parts.push("# Components");
475
+ parts.push("");
476
+ for (const component of Object.values(manifests.componentManifest.components)) parts.push(formatComponentLine(component));
477
+ parts.push("");
478
+ if (!manifests.docsManifest) return parts.join("\n").trim();
479
+ parts.push("# Docs");
480
+ parts.push("");
481
+ for (const doc of Object.values(manifests.docsManifest.docs)) parts.push(formatDocLine(doc));
482
+ return parts.join("\n").trim();
597
483
  }
598
484
  /**
599
- * Format a single docs manifest.
485
+ * Format multi-source manifests into grouped lists.
486
+ * Each source is displayed with a heading and its components/docs listed underneath.
487
+ * @param manifests - The multi-source manifests to format
488
+ * @returns Formatted string representation grouped by source
600
489
  */
601
- function formatDocsManifest(doc, format = "markdown") {
602
- return formatters[format].formatDocsManifest(doc);
490
+ function formatMultiSourceManifestsToLists(manifests) {
491
+ const parts = [];
492
+ for (const { source, componentManifest, docsManifest, error } of manifests) {
493
+ parts.push(`# ${source.title}`);
494
+ parts.push(`id: ${source.id}`);
495
+ parts.push("");
496
+ if (error) {
497
+ parts.push(`error: ${error}`);
498
+ parts.push("");
499
+ continue;
500
+ }
501
+ const components = Object.values(componentManifest.components);
502
+ if (components.length > 0) {
503
+ parts.push("## Components");
504
+ parts.push("");
505
+ for (const component of components) parts.push(formatComponentLine(component));
506
+ parts.push("");
507
+ }
508
+ if (docsManifest && Object.keys(docsManifest.docs).length > 0) {
509
+ parts.push("## Docs");
510
+ parts.push("");
511
+ for (const doc of Object.values(docsManifest.docs)) parts.push(formatDocLine(doc));
512
+ parts.push("");
513
+ }
514
+ }
515
+ return parts.join("\n").trim();
603
516
  }
604
517
  /**
605
- * Format a component manifest and optionally a docs manifest into lists.
518
+ * Format a single story's documentation.
606
519
  */
607
- function formatManifestsToLists(manifests, format = "markdown") {
608
- return formatters[format].formatManifestsToLists(manifests);
520
+ function formatStoryDocumentation(componentManifest, storyName) {
521
+ const story = componentManifest.stories?.find((s) => s.name === storyName);
522
+ if (!story || !story.snippet) return "";
523
+ const parts = [];
524
+ parts.push(`# ${componentManifest.name} - ${story.name}`);
525
+ parts.push("");
526
+ parts.push(...formatStoryContent(story, componentManifest.import));
527
+ return parts.join("\n").trim();
609
528
  }
610
529
 
611
530
  //#endregion
@@ -619,10 +538,29 @@ async function addListAllDocumentationTool(server, enabled) {
619
538
  enabled
620
539
  }, async () => {
621
540
  try {
622
- const manifests = await getManifests(server.ctx.custom?.request, server.ctx.custom?.manifestProvider);
623
- const lists = formatManifestsToLists(manifests, server.ctx.custom?.format ?? "markdown");
624
- await server.ctx.custom?.onListAllDocumentation?.({
625
- context: server.ctx.custom,
541
+ const ctx = server.ctx.custom;
542
+ if (ctx?.sources?.some((s) => s.url)) {
543
+ const multiSourceManifests = await getMultiSourceManifests(ctx.sources, ctx.request, ctx.manifestProvider);
544
+ const lists$1 = formatMultiSourceManifestsToLists(multiSourceManifests);
545
+ const firstSuccess = multiSourceManifests.find((m) => !m.error);
546
+ if (firstSuccess) await ctx.onListAllDocumentation?.({
547
+ context: ctx,
548
+ manifests: {
549
+ componentManifest: firstSuccess.componentManifest,
550
+ docsManifest: firstSuccess.docsManifest
551
+ },
552
+ resultText: lists$1,
553
+ sources: multiSourceManifests
554
+ });
555
+ return { content: [{
556
+ type: "text",
557
+ text: lists$1
558
+ }] };
559
+ }
560
+ const manifests = await getManifests(ctx?.request, ctx?.manifestProvider);
561
+ const lists = formatManifestsToLists(manifests);
562
+ await ctx?.onListAllDocumentation?.({
563
+ context: ctx,
626
564
  manifests,
627
565
  resultText: lists
628
566
  });
@@ -670,10 +608,9 @@ async function addGetStoryDocumentationTool(server, enabled) {
670
608
  isError: true
671
609
  };
672
610
  }
673
- const format = server.ctx.custom?.format ?? "markdown";
674
611
  return { content: [{
675
612
  type: "text",
676
- text: formatStoryDocumentation(component, input.storyName, format)
613
+ text: formatStoryDocumentation(component, input.storyName)
677
614
  }] };
678
615
  } catch (error) {
679
616
  return errorToMCPContent(error);
@@ -684,8 +621,13 @@ async function addGetStoryDocumentationTool(server, enabled) {
684
621
  //#endregion
685
622
  //#region src/tools/get-documentation.ts
686
623
  const GET_TOOL_NAME = "get-documentation";
687
- const GetDocumentationInput = v.object({ id: v.string() });
688
- async function addGetDocumentationTool(server, enabled) {
624
+ const BaseInput = { id: v.pipe(v.string(), v.description("The component or docs entry ID (e.g., \"button\")")) };
625
+ 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.")) };
626
+ async function addGetDocumentationTool(server, enabled, options) {
627
+ const schema = options?.multiSource ? v.object({
628
+ ...BaseInput,
629
+ ...StorybookIdField
630
+ }) : v.object(BaseInput);
689
631
  server.tool({
690
632
  name: GET_TOOL_NAME,
691
633
  title: "Get Documentation",
@@ -694,31 +636,53 @@ async function addGetDocumentationTool(server, enabled) {
694
636
  Returns the first ${MAX_STORIES_TO_SHOW} stories 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.
695
637
 
696
638
  Example: id="button" returns Primary, Secondary, Large stories with code like <Button variant="primary" size="large"> showing actual prop combinations.`,
697
- schema: GetDocumentationInput,
639
+ schema,
698
640
  enabled
699
641
  }, async (input) => {
700
642
  try {
701
- const { componentManifest, docsManifest } = await getManifests(server.ctx.custom?.request, server.ctx.custom?.manifestProvider);
702
- const component = componentManifest.components[input.id];
703
- const docsEntry = docsManifest?.docs[input.id];
643
+ const ctx = server.ctx.custom;
644
+ const { id, storybookId } = input;
645
+ const sources = ctx?.sources;
646
+ const isMultiSource = sources && sources.some((s) => s.url);
647
+ let source;
648
+ if (isMultiSource) {
649
+ if (!storybookId) return {
650
+ content: [{
651
+ type: "text",
652
+ text: `storybookId is required. Available sources: ${sources.map((s) => s.id).join(", ")}. Use the ${LIST_TOOL_NAME} tool to see available sources.`
653
+ }],
654
+ isError: true
655
+ };
656
+ source = sources.find((s) => s.id === storybookId);
657
+ if (!source) return {
658
+ content: [{
659
+ type: "text",
660
+ text: `Storybook source not found: "${storybookId}". Available sources: ${sources.map((s) => s.id).join(", ")}. Use the ${LIST_TOOL_NAME} tool to see available sources.`
661
+ }],
662
+ isError: true
663
+ };
664
+ }
665
+ const { componentManifest, docsManifest } = await getManifests(ctx?.request, ctx?.manifestProvider, source);
666
+ const component = componentManifest.components[id];
667
+ const docsEntry = docsManifest?.docs[id];
704
668
  if (!component && !docsEntry) {
705
- await server.ctx.custom?.onGetDocumentation?.({
706
- context: server.ctx.custom,
669
+ const suffix = storybookId ? ` in source "${storybookId}"` : "";
670
+ await ctx?.onGetDocumentation?.({
671
+ context: ctx,
707
672
  input
708
673
  });
709
674
  return {
710
675
  content: [{
711
676
  type: "text",
712
- text: `Component or Docs Entry not found: "${input.id}". Use the ${LIST_TOOL_NAME} tool to see available components and documentation entries.`
677
+ text: `Component or Docs Entry not found: "${id}"${suffix}. Use the ${LIST_TOOL_NAME} tool to see available components and documentation entries.`
713
678
  }],
714
679
  isError: true
715
680
  };
716
681
  }
717
682
  const documentation = component ?? docsEntry;
718
- const format = server.ctx.custom?.format ?? "markdown";
719
- const text = component ? formatComponentManifest(documentation, format) : formatDocsManifest(documentation, format);
720
- await server.ctx.custom?.onGetDocumentation?.({
721
- context: server.ctx.custom,
683
+ const text = component ? formatComponentManifest(documentation) : formatDocsManifest(documentation);
684
+ await ctx?.onGetDocumentation?.({
685
+ context: ctx,
722
686
  input,
723
687
  foundDocumentation: documentation,
724
688
  resultText: text
@@ -753,7 +717,6 @@ const createStorybookMcpHandler = async (options = {}) => {
753
717
  return (async (req, context) => {
754
718
  return await transport.respond(req, {
755
719
  request: req,
756
- format: context?.format ?? options.format ?? "markdown",
757
720
  manifestProvider: context?.manifestProvider ?? options.manifestProvider,
758
721
  onListAllDocumentation: context?.onListAllDocumentation ?? options.onListAllDocumentation,
759
722
  onGetDocumentation: context?.onGetDocumentation ?? options.onGetDocumentation
@@ -762,4 +725,4 @@ const createStorybookMcpHandler = async (options = {}) => {
762
725
  };
763
726
 
764
727
  //#endregion
765
- export { COMPONENT_MANIFEST_PATH, DOCS_MANIFEST_PATH, GET_STORY_TOOL_NAME, GET_TOOL_NAME, LIST_TOOL_NAME, addGetStoryDocumentationTool as addGetComponentStoryDocumentationTool, addGetDocumentationTool, addListAllDocumentationTool, createStorybookMcpHandler };
728
+ export { COMPONENT_MANIFEST_PATH, ComponentManifestMap, DOCS_MANIFEST_PATH, DocsManifestMap, GET_STORY_TOOL_NAME, GET_TOOL_NAME, LIST_TOOL_NAME, addGetStoryDocumentationTool as addGetComponentStoryDocumentationTool, addGetDocumentationTool, addListAllDocumentationTool, createStorybookMcpHandler, getMultiSourceManifests };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@storybook/mcp",
3
- "version": "0.2.2",
3
+ "version": "0.3.0",
4
4
  "description": "MCP server that serves knowledge about your components based on your Storybook stories and documentation",
5
5
  "keywords": [
6
6
  "mcp",