@storybook/mcp 0.0.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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2023 Storybook contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,3 @@
1
+ # `@storybook/mcp`
2
+
3
+ The hype is real.
@@ -0,0 +1,27 @@
1
+ import "valibot";
2
+
3
+ //#region src/types.d.ts
4
+
5
+ /**
6
+ * Custom context passed to MCP server and tools.
7
+ * Contains the source URL for fetching component manifests.
8
+ */
9
+ interface StorybookContext extends Record<string, unknown> {
10
+ /**
11
+ * The URL of the remote manifest to fetch component data from.
12
+ */
13
+ source?: string;
14
+ }
15
+ //#endregion
16
+ //#region src/index.d.ts
17
+ 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>;
26
+ //#endregion
27
+ export { createStorybookMcpHandler };
package/dist/index.js ADDED
@@ -0,0 +1,264 @@
1
+ import { McpServer } from "tmcp";
2
+ import { ValibotJsonSchemaAdapter } from "@tmcp/adapter-valibot";
3
+ import { HttpTransport } from "@tmcp/transport-http";
4
+ import * as v from "valibot";
5
+
6
+ //#region package.json
7
+ var name = "@storybook/mcp";
8
+ var version = "0.0.0";
9
+ var description = "MCP server that serves knowledge about your components based on your Storybook stories and documentation";
10
+
11
+ //#endregion
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
+ });
22
+ const BaseManifest = v.object({
23
+ name: v.string(),
24
+ description: v.exactOptional(v.string()),
25
+ import: v.exactOptional(v.string()),
26
+ jsDocTags: v.exactOptional(v.array(JSDocTag))
27
+ });
28
+ const Example = v.object({
29
+ ...BaseManifest.entries,
30
+ snippet: v.string()
31
+ });
32
+ const ComponentManifest = v.object({
33
+ ...BaseManifest.entries,
34
+ id: v.string(),
35
+ summary: v.exactOptional(v.string()),
36
+ examples: v.exactOptional(v.array(Example)),
37
+ props: v.exactOptional(v.any())
38
+ });
39
+ const ComponentManifestMap = v.object({
40
+ v: v.number(),
41
+ components: v.record(v.string(), ComponentManifest)
42
+ });
43
+
44
+ //#endregion
45
+ //#region src/utils/fetch-manifest.ts
46
+ /**
47
+ * Error thrown when fetching or parsing a manifest fails
48
+ */
49
+ var ManifestFetchError = class extends Error {
50
+ url;
51
+ cause;
52
+ constructor(message, url, cause) {
53
+ super(message);
54
+ this.name = "ManifestFetchError";
55
+ this.url = url ?? "No source URL provided";
56
+ this.cause = cause;
57
+ }
58
+ };
59
+ /**
60
+ * Converts an error to MCP-compatible content format
61
+ *
62
+ * @param error - The error to convert (can be any type)
63
+ * @returns A tool result with error content and isError flag
64
+ */
65
+ 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) {
68
+ const causeMessage = error.cause instanceof Error ? error.cause.message : String(error.cause);
69
+ fullMessage += `\nCaused by: ${causeMessage}`;
70
+ }
71
+ return {
72
+ content: [{
73
+ type: "text",
74
+ text: fullMessage
75
+ }],
76
+ isError: true
77
+ };
78
+ };
79
+ /**
80
+ * Fetches a component manifest from a remote URL
81
+ *
82
+ * @param url - The URL to fetch the manifest from
83
+ * @returns A promise that resolves to the parsed ComponentManifestMap
84
+ * @throws {ManifestFetchError} If the fetch fails or the response is invalid
85
+ */
86
+ async function fetchManifest(url) {
87
+ 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);
96
+ return manifest;
97
+ } 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);
100
+ }
101
+ }
102
+
103
+ //#endregion
104
+ //#region src/utils/dedent.ts
105
+ function dedent(templ, ...values) {
106
+ let strings = Array.from(typeof templ === "string" ? [templ] : templ);
107
+ strings[strings.length - 1] = strings[strings.length - 1].replace(/\r?\n([\t ]*)$/, "");
108
+ const indentLengths = strings.reduce((arr, str) => {
109
+ const matches = str.match(/\n([\t ]+|(?!\s).)/g);
110
+ if (matches) return arr.concat(matches.map((match) => match.match(/[\t ]/g)?.length ?? 0));
111
+ return arr;
112
+ }, []);
113
+ if (indentLengths.length) {
114
+ const pattern = new RegExp(`\n[\t ]{${Math.min(...indentLengths)}}`, "g");
115
+ strings = strings.map((str) => str.replace(pattern, "\n"));
116
+ }
117
+ strings[0] = strings[0].replace(/^\r?\n/, "");
118
+ let string = strings[0];
119
+ values.forEach((value, i) => {
120
+ const endentations = string.match(/(?:^|\n)( *)$/);
121
+ const endentation = endentations ? endentations[1] : "";
122
+ let indentedValue = value;
123
+ if (typeof value === "string" && value.includes("\n")) indentedValue = String(value).split("\n").map((str, i$1) => {
124
+ return i$1 === 0 ? str : `${endentation}${str}`;
125
+ }).join("\n");
126
+ string += indentedValue + strings[i + 1];
127
+ });
128
+ return string;
129
+ }
130
+
131
+ //#endregion
132
+ //#region src/utils/format-manifest.ts
133
+ function formatComponentManifest(componentManifest) {
134
+ const parts = [];
135
+ parts.push(dedent`<component>
136
+ <id>${componentManifest.id}</id>
137
+ <name>${componentManifest.name}</name>`);
138
+ if (componentManifest.description) parts.push(dedent`<description>
139
+ ${componentManifest.description}
140
+ </description>`);
141
+ if (componentManifest.examples && componentManifest.examples.length > 0) for (const example of componentManifest.examples) {
142
+ const exampleParts = [];
143
+ exampleParts.push(dedent`<example>
144
+ <example_name>${example.name.replace(/([A-Z])/g, " $1").trim()}</example_name>`);
145
+ if (example.description) exampleParts.push(dedent`<example_description>
146
+ ${example.description}
147
+ </example_description>`);
148
+ exampleParts.push("<example_code>");
149
+ const importStatement = example.import || componentManifest.import;
150
+ if (importStatement) exampleParts.push(`${importStatement}\n`);
151
+ exampleParts.push(dedent`${example.snippet}
152
+ </example_code>
153
+ </example>`);
154
+ parts.push(exampleParts.join("\n"));
155
+ }
156
+ parts.push("</component>");
157
+ return parts.join("\n");
158
+ }
159
+ const MAX_SUMMARY_LENGTH = 90;
160
+ function formatComponentManifestMapToList(manifest) {
161
+ const parts = [];
162
+ parts.push("<components>");
163
+ for (const component of Object.values(manifest.components)) {
164
+ parts.push(dedent`<component>
165
+ <id>${component.id}</id>
166
+ <name>${component.name}</name>`);
167
+ const summary = component.summary ?? (component.description ? component.description.length > MAX_SUMMARY_LENGTH ? `${component.description.slice(0, MAX_SUMMARY_LENGTH)}...` : component.description : void 0);
168
+ if (summary) parts.push(dedent`<summary>
169
+ ${summary}
170
+ </summary>`);
171
+ parts.push("</component>");
172
+ }
173
+ parts.push("</components>");
174
+ return parts.join("\n");
175
+ }
176
+
177
+ //#endregion
178
+ //#region src/tools/list-all-components.ts
179
+ const LIST_TOOL_NAME = "list-all-components";
180
+ async function addListAllComponentsTool(server) {
181
+ server.tool({
182
+ name: LIST_TOOL_NAME,
183
+ title: "List All Components",
184
+ description: "List all available UI components from the component library"
185
+ }, async () => {
186
+ try {
187
+ return { content: [{
188
+ type: "text",
189
+ text: formatComponentManifestMapToList(await fetchManifest(server.ctx.custom?.source))
190
+ }] };
191
+ } catch (error) {
192
+ return errorToMCPContent(error);
193
+ }
194
+ });
195
+ }
196
+
197
+ //#endregion
198
+ //#region src/tools/get-component-documentation.ts
199
+ const GET_TOOL_NAME = "get-component-documentation";
200
+ const GetComponentDocumentationInput = v.object({ componentIds: v.pipe(v.array(v.string()), v.minLength(1, "At least one component ID is required")) });
201
+ async function addGetComponentDocumentationTool(server) {
202
+ server.tool({
203
+ name: GET_TOOL_NAME,
204
+ title: "Get Documentation for Components",
205
+ description: "Get detailed documentation for specific UI components",
206
+ schema: GetComponentDocumentationInput
207
+ }, async (input) => {
208
+ try {
209
+ const manifest = await fetchManifest(server.ctx.custom?.source);
210
+ const content = [];
211
+ const notFoundIds = [];
212
+ for (const componentId of input.componentIds) {
213
+ const component = manifest.components[componentId];
214
+ if (!component) {
215
+ notFoundIds.push(componentId);
216
+ continue;
217
+ }
218
+ content.push({
219
+ type: "text",
220
+ text: formatComponentManifest(component)
221
+ });
222
+ }
223
+ const allNotFound = notFoundIds.length === input.componentIds.length;
224
+ if (notFoundIds.length > 0) {
225
+ const componentWord = notFoundIds.length > 1 ? "Components" : "Component";
226
+ const severity = allNotFound ? "Error" : "Warning";
227
+ content.push({
228
+ type: "text",
229
+ text: `${severity}: ${componentWord} not found: ${notFoundIds.join(", ")}`
230
+ });
231
+ }
232
+ return {
233
+ content,
234
+ ...allNotFound && { isError: true }
235
+ };
236
+ } catch (error) {
237
+ return errorToMCPContent(error);
238
+ }
239
+ });
240
+ }
241
+
242
+ //#endregion
243
+ //#region src/index.ts
244
+ const createStorybookMcpHandler = async (options = {}) => {
245
+ const adapter = new ValibotJsonSchemaAdapter();
246
+ const server = new McpServer({
247
+ name,
248
+ version,
249
+ description
250
+ }, {
251
+ adapter,
252
+ capabilities: { tools: { listChanged: true } }
253
+ }).withContext();
254
+ await addListAllComponentsTool(server);
255
+ await addGetComponentDocumentationTool(server);
256
+ const transport = new HttpTransport(server, { path: null });
257
+ return (async (req, context) => {
258
+ const source = context?.source ?? options.source;
259
+ return await transport.respond(req, { source });
260
+ });
261
+ };
262
+
263
+ //#endregion
264
+ export { createStorybookMcpHandler };
package/package.json ADDED
@@ -0,0 +1,50 @@
1
+ {
2
+ "name": "@storybook/mcp",
3
+ "version": "0.0.1",
4
+ "description": "MCP server that serves knowledge about your components based on your Storybook stories and documentation",
5
+ "keywords": [
6
+ "storybook",
7
+ "mcp"
8
+ ],
9
+ "homepage": "https://github.com/storybookjs/mcp/blob/main/packages/mcp/README.md",
10
+ "repository": {
11
+ "type": "git",
12
+ "url": "https://github.com/storybookjs/mcp.git",
13
+ "directory": "packages/mcp"
14
+ },
15
+ "license": "MIT",
16
+ "author": "Storybook Core Team",
17
+ "type": "module",
18
+ "exports": {
19
+ ".": {
20
+ "types": "./dist/index.d.ts",
21
+ "default": "./dist/index.js"
22
+ },
23
+ "./package.json": "./package.json"
24
+ },
25
+ "files": [
26
+ "dist"
27
+ ],
28
+ "dependencies": {
29
+ "@tmcp/adapter-valibot": "^0.1.4",
30
+ "@tmcp/transport-http": "^0.7.0",
31
+ "tmcp": "^1.15.2",
32
+ "valibot": "^1.1.0"
33
+ },
34
+ "devDependencies": {
35
+ "@tsconfig/node-ts": "^23.6.1",
36
+ "@tsconfig/node24": "^24.0.1",
37
+ "@types/node": "^24.7.2",
38
+ "@vitest/coverage-v8": "3.2.4",
39
+ "srvx": "^0.8.16",
40
+ "tsdown": "^0.15.7",
41
+ "typescript": "^5.9.3",
42
+ "vitest": "^3.2.4"
43
+ },
44
+ "scripts": {
45
+ "build": "tsdown",
46
+ "dev": "node --watch ./serve.ts",
47
+ "test": "vitest",
48
+ "inspect": "mcp-inspector --config ../../.mcp.inspect.json --server storybook-mcp"
49
+ }
50
+ }