@storybook/mcp 0.0.2 → 0.0.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -1,27 +1,35 @@
1
+ import { McpServer } from "tmcp";
1
2
  import "valibot";
2
3
 
3
4
  //#region src/types.d.ts
4
5
 
5
6
  /**
6
7
  * Custom context passed to MCP server and tools.
7
- * Contains the source URL for fetching component manifests.
8
+ * Contains the source URL for getting component manifests.
8
9
  */
9
10
  interface StorybookContext extends Record<string, unknown> {
10
11
  /**
11
- * The URL of the remote manifest to fetch component data from.
12
+ * The URL of the remote manifest to get component data from.
12
13
  */
13
14
  source?: string;
15
+ /**
16
+ * Optional function to provide custom manifest retrieval logic.
17
+ * If provided, this function will be called instead of using fetch.
18
+ * The function receives the source URL and should return the manifest as a string.
19
+ */
20
+ manifestProvider?: (source: string) => Promise<string>;
14
21
  }
15
22
  //#endregion
23
+ //#region src/tools/list-all-components.d.ts
24
+ declare const LIST_TOOL_NAME = "list-all-components";
25
+ declare function addListAllComponentsTool(server: McpServer<any, StorybookContext>): Promise<void>;
26
+ //#endregion
27
+ //#region src/tools/get-component-documentation.d.ts
28
+ declare const GET_TOOL_NAME = "get-component-documentation";
29
+ declare function addGetComponentDocumentationTool(server: McpServer<any, StorybookContext>): Promise<void>;
30
+ //#endregion
16
31
  //#region src/index.d.ts
17
32
  type Handler = (req: Request, context?: StorybookContext) => Promise<Response>;
18
- type StorybookMcpHandlerOptions = {
19
- /**
20
- * The default source URL for fetching component manifests.
21
- * Can be overridden per-request via context parameter.
22
- */
23
- source?: string;
24
- };
25
- declare const createStorybookMcpHandler: (options?: StorybookMcpHandlerOptions) => Promise<Handler>;
33
+ declare const createStorybookMcpHandler: (options?: StorybookContext) => Promise<Handler>;
26
34
  //#endregion
27
- export { createStorybookMcpHandler };
35
+ export { GET_TOOL_NAME, LIST_TOOL_NAME, type StorybookContext, addGetComponentDocumentationTool, addListAllComponentsTool, createStorybookMcpHandler };
package/dist/index.js CHANGED
@@ -5,25 +5,17 @@ import * as v from "valibot";
5
5
 
6
6
  //#region package.json
7
7
  var name = "@storybook/mcp";
8
- var version = "0.0.2";
8
+ var version = "0.0.4";
9
9
  var description = "MCP server that serves knowledge about your components based on your Storybook stories and documentation";
10
10
 
11
11
  //#endregion
12
12
  //#region src/types.ts
13
- const JSDocTag = v.object({
14
- key: v.string(),
15
- value: v.union([
16
- v.string(),
17
- v.number(),
18
- v.boolean(),
19
- v.null()
20
- ])
21
- });
13
+ const JSDocTag = v.record(v.string(), v.array(v.string()));
22
14
  const BaseManifest = v.object({
23
15
  name: v.string(),
24
16
  description: v.exactOptional(v.string()),
25
17
  import: v.exactOptional(v.string()),
26
- jsDocTags: v.exactOptional(v.array(JSDocTag))
18
+ jsDocTags: v.exactOptional(JSDocTag)
27
19
  });
28
20
  const Example = v.object({
29
21
  ...BaseManifest.entries,
@@ -34,7 +26,7 @@ const ComponentManifest = v.object({
34
26
  id: v.string(),
35
27
  summary: v.exactOptional(v.string()),
36
28
  examples: v.exactOptional(v.array(Example)),
37
- props: v.exactOptional(v.any())
29
+ reactDocgen: v.exactOptional(v.custom(() => true))
38
30
  });
39
31
  const ComponentManifestMap = v.object({
40
32
  v: v.number(),
@@ -42,16 +34,16 @@ const ComponentManifestMap = v.object({
42
34
  });
43
35
 
44
36
  //#endregion
45
- //#region src/utils/fetch-manifest.ts
37
+ //#region src/utils/get-manifest.ts
46
38
  /**
47
- * Error thrown when fetching or parsing a manifest fails
39
+ * Error thrown when getting or parsing a manifest fails
48
40
  */
49
- var ManifestFetchError = class extends Error {
41
+ var ManifestGetError = class extends Error {
50
42
  url;
51
43
  cause;
52
44
  constructor(message, url, cause) {
53
45
  super(message);
54
- this.name = "ManifestFetchError";
46
+ this.name = "ManifestGetError";
55
47
  this.url = url ?? "No source URL provided";
56
48
  this.cause = cause;
57
49
  }
@@ -63,8 +55,8 @@ var ManifestFetchError = class extends Error {
63
55
  * @returns A tool result with error content and isError flag
64
56
  */
65
57
  const errorToMCPContent = (error) => {
66
- let fullMessage = `${error instanceof ManifestFetchError ? "Error fetching manifest" : "Unexpected error"}: ${error instanceof Error ? error.message : String(error)}`;
67
- if (error instanceof ManifestFetchError && error.cause) {
58
+ let fullMessage = `${error instanceof ManifestGetError ? "Error getting manifest" : "Unexpected error"}: ${error instanceof Error ? error.message : String(error)}`;
59
+ if (error instanceof ManifestGetError && error.cause) {
68
60
  const causeMessage = error.cause instanceof Error ? error.cause.message : String(error.cause);
69
61
  fullMessage += `\nCaused by: ${causeMessage}`;
70
62
  }
@@ -77,28 +69,33 @@ const errorToMCPContent = (error) => {
77
69
  };
78
70
  };
79
71
  /**
80
- * Fetches a component manifest from a remote URL
72
+ * Gets a component manifest from a remote URL or using a custom provider
81
73
  *
82
- * @param url - The URL to fetch the manifest from
74
+ * @param url - The URL to get the manifest from
75
+ * @param manifestProvider - Optional custom function to get the manifest
83
76
  * @returns A promise that resolves to the parsed ComponentManifestMap
84
- * @throws {ManifestFetchError} If the fetch fails or the response is invalid
77
+ * @throws {ManifestGetError} If getting the manifest fails or the response is invalid
85
78
  */
86
- async function fetchManifest(url) {
79
+ async function getManifest(url, manifestProvider) {
87
80
  try {
88
- if (!url) throw new ManifestFetchError("The source URL is required, but was not part of the request context nor was a default source for the server set");
89
- const response = await fetch(url);
90
- if (!response.ok) throw new ManifestFetchError(`Failed to fetch manifest: ${response.status} ${response.statusText}`, url);
91
- const contentType = response.headers.get("content-type");
92
- if (!contentType?.includes("application/json")) throw new ManifestFetchError(`Invalid content type: expected application/json, got ${contentType}`, url);
93
- const data = await response.json();
94
- const manifest = v.parse(ComponentManifestMap, data);
95
- if (Object.keys(manifest.components).length === 0) throw new ManifestFetchError(`No components found in the manifest`, url);
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);
83
+ const manifestData = JSON.parse(manifestString);
84
+ const manifest = v.parse(ComponentManifestMap, manifestData);
85
+ if (Object.keys(manifest.components).length === 0) throw new ManifestGetError(`No components found in the manifest`, url);
96
86
  return manifest;
97
87
  } catch (error) {
98
- if (error instanceof ManifestFetchError) throw error;
99
- throw new ManifestFetchError(`Failed to fetch manifest: ${error instanceof Error ? error.message : String(error)}`, url, error instanceof Error ? error : void 0);
88
+ if (error instanceof ManifestGetError) throw error;
89
+ throw new ManifestGetError(`Failed to get manifest: ${error instanceof Error ? error.message : String(error)}`, url, error instanceof Error ? error : void 0);
100
90
  }
101
91
  }
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);
95
+ 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);
97
+ return response.text();
98
+ }
102
99
 
103
100
  //#endregion
104
101
  //#region src/utils/dedent.ts
@@ -128,6 +125,54 @@ function dedent(templ, ...values) {
128
125
  return string;
129
126
  }
130
127
 
128
+ //#endregion
129
+ //#region src/utils/parse-react-docgen.ts
130
+ function serializeTsType(tsType) {
131
+ if (!tsType) return void 0;
132
+ if ("raw" in tsType && typeof tsType.raw === "string" && tsType.raw.trim().length > 0) return tsType.raw;
133
+ if (!tsType.name) return void 0;
134
+ if ("elements" in tsType) {
135
+ const serializeElements = () => (tsType.elements ?? []).map((el) => serializeTsType(el) ?? "unknown");
136
+ switch (tsType.name) {
137
+ case "union": return serializeElements().join(" | ");
138
+ case "intersection": return serializeElements().join(" & ");
139
+ case "Array": return `${serializeTsType((tsType.elements ?? [])[0]) ?? "unknown"}[]`;
140
+ case "tuple": return `[${serializeElements().join(", ")}]`;
141
+ }
142
+ }
143
+ if ("value" in tsType && tsType.name === "literal") return tsType.value;
144
+ if ("signature" in tsType && tsType.name === "signature") {
145
+ if (tsType.type === "function") {
146
+ const args = (tsType.signature?.arguments ?? []).map((a) => {
147
+ const argType = serializeTsType(a.type) ?? "any";
148
+ return `${a.name}: ${argType}`;
149
+ });
150
+ const ret = serializeTsType(tsType.signature?.return) ?? "void";
151
+ return `(${args.join(", ")}) => ${ret}`;
152
+ }
153
+ if (tsType.type === "object") return `{ ${(tsType.signature?.properties ?? []).map((p) => {
154
+ const req = Boolean(p.value?.required);
155
+ const propType = serializeTsType(p.value) ?? "any";
156
+ return `${p.key}${req ? "" : "?"}: ${propType}`;
157
+ }).join("; ")} }`;
158
+ return "unknown";
159
+ }
160
+ if ("elements" in tsType) {
161
+ const inner = (tsType.elements ?? []).map((el) => serializeTsType(el) ?? "unknown");
162
+ if (inner.length > 0) return `${tsType.name}<${inner.join(", ")}>`;
163
+ }
164
+ return tsType.name;
165
+ }
166
+ const parseReactDocgen = (reactDocgen) => {
167
+ const props = reactDocgen?.props ?? {};
168
+ return { props: Object.fromEntries(Object.entries(props).map(([propName, prop]) => [propName, {
169
+ description: prop.description,
170
+ type: serializeTsType(prop.tsType ?? prop.type),
171
+ defaultValue: prop.defaultValue?.value,
172
+ required: prop.required
173
+ }])) };
174
+ };
175
+
131
176
  //#endregion
132
177
  //#region src/utils/format-manifest.ts
133
178
  function formatComponentManifest(componentManifest) {
@@ -153,6 +198,25 @@ function formatComponentManifest(componentManifest) {
153
198
  </example>`);
154
199
  parts.push(exampleParts.join("\n"));
155
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>");
216
+ }
217
+ parts.push("</props>");
218
+ }
219
+ }
156
220
  parts.push("</component>");
157
221
  return parts.join("\n");
158
222
  }
@@ -186,7 +250,7 @@ async function addListAllComponentsTool(server) {
186
250
  try {
187
251
  return { content: [{
188
252
  type: "text",
189
- text: formatComponentManifestMapToList(await fetchManifest(server.ctx.custom?.source))
253
+ text: formatComponentManifestMapToList(await getManifest(server.ctx.custom?.source, server.ctx.custom?.manifestProvider))
190
254
  }] };
191
255
  } catch (error) {
192
256
  return errorToMCPContent(error);
@@ -206,7 +270,7 @@ async function addGetComponentDocumentationTool(server) {
206
270
  schema: GetComponentDocumentationInput
207
271
  }, async (input) => {
208
272
  try {
209
- const manifest = await fetchManifest(server.ctx.custom?.source);
273
+ const manifest = await getManifest(server.ctx.custom?.source, server.ctx.custom?.manifestProvider);
210
274
  const content = [];
211
275
  const notFoundIds = [];
212
276
  for (const componentId of input.componentIds) {
@@ -256,9 +320,13 @@ const createStorybookMcpHandler = async (options = {}) => {
256
320
  const transport = new HttpTransport(server, { path: null });
257
321
  return (async (req, context) => {
258
322
  const source = context?.source ?? options.source;
259
- return await transport.respond(req, { source });
323
+ const manifestProvider = context?.manifestProvider ?? options.manifestProvider;
324
+ return await transport.respond(req, {
325
+ source,
326
+ manifestProvider
327
+ });
260
328
  });
261
329
  };
262
330
 
263
331
  //#endregion
264
- export { createStorybookMcpHandler };
332
+ export { GET_TOOL_NAME, LIST_TOOL_NAME, addGetComponentDocumentationTool, addListAllComponentsTool, createStorybookMcpHandler };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@storybook/mcp",
3
- "version": "0.0.2",
3
+ "version": "0.0.4",
4
4
  "description": "MCP server that serves knowledge about your components based on your Storybook stories and documentation",
5
5
  "keywords": [
6
6
  "storybook",
@@ -36,6 +36,7 @@
36
36
  "@tsconfig/node24": "^24.0.1",
37
37
  "@types/node": "20.19.0",
38
38
  "@vitest/coverage-v8": "3.2.4",
39
+ "react-docgen": "^8.0.2",
39
40
  "srvx": "^0.8.16",
40
41
  "tsdown": "^0.15.9",
41
42
  "typescript": "^5.9.3",