@storybook/mcp 0.0.7-next.0 → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/dist/index.d.ts +33 -18
  2. package/dist/index.js +244 -109
  3. package/package.json +6 -12
package/dist/index.d.ts CHANGED
@@ -3,22 +3,34 @@ import * as v from "valibot";
3
3
  import { Documentation } from "react-docgen";
4
4
 
5
5
  //#region src/types.d.ts
6
-
6
+ /**
7
+ * Supported output formats for component manifest formatting.
8
+ */
9
+ type OutputFormat = 'xml' | 'markdown';
7
10
  /**
8
11
  * Custom context passed to MCP server and tools.
9
- * Contains the source URL for getting component manifests.
12
+ * Contains the request object and optional manifest provider.
10
13
  */
11
- interface StorybookContext extends Record<string, unknown> {
14
+ type StorybookContext = {
15
+ /**
16
+ * The incoming HTTP request being processed.
17
+ */
18
+ request?: Request;
12
19
  /**
13
- * The URL of the remote manifest to get component data from.
20
+ * Output format for component manifests.
21
+ * @default 'markdown'
14
22
  */
15
- source?: string;
23
+ format?: OutputFormat;
16
24
  /**
17
25
  * Optional function to provide custom manifest retrieval logic.
18
- * If provided, this function will be called instead of using fetch.
19
- * The function receives the source URL and should return the manifest as a string.
26
+ * 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.
29
+ * The default provider requires a request object and constructs the manifest URL from the request origin,
30
+ * replacing /mcp with /manifests/components.json.
31
+ * Custom providers can use the request parameter to determine the manifest source, or ignore it entirely.
20
32
  */
21
- manifestProvider?: (source: string) => Promise<string>;
33
+ manifestProvider?: (request: Request | undefined, path: string) => Promise<string>;
22
34
  /**
23
35
  * Optional handler called when list-all-components tool is invoked.
24
36
  * Receives the context and the component manifest.
@@ -29,26 +41,25 @@ interface StorybookContext extends Record<string, unknown> {
29
41
  }) => void | Promise<void>;
30
42
  /**
31
43
  * Optional handler called when get-component-documentation tool is invoked.
32
- * Receives the context, input parameters, and the found components.
44
+ * Receives the context, input parameters, and the found component (if any).
33
45
  */
34
46
  onGetComponentDocumentation?: (params: {
35
47
  context: StorybookContext;
36
48
  input: {
37
- componentIds: string[];
49
+ componentId: string;
38
50
  };
39
- foundComponents: ComponentManifest[];
40
- notFoundIds: string[];
51
+ foundComponent?: ComponentManifest;
41
52
  }) => void | Promise<void>;
42
- }
53
+ };
43
54
  declare const ComponentManifest: v.ObjectSchema<{
44
55
  readonly id: v.StringSchema<undefined>;
45
56
  readonly path: v.StringSchema<undefined>;
46
57
  readonly summary: v.OptionalSchema<v.StringSchema<undefined>, undefined>;
58
+ readonly import: v.OptionalSchema<v.StringSchema<undefined>, undefined>;
47
59
  readonly stories: v.OptionalSchema<v.ArraySchema<v.ObjectSchema<{
48
60
  readonly snippet: v.OptionalSchema<v.StringSchema<undefined>, undefined>;
49
61
  readonly name: v.StringSchema<undefined>;
50
62
  readonly description: v.OptionalSchema<v.StringSchema<undefined>, undefined>;
51
- readonly import: v.OptionalSchema<v.StringSchema<undefined>, undefined>;
52
63
  readonly jsDocTags: v.OptionalSchema<v.RecordSchema<v.StringSchema<undefined>, v.ArraySchema<v.StringSchema<undefined>, undefined>, undefined>, undefined>;
53
64
  readonly error: v.OptionalSchema<v.ObjectSchema<{
54
65
  readonly name: v.StringSchema<undefined>;
@@ -58,7 +69,6 @@ declare const ComponentManifest: v.ObjectSchema<{
58
69
  readonly reactDocgen: v.OptionalSchema<v.CustomSchema<Documentation, undefined>, undefined>;
59
70
  readonly name: v.StringSchema<undefined>;
60
71
  readonly description: v.OptionalSchema<v.StringSchema<undefined>, undefined>;
61
- readonly import: v.OptionalSchema<v.StringSchema<undefined>, undefined>;
62
72
  readonly jsDocTags: v.OptionalSchema<v.RecordSchema<v.StringSchema<undefined>, v.ArraySchema<v.StringSchema<undefined>, undefined>, undefined>, undefined>;
63
73
  readonly error: v.OptionalSchema<v.ObjectSchema<{
64
74
  readonly name: v.StringSchema<undefined>;
@@ -72,11 +82,11 @@ declare const ComponentManifestMap: v.ObjectSchema<{
72
82
  readonly id: v.StringSchema<undefined>;
73
83
  readonly path: v.StringSchema<undefined>;
74
84
  readonly summary: v.OptionalSchema<v.StringSchema<undefined>, undefined>;
85
+ readonly import: v.OptionalSchema<v.StringSchema<undefined>, undefined>;
75
86
  readonly stories: v.OptionalSchema<v.ArraySchema<v.ObjectSchema<{
76
87
  readonly snippet: v.OptionalSchema<v.StringSchema<undefined>, undefined>;
77
88
  readonly name: v.StringSchema<undefined>;
78
89
  readonly description: v.OptionalSchema<v.StringSchema<undefined>, undefined>;
79
- readonly import: v.OptionalSchema<v.StringSchema<undefined>, undefined>;
80
90
  readonly jsDocTags: v.OptionalSchema<v.RecordSchema<v.StringSchema<undefined>, v.ArraySchema<v.StringSchema<undefined>, undefined>, undefined>, undefined>;
81
91
  readonly error: v.OptionalSchema<v.ObjectSchema<{
82
92
  readonly name: v.StringSchema<undefined>;
@@ -86,7 +96,6 @@ declare const ComponentManifestMap: v.ObjectSchema<{
86
96
  readonly reactDocgen: v.OptionalSchema<v.CustomSchema<Documentation, undefined>, undefined>;
87
97
  readonly name: v.StringSchema<undefined>;
88
98
  readonly description: v.OptionalSchema<v.StringSchema<undefined>, undefined>;
89
- readonly import: v.OptionalSchema<v.StringSchema<undefined>, undefined>;
90
99
  readonly jsDocTags: v.OptionalSchema<v.RecordSchema<v.StringSchema<undefined>, v.ArraySchema<v.StringSchema<undefined>, undefined>, undefined>, undefined>;
91
100
  readonly error: v.OptionalSchema<v.ObjectSchema<{
92
101
  readonly name: v.StringSchema<undefined>;
@@ -104,6 +113,12 @@ declare function addListAllComponentsTool(server: McpServer<any, StorybookContex
104
113
  declare const GET_TOOL_NAME = "get-component-documentation";
105
114
  declare function addGetComponentDocumentationTool(server: McpServer<any, StorybookContext>, enabled?: Parameters<McpServer<any, StorybookContext>['tool']>[0]['enabled']): Promise<void>;
106
115
  //#endregion
116
+ //#region src/utils/get-manifest.d.ts
117
+ /**
118
+ * The path to the component manifest file relative to the Storybook build
119
+ */
120
+ declare const MANIFEST_PATH = "./manifests/components.json";
121
+ //#endregion
107
122
  //#region src/index.d.ts
108
123
  type InitializeRequestParams = {
109
124
  protocolVersion: string;
@@ -142,4 +157,4 @@ interface StorybookMcpHandlerOptions extends StorybookContext {
142
157
  type Handler = (req: Request, context?: StorybookContext) => Promise<Response>;
143
158
  declare const createStorybookMcpHandler: (options?: StorybookMcpHandlerOptions) => Promise<Handler>;
144
159
  //#endregion
145
- export { type ComponentManifest, type ComponentManifestMap, GET_TOOL_NAME, LIST_TOOL_NAME, type StorybookContext, StorybookMcpHandlerOptions, addGetComponentDocumentationTool, addListAllComponentsTool, createStorybookMcpHandler };
160
+ export { type ComponentManifest, type ComponentManifestMap, GET_TOOL_NAME, LIST_TOOL_NAME, MANIFEST_PATH, type StorybookContext, StorybookMcpHandlerOptions, addGetComponentDocumentationTool, addListAllComponentsTool, createStorybookMcpHandler };
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.0.7-next.0";
8
+ var version = "0.1.1";
9
9
  var description = "MCP server that serves knowledge about your components based on your Storybook stories and documentation";
10
10
 
11
11
  //#endregion
@@ -14,7 +14,6 @@ const JSDocTag = v.record(v.string(), v.array(v.string()));
14
14
  const BaseManifest = v.object({
15
15
  name: v.string(),
16
16
  description: v.optional(v.string()),
17
- import: v.optional(v.string()),
18
17
  jsDocTags: v.optional(JSDocTag),
19
18
  error: v.optional(v.object({
20
19
  name: v.string(),
@@ -30,6 +29,7 @@ const ComponentManifest = v.object({
30
29
  id: v.string(),
31
30
  path: v.string(),
32
31
  summary: v.optional(v.string()),
32
+ import: v.optional(v.string()),
33
33
  stories: v.optional(v.array(Story)),
34
34
  reactDocgen: v.optional(v.custom(() => true))
35
35
  });
@@ -41,6 +41,10 @@ const ComponentManifestMap = v.object({
41
41
  //#endregion
42
42
  //#region src/utils/get-manifest.ts
43
43
  /**
44
+ * The path to the component manifest file relative to the Storybook build
45
+ */
46
+ const MANIFEST_PATH = "./manifests/components.json";
47
+ /**
44
48
  * Error thrown when getting or parsing a manifest fails
45
49
  */
46
50
  var ManifestGetError = class extends Error {
@@ -74,39 +78,65 @@ const errorToMCPContent = (error) => {
74
78
  };
75
79
  };
76
80
  /**
77
- * Gets a component manifest from a remote URL or using a custom provider
81
+ * Gets a component manifest from a request or using a custom provider
78
82
  *
79
- * @param url - The URL to get the manifest from
83
+ * @param request - The HTTP request to get the manifest for (optional when using custom manifestProvider)
80
84
  * @param manifestProvider - Optional custom function to get the manifest
81
85
  * @returns A promise that resolves to the parsed ComponentManifestMap
82
86
  * @throws {ManifestGetError} If getting the manifest fails or the response is invalid
83
87
  */
84
- async function getManifest(url, manifestProvider) {
88
+ async function getManifest(request, manifestProvider) {
85
89
  try {
86
- if (!url) throw new ManifestGetError("The source URL is required, but was not part of the request context nor was a default source for the server set");
87
- const manifestString = await (manifestProvider ?? defaultFetchManifestProvider)(url);
90
+ const manifestString = await (manifestProvider ?? defaultManifestProvider)(request, MANIFEST_PATH);
88
91
  const manifestData = JSON.parse(manifestString);
89
92
  const manifest = v.parse(ComponentManifestMap, manifestData);
90
- if (Object.keys(manifest.components).length === 0) throw new ManifestGetError(`No components found in the manifest`, url);
93
+ if (Object.keys(manifest.components).length === 0) throw new ManifestGetError(`No components found in the manifest`, request ? getManifestUrlFromRequest(request, MANIFEST_PATH) : "Unknown manifest source");
91
94
  return manifest;
92
95
  } catch (error) {
93
96
  if (error instanceof ManifestGetError) throw error;
97
+ const url = request ? getManifestUrlFromRequest(request, MANIFEST_PATH) : "Unknown manifest source";
94
98
  throw new ManifestGetError(`Failed to get manifest: ${error instanceof Error ? error.message : String(error)}`, url, error instanceof Error ? error : void 0);
95
99
  }
96
100
  }
97
- async function defaultFetchManifestProvider(source) {
98
- const response = await fetch(source);
99
- if (!response.ok) throw new ManifestGetError(`Failed to fetch manifest: ${response.status} ${response.statusText}`, source);
101
+ /**
102
+ * Constructs the manifest URL from a request by replacing /mcp with the provided path
103
+ */
104
+ function getManifestUrlFromRequest(request, path) {
105
+ const url = new URL(request.url);
106
+ const normalizedPath = path.replace(/^\.\//, "");
107
+ url.pathname = url.pathname.replace(/\/mcp\/?$/, `/${normalizedPath}`);
108
+ return url.toString();
109
+ }
110
+ /**
111
+ * Default manifest provider that fetches from the same origin as the request,
112
+ * replacing /mcp with the provided path
113
+ */
114
+ async function defaultManifestProvider(request, path) {
115
+ 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.");
116
+ const manifestUrl = getManifestUrlFromRequest(request, path);
117
+ const response = await fetch(manifestUrl);
118
+ if (!response.ok) throw new ManifestGetError(`Failed to fetch manifest: ${response.status} ${response.statusText}`, manifestUrl);
100
119
  const contentType = response.headers.get("content-type");
101
- if (!contentType?.includes("application/json")) throw new ManifestGetError(`Invalid content type: expected application/json, got ${contentType}`, source);
120
+ if (!contentType?.includes("application/json")) throw new ManifestGetError(`Invalid content type: expected application/json, got ${contentType}`, manifestUrl);
102
121
  return response.text();
103
122
  }
104
123
 
105
124
  //#endregion
106
125
  //#region src/utils/dedent.ts
126
+ /**
127
+ * Copied from https://github.com/tamino-martinius/node-ts-dedent/blob/18c4736c79806d7fe78bdaaaf5ae307b79f9574a/src/index.ts
128
+ *
129
+ * Rationale for vendoring instead of using the ts-dedent package:
130
+ * 1. The package has a broken ESM distribution - the IDE auto-imports as
131
+ * `import dedent from 'ts-dedent'` but that breaks at runtime, requiring
132
+ * manual changes to named imports. See:
133
+ * - https://github.com/tamino-martinius/node-ts-dedent/issues/42
134
+ * - https://github.com/tamino-martinius/node-ts-dedent/pull/41
135
+ * 2. Keeps bundle size smaller for such a simple utility (avoid "is-even" syndrome)
136
+ */
107
137
  function dedent(templ, ...values) {
108
138
  let strings = Array.from(typeof templ === "string" ? [templ] : templ);
109
- strings[strings.length - 1] = strings[strings.length - 1].replace(/\r?\n([\t ]*)$/, "");
139
+ strings[strings.length - 1] = strings.at(-1).replace(/\r?\n([\t ]*)$/, "");
110
140
  const indentLengths = strings.reduce((arr, str) => {
111
141
  const matches = str.match(/\n([\t ]+|(?!\s).)/g);
112
142
  if (matches) return arr.concat(matches.map((match) => match.match(/[\t ]/g)?.length ?? 0));
@@ -125,7 +155,7 @@ function dedent(templ, ...values) {
125
155
  if (typeof value === "string" && value.includes("\n")) indentedValue = String(value).split("\n").map((str, i$1) => {
126
156
  return i$1 === 0 ? str : `${endentation}${str}`;
127
157
  }).join("\n");
128
- string += indentedValue + strings[i + 1];
158
+ string += `${indentedValue}${strings[i + 1]}`;
129
159
  });
130
160
  return string;
131
161
  }
@@ -179,69 +209,185 @@ const parseReactDocgen = (reactDocgen) => {
179
209
  };
180
210
 
181
211
  //#endregion
182
- //#region src/utils/format-manifest.ts
183
- function formatComponentManifest(componentManifest) {
184
- const parts = [];
185
- parts.push(dedent`<component>
186
- <id>${componentManifest.id}</id>
187
- <name>${componentManifest.name}</name>`);
188
- if (componentManifest.description) parts.push(dedent`<description>
189
- ${componentManifest.description}
190
- </description>`);
191
- if (componentManifest.stories && componentManifest.stories.length > 0) for (const story of componentManifest.stories) {
192
- if (!story.snippet) continue;
193
- const storyParts = [];
194
- storyParts.push(dedent`<story>
195
- <story_name>${story.name.replace(/([A-Z])/g, " $1").trim()}</story_name>`);
196
- if (story.description) storyParts.push(dedent`<story_description>
197
- ${story.description}
198
- </story_description>`);
199
- storyParts.push("<story_code>");
200
- const importStatement = story.import || componentManifest.import;
201
- if (importStatement) storyParts.push(`${importStatement}\n`);
202
- storyParts.push(dedent`${story.snippet}
203
- </story_code>
204
- </story>`);
205
- parts.push(storyParts.join("\n"));
206
- }
207
- if (componentManifest.reactDocgen) {
208
- const parsedDocgen = parseReactDocgen(componentManifest.reactDocgen);
209
- const propEntries = Object.entries(parsedDocgen.props);
210
- if (propEntries.length > 0) {
211
- parts.push("<props>");
212
- for (const [propName, propInfo] of propEntries) {
213
- parts.push(dedent`<prop>
214
- <prop_name>${propName}</prop_name>`);
215
- if (propInfo.description !== void 0) parts.push(dedent`<prop_description>
216
- ${propInfo.description}
217
- </prop_description>`);
218
- if (propInfo.type !== void 0) parts.push(dedent`<prop_type>${propInfo.type}</prop_type>`);
219
- if (propInfo.required !== void 0) parts.push(dedent`<prop_required>${propInfo.required}</prop_required>`);
220
- if (propInfo.defaultValue !== void 0) parts.push(dedent`<prop_default>${propInfo.defaultValue}</prop_default>`);
221
- parts.push("</prop>");
212
+ //#region src/utils/manifest-formatter/xml.ts
213
+ const MAX_SUMMARY_LENGTH$1 = 90;
214
+ /**
215
+ * XML formatter for component manifests.
216
+ * Formats component data into XML structure with tags like <component>, <props>, etc.
217
+ */
218
+ const xmlFormatter = {
219
+ formatComponentManifest(componentManifest) {
220
+ const parts = [];
221
+ parts.push(dedent`<component>
222
+ <id>${componentManifest.id}</id>
223
+ <name>${componentManifest.name}</name>`);
224
+ if (componentManifest.description) parts.push(dedent`<description>
225
+ ${componentManifest.description}
226
+ </description>`);
227
+ if (componentManifest.stories && componentManifest.stories.length > 0) for (const story of componentManifest.stories) {
228
+ if (!story.snippet) continue;
229
+ const storyParts = [];
230
+ storyParts.push(dedent`<story>
231
+ <story_name>${story.name.replace(/([A-Z])/g, " $1").trim()}</story_name>`);
232
+ if (story.description) storyParts.push(dedent`<story_description>
233
+ ${story.description}
234
+ </story_description>`);
235
+ storyParts.push("<story_code>");
236
+ if (componentManifest.import) storyParts.push(`${componentManifest.import}\n`);
237
+ storyParts.push(dedent`${story.snippet}
238
+ </story_code>
239
+ </story>`);
240
+ parts.push(storyParts.join("\n"));
241
+ }
242
+ if (componentManifest.reactDocgen) {
243
+ const parsedDocgen = parseReactDocgen(componentManifest.reactDocgen);
244
+ const propEntries = Object.entries(parsedDocgen.props);
245
+ if (propEntries.length > 0) {
246
+ parts.push("<props>");
247
+ for (const [propName, propInfo] of propEntries) {
248
+ parts.push(dedent`<prop>
249
+ <prop_name>${propName}</prop_name>`);
250
+ if (propInfo.description !== void 0) parts.push(dedent`<prop_description>
251
+ ${propInfo.description}
252
+ </prop_description>`);
253
+ if (propInfo.type !== void 0) parts.push(dedent`<prop_type>${propInfo.type}</prop_type>`);
254
+ if (propInfo.required !== void 0) parts.push(dedent`<prop_required>${propInfo.required}</prop_required>`);
255
+ if (propInfo.defaultValue !== void 0) parts.push(dedent`<prop_default>${propInfo.defaultValue}</prop_default>`);
256
+ parts.push("</prop>");
257
+ }
258
+ parts.push("</props>");
222
259
  }
223
- parts.push("</props>");
224
260
  }
261
+ parts.push("</component>");
262
+ return parts.join("\n");
263
+ },
264
+ formatComponentManifestMapToList(manifest) {
265
+ const parts = [];
266
+ parts.push("<components>");
267
+ for (const component of Object.values(manifest.components)) {
268
+ parts.push(dedent`<component>
269
+ <id>${component.id}</id>
270
+ <name>${component.name}</name>`);
271
+ const summary = component.summary ?? (component.description ? component.description.length > MAX_SUMMARY_LENGTH$1 ? `${component.description.slice(0, MAX_SUMMARY_LENGTH$1)}...` : component.description : void 0);
272
+ if (summary) parts.push(dedent`<summary>
273
+ ${summary}
274
+ </summary>`);
275
+ parts.push("</component>");
276
+ }
277
+ parts.push("</components>");
278
+ return parts.join("\n");
225
279
  }
226
- parts.push("</component>");
227
- return parts.join("\n");
228
- }
280
+ };
281
+
282
+ //#endregion
283
+ //#region src/utils/manifest-formatter/markdown.ts
229
284
  const MAX_SUMMARY_LENGTH = 90;
230
- function formatComponentManifestMapToList(manifest) {
231
- const parts = [];
232
- parts.push("<components>");
233
- for (const component of Object.values(manifest.components)) {
234
- parts.push(dedent`<component>
235
- <id>${component.id}</id>
236
- <name>${component.name}</name>`);
237
- const summary = component.summary ?? (component.description ? component.description.length > MAX_SUMMARY_LENGTH ? `${component.description.slice(0, MAX_SUMMARY_LENGTH)}...` : component.description : void 0);
238
- if (summary) parts.push(dedent`<summary>
239
- ${summary}
240
- </summary>`);
241
- parts.push("</component>");
285
+ /**
286
+ * Markdown formatter for component manifests.
287
+ * Formats component data into token-efficient markdown with headers, lists, and tables.
288
+ * Uses adaptive formatting based on prop complexity to optimize token usage.
289
+ */
290
+ const markdownFormatter = {
291
+ formatComponentManifest(componentManifest) {
292
+ const parts = [];
293
+ parts.push(`# ${componentManifest.name}`);
294
+ parts.push("");
295
+ parts.push(`ID: ${componentManifest.id}`);
296
+ parts.push("");
297
+ if (componentManifest.description) {
298
+ parts.push(componentManifest.description);
299
+ parts.push("");
300
+ }
301
+ if (componentManifest.stories && componentManifest.stories.length > 0) {
302
+ parts.push("## Stories");
303
+ parts.push("");
304
+ for (const story of componentManifest.stories) {
305
+ if (!story.snippet) continue;
306
+ const storyName = story.name.replace(/([A-Z])/g, " $1").trim();
307
+ parts.push(`### ${storyName}`);
308
+ if (story.description) {
309
+ parts.push("");
310
+ parts.push(story.description);
311
+ }
312
+ parts.push("");
313
+ parts.push("```");
314
+ if (componentManifest.import) {
315
+ parts.push(componentManifest.import);
316
+ parts.push("");
317
+ }
318
+ parts.push(story.snippet);
319
+ parts.push("```");
320
+ parts.push("");
321
+ }
322
+ }
323
+ if (componentManifest.reactDocgen) {
324
+ const parsedDocgen = parseReactDocgen(componentManifest.reactDocgen);
325
+ const propEntries = Object.entries(parsedDocgen.props);
326
+ if (propEntries.length > 0) {
327
+ parts.push("## Props");
328
+ parts.push("");
329
+ parts.push("```");
330
+ parts.push("export type Props = {");
331
+ for (const [propName, propInfo] of propEntries) {
332
+ const type = propInfo.type ?? "any";
333
+ const isRequired = propInfo.required ?? true;
334
+ const hasDefault = propInfo.defaultValue !== void 0;
335
+ if (propInfo.description !== void 0) {
336
+ parts.push(" /**");
337
+ parts.push(` ${propInfo.description}`);
338
+ parts.push(" */");
339
+ }
340
+ let propLine = ` ${propName}`;
341
+ if (!isRequired) propLine += "?";
342
+ propLine += `: ${type}`;
343
+ if (hasDefault) propLine += ` = ${propInfo.defaultValue}`;
344
+ propLine += ";";
345
+ parts.push(propLine);
346
+ }
347
+ parts.push("}");
348
+ parts.push("```");
349
+ parts.push("");
350
+ }
351
+ }
352
+ return parts.join("\n").trim();
353
+ },
354
+ formatComponentManifestMapToList(manifest) {
355
+ const parts = [];
356
+ parts.push("# Components");
357
+ parts.push("");
358
+ for (const component of Object.values(manifest.components)) {
359
+ const summary = component.summary ?? (component.description ? component.description.length > MAX_SUMMARY_LENGTH ? `${component.description.slice(0, MAX_SUMMARY_LENGTH)}...` : component.description : void 0);
360
+ if (summary) parts.push(`- ${component.name} (${component.id}): ${summary}`);
361
+ else parts.push(`- ${component.name} (${component.id})`);
362
+ }
363
+ parts.push("");
364
+ return parts.join("\n").trim();
242
365
  }
243
- parts.push("</components>");
244
- return parts.join("\n");
366
+ };
367
+
368
+ //#endregion
369
+ //#region src/utils/format-manifest.ts
370
+ const formatters = {
371
+ xml: xmlFormatter,
372
+ markdown: markdownFormatter
373
+ };
374
+ /**
375
+ * Format a single component manifest.
376
+ * @param componentManifest - The component manifest to format
377
+ * @param format - The desired output format (defaults to 'markdown')
378
+ * @returns Formatted string representation of the component
379
+ */
380
+ function formatComponentManifest(componentManifest, format = "markdown") {
381
+ return formatters[format].formatComponentManifest(componentManifest);
382
+ }
383
+ /**
384
+ * Format a component manifest map into a list.
385
+ * @param manifest - The component manifest map to format
386
+ * @param format - The desired output format (defaults to 'markdown')
387
+ * @returns Formatted string representation of the component list
388
+ */
389
+ function formatComponentManifestMapToList(manifest, format = "markdown") {
390
+ return formatters[format].formatComponentManifestMapToList(manifest);
245
391
  }
246
392
 
247
393
  //#endregion
@@ -255,8 +401,8 @@ async function addListAllComponentsTool(server, enabled) {
255
401
  enabled
256
402
  }, async () => {
257
403
  try {
258
- const manifest = await getManifest(server.ctx.custom?.source, server.ctx.custom?.manifestProvider);
259
- const componentList = formatComponentManifestMapToList(manifest);
404
+ const manifest = await getManifest(server.ctx.custom?.request, server.ctx.custom?.manifestProvider);
405
+ const componentList = formatComponentManifestMapToList(manifest, server.ctx.custom?.format ?? "markdown");
260
406
  await server.ctx.custom?.onListAllComponents?.({
261
407
  context: server.ctx.custom,
262
408
  manifest
@@ -274,51 +420,39 @@ async function addListAllComponentsTool(server, enabled) {
274
420
  //#endregion
275
421
  //#region src/tools/get-component-documentation.ts
276
422
  const GET_TOOL_NAME = "get-component-documentation";
277
- const GetComponentDocumentationInput = v.object({ componentIds: v.pipe(v.array(v.string()), v.minLength(1, "At least one component ID is required")) });
423
+ const GetComponentDocumentationInput = v.object({ componentId: v.string() });
278
424
  async function addGetComponentDocumentationTool(server, enabled) {
279
425
  server.tool({
280
426
  name: GET_TOOL_NAME,
281
- title: "Get Documentation for Components",
282
- description: "Get detailed documentation for specific UI components",
427
+ title: "Get Documentation for Component",
428
+ description: "Get detailed documentation for a specific UI component",
283
429
  schema: GetComponentDocumentationInput,
284
430
  enabled
285
431
  }, async (input) => {
286
432
  try {
287
- const manifest = await getManifest(server.ctx.custom?.source, server.ctx.custom?.manifestProvider);
288
- const content = [];
289
- const notFoundIds = [];
290
- const foundComponents = [];
291
- for (const componentId of input.componentIds) {
292
- const component = manifest.components[componentId];
293
- if (!component) {
294
- notFoundIds.push(componentId);
295
- continue;
296
- }
297
- foundComponents.push(component);
298
- content.push({
299
- type: "text",
300
- text: formatComponentManifest(component)
301
- });
302
- }
303
- const allNotFound = notFoundIds.length === input.componentIds.length;
304
- if (notFoundIds.length > 0) {
305
- const componentWord = notFoundIds.length > 1 ? "Components" : "Component";
306
- const severity = allNotFound ? "Error" : "Warning";
307
- content.push({
308
- type: "text",
309
- text: `${severity}: ${componentWord} not found: ${notFoundIds.join(", ")}`
433
+ const component = (await getManifest(server.ctx.custom?.request, server.ctx.custom?.manifestProvider)).components[input.componentId];
434
+ if (!component) {
435
+ await server.ctx.custom?.onGetComponentDocumentation?.({
436
+ context: server.ctx.custom,
437
+ input: { componentId: input.componentId }
310
438
  });
439
+ return {
440
+ content: [{
441
+ type: "text",
442
+ text: `Component not found: "${input.componentId}". Use the list-all-components tool to see available components.`
443
+ }],
444
+ isError: true
445
+ };
311
446
  }
312
447
  await server.ctx.custom?.onGetComponentDocumentation?.({
313
448
  context: server.ctx.custom,
314
- input: { componentIds: input.componentIds },
315
- foundComponents,
316
- notFoundIds
449
+ input: { componentId: input.componentId },
450
+ foundComponent: component
317
451
  });
318
- return {
319
- content,
320
- ...allNotFound && { isError: true }
321
- };
452
+ return { content: [{
453
+ type: "text",
454
+ text: formatComponentManifest(component, server.ctx.custom?.format ?? "markdown")
455
+ }] };
322
456
  } catch (error) {
323
457
  return errorToMCPContent(error);
324
458
  }
@@ -343,7 +477,8 @@ const createStorybookMcpHandler = async (options = {}) => {
343
477
  const transport = new HttpTransport(server, { path: null });
344
478
  return (async (req, context) => {
345
479
  return await transport.respond(req, {
346
- source: context?.source ?? options.source,
480
+ request: req,
481
+ format: context?.format ?? options.format ?? "markdown",
347
482
  manifestProvider: context?.manifestProvider ?? options.manifestProvider,
348
483
  onListAllComponents: context?.onListAllComponents ?? options.onListAllComponents,
349
484
  onGetComponentDocumentation: context?.onGetComponentDocumentation ?? options.onGetComponentDocumentation
@@ -352,4 +487,4 @@ const createStorybookMcpHandler = async (options = {}) => {
352
487
  };
353
488
 
354
489
  //#endregion
355
- export { GET_TOOL_NAME, LIST_TOOL_NAME, addGetComponentDocumentationTool, addListAllComponentsTool, createStorybookMcpHandler };
490
+ export { GET_TOOL_NAME, LIST_TOOL_NAME, MANIFEST_PATH, addGetComponentDocumentationTool, addListAllComponentsTool, createStorybookMcpHandler };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@storybook/mcp",
3
- "version": "0.0.7-next.0",
3
+ "version": "0.1.1",
4
4
  "description": "MCP server that serves knowledge about your components based on your Storybook stories and documentation",
5
5
  "keywords": [
6
6
  "storybook",
@@ -28,26 +28,20 @@
28
28
  "@tmcp/adapter-valibot": "^0.1.4",
29
29
  "@tmcp/transport-http": "^0.8.0",
30
30
  "tmcp": "^1.16.0",
31
- "valibot": "^1.1.0"
31
+ "valibot": "1.2.0"
32
32
  },
33
33
  "devDependencies": {
34
- "@tsconfig/node-ts": "^23.6.1",
35
- "@tsconfig/node24": "^24.0.1",
36
- "@types/node": "20.19.0",
37
- "@vitest/coverage-v8": "3.2.4",
38
- "publint": "0.3.15",
34
+ "@tmcp/transport-stdio": "^0.4.1",
39
35
  "react-docgen": "^8.0.2",
40
36
  "srvx": "^0.8.16",
41
- "tsdown": "^0.15.12",
42
- "typescript": "^5.9.3",
43
- "vitest": "3.2.4"
37
+ "tinyexec": "^1.0.2"
44
38
  },
45
39
  "scripts": {
46
40
  "build": "tsdown",
47
41
  "dev": "node --watch ./serve.ts",
48
42
  "inspect": "mcp-inspector --config ../../.mcp.inspect.json --server storybook-mcp",
49
43
  "publint": "publint",
50
- "test": "vitest",
51
- "typecheck": "tsc --noEmit"
44
+ "test": "cd ../.. && pnpm vitest --project=@storybook/mcp",
45
+ "typecheck": "tsc"
52
46
  }
53
47
  }