@storybook/mcp 0.0.6 → 0.1.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 +65 -32
  2. package/dist/index.js +245 -115
  3. package/package.json +8 -13
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
14
  interface StorybookContext extends Record<string, unknown> {
12
15
  /**
13
- * The URL of the remote manifest to get component data from.
16
+ * The incoming HTTP request being processed.
14
17
  */
15
- source?: string;
18
+ request?: Request;
19
+ /**
20
+ * Output format for component manifests.
21
+ * @default 'markdown'
22
+ */
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,51 +41,66 @@ 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
- readonly summary: v.ExactOptionalSchema<v.StringSchema<undefined>, undefined>;
46
- readonly examples: v.ExactOptionalSchema<v.ArraySchema<v.ObjectSchema<{
47
- readonly snippet: v.StringSchema<undefined>;
56
+ readonly path: v.StringSchema<undefined>;
57
+ readonly summary: v.OptionalSchema<v.StringSchema<undefined>, undefined>;
58
+ readonly import: v.OptionalSchema<v.StringSchema<undefined>, undefined>;
59
+ readonly stories: v.OptionalSchema<v.ArraySchema<v.ObjectSchema<{
60
+ readonly snippet: v.OptionalSchema<v.StringSchema<undefined>, undefined>;
48
61
  readonly name: v.StringSchema<undefined>;
49
- readonly description: v.ExactOptionalSchema<v.StringSchema<undefined>, undefined>;
50
- readonly import: v.ExactOptionalSchema<v.StringSchema<undefined>, undefined>;
51
- readonly jsDocTags: v.ExactOptionalSchema<v.RecordSchema<v.StringSchema<undefined>, v.ArraySchema<v.StringSchema<undefined>, undefined>, undefined>, undefined>;
62
+ readonly description: v.OptionalSchema<v.StringSchema<undefined>, undefined>;
63
+ readonly jsDocTags: v.OptionalSchema<v.RecordSchema<v.StringSchema<undefined>, v.ArraySchema<v.StringSchema<undefined>, undefined>, undefined>, undefined>;
64
+ readonly error: v.OptionalSchema<v.ObjectSchema<{
65
+ readonly name: v.StringSchema<undefined>;
66
+ readonly message: v.StringSchema<undefined>;
67
+ }, undefined>, undefined>;
52
68
  }, undefined>, undefined>, undefined>;
53
- readonly reactDocgen: v.ExactOptionalSchema<v.CustomSchema<Documentation, undefined>, undefined>;
69
+ readonly reactDocgen: v.OptionalSchema<v.CustomSchema<Documentation, undefined>, undefined>;
54
70
  readonly name: v.StringSchema<undefined>;
55
- readonly description: v.ExactOptionalSchema<v.StringSchema<undefined>, undefined>;
56
- readonly import: v.ExactOptionalSchema<v.StringSchema<undefined>, undefined>;
57
- readonly jsDocTags: v.ExactOptionalSchema<v.RecordSchema<v.StringSchema<undefined>, v.ArraySchema<v.StringSchema<undefined>, undefined>, undefined>, undefined>;
71
+ readonly description: v.OptionalSchema<v.StringSchema<undefined>, undefined>;
72
+ readonly jsDocTags: v.OptionalSchema<v.RecordSchema<v.StringSchema<undefined>, v.ArraySchema<v.StringSchema<undefined>, undefined>, undefined>, undefined>;
73
+ readonly error: v.OptionalSchema<v.ObjectSchema<{
74
+ readonly name: v.StringSchema<undefined>;
75
+ readonly message: v.StringSchema<undefined>;
76
+ }, undefined>, undefined>;
58
77
  }, undefined>;
59
78
  type ComponentManifest = v.InferOutput<typeof ComponentManifest>;
60
79
  declare const ComponentManifestMap: v.ObjectSchema<{
61
80
  readonly v: v.NumberSchema<undefined>;
62
81
  readonly components: v.RecordSchema<v.StringSchema<undefined>, v.ObjectSchema<{
63
82
  readonly id: v.StringSchema<undefined>;
64
- readonly summary: v.ExactOptionalSchema<v.StringSchema<undefined>, undefined>;
65
- readonly examples: v.ExactOptionalSchema<v.ArraySchema<v.ObjectSchema<{
66
- readonly snippet: v.StringSchema<undefined>;
83
+ readonly path: v.StringSchema<undefined>;
84
+ readonly summary: v.OptionalSchema<v.StringSchema<undefined>, undefined>;
85
+ readonly import: v.OptionalSchema<v.StringSchema<undefined>, undefined>;
86
+ readonly stories: v.OptionalSchema<v.ArraySchema<v.ObjectSchema<{
87
+ readonly snippet: v.OptionalSchema<v.StringSchema<undefined>, undefined>;
67
88
  readonly name: v.StringSchema<undefined>;
68
- readonly description: v.ExactOptionalSchema<v.StringSchema<undefined>, undefined>;
69
- readonly import: v.ExactOptionalSchema<v.StringSchema<undefined>, undefined>;
70
- readonly jsDocTags: v.ExactOptionalSchema<v.RecordSchema<v.StringSchema<undefined>, v.ArraySchema<v.StringSchema<undefined>, undefined>, undefined>, undefined>;
89
+ readonly description: v.OptionalSchema<v.StringSchema<undefined>, undefined>;
90
+ readonly jsDocTags: v.OptionalSchema<v.RecordSchema<v.StringSchema<undefined>, v.ArraySchema<v.StringSchema<undefined>, undefined>, undefined>, undefined>;
91
+ readonly error: v.OptionalSchema<v.ObjectSchema<{
92
+ readonly name: v.StringSchema<undefined>;
93
+ readonly message: v.StringSchema<undefined>;
94
+ }, undefined>, undefined>;
71
95
  }, undefined>, undefined>, undefined>;
72
- readonly reactDocgen: v.ExactOptionalSchema<v.CustomSchema<Documentation, undefined>, undefined>;
96
+ readonly reactDocgen: v.OptionalSchema<v.CustomSchema<Documentation, undefined>, undefined>;
73
97
  readonly name: v.StringSchema<undefined>;
74
- readonly description: v.ExactOptionalSchema<v.StringSchema<undefined>, undefined>;
75
- readonly import: v.ExactOptionalSchema<v.StringSchema<undefined>, undefined>;
76
- readonly jsDocTags: v.ExactOptionalSchema<v.RecordSchema<v.StringSchema<undefined>, v.ArraySchema<v.StringSchema<undefined>, undefined>, undefined>, undefined>;
98
+ readonly description: v.OptionalSchema<v.StringSchema<undefined>, undefined>;
99
+ readonly jsDocTags: v.OptionalSchema<v.RecordSchema<v.StringSchema<undefined>, v.ArraySchema<v.StringSchema<undefined>, undefined>, undefined>, undefined>;
100
+ readonly error: v.OptionalSchema<v.ObjectSchema<{
101
+ readonly name: v.StringSchema<undefined>;
102
+ readonly message: v.StringSchema<undefined>;
103
+ }, undefined>, undefined>;
77
104
  }, undefined>, undefined>;
78
105
  }, undefined>;
79
106
  type ComponentManifestMap = v.InferOutput<typeof ComponentManifestMap>;
@@ -86,6 +113,12 @@ declare function addListAllComponentsTool(server: McpServer<any, StorybookContex
86
113
  declare const GET_TOOL_NAME = "get-component-documentation";
87
114
  declare function addGetComponentDocumentationTool(server: McpServer<any, StorybookContext>, enabled?: Parameters<McpServer<any, StorybookContext>['tool']>[0]['enabled']): Promise<void>;
88
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
89
122
  //#region src/index.d.ts
90
123
  type InitializeRequestParams = {
91
124
  protocolVersion: string;
@@ -124,4 +157,4 @@ interface StorybookMcpHandlerOptions extends StorybookContext {
124
157
  type Handler = (req: Request, context?: StorybookContext) => Promise<Response>;
125
158
  declare const createStorybookMcpHandler: (options?: StorybookMcpHandlerOptions) => Promise<Handler>;
126
159
  //#endregion
127
- 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.6";
8
+ var version = "0.1.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
@@ -13,20 +13,25 @@ var description = "MCP server that serves knowledge about your components based
13
13
  const JSDocTag = v.record(v.string(), v.array(v.string()));
14
14
  const BaseManifest = v.object({
15
15
  name: v.string(),
16
- description: v.exactOptional(v.string()),
17
- import: v.exactOptional(v.string()),
18
- jsDocTags: v.exactOptional(JSDocTag)
16
+ description: v.optional(v.string()),
17
+ jsDocTags: v.optional(JSDocTag),
18
+ error: v.optional(v.object({
19
+ name: v.string(),
20
+ message: v.string()
21
+ }))
19
22
  });
20
- const Example = v.object({
23
+ const Story = v.object({
21
24
  ...BaseManifest.entries,
22
- snippet: v.string()
25
+ snippet: v.optional(v.string())
23
26
  });
24
27
  const ComponentManifest = v.object({
25
28
  ...BaseManifest.entries,
26
29
  id: v.string(),
27
- summary: v.exactOptional(v.string()),
28
- examples: v.exactOptional(v.array(Example)),
29
- reactDocgen: v.exactOptional(v.custom(() => true))
30
+ path: v.string(),
31
+ summary: v.optional(v.string()),
32
+ import: v.optional(v.string()),
33
+ stories: v.optional(v.array(Story)),
34
+ reactDocgen: v.optional(v.custom(() => true))
30
35
  });
31
36
  const ComponentManifestMap = v.object({
32
37
  v: v.number(),
@@ -36,6 +41,10 @@ const ComponentManifestMap = v.object({
36
41
  //#endregion
37
42
  //#region src/utils/get-manifest.ts
38
43
  /**
44
+ * The path to the component manifest file relative to the Storybook build
45
+ */
46
+ const MANIFEST_PATH = "./manifests/components.json";
47
+ /**
39
48
  * Error thrown when getting or parsing a manifest fails
40
49
  */
41
50
  var ManifestGetError = class extends Error {
@@ -69,31 +78,46 @@ const errorToMCPContent = (error) => {
69
78
  };
70
79
  };
71
80
  /**
72
- * 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
73
82
  *
74
- * @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)
75
84
  * @param manifestProvider - Optional custom function to get the manifest
76
85
  * @returns A promise that resolves to the parsed ComponentManifestMap
77
86
  * @throws {ManifestGetError} If getting the manifest fails or the response is invalid
78
87
  */
79
- async function getManifest(url, manifestProvider) {
88
+ async function getManifest(request, manifestProvider) {
80
89
  try {
81
- 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");
82
- const manifestString = await (manifestProvider ?? defaultFetchManifestProvider)(url);
90
+ const manifestString = await (manifestProvider ?? defaultManifestProvider)(request, MANIFEST_PATH);
83
91
  const manifestData = JSON.parse(manifestString);
84
92
  const manifest = v.parse(ComponentManifestMap, manifestData);
85
- 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");
86
94
  return manifest;
87
95
  } catch (error) {
88
96
  if (error instanceof ManifestGetError) throw error;
97
+ const url = request ? getManifestUrlFromRequest(request, MANIFEST_PATH) : "Unknown manifest source";
89
98
  throw new ManifestGetError(`Failed to get manifest: ${error instanceof Error ? error.message : String(error)}`, url, error instanceof Error ? error : void 0);
90
99
  }
91
100
  }
92
- async function defaultFetchManifestProvider(source) {
93
- const response = await fetch(source);
94
- 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);
95
119
  const contentType = response.headers.get("content-type");
96
- 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);
97
121
  return response.text();
98
122
  }
99
123
 
@@ -101,7 +125,7 @@ async function defaultFetchManifestProvider(source) {
101
125
  //#region src/utils/dedent.ts
102
126
  function dedent(templ, ...values) {
103
127
  let strings = Array.from(typeof templ === "string" ? [templ] : templ);
104
- strings[strings.length - 1] = strings[strings.length - 1].replace(/\r?\n([\t ]*)$/, "");
128
+ strings[strings.length - 1] = strings.at(-1).replace(/\r?\n([\t ]*)$/, "");
105
129
  const indentLengths = strings.reduce((arr, str) => {
106
130
  const matches = str.match(/\n([\t ]+|(?!\s).)/g);
107
131
  if (matches) return arr.concat(matches.map((match) => match.match(/[\t ]/g)?.length ?? 0));
@@ -120,7 +144,7 @@ function dedent(templ, ...values) {
120
144
  if (typeof value === "string" && value.includes("\n")) indentedValue = String(value).split("\n").map((str, i$1) => {
121
145
  return i$1 === 0 ? str : `${endentation}${str}`;
122
146
  }).join("\n");
123
- string += indentedValue + strings[i + 1];
147
+ string += `${indentedValue}${strings[i + 1]}`;
124
148
  });
125
149
  return string;
126
150
  }
@@ -174,68 +198,185 @@ const parseReactDocgen = (reactDocgen) => {
174
198
  };
175
199
 
176
200
  //#endregion
177
- //#region src/utils/format-manifest.ts
178
- function formatComponentManifest(componentManifest) {
179
- const parts = [];
180
- parts.push(dedent`<component>
181
- <id>${componentManifest.id}</id>
182
- <name>${componentManifest.name}</name>`);
183
- if (componentManifest.description) parts.push(dedent`<description>
184
- ${componentManifest.description}
185
- </description>`);
186
- if (componentManifest.examples && componentManifest.examples.length > 0) for (const example of componentManifest.examples) {
187
- const exampleParts = [];
188
- exampleParts.push(dedent`<example>
189
- <example_name>${example.name.replace(/([A-Z])/g, " $1").trim()}</example_name>`);
190
- if (example.description) exampleParts.push(dedent`<example_description>
191
- ${example.description}
192
- </example_description>`);
193
- exampleParts.push("<example_code>");
194
- const importStatement = example.import || componentManifest.import;
195
- if (importStatement) exampleParts.push(`${importStatement}\n`);
196
- exampleParts.push(dedent`${example.snippet}
197
- </example_code>
198
- </example>`);
199
- parts.push(exampleParts.join("\n"));
200
- }
201
- if (componentManifest.reactDocgen) {
202
- const parsedDocgen = parseReactDocgen(componentManifest.reactDocgen);
203
- const propEntries = Object.entries(parsedDocgen.props);
204
- if (propEntries.length > 0) {
205
- parts.push("<props>");
206
- for (const [propName, propInfo] of propEntries) {
207
- parts.push(dedent`<prop>
208
- <prop_name>${propName}</prop_name>`);
209
- if (propInfo.description !== void 0) parts.push(dedent`<prop_description>
210
- ${propInfo.description}
211
- </prop_description>`);
212
- if (propInfo.type !== void 0) parts.push(dedent`<prop_type>${propInfo.type}</prop_type>`);
213
- if (propInfo.required !== void 0) parts.push(dedent`<prop_required>${propInfo.required}</prop_required>`);
214
- if (propInfo.defaultValue !== void 0) parts.push(dedent`<prop_default>${propInfo.defaultValue}</prop_default>`);
215
- parts.push("</prop>");
201
+ //#region src/utils/manifest-formatter/xml.ts
202
+ const MAX_SUMMARY_LENGTH$1 = 90;
203
+ /**
204
+ * XML formatter for component manifests.
205
+ * Formats component data into XML structure with tags like <component>, <props>, etc.
206
+ */
207
+ const xmlFormatter = {
208
+ formatComponentManifest(componentManifest) {
209
+ const parts = [];
210
+ parts.push(dedent`<component>
211
+ <id>${componentManifest.id}</id>
212
+ <name>${componentManifest.name}</name>`);
213
+ if (componentManifest.description) parts.push(dedent`<description>
214
+ ${componentManifest.description}
215
+ </description>`);
216
+ if (componentManifest.stories && componentManifest.stories.length > 0) for (const story of componentManifest.stories) {
217
+ if (!story.snippet) continue;
218
+ const storyParts = [];
219
+ storyParts.push(dedent`<story>
220
+ <story_name>${story.name.replace(/([A-Z])/g, " $1").trim()}</story_name>`);
221
+ if (story.description) storyParts.push(dedent`<story_description>
222
+ ${story.description}
223
+ </story_description>`);
224
+ storyParts.push("<story_code>");
225
+ if (componentManifest.import) storyParts.push(`${componentManifest.import}\n`);
226
+ storyParts.push(dedent`${story.snippet}
227
+ </story_code>
228
+ </story>`);
229
+ parts.push(storyParts.join("\n"));
230
+ }
231
+ if (componentManifest.reactDocgen) {
232
+ const parsedDocgen = parseReactDocgen(componentManifest.reactDocgen);
233
+ const propEntries = Object.entries(parsedDocgen.props);
234
+ if (propEntries.length > 0) {
235
+ parts.push("<props>");
236
+ for (const [propName, propInfo] of propEntries) {
237
+ parts.push(dedent`<prop>
238
+ <prop_name>${propName}</prop_name>`);
239
+ if (propInfo.description !== void 0) parts.push(dedent`<prop_description>
240
+ ${propInfo.description}
241
+ </prop_description>`);
242
+ if (propInfo.type !== void 0) parts.push(dedent`<prop_type>${propInfo.type}</prop_type>`);
243
+ if (propInfo.required !== void 0) parts.push(dedent`<prop_required>${propInfo.required}</prop_required>`);
244
+ if (propInfo.defaultValue !== void 0) parts.push(dedent`<prop_default>${propInfo.defaultValue}</prop_default>`);
245
+ parts.push("</prop>");
246
+ }
247
+ parts.push("</props>");
216
248
  }
217
- parts.push("</props>");
218
249
  }
250
+ parts.push("</component>");
251
+ return parts.join("\n");
252
+ },
253
+ formatComponentManifestMapToList(manifest) {
254
+ const parts = [];
255
+ parts.push("<components>");
256
+ for (const component of Object.values(manifest.components)) {
257
+ parts.push(dedent`<component>
258
+ <id>${component.id}</id>
259
+ <name>${component.name}</name>`);
260
+ 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);
261
+ if (summary) parts.push(dedent`<summary>
262
+ ${summary}
263
+ </summary>`);
264
+ parts.push("</component>");
265
+ }
266
+ parts.push("</components>");
267
+ return parts.join("\n");
219
268
  }
220
- parts.push("</component>");
221
- return parts.join("\n");
222
- }
269
+ };
270
+
271
+ //#endregion
272
+ //#region src/utils/manifest-formatter/markdown.ts
223
273
  const MAX_SUMMARY_LENGTH = 90;
224
- function formatComponentManifestMapToList(manifest) {
225
- const parts = [];
226
- parts.push("<components>");
227
- for (const component of Object.values(manifest.components)) {
228
- parts.push(dedent`<component>
229
- <id>${component.id}</id>
230
- <name>${component.name}</name>`);
231
- const summary = component.summary ?? (component.description ? component.description.length > MAX_SUMMARY_LENGTH ? `${component.description.slice(0, MAX_SUMMARY_LENGTH)}...` : component.description : void 0);
232
- if (summary) parts.push(dedent`<summary>
233
- ${summary}
234
- </summary>`);
235
- parts.push("</component>");
274
+ /**
275
+ * Markdown formatter for component manifests.
276
+ * Formats component data into token-efficient markdown with headers, lists, and tables.
277
+ * Uses adaptive formatting based on prop complexity to optimize token usage.
278
+ */
279
+ const markdownFormatter = {
280
+ formatComponentManifest(componentManifest) {
281
+ const parts = [];
282
+ parts.push(`# ${componentManifest.name}`);
283
+ parts.push("");
284
+ parts.push(`ID: ${componentManifest.id}`);
285
+ parts.push("");
286
+ if (componentManifest.description) {
287
+ parts.push(componentManifest.description);
288
+ parts.push("");
289
+ }
290
+ if (componentManifest.stories && componentManifest.stories.length > 0) {
291
+ parts.push("## Stories");
292
+ parts.push("");
293
+ for (const story of componentManifest.stories) {
294
+ if (!story.snippet) continue;
295
+ const storyName = story.name.replace(/([A-Z])/g, " $1").trim();
296
+ parts.push(`### ${storyName}`);
297
+ if (story.description) {
298
+ parts.push("");
299
+ parts.push(story.description);
300
+ }
301
+ parts.push("");
302
+ parts.push("```");
303
+ if (componentManifest.import) {
304
+ parts.push(componentManifest.import);
305
+ parts.push("");
306
+ }
307
+ parts.push(story.snippet);
308
+ parts.push("```");
309
+ parts.push("");
310
+ }
311
+ }
312
+ if (componentManifest.reactDocgen) {
313
+ const parsedDocgen = parseReactDocgen(componentManifest.reactDocgen);
314
+ const propEntries = Object.entries(parsedDocgen.props);
315
+ if (propEntries.length > 0) {
316
+ parts.push("## Props");
317
+ parts.push("");
318
+ parts.push("```");
319
+ parts.push("export type Props = {");
320
+ for (const [propName, propInfo] of propEntries) {
321
+ const type = propInfo.type ?? "any";
322
+ const isRequired = propInfo.required ?? true;
323
+ const hasDefault = propInfo.defaultValue !== void 0;
324
+ if (propInfo.description !== void 0) {
325
+ parts.push(" /**");
326
+ parts.push(` ${propInfo.description}`);
327
+ parts.push(" */");
328
+ }
329
+ let propLine = ` ${propName}`;
330
+ if (!isRequired) propLine += "?";
331
+ propLine += `: ${type}`;
332
+ if (hasDefault) propLine += ` = ${propInfo.defaultValue}`;
333
+ propLine += ";";
334
+ parts.push(propLine);
335
+ }
336
+ parts.push("}");
337
+ parts.push("```");
338
+ parts.push("");
339
+ }
340
+ }
341
+ return parts.join("\n").trim();
342
+ },
343
+ formatComponentManifestMapToList(manifest) {
344
+ const parts = [];
345
+ parts.push("# Components");
346
+ parts.push("");
347
+ for (const component of Object.values(manifest.components)) {
348
+ const summary = component.summary ?? (component.description ? component.description.length > MAX_SUMMARY_LENGTH ? `${component.description.slice(0, MAX_SUMMARY_LENGTH)}...` : component.description : void 0);
349
+ if (summary) parts.push(`- ${component.name} (${component.id}): ${summary}`);
350
+ else parts.push(`- ${component.name} (${component.id})`);
351
+ }
352
+ parts.push("");
353
+ return parts.join("\n").trim();
236
354
  }
237
- parts.push("</components>");
238
- return parts.join("\n");
355
+ };
356
+
357
+ //#endregion
358
+ //#region src/utils/format-manifest.ts
359
+ const formatters = {
360
+ xml: xmlFormatter,
361
+ markdown: markdownFormatter
362
+ };
363
+ /**
364
+ * Format a single component manifest.
365
+ * @param componentManifest - The component manifest to format
366
+ * @param format - The desired output format (defaults to 'markdown')
367
+ * @returns Formatted string representation of the component
368
+ */
369
+ function formatComponentManifest(componentManifest, format = "markdown") {
370
+ return formatters[format].formatComponentManifest(componentManifest);
371
+ }
372
+ /**
373
+ * Format a component manifest map into a list.
374
+ * @param manifest - The component manifest map to format
375
+ * @param format - The desired output format (defaults to 'markdown')
376
+ * @returns Formatted string representation of the component list
377
+ */
378
+ function formatComponentManifestMapToList(manifest, format = "markdown") {
379
+ return formatters[format].formatComponentManifestMapToList(manifest);
239
380
  }
240
381
 
241
382
  //#endregion
@@ -249,8 +390,8 @@ async function addListAllComponentsTool(server, enabled) {
249
390
  enabled
250
391
  }, async () => {
251
392
  try {
252
- const manifest = await getManifest(server.ctx.custom?.source, server.ctx.custom?.manifestProvider);
253
- const componentList = formatComponentManifestMapToList(manifest);
393
+ const manifest = await getManifest(server.ctx.custom?.request, server.ctx.custom?.manifestProvider);
394
+ const componentList = formatComponentManifestMapToList(manifest, server.ctx.custom?.format ?? "markdown");
254
395
  await server.ctx.custom?.onListAllComponents?.({
255
396
  context: server.ctx.custom,
256
397
  manifest
@@ -268,51 +409,39 @@ async function addListAllComponentsTool(server, enabled) {
268
409
  //#endregion
269
410
  //#region src/tools/get-component-documentation.ts
270
411
  const GET_TOOL_NAME = "get-component-documentation";
271
- const GetComponentDocumentationInput = v.object({ componentIds: v.pipe(v.array(v.string()), v.minLength(1, "At least one component ID is required")) });
412
+ const GetComponentDocumentationInput = v.object({ componentId: v.string() });
272
413
  async function addGetComponentDocumentationTool(server, enabled) {
273
414
  server.tool({
274
415
  name: GET_TOOL_NAME,
275
- title: "Get Documentation for Components",
276
- description: "Get detailed documentation for specific UI components",
416
+ title: "Get Documentation for Component",
417
+ description: "Get detailed documentation for a specific UI component",
277
418
  schema: GetComponentDocumentationInput,
278
419
  enabled
279
420
  }, async (input) => {
280
421
  try {
281
- const manifest = await getManifest(server.ctx.custom?.source, server.ctx.custom?.manifestProvider);
282
- const content = [];
283
- const notFoundIds = [];
284
- const foundComponents = [];
285
- for (const componentId of input.componentIds) {
286
- const component = manifest.components[componentId];
287
- if (!component) {
288
- notFoundIds.push(componentId);
289
- continue;
290
- }
291
- foundComponents.push(component);
292
- content.push({
293
- type: "text",
294
- text: formatComponentManifest(component)
295
- });
296
- }
297
- const allNotFound = notFoundIds.length === input.componentIds.length;
298
- if (notFoundIds.length > 0) {
299
- const componentWord = notFoundIds.length > 1 ? "Components" : "Component";
300
- const severity = allNotFound ? "Error" : "Warning";
301
- content.push({
302
- type: "text",
303
- text: `${severity}: ${componentWord} not found: ${notFoundIds.join(", ")}`
422
+ const component = (await getManifest(server.ctx.custom?.request, server.ctx.custom?.manifestProvider)).components[input.componentId];
423
+ if (!component) {
424
+ await server.ctx.custom?.onGetComponentDocumentation?.({
425
+ context: server.ctx.custom,
426
+ input: { componentId: input.componentId }
304
427
  });
428
+ return {
429
+ content: [{
430
+ type: "text",
431
+ text: `Component not found: "${input.componentId}". Use the list-all-components tool to see available components.`
432
+ }],
433
+ isError: true
434
+ };
305
435
  }
306
436
  await server.ctx.custom?.onGetComponentDocumentation?.({
307
437
  context: server.ctx.custom,
308
- input: { componentIds: input.componentIds },
309
- foundComponents,
310
- notFoundIds
438
+ input: { componentId: input.componentId },
439
+ foundComponent: component
311
440
  });
312
- return {
313
- content,
314
- ...allNotFound && { isError: true }
315
- };
441
+ return { content: [{
442
+ type: "text",
443
+ text: formatComponentManifest(component, server.ctx.custom?.format ?? "markdown")
444
+ }] };
316
445
  } catch (error) {
317
446
  return errorToMCPContent(error);
318
447
  }
@@ -337,7 +466,8 @@ const createStorybookMcpHandler = async (options = {}) => {
337
466
  const transport = new HttpTransport(server, { path: null });
338
467
  return (async (req, context) => {
339
468
  return await transport.respond(req, {
340
- source: context?.source ?? options.source,
469
+ request: req,
470
+ format: context?.format ?? options.format ?? "markdown",
341
471
  manifestProvider: context?.manifestProvider ?? options.manifestProvider,
342
472
  onListAllComponents: context?.onListAllComponents ?? options.onListAllComponents,
343
473
  onGetComponentDocumentation: context?.onGetComponentDocumentation ?? options.onGetComponentDocumentation
@@ -346,4 +476,4 @@ const createStorybookMcpHandler = async (options = {}) => {
346
476
  };
347
477
 
348
478
  //#endregion
349
- export { GET_TOOL_NAME, LIST_TOOL_NAME, addGetComponentDocumentationTool, addListAllComponentsTool, createStorybookMcpHandler };
479
+ 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.6",
3
+ "version": "0.1.0",
4
4
  "description": "MCP server that serves knowledge about your components based on your Storybook stories and documentation",
5
5
  "keywords": [
6
6
  "storybook",
@@ -8,8 +8,7 @@
8
8
  ],
9
9
  "homepage": "https://github.com/storybookjs/mcp/blob/main/packages/mcp/README.md",
10
10
  "repository": {
11
- "type": "git",
12
- "url": "https://github.com/storybookjs/mcp.git",
11
+ "url": "git+https://github.com/storybookjs/mcp.git",
13
12
  "directory": "packages/mcp"
14
13
  },
15
14
  "license": "MIT",
@@ -29,24 +28,20 @@
29
28
  "@tmcp/adapter-valibot": "^0.1.4",
30
29
  "@tmcp/transport-http": "^0.8.0",
31
30
  "tmcp": "^1.16.0",
32
- "valibot": "^1.1.0"
31
+ "valibot": "1.1.0"
33
32
  },
34
33
  "devDependencies": {
35
- "@tsconfig/node-ts": "^23.6.1",
36
- "@tsconfig/node24": "^24.0.1",
37
- "@types/node": "20.19.0",
38
- "@vitest/coverage-v8": "3.2.4",
34
+ "@tmcp/transport-stdio": "^0.4.1",
39
35
  "react-docgen": "^8.0.2",
40
36
  "srvx": "^0.8.16",
41
- "tsdown": "^0.15.9",
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
- "test": "vitest",
49
42
  "inspect": "mcp-inspector --config ../../.mcp.inspect.json --server storybook-mcp",
50
- "typecheck": "tsc --noEmit"
43
+ "publint": "publint",
44
+ "test": "cd ../.. && pnpm vitest --project=@storybook/mcp",
45
+ "typecheck": "tsc"
51
46
  }
52
47
  }