@storybook/addon-mcp 0.6.0 → 10.6.0-alpha.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/preset.js CHANGED
@@ -1,704 +1,1791 @@
1
+ import CJS_COMPAT_NODE_URL_8rqf2mfsb9h from 'node:url';
2
+ import CJS_COMPAT_NODE_PATH_8rqf2mfsb9h from 'node:path';
3
+ import CJS_COMPAT_NODE_MODULE_8rqf2mfsb9h from "node:module";
4
+
5
+ var __filename = CJS_COMPAT_NODE_URL_8rqf2mfsb9h.fileURLToPath(import.meta.url);
6
+ var __dirname = CJS_COMPAT_NODE_PATH_8rqf2mfsb9h.dirname(__filename);
7
+ var require = CJS_COMPAT_NODE_MODULE_8rqf2mfsb9h.createRequire(import.meta.url);
8
+
9
+ // ------------------------------------------------------------
10
+ // end of CJS compatibility banner, injected by Storybook's esbuild configuration
11
+ // ------------------------------------------------------------
12
+
13
+ // src/mcp-handler.ts
1
14
  import { McpServer } from "tmcp";
2
15
  import { ValibotJsonSchemaAdapter } from "@tmcp/adapter-valibot";
3
16
  import { HttpTransport } from "@tmcp/transport-http";
4
- import url from "node:url";
5
- import * as v from "valibot";
17
+
18
+ // package.json
19
+ var package_default = {
20
+ name: "@storybook/addon-mcp",
21
+ version: "10.6.0-alpha.4",
22
+ description: "Help agents automatically write and test stories for your UI components",
23
+ keywords: [
24
+ "ai",
25
+ "mcp",
26
+ "storybook-addon"
27
+ ],
28
+ homepage: "https://github.com/storybookjs/storybook/tree/next/code/addons/mcp",
29
+ bugs: {
30
+ url: "https://github.com/storybookjs/storybook/issues"
31
+ },
32
+ repository: {
33
+ type: "git",
34
+ url: "https://github.com/storybookjs/storybook.git",
35
+ directory: "code/addons/mcp"
36
+ },
37
+ funding: {
38
+ type: "opencollective",
39
+ url: "https://opencollective.com/storybook"
40
+ },
41
+ license: "MIT",
42
+ author: "Storybook Core Team",
43
+ type: "module",
44
+ exports: {
45
+ "./internal/preview-stories-app-script": "./dist/tools/preview-stories/preview-stories-app-script.js",
46
+ "./package.json": "./package.json",
47
+ "./preset": "./dist/preset.js"
48
+ },
49
+ files: [
50
+ "dist/**/*",
51
+ "README.md",
52
+ "*.js",
53
+ "*.d.ts",
54
+ "!src/**/*"
55
+ ],
56
+ dependencies: {
57
+ "@storybook/mcp": "workspace:*",
58
+ "@tmcp/adapter-valibot": "^0.1.5",
59
+ "@tmcp/transport-http": "^0.8.5",
60
+ picoquery: "^2.5.0",
61
+ tmcp: "^1.19.4",
62
+ valibot: "^1.4.0"
63
+ },
64
+ devDependencies: {
65
+ "@storybook/addon-a11y": "workspace:*",
66
+ "@storybook/addon-vitest": "workspace:*",
67
+ storybook: "workspace:*",
68
+ typescript: "^6.0.3"
69
+ },
70
+ peerDependencies: {
71
+ "@storybook/addon-vitest": "workspace:^",
72
+ storybook: "workspace:^"
73
+ },
74
+ peerDependenciesMeta: {
75
+ "@storybook/addon-vitest": {
76
+ optional: !0
77
+ }
78
+ },
79
+ publishConfig: {
80
+ access: "public"
81
+ },
82
+ mcpName: "io.github.storybookjs/addon-mcp",
83
+ storybook: {
84
+ displayName: "Addon MCP",
85
+ supportedFrameworks: [
86
+ "react",
87
+ "vue3",
88
+ "angular",
89
+ "web-components",
90
+ "html",
91
+ "svelte",
92
+ "preact",
93
+ "react-native"
94
+ ],
95
+ icon: "https://user-images.githubusercontent.com/321738/63501763-88dbf600-c4cc-11e9-96cd-94adadc2fd72.png"
96
+ }
97
+ };
98
+
99
+ // src/mcp-handler.ts
100
+ import { buffer } from "node:stream/consumers";
101
+
102
+ // src/telemetry.ts
6
103
  import { logger } from "storybook/internal/node-logger";
7
104
  import { telemetry } from "storybook/internal/telemetry";
8
- import { stringify } from "picoquery";
105
+ async function collectTelemetry({
106
+ event,
107
+ server,
108
+ ...payload
109
+ }) {
110
+ try {
111
+ return await telemetry("addon-mcp", {
112
+ event,
113
+ mcpSessionId: server.ctx.sessionId,
114
+ clientInfo: server.ctx.sessionInfo?.clientInfo,
115
+ clientCapabilities: server.ctx.sessionInfo?.clientCapabilities,
116
+ ...payload
117
+ });
118
+ } catch (error) {
119
+ logger.debug(`Error collecting telemetry: ${String(error)}`);
120
+ }
121
+ }
122
+
123
+ // src/mcp-handler.ts
124
+ import { logger as logger6 } from "storybook/internal/node-logger";
125
+
126
+ // src/utils/module-graph.ts
127
+ import { importModule } from "storybook/internal/common";
128
+ var MODULE_GRAPH_SERVICE_ID = "core/module-graph", probed;
129
+ async function probe() {
130
+ if (probed !== void 0) return probed;
131
+ try {
132
+ let fn = (await import("storybook/internal/core-server")).getService;
133
+ probed = typeof fn == "function" ? fn : null;
134
+ } catch {
135
+ probed = null;
136
+ }
137
+ return probed;
138
+ }
139
+ async function isModuleGraphSupported() {
140
+ return await getModuleGraphService() !== void 0;
141
+ }
142
+ async function isModuleGraphSupportedByBuilder(options) {
143
+ let builder = (await options.presets.apply("core", {}))?.builder, builderName = typeof builder == "string" ? builder : builder?.name;
144
+ if (!builderName)
145
+ return !1;
146
+ try {
147
+ return typeof (await importModule(builderName)).changeDetectionAdapter == "function";
148
+ } catch {
149
+ return !1;
150
+ }
151
+ }
152
+ async function getModuleGraphService() {
153
+ let getService = await probe();
154
+ if (getService)
155
+ try {
156
+ return getService(MODULE_GRAPH_SERVICE_ID, { internal: !0 });
157
+ } catch {
158
+ return;
159
+ }
160
+ }
161
+
162
+ // src/utils/is-review-available.ts
163
+ var getReviewStatus = async (options, { features: features2 } = {}) => {
164
+ let resolvedFeatures = features2 ?? await options.presets.apply("features", {}), hasFeatureFlag = !!resolvedFeatures?.experimentalReview, changeDetection = !!resolvedFeatures?.changeDetection;
165
+ return {
166
+ // Review is opt-in via `experimentalReview` for direct MCP clients and
167
+ // builds on the change-detection pipeline, so it needs both flags.
168
+ available: hasFeatureFlag && changeDetection,
169
+ availableForCli: resolvedFeatures?.experimentalReview !== !1 && changeDetection,
170
+ hasFeatureFlag
171
+ };
172
+ };
173
+
174
+ // src/tools/is-manifest-available.ts
175
+ var hasComponentManifestFeature = (features2) => !!(features2?.componentsManifest ?? features2?.experimentalComponentsManifest), isDocgenServerMode = (features2) => !!(features2?.experimentalDocgenServer && features2?.componentsManifest), getManifestStatus = async (options) => {
176
+ let [
177
+ features2,
178
+ manifests,
179
+ // Added for backwards compatibility with Storybook versions prior to v10.2.0-alpha.10
180
+ // Should be removed once support for Storybook version < 10.2.0 is dropped
181
+ legacyComponentManifestGenerator
182
+ ] = await Promise.all([
183
+ options.presets.apply("features"),
184
+ options.presets.apply("experimental_manifests", void 0, {
185
+ manifestEntries: []
186
+ }),
187
+ options.presets.apply("experimental_componentManifestGenerator")
188
+ ]), hasFeatureFlag = hasComponentManifestFeature(features2), docgenServer = isDocgenServerMode(features2), hasManifests = docgenServer || manifests && "components" in manifests || !!legacyComponentManifestGenerator;
189
+ return {
190
+ available: hasFeatureFlag && hasManifests,
191
+ hasManifests,
192
+ hasFeatureFlag,
193
+ docgenServer
194
+ };
195
+ };
196
+
197
+ // src/tools/run-story-tests.ts
198
+ import { logger as logger4 } from "storybook/internal/node-logger";
199
+ import * as v2 from "valibot";
200
+
201
+ // src/utils/get-story-index.ts
202
+ import { logger as logger2 } from "storybook/internal/node-logger";
203
+ async function getStoryIndex(options) {
204
+ let generator = await options.presets.apply(
205
+ "storyIndexGenerator"
206
+ );
207
+ if (!generator)
208
+ throw new Error(
209
+ "Storybook story index generator is unavailable. These MCP tools require a running Storybook dev server with a builder that exposes the story index."
210
+ );
211
+ let index = await generator.getIndex();
212
+ return logger2.debug(`Story index entries found: ${Object.keys(index.entries).length}`), index;
213
+ }
214
+
215
+ // src/utils/find-story-ids.ts
9
216
  import path from "node:path";
10
217
  import { normalizeStoryPath } from "storybook/internal/common";
11
218
  import { storyNameFromExport } from "storybook/internal/csf";
12
- import { ComponentManifestMap, DocsManifestMap, GET_TOOL_NAME, LIST_TOOL_NAME, STORYBOOK_MCP_INSTRUCTIONS, addGetDocumentationTool, addGetStoryDocumentationTool, addListAllDocumentationTool } from "@storybook/mcp";
13
- import fs from "node:fs/promises";
14
- import { buffer } from "node:stream/consumers";
219
+ import { logger as logger3 } from "storybook/internal/node-logger";
15
220
 
16
- //#region package.json
17
- var name = "@storybook/addon-mcp";
18
- var version = "0.6.0";
19
- var description = "Help agents automatically write and test stories for your UI components";
20
-
21
- //#endregion
22
- //#region src/telemetry.ts
23
- async function collectTelemetry({ event, server, ...payload }) {
24
- try {
25
- return await telemetry("addon-mcp", {
26
- event,
27
- mcpSessionId: server.ctx.sessionId,
28
- clientInfo: server.ctx.sessionInfo?.clientInfo,
29
- clientCapabilities: server.ctx.sessionInfo?.clientCapabilities,
30
- ...payload
31
- });
32
- } catch (error) {
33
- logger.debug(`Error collecting telemetry: ${String(error)}`);
34
- }
35
- }
36
-
37
- //#endregion
38
- //#region src/utils/build-args-param.ts
39
- const HEX_REGEXP = /^#([a-f0-9]{3,4}|[a-f0-9]{6}|[a-f0-9]{8})$/i;
40
- const COLOR_REGEXP = /^(rgba?|hsla?)\(([0-9]{1,3}),\s?([0-9]{1,3})%?,\s?([0-9]{1,3})%?,?\s?([0-9](\.[0-9]{1,2})?)?\)$/i;
41
- /**
42
- * Encodes special values for Storybook's args URL format.
43
- * Handles undefined, null, booleans, dates, hex colors, and rgba/hsla colors.
44
- */
45
- function encodeSpecialValues(value) {
46
- if (value === void 0) return "!undefined";
47
- if (value === null) return "!null";
48
- if (typeof value === "string") {
49
- if (HEX_REGEXP.test(value)) return `!hex(${value.slice(1)})`;
50
- if (COLOR_REGEXP.test(value)) return `!${value.replace(/[\s%]/g, "")}`;
51
- return value;
52
- }
53
- if (typeof value === "boolean") return `!${value}`;
54
- if (value instanceof Date) return `!date(${value.toISOString()})`;
55
- if (Array.isArray(value)) return value.map(encodeSpecialValues);
56
- if (typeof value === "object" && value !== null) return Object.entries(value).reduce((acc, [key, val]) => Object.assign(acc, { [key]: encodeSpecialValues(val) }), {});
57
- return value;
58
- }
59
- /**
60
- * Replaces some url-encoded characters with their decoded equivalents.
61
- * The URI RFC specifies these should be encoded, but all browsers will
62
- * tolerate them being decoded, so we opt to go with it for cleaner looking URIs.
63
- */
64
- function decodeKnownQueryChar(chr) {
65
- switch (chr) {
66
- case "%20": return "+";
67
- case "%5B": return "[";
68
- case "%5D": return "]";
69
- case "%2C": return ",";
70
- case "%3A": return ":";
71
- }
72
- return chr;
73
- }
74
- const KNOWN_QUERY_CHAR_REGEXP = /%[0-9A-F]{2}/g;
75
- /**
76
- * Builds a Storybook args query parameter string from an object of props.
77
- *
78
- * The format uses semicolons as delimiters and colons for key:value pairs,
79
- * with special encoding for booleans, null, undefined, dates, and colors.
80
- *
81
- * Example output: "disabled:!true;label:Hello+World;count:42"
82
- */
83
- function buildArgsParam(args) {
84
- if (!args || Object.keys(args).length === 0) return "";
85
- return stringify(encodeSpecialValues(args), {
86
- delimiter: ";",
87
- nesting: true,
88
- nestingSyntax: "js"
89
- }).replace(KNOWN_QUERY_CHAR_REGEXP, decodeKnownQueryChar).split(";").map((part) => part.replace("=", ":")).join(";");
90
- }
91
-
92
- //#endregion
93
- //#region src/utils/fetch-story-index.ts
94
- /**
95
- * Fetches the Storybook story index from the running Storybook instance.
96
- *
97
- * @param origin - The origin URL of the Storybook instance (e.g., http://localhost:6006)
98
- * @returns A promise that resolves to the StoryIndex
99
- * @throws If the fetch fails or returns invalid data
100
- */
101
- async function fetchStoryIndex(origin) {
102
- const indexUrl = `${origin}/index.json`;
103
- logger.debug(`Fetching story index from: ${indexUrl}`);
104
- const response = await fetch(indexUrl);
105
- if (!response.ok) throw new Error(`Failed to fetch story index: ${response.status} ${response.statusText}`);
106
- const index = await response.json();
107
- logger.debug(`Story index entries found: ${Object.keys(index.entries).length}`);
108
- return index;
109
- }
110
-
111
- //#endregion
112
- //#region src/utils/slash.ts
113
- /**
114
- * Normalize paths to forward slashes for cross-platform compatibility
115
- * Storybook import paths always use forward slashes
116
- */
117
- function slash(path) {
118
- return path.replace(/\\/g, "/");
119
- }
120
-
121
- //#endregion
122
- //#region src/utils/find-story-ids.ts
221
+ // src/utils/slash.ts
222
+ function slash(path5) {
223
+ return path5.replace(/\\/g, "/");
224
+ }
225
+
226
+ // src/utils/find-story-ids.ts
123
227
  function isStoryIdInput(input) {
124
- return "storyId" in input;
228
+ return "storyId" in input;
125
229
  }
126
230
  function normalizeImportPath(importPath) {
127
- return slash(normalizeStoryPath(path.posix.normalize(slash(importPath))));
128
- }
129
- /**
130
- * Finds story IDs in the story index that match the given story inputs.
131
- *
132
- * @param index - The Storybook story index
133
- * @param stories - Array of story inputs to search for
134
- * @returns Array of per-input lookup results in the exact same order as the input stories
135
- */
231
+ let normalized = path.posix.normalize(slash(importPath));
232
+ return slash(normalizeStoryPath(normalized));
233
+ }
136
234
  function findStoryIds(index, stories) {
137
- const entriesList = Object.values(index.entries);
138
- const result = [];
139
- for (const storyInput of stories) {
140
- if (isStoryIdInput(storyInput)) {
141
- const foundEntry = index.entries[storyInput.storyId];
142
- if (foundEntry) {
143
- logger.debug(`Found story ID: ${foundEntry.id}`);
144
- result.push({
145
- id: foundEntry.id,
146
- input: storyInput
147
- });
148
- } else {
149
- logger.debug("No story found");
150
- result.push({
151
- input: storyInput,
152
- errorMessage: `No story found for story ID "${storyInput.storyId}"`
153
- });
154
- }
155
- continue;
156
- }
157
- const { exportName, explicitStoryName, absoluteStoryPath } = storyInput;
158
- const normalizedCwd = slash(process.cwd());
159
- const normalizedAbsolutePath = slash(absoluteStoryPath);
160
- const relativePath = normalizeImportPath(path.posix.relative(normalizedCwd, normalizedAbsolutePath));
161
- logger.debug("Searching for:");
162
- logger.debug({
163
- exportName,
164
- explicitStoryName,
165
- absoluteStoryPath,
166
- relativePath
167
- });
168
- const foundEntry = entriesList.find((entry) => normalizeImportPath(entry.importPath) === relativePath && [explicitStoryName, storyNameFromExport(exportName)].includes(entry.name));
169
- if (foundEntry) {
170
- logger.debug(`Found story ID: ${foundEntry.id}`);
171
- result.push({
172
- id: foundEntry.id,
173
- input: storyInput
174
- });
175
- } else {
176
- logger.debug("No story found");
177
- let errorMessage = `No story found for export name "${exportName}" with absolute file path "${absoluteStoryPath}"`;
178
- if (!explicitStoryName) errorMessage += ` (did you forget to pass the explicit story name?)`;
179
- result.push({
180
- input: storyInput,
181
- errorMessage
182
- });
183
- }
184
- }
185
- return result;
186
- }
187
-
188
- //#endregion
189
- //#region src/utils/errors.ts
190
- /**
191
- * Converts an error to MCP-compatible content format
192
- *
193
- * @param error - The error to convert (can be any type)
194
- * @returns A tool result with error content and isError flag
195
- */
196
- const errorToMCPContent = (error) => {
197
- return {
198
- content: [{
199
- type: "text",
200
- text: `Error: ${error instanceof Error ? error.message : String(error)}`
201
- }],
202
- isError: true
203
- };
204
- };
235
+ let entriesList = Object.values(index.entries), result = [];
236
+ for (let storyInput of stories) {
237
+ if (isStoryIdInput(storyInput)) {
238
+ let foundEntry2 = index.entries[storyInput.storyId];
239
+ foundEntry2 ? (logger3.debug(`Found story ID: ${foundEntry2.id}`), result.push({
240
+ id: foundEntry2.id,
241
+ input: storyInput
242
+ })) : (logger3.debug("No story found"), result.push({
243
+ input: storyInput,
244
+ errorMessage: `No story found for story ID "${storyInput.storyId}"`
245
+ }));
246
+ continue;
247
+ }
248
+ let { exportName, explicitStoryName, absoluteStoryPath } = storyInput, normalizedCwd = slash(process.cwd()), normalizedAbsolutePath = slash(absoluteStoryPath), relativePath = normalizeImportPath(
249
+ path.posix.relative(normalizedCwd, normalizedAbsolutePath)
250
+ );
251
+ logger3.debug("Searching for:"), logger3.debug({
252
+ exportName,
253
+ explicitStoryName,
254
+ absoluteStoryPath,
255
+ relativePath
256
+ });
257
+ let foundEntry = entriesList.find(
258
+ (entry) => normalizeImportPath(entry.importPath) === relativePath && [explicitStoryName, storyNameFromExport(exportName)].includes(entry.name)
259
+ );
260
+ if (foundEntry)
261
+ logger3.debug(`Found story ID: ${foundEntry.id}`), result.push({
262
+ id: foundEntry.id,
263
+ input: storyInput
264
+ });
265
+ else {
266
+ logger3.debug("No story found");
267
+ let errorMessage = `No story found for export name "${exportName}" with absolute file path "${absoluteStoryPath}"`;
268
+ explicitStoryName || (errorMessage += " (did you forget to pass the explicit story name?)"), result.push({
269
+ input: storyInput,
270
+ errorMessage
271
+ });
272
+ }
273
+ }
274
+ return result;
275
+ }
276
+
277
+ // src/utils/errors.ts
278
+ var errorToMCPContent = (error) => ({
279
+ content: [
280
+ {
281
+ type: "text",
282
+ text: `Error: ${error instanceof Error ? error.message : String(error)}`
283
+ }
284
+ ],
285
+ isError: !0
286
+ });
287
+
288
+ // src/types.ts
289
+ import * as v from "valibot";
290
+ import { GET_TOOL_NAME, LIST_TOOL_NAME } from "@storybook/mcp";
291
+
292
+ // src/tools/tool-names.ts
293
+ var PREVIEW_STORIES_TOOL_NAME = "preview-stories", GET_CHANGED_STORIES_TOOL_NAME = "get-changed-stories", GET_STORIES_BY_COMPONENT_TOOL_NAME = "get-stories-by-component", GET_UI_BUILDING_INSTRUCTIONS_TOOL_NAME = "get-storybook-story-instructions", RUN_STORY_TESTS_TOOL_NAME = "run-story-tests", DISPLAY_REVIEW_TOOL_NAME = "display-review";
205
294
 
206
- //#endregion
207
- //#region src/tools/tool-names.ts
208
- /**
209
- * Tool name constants extracted to avoid circular dependencies.
210
- */
211
- const PREVIEW_STORIES_TOOL_NAME = "preview-stories";
212
- const GET_UI_BUILDING_INSTRUCTIONS_TOOL_NAME = "get-storybook-story-instructions";
213
- const RUN_STORY_TESTS_TOOL_NAME = "run-story-tests";
214
-
215
- //#endregion
216
- //#region src/types.ts
217
- const AddonOptions = v.object({ toolsets: v.optional(v.object({
218
- dev: v.exactOptional(v.boolean(), true),
219
- docs: v.exactOptional(v.boolean(), true),
220
- test: v.exactOptional(v.boolean(), true)
221
- }), {
222
- dev: true,
223
- docs: true,
224
- test: true
225
- }) });
226
- const StoryInputProps = {
227
- props: v.pipe(v.optional(v.record(v.string(), v.any())), v.description(`Optional custom props to pass to the story for rendering. Use this when you don't want to render the default story,
295
+ // src/types.ts
296
+ var isLiteralEndpointPathname = (endpoint) => {
297
+ try {
298
+ let { pathname } = new URL(endpoint, "http://storybook.local");
299
+ return pathname === endpoint && pathname !== "/";
300
+ } catch {
301
+ return !1;
302
+ }
303
+ }, AddonOptions = v.object({
304
+ endpoint: v.optional(
305
+ v.pipe(
306
+ v.string(),
307
+ v.check(isLiteralEndpointPathname, "Endpoint must be a literal URL pathname")
308
+ )
309
+ ),
310
+ toolsets: v.optional(
311
+ v.object({
312
+ dev: v.exactOptional(v.boolean(), !0),
313
+ docs: v.exactOptional(v.boolean(), !0),
314
+ test: v.exactOptional(v.boolean(), !0)
315
+ }),
316
+ {
317
+ // Default values for toolsets
318
+ dev: !0,
319
+ docs: !0,
320
+ test: !0
321
+ }
322
+ )
323
+ }), StoryInputProps = {
324
+ /**
325
+ * Optional props to pass to the story.
326
+ */
327
+ props: v.pipe(
328
+ v.optional(v.record(v.string(), v.any())),
329
+ v.description(`Optional custom props to pass to the story for rendering. Use this when you don't want to render the default story,
228
330
  but you want to customize some args or other props.
229
- You can look up the component's documentation using the ${GET_UI_BUILDING_INSTRUCTIONS_TOOL_NAME} tool to see what props are available.`)),
230
- globals: v.pipe(v.optional(v.record(v.string(), v.any())), v.description(`Optional Storybook globals to set for the story preview. Globals are used for things like theme, locale, viewport, and other cross-cutting concerns.
231
- Common globals include 'theme' (e.g., 'dark', 'light'), 'locale' (e.g., 'en', 'fr'), and 'backgrounds' (e.g., { value: '#000' }).`))
232
- };
233
- /**
234
- * Schema for a single story input when requesting story URLs.
235
- */
236
- const StoryInput = v.union([v.object({
237
- exportName: v.pipe(v.string(), v.description(`The export name of the story from the story file.
331
+ You can look up the component's documentation using the ${GET_UI_BUILDING_INSTRUCTIONS_TOOL_NAME} tool to see what props are available.`)
332
+ ),
333
+ /**
334
+ * Optional globals to set for the story.
335
+ */
336
+ globals: v.pipe(
337
+ v.optional(v.record(v.string(), v.any())),
338
+ v.description(`Optional Storybook globals to set for the story preview. Globals are used for things like theme, locale, viewport, and other cross-cutting concerns.
339
+ Common globals include 'theme' (e.g., 'dark', 'light'), 'locale' (e.g., 'en', 'fr'), and 'backgrounds' (e.g., { value: '#000' }).`)
340
+ )
341
+ }, StoryInput = v.union([
342
+ v.object({
343
+ /**
344
+ * The export name of the story from the story file.
345
+ * Example: "Primary", "WithArgs", "Default"
346
+ */
347
+ exportName: v.pipe(
348
+ v.string(),
349
+ v.description(
350
+ `The export name of the story from the story file.
238
351
  Use this path-based shape only when you're already editing a .stories.* file and know the export names in that file.
239
- If you do not already have story file context, prefer the storyId shape instead of searching files.`)),
240
- explicitStoryName: v.pipe(v.optional(v.string()), v.description(`If the story has an explicit name set via the "name" property, that is different from the export name, provide it here.
241
- Otherwise don't set this.`)),
242
- absoluteStoryPath: v.pipe(v.string(), v.description("Absolute path to the story file. Use together with exportName only when story file context is already available.")),
243
- ...StoryInputProps
244
- }), v.object({
245
- storyId: v.pipe(v.string(), v.description(`The full Storybook story ID (for example "button--primary").
352
+ If you do not already have story file context, prefer the storyId shape instead of searching files.`
353
+ )
354
+ ),
355
+ /**
356
+ * Optional explicit story name if different from the export name.
357
+ * This is used when a story has a custom name defined.
358
+ */
359
+ explicitStoryName: v.pipe(
360
+ v.optional(v.string()),
361
+ v.description(
362
+ `If the story has an explicit name set via the "name" property, that is different from the export name, provide it here.
363
+ Otherwise don't set this.`
364
+ )
365
+ ),
366
+ /**
367
+ * Absolute file path to the story file.
368
+ */
369
+ absoluteStoryPath: v.pipe(
370
+ v.string(),
371
+ v.description(
372
+ "Absolute path to the story file. Use together with exportName only when story file context is already available."
373
+ )
374
+ ),
375
+ ...StoryInputProps
376
+ }),
377
+ v.object({
378
+ storyId: v.pipe(
379
+ v.string(),
380
+ v.description(
381
+ `The full Storybook story ID (for example "button--primary").
246
382
  Prefer this shape whenever you are not already working in a specific story file.
247
- Use IDs discovered from ${LIST_TOOL_NAME} (withStoryIds=true) or ${GET_TOOL_NAME}.`)),
248
- ...StoryInputProps
249
- })]);
250
- /**
251
- * Schema for the array of stories to fetch URLs for.
252
- */
253
- const StoryInputArray = v.array(StoryInput);
254
-
255
- //#endregion
256
- //#region src/tools/preview-stories/preview-stories-app-template.html
257
- var preview_stories_app_template_default = "<!doctype html>\n<html>\n <head>\n <meta charset=\"utf-8\" />\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\" />\n <style>\n * {\n margin: 0;\n padding: 0;\n box-sizing: border-box;\n }\n html[data-theme='light'] {\n color-scheme: light;\n }\n html[data-theme='dark'] {\n color-scheme: dark;\n }\n html,\n body {\n width: 100%;\n margin: 0;\n padding: 0;\n background-color: var(--color-background-secondary);\n }\n body {\n display: flex;\n flex-direction: column;\n gap: 1rem;\n }\n :root {\n /*\n These are fallback values, if the MCP client doesn't set them.\n See https://github.com/modelcontextprotocol/ext-apps/blob/main/specification/draft/apps.mdx#theming\n */\n --color-text-primary: light-dark(black, white);\n --color-border-primary: light-dark(#ccc, #444);\n --color-background-secondary: light-dark(#f9f9f9, #1e1e1e);\n --font-sans:\n -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Oxygen-Sans', Ubuntu, Cantarell,\n 'Helvetica Neue', sans-serif;\n --font-heading-xs-size: 1rem;\n --font-heading-xs-line-height: 1.25;\n --border-width-regular: 1px;\n }\n .story-heading {\n font-family: var(--font-sans);\n font-size: var(--font-heading-xs-size);\n line-height: var(--font-heading-xs-line-height);\n color: var(--color-text-primary);\n padding: 0.5rem 0;\n }\n .story-iframe {\n background-color: white;\n border: var(--border-width-regular) solid var(--color-border-primary);\n }\n body:has(> article:only-child) h1 {\n /* if there is only one story rendered, hide its heading */\n display: none;\n }\n </style>\n <template id=\"preview-template\">\n <article>\n <h1 class=\"story-heading\"></h1>\n <iframe class=\"story-iframe\"></iframe>\n </article>\n </template>\n <script type=\"module\">\n // APP_SCRIPT_PLACEHOLDER\n <\/script>\n </head>\n <body></body>\n</html>\n";
258
-
259
- //#endregion
260
- //#region src/tools/preview-stories.ts
261
- const PREVIEW_STORIES_RESOURCE_URI = `ui://${PREVIEW_STORIES_TOOL_NAME}/preview.html`;
262
- const PreviewStoriesInput = v.object({ stories: v.pipe(StoryInputArray, v.description(`Stories to preview.
263
- Prefer { storyId } when you don't already have story file context, since this avoids filesystem discovery.
264
- Use { storyId } when IDs were discovered from documentation tools.
265
- Use { absoluteStoryPath + exportName } only when you're already working in a specific .stories.* file and already have that context.`)) });
266
- const PreviewStoriesOutput = v.object({ stories: v.array(v.union([v.object({
267
- title: v.string(),
268
- name: v.string(),
269
- previewUrl: v.pipe(v.string(), v.description("Direct URL to open the story preview. Always include this URL in the final user-facing response so users can open it directly."))
270
- }), v.object({
271
- input: StoryInput,
272
- error: v.string()
273
- })])) });
274
- async function addPreviewStoriesTool(server) {
275
- const previewStoryAppScript = await fs.readFile(url.fileURLToPath(import.meta.resolve("@storybook/addon-mcp/internal/preview-stories-app-script")), "utf-8");
276
- const appHtml = preview_stories_app_template_default.replace("// APP_SCRIPT_PLACEHOLDER", previewStoryAppScript);
277
- server.resource({
278
- name: PREVIEW_STORIES_RESOURCE_URI,
279
- description: "App resource for the Preview Stories tool",
280
- uri: PREVIEW_STORIES_RESOURCE_URI,
281
- mimeType: "text/html;profile=mcp-app"
282
- }, () => {
283
- const origin = server.ctx.custom.origin;
284
- return { contents: [{
285
- uri: PREVIEW_STORIES_RESOURCE_URI,
286
- mimeType: "text/html;profile=mcp-app",
287
- text: appHtml,
288
- _meta: { ui: {
289
- prefersBorder: false,
290
- domain: origin,
291
- csp: {
292
- connectDomains: [origin],
293
- resourceDomains: [origin],
294
- frameDomains: [origin],
295
- baseUriDomains: [origin]
296
- }
297
- } }
298
- }] };
299
- });
300
- server.tool({
301
- name: PREVIEW_STORIES_TOOL_NAME,
302
- title: "Get story preview URLs",
303
- description: `Use this tool to get one or more Storybook preview URLs.
304
- Always include each returned preview URL in your final user-facing response so users can open them directly.`,
305
- schema: PreviewStoriesInput,
306
- outputSchema: PreviewStoriesOutput,
307
- enabled: () => server.ctx.custom?.toolsets?.dev ?? true,
308
- _meta: { ui: { resourceUri: PREVIEW_STORIES_RESOURCE_URI } }
309
- }, async (input) => {
310
- try {
311
- const { origin, disableTelemetry } = server.ctx.custom ?? {};
312
- if (!origin) throw new Error("Origin is required in addon context");
313
- const index = await fetchStoryIndex(origin);
314
- const resolvedStories = findStoryIds(index, input.stories);
315
- const structuredResult = [];
316
- const textResult = [];
317
- for (const story of resolvedStories) {
318
- if ("errorMessage" in story) {
319
- structuredResult.push({
320
- input: story.input,
321
- error: story.errorMessage
322
- });
323
- textResult.push(story.errorMessage);
324
- continue;
325
- }
326
- const indexEntry = index.entries[story.id];
327
- if (!indexEntry) {
328
- structuredResult.push({
329
- input: story.input,
330
- error: `No story found for story ID "${story.id}"`
331
- });
332
- textResult.push(`No story found for story ID "${story.id}"`);
333
- continue;
334
- }
335
- let previewUrl = `${origin}/?path=/story/${story.id}`;
336
- const argsParam = buildArgsParam(story.input.props ?? {});
337
- if (argsParam) previewUrl += `&args=${argsParam}`;
338
- const globalsParam = buildArgsParam(story.input.globals ?? {});
339
- if (globalsParam) previewUrl += `&globals=${globalsParam}`;
340
- structuredResult.push({
341
- title: indexEntry.title,
342
- name: indexEntry.name,
343
- previewUrl
344
- });
345
- textResult.push(previewUrl);
346
- }
347
- if (!disableTelemetry) await collectTelemetry({
348
- event: "tool:previewStories",
349
- server,
350
- toolset: "dev",
351
- inputStoryCount: input.stories.length,
352
- outputStoryCount: structuredResult.length
353
- });
354
- return {
355
- content: textResult.map((text) => ({
356
- type: "text",
357
- text
358
- })),
359
- structuredContent: { stories: structuredResult }
360
- };
361
- } catch (error) {
362
- return errorToMCPContent(error);
363
- }
364
- });
365
- }
366
-
367
- //#endregion
368
- //#region src/tools/run-story-tests.ts
369
- /**
370
- * Check if addon-vitest is available by trying to import its constants.
371
- * Returns the constants if available, undefined otherwise.
372
- */
383
+ Use IDs discovered from ${LIST_TOOL_NAME} (withStoryIds=true) or ${GET_TOOL_NAME}.`
384
+ )
385
+ ),
386
+ ...StoryInputProps
387
+ })
388
+ ]), StoryInputArray = v.array(StoryInput);
389
+
390
+ // src/tools/run-story-tests.ts
373
391
  async function getAddonVitestConstants() {
374
- try {
375
- const mod = await import("@storybook/addon-vitest/constants");
376
- return {
377
- TRIGGER_TEST_RUN_REQUEST: mod.TRIGGER_TEST_RUN_REQUEST,
378
- TRIGGER_TEST_RUN_RESPONSE: mod.TRIGGER_TEST_RUN_RESPONSE
379
- };
380
- } catch {
381
- return;
382
- }
383
- }
384
- const RunStoryTestsInput = v.object({
385
- stories: v.optional(v.pipe(StoryInputArray, v.description(`Stories to test for focused feedback. Omit this field to run tests for all available stories.
392
+ try {
393
+ let mod = await import("@storybook/addon-vitest/constants");
394
+ return {
395
+ TRIGGER_TEST_RUN_REQUEST: mod.TRIGGER_TEST_RUN_REQUEST,
396
+ TRIGGER_TEST_RUN_RESPONSE: mod.TRIGGER_TEST_RUN_RESPONSE
397
+ };
398
+ } catch {
399
+ return;
400
+ }
401
+ }
402
+ var RunStoryTestsInput = v2.object({
403
+ stories: v2.optional(
404
+ v2.pipe(
405
+ StoryInputArray,
406
+ v2.description(
407
+ `Stories to test for focused feedback. Omit this field to run tests for all available stories.
386
408
  Prefer running tests for specific stories while developing to get faster feedback,
387
409
  and only omit this when you explicitly need to run all tests for comprehensive verification.
388
410
  Prefer { storyId } when you don't already have story file context, since this avoids filesystem discovery.
389
411
  Use { storyId } when IDs were discovered from documentation tools.
390
- Use { absoluteStoryPath + exportName } only when you're currently working in a story file and already know those values.`))),
391
- a11y: v.optional(v.pipe(v.boolean(), v.description("Whether to run accessibility tests. Defaults to true. Disable if you only need component test results.")), true)
412
+ Use { absoluteStoryPath + exportName } only when you're currently working in a story file and already know those values.`
413
+ )
414
+ )
415
+ ),
416
+ a11y: v2.optional(
417
+ v2.pipe(
418
+ v2.boolean(),
419
+ v2.description(
420
+ "Whether to run accessibility tests. Defaults to true. Disable if you only need component test results."
421
+ )
422
+ ),
423
+ !0
424
+ )
392
425
  });
393
- /**
394
- * Creates a queue that ensures concurrent calls are executed in sequence.
395
- * Call `wait()` to wait for your turn, then call the
396
- * returned `done()` function when done to unblock the next caller.
397
- */
398
- function createAsyncQueue() {
399
- let tail = Promise.resolve();
400
- /**
401
- * Wait for all previously queued operations to complete, then return
402
- * a `done` function that must be called when the current operation finishes.
403
- */
404
- async function wait() {
405
- let done;
406
- const gate = new Promise((resolve) => {
407
- done = resolve;
408
- });
409
- const previousTail = tail;
410
- tail = previousTail.then(() => gate, () => gate);
411
- await previousTail.catch(() => {});
412
- return done;
413
- }
414
- return { wait };
415
- }
416
- async function addRunStoryTestsTool(server, { a11yEnabled }) {
417
- const addonVitestConstants = await getAddonVitestConstants();
418
- const testRunQueue = createAsyncQueue();
419
- const description = `Run story tests.
426
+ function getRunStoryTestsToolDescription(a11yEnabled2) {
427
+ return `Run story tests.
428
+ Run them after editing anything that changes how the UI looks \u2014 components, stories, styles, CSS, themes, colors, or design tokens \u2014 shell-level substitutes like typecheck, lint, or package.json test scripts do not replace this.
420
429
  Provide stories for focused runs (faster while iterating),
421
430
  or omit stories to run all tests for full-project verification.
422
431
  Use this continuously to monitor test results as you work on your UI components and stories.
423
- Results will include passing/failing status` + (a11yEnabled ? `, and accessibility violation reports.
432
+ Results will include passing/failing status` + (a11yEnabled2 ? `, and accessibility violation reports.
424
433
  For visual/design accessibility violations (for example color contrast), ask the user before changing styles.` : ".");
425
- server.tool({
426
- name: RUN_STORY_TESTS_TOOL_NAME,
427
- title: "Storybook Tests",
428
- description,
429
- schema: RunStoryTestsInput,
430
- enabled: () => {
431
- if (!addonVitestConstants) return false;
432
- return server.ctx.custom?.toolsets?.test ?? true;
433
- }
434
- }, async (input) => {
435
- let done;
436
- try {
437
- done = await testRunQueue.wait();
438
- const runA11y = input.a11y ?? true;
439
- const { origin, options, disableTelemetry } = server.ctx.custom ?? {};
440
- if (!origin) throw new Error("Origin is required in addon context");
441
- if (!options) throw new Error("Options are required in addon context");
442
- const channel = options.channel;
443
- if (!channel) throw new Error("Channel is not available");
444
- let storyIds;
445
- let inputStoryCount = 0;
446
- if (input.stories) {
447
- const resolvedStories = findStoryIds(await fetchStoryIndex(origin), input.stories);
448
- storyIds = resolvedStories.filter((story) => "id" in story).map((story) => story.id);
449
- inputStoryCount = input.stories.length;
450
- if (storyIds.length === 0) {
451
- const errorMessages = resolvedStories.filter((story) => "errorMessage" in story).map((story) => story.errorMessage).join("\n");
452
- if (!disableTelemetry) await collectTelemetry({
453
- event: "tool:runStoryTests",
454
- server,
455
- toolset: "test",
456
- runA11y,
457
- inputStoryCount,
458
- matchedStoryCount: 0,
459
- passingStoryCount: 0,
460
- failingStoryCount: 0,
461
- a11yViolationCount: 0,
462
- unhandledErrorCount: 0
463
- });
464
- return { content: [{
465
- type: "text",
466
- text: `No stories found matching the provided input.
434
+ }
435
+ function getRunStoryTestsToolMetadata({ a11yEnabled: a11yEnabled2 }) {
436
+ return {
437
+ name: RUN_STORY_TESTS_TOOL_NAME,
438
+ title: "Storybook Tests",
439
+ description: getRunStoryTestsToolDescription(a11yEnabled2),
440
+ schema: RunStoryTestsInput
441
+ };
442
+ }
443
+ function createAsyncQueue() {
444
+ let tail = Promise.resolve();
445
+ async function wait() {
446
+ let done, gate = new Promise((resolve) => {
447
+ done = resolve;
448
+ }), previousTail = tail;
449
+ return tail = previousTail.then(
450
+ () => gate,
451
+ () => gate
452
+ ), await previousTail.catch(() => {
453
+ }), done;
454
+ }
455
+ return { wait };
456
+ }
457
+ async function addRunStoryTestsTool(server, { a11yEnabled: a11yEnabled2 }, enabled = () => server.ctx.custom?.toolsets?.test ?? !0) {
458
+ let addonVitestConstants = await getAddonVitestConstants(), testRunQueue = createAsyncQueue();
459
+ server.tool(
460
+ {
461
+ ...getRunStoryTestsToolMetadata({ a11yEnabled: a11yEnabled2 }),
462
+ enabled: () => addonVitestConstants ? typeof enabled == "function" ? enabled() : enabled : !1
463
+ },
464
+ async (input) => {
465
+ let done;
466
+ try {
467
+ done = await testRunQueue.wait();
468
+ let runA11y = input.a11y ?? !0, { origin: origin2, options, disableTelemetry: disableTelemetry2 } = server.ctx.custom ?? {};
469
+ if (!origin2)
470
+ throw new Error("Origin is required in addon context");
471
+ if (!options)
472
+ throw new Error("Options are required in addon context");
473
+ let channel = options.channel;
474
+ if (!channel)
475
+ throw new Error("Channel is not available");
476
+ let storyIds, inputStoryCount = 0;
477
+ if (input.stories) {
478
+ let index = await getStoryIndex(options), resolvedStories = findStoryIds(index, input.stories);
479
+ if (storyIds = resolvedStories.filter((story) => "id" in story).map((story) => story.id), inputStoryCount = input.stories.length, storyIds.length === 0) {
480
+ let errorMessages = resolvedStories.filter((story) => "errorMessage" in story).map((story) => story.errorMessage).join(`
481
+ `);
482
+ return disableTelemetry2 || await collectTelemetry({
483
+ event: "tool:runStoryTests",
484
+ server,
485
+ toolset: "test",
486
+ runA11y,
487
+ inputStoryCount,
488
+ matchedStoryCount: 0,
489
+ passingStoryCount: 0,
490
+ failingStoryCount: 0,
491
+ a11yViolationCount: 0,
492
+ unhandledErrorCount: 0
493
+ }), {
494
+ content: [
495
+ {
496
+ type: "text",
497
+ text: `No stories found matching the provided input.
467
498
 
468
499
  ${errorMessages}`
469
- }] };
470
- }
471
- logger.info(`Running focused tests for story IDs: ${storyIds.join(", ")}`);
472
- } else logger.info("Running tests for all stories");
473
- const testResults = (await triggerTestRun(channel, addonVitestConstants.TRIGGER_TEST_RUN_REQUEST, addonVitestConstants.TRIGGER_TEST_RUN_RESPONSE, storyIds, { a11y: runA11y })).result;
474
- if (!testResults) throw new Error("Test run response missing result data");
475
- const { text, summary } = formatRunStoryTestResults({
476
- testResults,
477
- runA11y,
478
- origin
479
- });
480
- if (!disableTelemetry) await collectTelemetry({
481
- event: "tool:runStoryTests",
482
- server,
483
- toolset: "test",
484
- runA11y,
485
- inputStoryCount,
486
- matchedStoryCount: testResults.storyIds?.length ?? storyIds?.length ?? 0,
487
- ...summary
488
- });
489
- return { content: [{
490
- type: "text",
491
- text
492
- }] };
493
- } catch (error) {
494
- return errorToMCPContent(error);
495
- } finally {
496
- try {
497
- done?.();
498
- } catch (error) {
499
- logger.warn(`Failed to release test run queue: ${String(error)}`);
500
- }
501
- }
502
- });
503
- }
504
- /**
505
- * Trigger a test run via Storybook channel events.
506
- * This is the channel-based API for triggering tests in addon-vitest.
507
- */
500
+ }
501
+ ]
502
+ };
503
+ }
504
+ logger4.info(`Running focused tests for story IDs: ${storyIds.join(", ")}`);
505
+ } else
506
+ logger4.info("Running tests for all stories");
507
+ let testResults = (await triggerTestRun(
508
+ channel,
509
+ addonVitestConstants.TRIGGER_TEST_RUN_REQUEST,
510
+ addonVitestConstants.TRIGGER_TEST_RUN_RESPONSE,
511
+ storyIds,
512
+ { a11y: runA11y }
513
+ )).result;
514
+ if (!testResults)
515
+ throw new Error("Test run response missing result data");
516
+ let { text, summary } = formatRunStoryTestResults({
517
+ testResults,
518
+ runA11y,
519
+ origin: origin2
520
+ });
521
+ return disableTelemetry2 || await collectTelemetry({
522
+ event: "tool:runStoryTests",
523
+ server,
524
+ toolset: "test",
525
+ runA11y,
526
+ inputStoryCount,
527
+ matchedStoryCount: testResults.storyIds?.length ?? storyIds?.length ?? 0,
528
+ ...summary
529
+ }), {
530
+ content: [
531
+ {
532
+ type: "text",
533
+ text
534
+ }
535
+ ]
536
+ };
537
+ } catch (error) {
538
+ return errorToMCPContent(error);
539
+ } finally {
540
+ try {
541
+ done?.();
542
+ } catch (error) {
543
+ logger4.warn(`Failed to release test run queue: ${String(error)}`);
544
+ }
545
+ }
546
+ }
547
+ );
548
+ }
508
549
  function triggerTestRun(channel, triggerTestRunRequestEventName, triggerTestRunResponseEventName, storyIds, config) {
509
- return new Promise((resolve, reject) => {
510
- const requestId = `mcp-${Date.now()}`;
511
- let settled = false;
512
- const cleanup = () => {
513
- channel.off(triggerTestRunResponseEventName, handleResponse);
514
- };
515
- const settle = (callback) => {
516
- if (settled) return;
517
- settled = true;
518
- cleanup();
519
- callback();
520
- };
521
- const handleResponse = (payload) => {
522
- if (payload.requestId !== requestId) return;
523
- switch (payload.status) {
524
- case "completed":
525
- if (payload.result) settle(() => resolve(payload));
526
- else settle(() => reject(/* @__PURE__ */ new Error("Test run completed but no result was returned")));
527
- break;
528
- case "error":
529
- settle(() => reject(new Error(payload.error?.message ?? "Test run failed with unknown error")));
530
- break;
531
- case "cancelled":
532
- settle(() => reject(/* @__PURE__ */ new Error("Test run was cancelled")));
533
- break;
534
- default: settle(() => reject(/* @__PURE__ */ new Error("Unexpected test run response")));
535
- }
536
- };
537
- channel.on(triggerTestRunResponseEventName, handleResponse);
538
- const request = {
539
- requestId,
540
- actor: "addon-mcp",
541
- storyIds,
542
- config
543
- };
544
- try {
545
- channel.emit(triggerTestRunRequestEventName, request);
546
- } catch (error) {
547
- settle(() => reject(error instanceof Error ? error : new Error(String(error))));
548
- }
549
- });
550
- }
551
- function formatRunStoryTestResults({ testResults, runA11y, origin }) {
552
- const sections = [];
553
- const componentTestStatuses = testResults.componentTestStatuses;
554
- const passingStories = componentTestStatuses.filter((status) => status.value === "status-value:success");
555
- const failingStories = componentTestStatuses.filter((status) => status.value === "status-value:error");
556
- if (passingStories.length > 0) sections.push(formatPassingStoriesSection(passingStories));
557
- if (failingStories.length > 0) sections.push(formatFailingStoriesSection(failingStories));
558
- const a11yReports = testResults.a11yReports;
559
- const a11yViolationCount = runA11y ? countA11yViolations(a11yReports) : 0;
560
- if (runA11y && a11yReports && Object.keys(a11yReports).length > 0) {
561
- const a11ySection = formatA11yReportsSection({
562
- a11yReports,
563
- origin
564
- });
565
- if (a11ySection) sections.push(a11ySection);
566
- }
567
- if (testResults.unhandledErrors.length > 0) sections.push(formatUnhandledErrorsSection(testResults.unhandledErrors));
568
- return {
569
- text: sections.join("\n\n"),
570
- summary: {
571
- passingStoryCount: passingStories.length,
572
- failingStoryCount: failingStories.length,
573
- a11yViolationCount,
574
- unhandledErrorCount: testResults.unhandledErrors.length
575
- }
576
- };
550
+ return new Promise((resolve, reject) => {
551
+ let requestId = `mcp-${Date.now()}`, settled = !1, cleanup = () => {
552
+ channel.off(triggerTestRunResponseEventName, handleResponse);
553
+ }, settle = (callback) => {
554
+ settled || (settled = !0, cleanup(), callback());
555
+ }, handleResponse = (payload) => {
556
+ if (payload.requestId === requestId)
557
+ switch (payload.status) {
558
+ case "completed":
559
+ payload.result ? settle(() => resolve(payload)) : settle(() => reject(new Error("Test run completed but no result was returned")));
560
+ break;
561
+ case "error":
562
+ settle(
563
+ () => reject(new Error(payload.error?.message ?? "Test run failed with unknown error"))
564
+ );
565
+ break;
566
+ case "cancelled":
567
+ settle(() => reject(new Error("Test run was cancelled")));
568
+ break;
569
+ default: {
570
+ let exhaustive = payload.status;
571
+ return settle(() => reject(new Error("Unexpected test run response"))), exhaustive;
572
+ }
573
+ }
574
+ };
575
+ channel.on(triggerTestRunResponseEventName, handleResponse);
576
+ let request = {
577
+ requestId,
578
+ actor: "addon-mcp",
579
+ storyIds,
580
+ config
581
+ };
582
+ try {
583
+ channel.emit(triggerTestRunRequestEventName, request);
584
+ } catch (error) {
585
+ settle(() => reject(error instanceof Error ? error : new Error(String(error))));
586
+ }
587
+ });
588
+ }
589
+ function formatRunStoryTestResults({
590
+ testResults,
591
+ runA11y,
592
+ origin: origin2
593
+ }) {
594
+ let sections = [], componentTestStatuses = testResults.componentTestStatuses, passingStories = componentTestStatuses.filter(
595
+ (status) => status.value === "status-value:success"
596
+ ), failingStories = componentTestStatuses.filter(
597
+ (status) => status.value === "status-value:error"
598
+ );
599
+ passingStories.length > 0 && sections.push(formatPassingStoriesSection(passingStories)), failingStories.length > 0 && sections.push(formatFailingStoriesSection(failingStories));
600
+ let a11yReports = testResults.a11yReports, a11yViolationCount = runA11y ? countA11yViolations(a11yReports) : 0;
601
+ if (runA11y && a11yReports && Object.keys(a11yReports).length > 0) {
602
+ let a11ySection = formatA11yReportsSection({ a11yReports, origin: origin2 });
603
+ a11ySection && sections.push(a11ySection);
604
+ }
605
+ return testResults.unhandledErrors.length > 0 && sections.push(formatUnhandledErrorsSection(testResults.unhandledErrors)), {
606
+ text: sections.join(`
607
+
608
+ `),
609
+ summary: {
610
+ passingStoryCount: passingStories.length,
611
+ failingStoryCount: failingStories.length,
612
+ a11yViolationCount,
613
+ unhandledErrorCount: testResults.unhandledErrors.length
614
+ }
615
+ };
577
616
  }
578
617
  function formatPassingStoriesSection(passingStories) {
579
- return `## Passing Stories
618
+ return `## Passing Stories
580
619
 
581
- - ${passingStories.map((status) => status.storyId).join("\n- ")}`;
620
+ - ${passingStories.map((status) => status.storyId).join(`
621
+ - `)}`;
582
622
  }
583
623
  function formatFailingStoriesSection(statuses) {
584
- return `## Failing Stories
624
+ return `## Failing Stories
625
+
626
+ ${statuses.map(
627
+ (status) => `### ${status.storyId}
585
628
 
586
- ${statuses.map((status) => `### ${status.storyId}
629
+ ${status.description || "No failure details available."}`
630
+ ).join(`
587
631
 
588
- ${status.description || "No failure details available."}`).join("\n\n")}`;
632
+ `)}`;
589
633
  }
590
- function formatA11yReportsSection({ a11yReports, origin }) {
591
- const a11yViolationSections = [];
592
- for (const [storyId, reports] of Object.entries(a11yReports)) for (const report of reports) {
593
- if ("error" in report && report.error) {
594
- a11yViolationSections.push(`### ${storyId} - Error
634
+ function formatA11yReportsSection({
635
+ a11yReports,
636
+ origin: origin2
637
+ }) {
638
+ let a11yViolationSections = [];
639
+ for (let [storyId, reports] of Object.entries(a11yReports))
640
+ for (let report of reports) {
641
+ if ("error" in report && report.error) {
642
+ a11yViolationSections.push(`### ${storyId} - Error
595
643
 
596
644
  ${report.error.message}`);
597
- continue;
598
- }
599
- const violations = getA11yViolations(report);
600
- if (violations.length === 0) continue;
601
- for (const violation of violations) {
602
- const nodes = violation.nodes.map((node) => {
603
- const inspectLink = node.linkPath ? `${origin}${node.linkPath}` : void 0;
604
- const parts = [];
605
- if (node.impact) parts.push(`- **Impact**: ${node.impact}`);
606
- if (node.failureSummary || node.message) parts.push(` **Message**: ${node.failureSummary || node.message}`);
607
- parts.push(` **Element**: ${node.html || "(no html available)"}`);
608
- if (inspectLink) parts.push(` **Inspect**: ${inspectLink}`);
609
- return parts.join("\n");
610
- }).join("\n");
611
- a11yViolationSections.push(`### ${storyId} - ${violation.id}
645
+ continue;
646
+ }
647
+ let violations = getA11yViolations(report);
648
+ if (violations.length !== 0)
649
+ for (let violation of violations) {
650
+ let nodes = violation.nodes.map((node) => {
651
+ let inspectLink = node.linkPath ? `${origin2}${node.linkPath}` : void 0, parts = [];
652
+ return node.impact && parts.push(`- **Impact**: ${node.impact}`), (node.failureSummary || node.message) && parts.push(` **Message**: ${node.failureSummary || node.message}`), parts.push(` **Element**: ${node.html || "(no html available)"}`), inspectLink && parts.push(` **Inspect**: ${inspectLink}`), parts.join(`
653
+ `);
654
+ }).join(`
655
+ `);
656
+ a11yViolationSections.push(`### ${storyId} - ${violation.id}
612
657
 
613
658
  ${violation.description}
614
659
 
615
660
  #### Affected Elements
616
661
  ${nodes}`);
617
- }
618
- }
619
- if (a11yViolationSections.length === 0) return;
620
- return `## Accessibility Violations
662
+ }
663
+ }
664
+ if (a11yViolationSections.length !== 0)
665
+ return `## Accessibility Violations
621
666
 
622
- ${a11yViolationSections.join("\n\n")}`;
667
+ ${a11yViolationSections.join(`
668
+
669
+ `)}`;
623
670
  }
624
671
  function formatUnhandledErrorsSection(errors) {
625
- return `## Unhandled Errors
672
+ return `## Unhandled Errors
626
673
 
627
- ${errors.map((unhandledError) => `### ${unhandledError.name || "Unknown Error"}
674
+ ${errors.map(
675
+ (unhandledError) => `### ${unhandledError.name || "Unknown Error"}
628
676
 
629
677
  **Error message**: ${unhandledError.message || "No message available"}
630
678
  **Path**: ${unhandledError.VITEST_TEST_PATH || "No path available"}
631
679
  **Test name**: ${unhandledError.VITEST_TEST_NAME || "No test name available"}
632
680
  **Stack trace**:
633
- ${unhandledError.stack || "No stack trace available"}`).join("\n\n")}`;
681
+ ${unhandledError.stack || "No stack trace available"}`
682
+ ).join(`
683
+
684
+ `)}`;
634
685
  }
635
686
  function countA11yViolations(a11yReports) {
636
- let count = 0;
637
- for (const reports of Object.values(a11yReports ?? {})) for (const report of reports) {
638
- if ("error" in report && report.error) continue;
639
- count += getA11yViolations(report).length;
640
- }
641
- return count;
687
+ let count = 0;
688
+ for (let reports of Object.values(a11yReports ?? {}))
689
+ for (let report of reports)
690
+ "error" in report && report.error || (count += getA11yViolations(report).length);
691
+ return count;
642
692
  }
643
693
  function getA11yViolations(report) {
644
- if (!("violations" in report)) return [];
645
- const { violations } = report;
646
- if (!Array.isArray(violations)) return [];
647
- return violations.map((violation) => ({
648
- id: violation.id,
649
- description: violation.description,
650
- nodes: violation.nodes.map((node) => ({
651
- impact: typeof node.impact === "string" ? node.impact : void 0,
652
- failureSummary: typeof node.failureSummary === "string" ? node.failureSummary : void 0,
653
- html: typeof node.html === "string" ? node.html : void 0,
654
- linkPath: typeof node.linkPath === "string" ? node.linkPath : void 0
655
- }))
656
- }));
657
- }
658
-
659
- //#endregion
660
- //#region src/instructions/storybook-story-instructions.md
661
- var storybook_story_instructions_default = "# Writing User Interfaces\n\nWhen writing UI, prefer breaking larger components up into smaller parts.\n\nALWAYS write a Storybook story for any component written. If editing a component, ensure appropriate changes have been made to stories for that component.\n\n## How to write good stories\n\nGoal: Cover every distinct piece of business logic and state the component can reach (happy paths, error/edge states, loading, permissions/roles, empty states, variations from props/context). Avoid redundant stories that show the same logic.\n\nInteractivity: If the component is interactive, add Interaction tests using play functions that drive the UI with storybook/test utilities (e.g., fn, userEvent, expect). Simulate key user flows: clicking buttons/links, typing, focus/blur, keyboard nav, form submit, async responses, toggle/selection changes, pagination/filters, etc. When passing `fn` functions as `args` for callback functions, make sure to add a play function which interacts with the component and assert whether the callback function was actually called.\n\nData/setup: Provide realistic props, state, and mocked data. Include meaningful labels/text to make behaviors observable. Stub network/services with deterministic fixtures; keep stories reliable.\n\nAssertions: In play functions, assert the visible outcome of the interaction (text, aria state, enabled/disabled, class/state changes, emitted events). Prefer role/label-based queries.\n\nVariants to consider (pick only those that change behavior): default vs. alternate themes; loading vs. loaded vs. empty vs. error; validated vs. invalid input; permissions/roles/capabilities; feature flags; size/density/layout variants that alter logic.\n\nAccessibility: Use semantic roles/labels; ensure focusable/keyboard interactions are test-covered where relevant.\n\nNaming/structure: Use clear story names that describe the scenario (“Error state after failed submit”). Group related variants logically; don’t duplicate.\n\nImports/format: Import Meta/StoryObj from the framework package; import test helpers from storybook/test (not @storybook/test). Keep stories minimal—only what's needed to demonstrate behavior.\n\n## Storybook 9 Essential Changes for Story Writing\n\n### Package Consolidation\n\n#### `Meta` and `StoryObj` imports\n\nUpdate story imports to use the framework package:\n\n```diff\n- import { Meta, StoryObj } from '{{RENDERER}}';\n+ import { Meta, StoryObj } from '{{FRAMEWORK}}';\n```\n\n#### Test utility imports\n\nUpdate test imports to use `storybook/test` instead of `@storybook/test`\n\n```diff\n- import { fn } from '@storybook/test';\n+ import { fn } from 'storybook/test';\n```\n\n### Global State Changes\n\nThe `globals` annotation has be renamed to `initialGlobals`:\n\n```diff\n// .storybook/preview.js\nexport default {\n- globals: { theme: 'light' }\n+ initialGlobals: { theme: 'light' }\n};\n```\n\n### Autodocs Configuration\n\nInstead of `parameters.docs.autodocs` in main.js, use tags:\n\n```js\n// .storybook/preview.js or in individual stories\nexport default {\n tags: ['autodocs'], // generates autodocs for all stories\n};\n```\n\n### Mocking imports in Storybook\n\nTo mock imports in Storybook, use Storybook's mocking features. ALWAYS mock external dependencies to ensure stories render consistently.\n\n1. **Register in the mock in Storybook's preview file**:\n To mock dependendencies, you MUST register a module mock in `.storybook/preview.ts` (or equivalent):\n\n```js\nimport { sb } from 'storybook/test';\n\n// Prefer spy mocks (keeps functions, but allows to override them and spy on them)\nsb.mock(import('some-library'), { spy: true });\n```\n\n**Important: Use file extensions when referring to relative files!**\n\n```js\nsb.mock(import('./relative/module.ts'), { spy: true });\n```\n\n2. **Specify mock values in stories**:\n You can override the behaviour of the mocks per-story using `beforeEach` and the `mocked()` type function:\n\n```js\nimport { expect, mocked, fn } from 'storybook/test';\nimport { library } from 'some-library';\n\nconst meta = {\n component: AuthButton,\n beforeEach: async () => {\n mocked(library).mockResolvedValue({ user: 'data' });\n },\n};\n\nexport const LoggedIn: Story = {\n play: async ({ canvas }) => {\n await expect(library).toHaveBeenCalled();\n },\n};\n```\n\nBefore doing this ensure you have mocked the import in the preview file.\n\n### Play Function Parameters\n\n- The play function has a `canvas` parameter that can be used directly with testing-library-like query methods.\n- It also has a `canvasElement` which is the actual DOM element.\n- The `within`-function imported from `storybook/test` transforms a DOM element to an object with query methods, similar to `canvas`.\n\n**DO NOT** use `within(canvas)` - it is redundant because `canvas` already has the query methods, `canvas` is not a DOM element.\n\n```ts\n// ✅ Correct: Use canvas directly\nplay: async ({ canvas }) => {\n await canvas.getByLabelText('Submit').click();\n};\n\n// ⚠️ Also acceptable: Use `canvasElement` with `within`\nimport { within } from 'storybook/test';\n\nplay: async ({ canvasElement }) => {\n const canvas = within(canvasElement);\n await canvas.getByLabelText('Submit').click();\n};\n\n// ❌ Wrong: Do NOT use within(canvas)\nplay: async ({ canvas }) => {\n const screen = within(canvas); // Error!\n};\n```\n\n### Key Requirements\n\n- **Node.js 20+**, **TypeScript 4.9+**\n- React Native uses `.rnstorybook` directory\n\n## Story Linking Agent Behavior\n\n- ALWAYS provide story links after any changes to stories files, including changes to existing stories.\n- After changing any UI components, ALWAYS search for related stories that might cover the changes you've made. If you find any, provide the story links to the user. THIS IS VERY IMPORTANT, as it allows the user to visually inspect the changes you've made. Even later in a session when changing UI components or stories that have already been linked to previously, YOU MUST PROVIDE THE LINKS AGAIN.\n- Use the {{PREVIEW_STORIES_TOOL_NAME}} tool to get the correct URLs for links to stories.\n";
662
-
663
- //#endregion
664
- //#region src/instructions/story-testing-instructions.md
665
- var story_testing_instructions_default = "## Story Testing Requirements\n\n**Run `{{RUN_STORY_TESTS_TOOL_NAME}}` after EVERY component or story change.** This includes creating, modifying, or refactoring components, stories, or their dependencies.\n\n### Workflow\n\n1. Make your change\n2. Run `{{RUN_STORY_TESTS_TOOL_NAME}}` with affected stories for focused feedback (faster while iterating)\n3. If tests fail: analyze, fix{{A11Y_FIX_SUFFIX}}, re-run\n4. Repeat until all tests pass\n\nDo not skip tests, ignore failures, or move on with failing tests. If stuck after multiple attempts, report to user.\n\n### Focused vs. full-suite test runs\n\n- Prefer focused runs (`stories` input) during development to validate the parts you changed quickly.\n- Run all tests (omit `stories`) before final handoff, after broad/refactor changes, or when impact is unclear and you need project-wide verification.\n";
666
-
667
- //#endregion
668
- //#region src/instructions/a11y-instructions.md
669
- var a11y_instructions_default = "### Accessibility Violations\n\n**Fix automatically** (semantic/structural, no visual change):\n\n- ARIA attributes, roles, labels, alt text\n- Heading hierarchy, landmarks, table structure\n- Keyboard access (tabindex, focus, handlers)\n- Document-level: lang attr, frame titles, duplicate IDs\n\n**Confirm with user first** (visual/design changes):\n\n- Color contrast ratios\n- Font sizes, spacing, layout\n- Focus indicator styling\n\nDescribe the issue, ask how the user wants to proceed, and provide 2-3 concrete options.\nDo not auto-apply visual changes before user confirmation, and do not claim visual issues are fixed until they approve an option.\n";
670
-
671
- //#endregion
672
- //#region src/utils/is-addon-a11y-enabled.ts
673
- /**
674
- * Check if @storybook/addon-a11y is enabled in the Storybook configuration.
675
- */
694
+ if (!("violations" in report))
695
+ return [];
696
+ let { violations } = report;
697
+ return Array.isArray(violations) ? violations.map((violation) => ({
698
+ id: violation.id,
699
+ description: violation.description,
700
+ nodes: violation.nodes.map((node) => ({
701
+ impact: typeof node.impact == "string" ? node.impact : void 0,
702
+ failureSummary: typeof node.failureSummary == "string" ? node.failureSummary : void 0,
703
+ html: typeof node.html == "string" ? node.html : void 0,
704
+ linkPath: typeof node.linkPath == "string" ? node.linkPath : void 0
705
+ }))
706
+ })) : [];
707
+ }
708
+
709
+ // src/utils/is-addon-a11y-enabled.ts
676
710
  async function isAddonA11yEnabled(options) {
677
- try {
678
- return await options.presets.apply("isAddonA11yEnabled", false);
679
- } catch {
680
- return false;
681
- }
682
- }
683
-
684
- //#endregion
685
- //#region src/tools/get-storybook-story-instructions.ts
686
- async function addGetUIBuildingInstructionsTool(server) {
687
- const addonVitestAvailable = !!await getAddonVitestConstants();
688
- server.tool({
689
- name: GET_UI_BUILDING_INSTRUCTIONS_TOOL_NAME,
690
- title: "Storybook Story Development Instructions",
691
- get description() {
692
- const testToolsetAvailable = (server.ctx.custom?.toolsets?.test ?? true) && addonVitestAvailable;
693
- const a11yAvailable = testToolsetAvailable && (server.ctx.custom?.a11yEnabled ?? false);
694
- return `Get comprehensive instructions for writing, testing, and fixing Storybook stories (.stories.tsx, .stories.ts, .stories.jsx, .stories.js, .stories.svelte, .stories.vue files).
711
+ try {
712
+ return await options.presets.apply("isAddonA11yEnabled", !1);
713
+ } catch {
714
+ return !1;
715
+ }
716
+ }
717
+
718
+ // src/utils/get-tool-availability.ts
719
+ function getEffectiveToolAvailability(availability, { multiSource = !1 } = {}) {
720
+ return multiSource ? {
721
+ ...availability,
722
+ docsEnabled: !0,
723
+ docsHasManifests: !0,
724
+ docsFeatureEnabled: !0
725
+ } : availability;
726
+ }
727
+ async function getToolAvailability(options, { features: features2, moduleGraphSupported: moduleGraphSupportedOverride } = {}) {
728
+ let resolvedFeatures = features2 ?? await options.presets.apply("features", {}), [moduleGraphSupported, reviewStatus, manifestStatus, addonVitestConstants, a11yEnabled2] = await Promise.all([
729
+ moduleGraphSupportedOverride ?? isModuleGraphSupported(),
730
+ getReviewStatus(options, { features: resolvedFeatures }),
731
+ getManifestStatus(options),
732
+ getAddonVitestConstants(),
733
+ isAddonA11yEnabled(options)
734
+ ]);
735
+ return {
736
+ moduleGraphSupported,
737
+ changeDetectionEnabled: resolvedFeatures?.changeDetection ?? !1,
738
+ reviewEnabled: reviewStatus.available,
739
+ reviewEnabledForCli: reviewStatus.availableForCli,
740
+ docsEnabled: manifestStatus.available,
741
+ docsHasManifests: manifestStatus.hasManifests,
742
+ docsFeatureEnabled: manifestStatus.hasFeatureFlag,
743
+ testSupported: !!addonVitestConstants,
744
+ a11yEnabled: a11yEnabled2,
745
+ docgenServer: manifestStatus.docgenServer
746
+ };
747
+ }
748
+
749
+ // src/utils/estimate-tokens.ts
750
+ function isWhitespace(code) {
751
+ return code === 32 || code === 9 || code === 10 || code === 13;
752
+ }
753
+ function isAlphanumeric(code) {
754
+ return code >= 48 && code <= 57 || code >= 65 && code <= 90 || code >= 97 && code <= 122 || code === 95;
755
+ }
756
+ function estimateTokens(text) {
757
+ if (!text) return 0;
758
+ let tokenCount = 0, i = 0, len = text.length;
759
+ for (; i < len; ) {
760
+ let code = text.charCodeAt(i);
761
+ if (isWhitespace(code))
762
+ for (tokenCount++, i++; i < len && isWhitespace(text.charCodeAt(i)); )
763
+ i++;
764
+ else if (isAlphanumeric(code))
765
+ for (tokenCount++, i++; i < len && isAlphanumeric(text.charCodeAt(i)); )
766
+ i++;
767
+ else
768
+ tokenCount++, i++;
769
+ }
770
+ return tokenCount;
771
+ }
772
+
773
+ // src/instructions/dev-instructions.md
774
+ var dev_instructions_default = `## UI Building and Story Writing Workflow
775
+
776
+ - Before creating or editing components or stories, call **get-storybook-story-instructions**; its output is the source of truth for imports, story patterns, and testing conventions.
777
+ - {{PREVIEW_STORIES_STEP}}
778
+ - {{FINAL_LINKS_STEP}}{{DISPLAY_REVIEW_STEP}}
779
+ - Only use story IDs returned by tools \u2014 never derive them from file names or memory. **get-stories-by-component** maps any input to stories; its description covers the workflow. No matches means no stories exist yet \u2014 say so.
780
+ `;
781
+
782
+ // src/instructions/legacy-dev-instructions.md
783
+ var legacy_dev_instructions_default = `## UI Building and Story Writing Workflow
784
+
785
+ - Before creating or editing components or stories, call **get-storybook-story-instructions**.
786
+ - Treat its output as the source of truth for imports, story patterns, and testing conventions.
787
+ - After editing anything that changes how the UI looks \u2014 components, stories, styles, themes, colors, design tokens \u2014 call **preview-stories**, no exceptions; a shared file has no stories of its own, so preview its consumers' stories.
788
+ - Include every returned preview URL in your final response.
789
+ `;
790
+
791
+ // src/instructions/legacy-test-instructions.md
792
+ var legacy_test_instructions_default = `## Validation Workflow
793
+
794
+ - After editing anything that changes how the UI looks, run **run-story-tests** \u2014 never a package.json test script.
795
+ - Use focused runs while iterating, then a broad pass before handoff when scope is unclear or wide.
796
+ - Fix failing tests; never report completion while they are failing.
797
+ `;
798
+
799
+ // src/instructions/review-docs-instructions.md
800
+ var review_docs_instructions_default = `## Documentation Workflow
801
+
802
+ **CRITICAL: Never hallucinate component properties!** Undocumented props do not exist \u2014 never assume them from naming or other libraries; verify every prop via these tools, not source or types in node_modules.
803
+
804
+ 1. Call **list-all-documentation** once at task start for component and docs IDs.
805
+ 2. Call **get-documentation** with an \`id\` from that list for props and usage examples.
806
+
807
+ Only reference IDs returned by these tools \u2014 never guess; scope multi-source requests with \`storybookId\`.
808
+ `;
809
+
810
+ // src/instructions/test-instructions.md
811
+ var test_instructions_default = `## Validation Workflow
812
+
813
+ - After editing anything that changes how the UI looks, run **run-story-tests** \u2014 never a package.json test script.
814
+ - Never report completion while story tests are failing.
815
+ `;
816
+
817
+ // src/instructions/build-server-instructions.ts
818
+ import { STORYBOOK_MCP_INSTRUCTIONS } from "@storybook/mcp";
819
+ function getFinalLinksGuidance(reviewToolAvailable) {
820
+ return reviewToolAvailable ? 'In your final user-facing response, show one set of links \u2014 never both. If you published a review with **display-review**, finish your reply with a dedicated review section as the very last thing in the output: its own top-level heading on a line by itself (for example `## \u{1F440} Review your changes`), then a one-line explanation that the review shows the handful of stories most relevant to this change and that, because it is AI-curated, results may be inaccurate or incomplete, then on the next line the review page as a markdown link prefixed with a \u{1F449} so it is easy to spot, using the returned `reviewUrl` (for example `\u{1F449} [Open the Storybook review page](<reviewUrl>)`). Nothing should come after this section. Never also list the individual story or preview URLs. Avoid internal jargon like "collection" or "trigger" in anything the user reads \u2014 those are terms from this tooling, not words that mean anything to them; use plain language unless the user used the term first. A visually observable change is not finished until its review is published \u2014 never substitute preview URLs for the review. Only when there is no review because the change has no visually observable impact, say so plainly; include preview URLs only if the user asked to see specific stories.' : "In your final user-facing response, include every returned preview URL so the user can verify the visual result, ordered consistently (changed-stories fallback first if relevant, then the specific preview URLs).";
821
+ }
822
+ function buildServerInstructions(options) {
823
+ let sections = [
824
+ options.docsEnabled ? "Follow these workflows when working with UI and/or Storybook. Answer questions about component props, API, or usage with the documentation tools \u2014 never from source or type definitions." : "Follow these workflows when working with UI and/or Storybook."
825
+ ], reviewEnabled = options.reviewEnabled ?? !1;
826
+ if (options.devEnabled && !reviewEnabled)
827
+ sections.push(legacy_dev_instructions_default.trim());
828
+ else if (options.devEnabled) {
829
+ let changeDetection = options.changeDetectionEnabled ?? !1, graphSupported = options.moduleGraphSupported ?? !1, previewStoriesStep = changeDetection ? "After editing anything that changes how the UI looks \u2014 components, stories, styles, themes, tokens \u2014 call **get-changed-stories** to discover the affected stories." : graphSupported ? "After editing anything that changes how the UI looks, call **get-stories-by-component** with the files you touched." : "After editing anything that changes how the UI looks, identify the affected stories.";
830
+ sections.push(
831
+ dev_instructions_default.replace("{{PREVIEW_STORIES_STEP}}", previewStoriesStep).replace("{{FINAL_LINKS_STEP}}", "End your final response with the review section from **display-review**'s result \u2014 never substitute preview URLs. **preview-stories** is only for mid-loop iteration or a requested direct link. If nothing visually changed, say so.").replace(
832
+ "{{DISPLAY_REVIEW_STEP}}",
833
+ `
834
+ - After a visually observable UI change, or when the user asks to see or browse stories/components, call **display-review** (again on each iteration) and follow its description and result. Visual work is not done until the review is published; any newly created story MUST be included.`
835
+ ).trim()
836
+ );
837
+ }
838
+ return options.testEnabled && sections.push((reviewEnabled ? test_instructions_default : legacy_test_instructions_default).trim()), options.docsEnabled && sections.push((reviewEnabled ? review_docs_instructions_default : STORYBOOK_MCP_INSTRUCTIONS).trim()), sections.length === 1 ? "" : sections.join(`
839
+
840
+ `);
841
+ }
842
+
843
+ // src/constants.ts
844
+ var PUSH_REVIEW_EVENT = "storybook/review/push-review", REVIEW_PAGE_PATH = "/review/", STORYBOOK_MCP_PROXY_HEADER = "X-Storybook-MCP-Proxy", DEFAULT_MCP_ENDPOINT = "/mcp";
845
+
846
+ // src/tools/tool-registry.ts
847
+ import { logger as logger5 } from "storybook/internal/node-logger";
848
+ import {
849
+ addGetDocumentationTool,
850
+ addGetStoryDocumentationTool,
851
+ addListAllDocumentationTool,
852
+ GET_STORY_TOOL_NAME,
853
+ GET_TOOL_NAME as GET_TOOL_NAME2,
854
+ getDocumentationToolMetadata,
855
+ getListAllDocumentationToolMetadata,
856
+ getStoryDocumentationToolMetadata,
857
+ LIST_TOOL_NAME as LIST_TOOL_NAME2
858
+ } from "@storybook/mcp";
859
+
860
+ // src/tools/display-review.ts
861
+ import * as v3 from "valibot";
862
+
863
+ // src/utils/format-validation-issues.ts
864
+ function formatPath(path5) {
865
+ if (!path5 || path5.length === 0) return "";
866
+ let out = "";
867
+ for (let segment of path5) {
868
+ let key = typeof segment == "object" && segment !== null && "key" in segment ? segment.key : segment;
869
+ typeof key == "number" ? out += `[${key}]` : key != null && (out += out === "" ? String(key) : `.${String(key)}`);
870
+ }
871
+ return out;
872
+ }
873
+ function summarizeIssue(issue) {
874
+ let path5 = formatPath(issue.path);
875
+ if (issue.kind === "schema" && (issue.type === "object" || issue.type === "strict_object" || issue.type === "loose_object") && typeof issue.expected == "string" && issue.expected.length >= 2 && issue.expected.startsWith('"') && issue.expected.endsWith('"') && issue.received === "undefined") {
876
+ let field = issue.expected.slice(1, -1), parentPathStr = formatPath((issue.path ?? []).slice(0, -1)), where = parentPathStr ? ` at \`${parentPathStr}\`` : "";
877
+ return { path: path5, message: `Missing required field \`${field}\`${where}.` };
878
+ }
879
+ return { path: path5, message: issue.message };
880
+ }
881
+ function withFriendlyErrors(schema) {
882
+ let original = schema["~standard"];
883
+ return {
884
+ ...schema,
885
+ "~standard": {
886
+ ...original,
887
+ validate(input) {
888
+ let result = original.validate(input), trim = (r) => (
889
+ // Cast: the spec issue type is the base shape; validators
890
+ // (notably valibot) augment with `kind`, `type`, `expected`,
891
+ // `received` — see {@link StandardSchemaIssue}.
892
+ r.issues ? { issues: r.issues.map(summarizeIssue) } : r
893
+ );
894
+ return result instanceof Promise ? result.then(trim) : trim(result);
895
+ }
896
+ }
897
+ };
898
+ }
899
+
900
+ // src/tools/display-review.ts
901
+ var DISPLAY_REVIEW_TOOL_DESCRIPTION = `Publish a curated review to Storybook's review page for spot-checking **visual impact**. Each call replaces the single active review \u2014 call it again whenever the user iterates on the changes.
902
+
903
+ ## When to call
904
+ - **Trigger 1 \u2014 visual change** (components, stories, CSS, themes, colors, design tokens, i18n \u2014 anything that changes how the UI looks): when the user should spot-check rendering. A shared file (token, style, util) has no stories of its own \u2014 review its consumers' stories. Skip non-visual refactors unless side-effects are plausible. Start from \`get-changed-stories\`; fall back to \`get-stories-by-component\` if change detection is unavailable. Include \`changedFiles\`.
905
+ - **Trigger 2 \u2014 browse request** ("show me the Badge component"): resolve via \`get-stories-by-component\` / \`list-all-documentation\`; you may consult other sources to interpret the ask, but IDs must still come from those tools. Pass \`changedFiles: []\` \u2014 no code changed.
906
+
907
+ ## Hard rules
908
+ 1. Every \`storyId\` MUST come from those tools. Reject IDs derived from file paths, story names, or memory. Unknown IDs cause a runtime error; obtain real IDs via \`get-stories-by-component\` or \`list-all-documentation\`, then retry.
909
+ 2. Every story you CREATED in this change MUST appear in the review \u2014 including interaction/play-function stories. Showing the stories you modified is encouraged too. Curate by grouping, never by omission.
910
+ 3. Prefer 2-5 collections; avoid one-story collections unless truly isolated.
911
+ 4. Follow-up reviews: stabilize collection/story order to avoid disorientation from reshuffling.
912
+ 5. Apply the field formatting rules from each schema property. Do not use em-dashes in review payload field values (title, rationale, description, etc.).
913
+ 6. Do not instruct or tell the user what to do unless they explicitly ask for guidance.
914
+ 7. "Collection" and "trigger" are internal terms for this tool's mechanics and mean nothing to users. Never use them in user-facing text unless the user used them first; say "group of stories" or just describe the contents in plain language.
915
+
916
+ ## Curating (Trigger 1)
917
+ Trace the **visual cascade** up the **import graph** to **page-level UI surfaces** \u2014 one collection per layer (\`distance 0\` \u2192 direct importers \u2192 page context). Include **control stories** where the change is **not supposed to be visible**. **Theme tokens**, **shared styles**, and **layout primitives** need page-level coverage even from a single-file edit. **Localized changes:** affected component \u2192 **usage locations** \u2192 outer surfaces. **Larger features:** central page/module \u2192 lower-level pieces \u2192 outer **usage locations**.
918
+
919
+ ## Curating (Trigger 2)
920
+ Exactly what the user asked for \u2014 **no more, no less**. Group logically or follow **story index hierarchy**.`, ReviewCollectionSchema = v3.object({
921
+ title: v3.pipe(
922
+ v3.string(),
923
+ v3.description(
924
+ "Title describing **what** this collection consists of, phrased the way a person would say it. Avoid typographic marks and CamelCase. Plain text, no markdown."
925
+ )
926
+ ),
927
+ rationale: v3.pipe(
928
+ v3.string(),
929
+ v3.description(
930
+ "Rationale explaining **why** this collection is relevant to the user. Shown alongside the title. One or two sentences. Plain text, no markdown."
931
+ )
932
+ ),
933
+ storyIds: v3.pipe(
934
+ v3.array(v3.string()),
935
+ v3.description(
936
+ 'Story IDs that represent this collection (e.g. "button--primary"). The page renders exactly these.'
937
+ )
938
+ )
939
+ }), ReviewStateSchema = v3.object({
940
+ title: v3.pipe(
941
+ v3.string(),
942
+ v3.description(
943
+ "Terse, human-readable title for the overall review. What is this review about? Avoid typographic marks and CamelCase. Plain text, no markdown."
944
+ )
945
+ ),
946
+ description: v3.pipe(
947
+ v3.string(),
948
+ v3.description(
949
+ "Description of the review scope, including what's there, why it's relevant, and what to look for. Preferably one or two sentences. At most 2 paragraphs for reviews spanning multiple topics. Markdown formatting restricted to **bold**, _italic_, and `code` (backticks). Use emphasis for the key **what** and _why_, and backticks for literal source code references like component or token names."
950
+ )
951
+ ),
952
+ collections: v3.pipe(
953
+ v3.array(ReviewCollectionSchema),
954
+ v3.description(
955
+ "Groups of stories to show in the review, most relevant first. Prefer 2-5 groups."
956
+ )
957
+ ),
958
+ changedFiles: v3.pipe(
959
+ v3.array(v3.string()),
960
+ v3.description(
961
+ "Paths of the files you changed, most central first. Pass an empty array `[]` only when no code changed (browse requests, Trigger 2)."
962
+ )
963
+ )
964
+ }), DisplayReviewOutput = v3.object({
965
+ reviewUrl: v3.pipe(
966
+ v3.string(),
967
+ v3.description(
968
+ "URL of the Storybook review page. Always include this URL in your final user-facing response so the user can open it directly."
969
+ )
970
+ )
971
+ });
972
+ function storybookRootFromRequest(request, trustedOrigin, endpoint) {
973
+ if (request?.url)
974
+ try {
975
+ let url2 = new URL(request.url), normalizedEndpoint = endpoint.replace(/\/$/, ""), normalizedPathname = url2.pathname.replace(/\/$/, ""), rootPath = normalizedPathname.endsWith(normalizedEndpoint) ? normalizedPathname.slice(0, -normalizedEndpoint.length) : normalizedPathname.replace(/\/[^/]+$/, "");
976
+ return `${trustedOrigin.replace(/\/$/, "")}${rootPath}`;
977
+ } catch {
978
+ return;
979
+ }
980
+ }
981
+ function buildReviewUrl(ctx) {
982
+ let trustedOrigin = ctx.origin;
983
+ if (!trustedOrigin)
984
+ throw new Error("Cannot resolve the Storybook URL: missing trusted origin in addon context.");
985
+ return `${(ctx.request ? storybookRootFromRequest(ctx.request, trustedOrigin, ctx.endpoint ?? DEFAULT_MCP_ENDPOINT) ?? trustedOrigin : trustedOrigin).replace(/\/$/, "")}/?path=${REVIEW_PAGE_PATH}`;
986
+ }
987
+ function getDisplayReviewToolMetadata() {
988
+ return {
989
+ name: DISPLAY_REVIEW_TOOL_NAME,
990
+ title: "Display Storybook review",
991
+ description: DISPLAY_REVIEW_TOOL_DESCRIPTION,
992
+ schema: withFriendlyErrors(ReviewStateSchema),
993
+ outputSchema: DisplayReviewOutput
994
+ };
995
+ }
996
+ async function collectUnknownStoryIds(collections, options) {
997
+ let requested = /* @__PURE__ */ new Set(), inOrder = [];
998
+ for (let collection of collections)
999
+ for (let id of collection.storyIds)
1000
+ requested.has(id) || (requested.add(id), inOrder.push(id));
1001
+ if (inOrder.length === 0) return [];
1002
+ let index = await getStoryIndex(options);
1003
+ return inOrder.filter((id) => index.entries[id]?.type !== "story");
1004
+ }
1005
+ function formatUnknownStoryIdsError(unknownIds) {
1006
+ let list = unknownIds.map((id) => `- \`${id}\``).join(`
1007
+ `), plural = unknownIds.length === 1 ? "ID is" : "IDs are";
1008
+ return `Refusing to publish review: ${unknownIds.length} story ${plural} not backed by a story entry in the live Storybook index (docs entries cannot be review slots):
1009
+ ${list}
1010
+
1011
+ This usually means the IDs were inferred from file paths or naming conventions rather than returned by a tool. Resolve real IDs by calling \`get-stories-by-component\` (for components you've edited or want covered) or \`list-all-documentation\` (to browse the index), then retry \`display-review\` with the verified IDs. Do not invent IDs to satisfy this check.`;
1012
+ }
1013
+ async function addDisplayReviewTool(server, enabled = () => server.ctx.custom?.toolsets?.dev ?? !0) {
1014
+ server.tool(
1015
+ {
1016
+ ...getDisplayReviewToolMetadata(),
1017
+ enabled
1018
+ },
1019
+ async (input) => {
1020
+ try {
1021
+ let customContext = server.ctx.custom;
1022
+ if (!customContext?.origin)
1023
+ throw new Error(
1024
+ "Cannot resolve the Storybook URL: missing trusted origin in addon context."
1025
+ );
1026
+ if (!customContext.options)
1027
+ throw new Error("Storybook options are required in addon context.");
1028
+ let unknownIds = await collectUnknownStoryIds(input.collections, customContext.options);
1029
+ if (unknownIds.length > 0)
1030
+ throw new Error(formatUnknownStoryIdsError(unknownIds));
1031
+ let reviewUrl = buildReviewUrl({
1032
+ origin: customContext.origin,
1033
+ request: customContext.request,
1034
+ endpoint: customContext.endpoint
1035
+ });
1036
+ server.ctx.custom?.options?.channel?.emit(PUSH_REVIEW_EVENT, input);
1037
+ let collectionCount = input.collections.length, storyCount = input.collections.reduce((n, c) => n + c.storyIds.length, 0);
1038
+ return customContext.disableTelemetry || await collectTelemetry({
1039
+ event: "tool:displayReview",
1040
+ server,
1041
+ toolset: "dev",
1042
+ collectionCount,
1043
+ storyCount,
1044
+ changedFileCount: input.changedFiles.length
1045
+ }), {
1046
+ content: [
1047
+ {
1048
+ type: "text",
1049
+ text: `Review applied: ${collectionCount} collection${collectionCount === 1 ? "" : "s"}, ${storyCount} stor${storyCount === 1 ? "y" : "ies"}. Storybook is already running at ${customContext.origin} \u2014 reuse it. Do NOT start another Storybook or change its port to view this review; the running instance already serves it.
1050
+
1051
+ Two things you must do now, both of them:
1052
+ 1. **Open ${reviewUrl} yourself in your preview browser.** If you have any browser-preview or navigate tool in this session (e.g. preview_eval or an equivalent), call it on this URL so the review opens in your preview window immediately. Don't merely print the link and stop \u2014 actually open it.
1053
+ 2. **Show the link to the user too.** End your final response with a dedicated review section as the very last thing: its own heading on a line by itself (e.g. \`## \u{1F440} Review your changes\`), then a one-line explanation of what the review is, then on the next line the review page as a markdown link prefixed with a \u{1F449} so it's easy to spot: \`\u{1F449} [Open the Storybook review page](${reviewUrl})\`. For the explanation, use something like: "The review shows the ${storyCount} stor${storyCount === 1 ? "y" : "ies"} most relevant for you to review right now. Because this is AI-curated, results may be inaccurate or incomplete." Put nothing after the link \u2014 not a trailing sentence the user has to hunt for. The user needs to see this link even after you've opened it yourself.`
1054
+ }
1055
+ ],
1056
+ structuredContent: { reviewUrl }
1057
+ };
1058
+ } catch (error) {
1059
+ return errorToMCPContent(error);
1060
+ }
1061
+ }
1062
+ );
1063
+ }
1064
+
1065
+ // src/tools/get-changed-stories.ts
1066
+ import { experimental_getStatusStore } from "storybook/internal/core-server";
1067
+
1068
+ // src/utils/detect-unreachable-changes.ts
1069
+ import { execSync } from "node:child_process";
1070
+ import path2 from "node:path";
1071
+ var SOURCE_EXT_RE = /\.(?:tsx?|jsx?|mjs|cjs)$/i, CHUNK_SIZE = 50;
1072
+ function parsePorcelain(output) {
1073
+ return output.split(`
1074
+ `).filter(Boolean).map((line) => {
1075
+ let rest = line.slice(3), arrow = rest.indexOf(" -> ");
1076
+ return arrow >= 0 ? rest.slice(arrow + 4).trim() : rest.trim();
1077
+ });
1078
+ }
1079
+ async function detectUnreachableChanges(maxFiles = 10) {
1080
+ let moduleGraph = await getModuleGraphService();
1081
+ if (!moduleGraph) return [];
1082
+ if ((await moduleGraph.queries.status.loaded(void 0)).value !== "ready") return [];
1083
+ let workingDir = process.cwd(), porcelain;
1084
+ try {
1085
+ porcelain = execSync("git status --porcelain", {
1086
+ cwd: workingDir,
1087
+ encoding: "utf-8",
1088
+ stdio: ["ignore", "pipe", "ignore"]
1089
+ });
1090
+ } catch {
1091
+ return [];
1092
+ }
1093
+ let relFiles = parsePorcelain(porcelain).filter((f) => SOURCE_EXT_RE.test(f));
1094
+ if (relFiles.length === 0) return [];
1095
+ let unreachable = [];
1096
+ for (let start = 0; start < relFiles.length && unreachable.length < maxFiles; start += CHUNK_SIZE) {
1097
+ let chunk = relFiles.slice(start, start + CHUNK_SIZE), absChunk = chunk.map((rel) => slash(path2.resolve(workingDir, rel))), hits = await moduleGraph.queries.storiesForFiles.loaded({ files: absChunk });
1098
+ for (let [i, rel] of chunk.entries()) {
1099
+ if (unreachable.length >= maxFiles) break;
1100
+ (hits[i]?.length ?? 0) === 0 && unreachable.push(rel);
1101
+ }
1102
+ }
1103
+ return unreachable;
1104
+ }
1105
+ var BANNER_INLINE_LIMIT = 3;
1106
+ function formatPartialCoverageBanner(unreachable) {
1107
+ if (unreachable.length === 0) return "";
1108
+ let fileList = unreachable.length <= BANNER_INLINE_LIMIT ? unreachable.join(", ") : `${unreachable.slice(0, BANNER_INLINE_LIMIT).join(", ")}, +${unreachable.length - BANNER_INLINE_LIMIT} more`, noun = unreachable.length === 1 ? "file" : "files";
1109
+ return `\u26A0 Coverage gap: ${unreachable.length} modified ${noun} unreachable from any story (${fileList}) \u2014 full sanity-check note at end of this response.
1110
+
1111
+ `;
1112
+ }
1113
+ function formatUnreachableHint(unreachable) {
1114
+ return unreachable.length === 0 ? "" : `
1115
+
1116
+ The following working-tree file(s) are modified but unreachable from any story (no static import path connects them \u2014 they are likely theme tokens, decorators, or other Storybook-preview-runtime files):
1117
+ ${unreachable.map((f) => `- ${f}`).join(`
1118
+ `)}
1119
+
1120
+ For these, grep the codebase for their exports (e.g. specific tokens or symbols) to find runtime consumers, then call \`get-stories-by-component\` with those consumer file paths.`;
1121
+ }
1122
+ function formatPartialCoverageHint(unreachable) {
1123
+ return unreachable.length === 0 ? "" : `
1124
+
1125
+ Coverage sanity check: the working tree also contains modified file(s) that aren't reachable from any story above (no static import path connects them \u2014 typically theme tokens, decorators, or other preview-runtime files):
1126
+ ${unreachable.map((f) => `- ${f}`).join(`
1127
+ `)}
1128
+
1129
+ The list above is real but may be stale w.r.t. these files \u2014 they're often left over from an earlier sub-change in the same diff. Before composing a review, grep the codebase for their exports and call \`get-stories-by-component\` with the runtime consumers' file paths. Do not assume the list above already covers them, and never invent story IDs to fill the gap.`;
1130
+ }
1131
+
1132
+ // src/tools/get-changed-stories.ts
1133
+ var GET_CHANGED_STORIES_TOOL_DESCRIPTION = `Get Storybook stories marked as new, modified, or related. Returns story metadata only (no URLs).
1134
+
1135
+ The result reflects the cumulative working-tree diff, not just your latest edit \u2014 after multiple edits in one session, a non-empty result may cover an earlier sub-change and miss your most recent one. Check that every file you touched is represented; for any that isn't, find its consumer components and pass their paths to get-stories-by-component instead. The response surfaces this gap with a "coverage sanity check" hint when it detects unreachable working-tree files.`, CHANGE_DETECTION_TYPE = "storybook/change-detection", INCLUDED_STATUS_VALUES = /* @__PURE__ */ new Set([
1136
+ "status-value:new",
1137
+ "status-value:modified",
1138
+ "status-value:affected"
1139
+ ]);
1140
+ function statusPriority(statusValue) {
1141
+ return statusValue === "status-value:new" ? 0 : statusValue === "status-value:modified" ? 1 : 2;
1142
+ }
1143
+ function getChangedStoriesToolMetadata() {
1144
+ return {
1145
+ name: GET_CHANGED_STORIES_TOOL_NAME,
1146
+ title: "Get changed stories metadata",
1147
+ description: GET_CHANGED_STORIES_TOOL_DESCRIPTION
1148
+ };
1149
+ }
1150
+ async function addGetChangedStoriesTool(server, enabled = () => server.ctx.custom?.toolsets?.dev ?? !0, { reviewEnabled = !1 } = {}) {
1151
+ server.tool(
1152
+ {
1153
+ ...getChangedStoriesToolMetadata(),
1154
+ enabled
1155
+ },
1156
+ async () => {
1157
+ try {
1158
+ let { options, disableTelemetry: disableTelemetry2 } = server.ctx.custom ?? {};
1159
+ if (!options)
1160
+ throw new Error("Storybook options are required in addon context");
1161
+ let allStatuses = experimental_getStatusStore(CHANGE_DETECTION_TYPE).getAll(), changedStoriesFromStatusStore = [];
1162
+ for (let byType of Object.values(allStatuses)) {
1163
+ let status = byType?.[CHANGE_DETECTION_TYPE];
1164
+ status?.value && INCLUDED_STATUS_VALUES.has(status.value) && changedStoriesFromStatusStore.push(status);
1165
+ }
1166
+ if (changedStoriesFromStatusStore.length === 0) {
1167
+ disableTelemetry2 || await collectTelemetry({
1168
+ event: "tool:getChangedStories",
1169
+ server,
1170
+ toolset: "dev",
1171
+ storyCount: 0,
1172
+ newStoryCount: 0,
1173
+ modifiedStoryCount: 0,
1174
+ affectedStoryCount: 0
1175
+ });
1176
+ let unreachable2 = await detectUnreachableChanges();
1177
+ return {
1178
+ content: [
1179
+ {
1180
+ type: "text",
1181
+ text: `No new, modified, or related stories detected.${formatUnreachableHint(unreachable2)}`
1182
+ }
1183
+ ]
1184
+ };
1185
+ }
1186
+ let index = await getStoryIndex(options), stories = changedStoriesFromStatusStore.flatMap(
1187
+ ({ storyId, value }) => {
1188
+ let entry = index.entries[storyId];
1189
+ return entry ? [
1190
+ {
1191
+ storyId,
1192
+ statusValue: value,
1193
+ title: entry.title,
1194
+ name: entry.name,
1195
+ importPath: entry.importPath
1196
+ }
1197
+ ] : [];
1198
+ }
1199
+ );
1200
+ stories.sort((a, b) => {
1201
+ let priorityDelta = statusPriority(a.statusValue) - statusPriority(b.statusValue);
1202
+ return priorityDelta !== 0 ? priorityDelta : a.storyId.localeCompare(b.storyId);
1203
+ });
1204
+ let buckets = {
1205
+ new: stories.filter((story) => story.statusValue === "status-value:new"),
1206
+ modified: stories.filter((story) => story.statusValue === "status-value:modified"),
1207
+ affected: stories.filter((story) => story.statusValue === "status-value:affected")
1208
+ }, counts = {
1209
+ new: buckets.new.length,
1210
+ modified: buckets.modified.length,
1211
+ affected: buckets.affected.length
1212
+ };
1213
+ disableTelemetry2 || await collectTelemetry({
1214
+ event: "tool:getChangedStories",
1215
+ server,
1216
+ toolset: "dev",
1217
+ storyCount: stories.length,
1218
+ newStoryCount: counts.new,
1219
+ modifiedStoryCount: counts.modified,
1220
+ affectedStoryCount: counts.affected
1221
+ });
1222
+ let unreachable = await detectUnreachableChanges(), text = `${formatPartialCoverageBanner(unreachable)}Detected ${stories.length} changed stor${stories.length === 1 ? "y" : "ies"} (${counts.new} new, ${counts.modified} modified, ${counts.affected} related).`;
1223
+ reviewEnabled && stories.length > 0 && (text += `
1224
+
1225
+ Next: if the change is visually observable, publish the review now \u2014 call **display-review** curating these story IDs. That review link is how you finish; do not substitute individual preview URLs for it.`);
1226
+ let serializeStory = ({ storyId, title, name, importPath }) => `- \`${storyId}\`: ${title} / ${name} (\`${importPath}\`)`;
1227
+ return buckets.new.length > 0 && (text += `
1228
+
1229
+ New stories:
1230
+ `, text += buckets.new.map(serializeStory).join(`
1231
+ `)), buckets.modified.length > 0 && (text += `
1232
+
1233
+ Modified stories:
1234
+ `, text += buckets.modified.map(serializeStory).join(`
1235
+ `)), buckets.affected.length > 0 && (text += `
1236
+
1237
+ Related stories:
1238
+ `, text += buckets.affected.map(serializeStory).join(`
1239
+ `)), text += formatPartialCoverageHint(unreachable), { content: [{ type: "text", text }] };
1240
+ } catch (error) {
1241
+ return errorToMCPContent(error);
1242
+ }
1243
+ }
1244
+ );
1245
+ }
1246
+
1247
+ // src/tools/get-stories-by-component.ts
1248
+ import * as v4 from "valibot";
1249
+
1250
+ // src/utils/resolve-component-stories.ts
1251
+ import fs from "node:fs";
1252
+ import path3 from "node:path";
1253
+ var SOURCE_EXTENSIONS = [".ts", ".tsx", ".js", ".jsx", ".mjs", ".cjs"], INDEX_BASENAMES = SOURCE_EXTENSIONS.map((ext) => `index${ext}`);
1254
+ function expandBarrelTargets(absoluteComponentPath) {
1255
+ let targets = /* @__PURE__ */ new Set([absoluteComponentPath]), dir = path3.dirname(absoluteComponentPath), ext = path3.extname(absoluteComponentPath), base = path3.basename(absoluteComponentPath, ext), dirName = path3.basename(dir);
1256
+ if (base.toLowerCase() === "index")
1257
+ for (let candidateExt of SOURCE_EXTENSIONS) {
1258
+ let candidate = path3.join(dir, `${dirName}${candidateExt}`);
1259
+ fs.existsSync(candidate) && targets.add(candidate);
1260
+ }
1261
+ else if (base.toLowerCase() === dirName.toLowerCase())
1262
+ for (let indexBasename of INDEX_BASENAMES) {
1263
+ let candidate = path3.join(dir, indexBasename);
1264
+ fs.existsSync(candidate) && targets.add(candidate);
1265
+ }
1266
+ return [...targets].map((p) => slash(path3.normalize(p)));
1267
+ }
1268
+ function canonicalise(absolutePath) {
1269
+ try {
1270
+ return fs.realpathSync.native(absolutePath);
1271
+ } catch (err) {
1272
+ if (err.code === "ENOENT") return;
1273
+ throw err;
1274
+ }
1275
+ }
1276
+ function toStoryIndexPath(importPath) {
1277
+ let normalized = slash(importPath);
1278
+ return normalized.startsWith("./") || normalized.startsWith("../") ? normalized : `./${normalized}`;
1279
+ }
1280
+ function buildStoryIdsByFile(storyIndex) {
1281
+ let storyIdsByFile = /* @__PURE__ */ new Map();
1282
+ for (let entry of Object.values(storyIndex.entries)) {
1283
+ if (entry.type !== "story" || entry.importPath.startsWith("virtual:")) continue;
1284
+ let filePath = toStoryIndexPath(entry.importPath), ids = storyIdsByFile.get(filePath);
1285
+ ids || (ids = /* @__PURE__ */ new Set(), storyIdsByFile.set(filePath, ids)), ids.add(entry.id);
1286
+ }
1287
+ return storyIdsByFile;
1288
+ }
1289
+ function reasonForStatus(status) {
1290
+ switch (status.value) {
1291
+ case "booting":
1292
+ return "Storybook's story module graph hasn't built yet \u2014 it is still being constructed. Retry shortly.";
1293
+ case "unavailable":
1294
+ return `Storybook's story module graph is unavailable: ${status.reason}`;
1295
+ case "error":
1296
+ return `Storybook's story module graph failed to build: ${status.error.message}`;
1297
+ case "ready":
1298
+ return "Storybook's story module graph is ready.";
1299
+ default:
1300
+ return status;
1301
+ }
1302
+ }
1303
+ async function resolveComponentStories(request, deps) {
1304
+ let moduleGraph = await getModuleGraphService();
1305
+ if (!moduleGraph)
1306
+ return {
1307
+ available: !1,
1308
+ reason: "Storybook's story module graph is unavailable. This Storybook version may not ship the open-service API, the module-graph service isn't registered (e.g. a builder without change detection), or the dev server is not running."
1309
+ };
1310
+ let status = await moduleGraph.queries.status.loaded(void 0);
1311
+ if (status.value !== "ready")
1312
+ return { available: !1, reason: reasonForStatus(status) };
1313
+ let workingDir = deps.workingDir ?? process.cwd(), storyIndex = await deps.getStoryIndex(), storyIdsByFile = buildStoryIdsByFile(storyIndex), resolved = [...new Set(request.componentPaths)].map((componentPath) => {
1314
+ let absolute = path3.resolve(workingDir, componentPath), canonical = canonicalise(absolute), echo = path3.normalize(componentPath);
1315
+ if (!canonical)
1316
+ return { componentPath: echo, targets: [], pathNotFound: !0 };
1317
+ let targets = new Set(expandBarrelTargets(absolute));
1318
+ if (canonical !== absolute)
1319
+ for (let t of expandBarrelTargets(canonical)) targets.add(t);
1320
+ return { componentPath: echo, targets: [...targets] };
1321
+ }), allTargets = [...new Set(resolved.flatMap((c) => c.targets))], hitsByTarget = /* @__PURE__ */ new Map();
1322
+ if (allTargets.length > 0) {
1323
+ let batched = await moduleGraph.queries.storiesForFiles.loaded({ files: allTargets });
1324
+ allTargets.forEach((target, i) => {
1325
+ hitsByTarget.set(target, batched[i] ?? []);
1326
+ });
1327
+ }
1328
+ return { available: !0, results: resolved.map((component) => {
1329
+ if (component.pathNotFound)
1330
+ return { componentPath: component.componentPath, matches: [], pathNotFound: !0 };
1331
+ let byStoryId = /* @__PURE__ */ new Map();
1332
+ for (let target of component.targets) {
1333
+ let hits = hitsByTarget.get(target) ?? [];
1334
+ for (let { storyFile, depth } of hits) {
1335
+ let storyIds = storyIdsByFile.get(storyFile);
1336
+ if (storyIds)
1337
+ for (let storyId of storyIds) {
1338
+ let existing = byStoryId.get(storyId);
1339
+ (existing === void 0 || depth < existing) && byStoryId.set(storyId, depth);
1340
+ }
1341
+ }
1342
+ }
1343
+ let matches = [...byStoryId.entries()].map(([storyId, depth]) => ({ storyId, depth })).sort((a, b) => a.depth !== b.depth ? a.depth - b.depth : a.storyId.localeCompare(b.storyId));
1344
+ return { componentPath: component.componentPath, matches };
1345
+ }) };
1346
+ }
1347
+
1348
+ // src/tools/get-stories-by-component.ts
1349
+ var DEFAULT_MAX_DISTANCE = 3;
1350
+ function getStoriesByComponentToolDescription({
1351
+ reviewEnabled = !1
1352
+ } = {}) {
1353
+ return `Map component source files to the stories that render them, returning grounded \`storyId\` values from the live Storybook index \u2014 hand these to ${reviewEnabled ? `${PREVIEW_STORIES_TOOL_NAME} or display-review` : PREVIEW_STORIES_TOOL_NAME} instead of guessing.
1354
+
1355
+ Reach for this whenever you need story IDs, whatever shape the input has: ${reviewEnabled ? 'files you just edited, a feature/domain/topic the user named, a query like "all consumers of X", or an autonomous review after a UI change' : 'files you just edited, a feature/domain/topic the user named, or a query like "all consumers of X"'}. First resolve the input to a list of absolute component file paths using filesystem search (grep / Glob / find) and code reading \u2014 that bridge is yours to build; this tool starts where it ends. One common trap: when the changed file is _shared_ infrastructure (theme token, design token, util, hook, CSS module) it isn't itself a component \u2014 grep for its consumers and pass _their_ paths, not the shared file's. If the symbol you grepped looks like one member of a related group (sibling tokens, neighboring exports), widen to the rest of the group too \u2014 a too-narrow grep silently drops stories. Try \`${GET_CHANGED_STORIES_TOOL_NAME}\` first for "I just edited X" when it's available; if a file you touched is missing from its response, treat that file as the shared-infrastructure case and route its consumers through this tool.
1356
+
1357
+ Results are sorted by \`distance\` (0 = the path you passed is itself a story file, 1 = direct importer, 2+ = transitive; lower = stronger). Shared primitives are usually consumed through wrapper components, so the distance-1 bucket is often empty \u2014 the default \`maxDistance: 3\` keeps that cascade visible while capping noise from wide decorators; raise it to widen recall, lower it to tighten precision. ${reviewEnabled ? "For display-review, the distance buckets map onto the visual cascade (the component itself \u2192 direct importers \u2192 page-level context) \u2014 one collection per layer; when several stories of a component share a distance, prefer the variant whose name signals it renders the changed surface." : "The distance buckets map onto the visual cascade (the component itself \u2192 direct importers \u2192 page-level context) \u2014 use them to decide which stories to preview; when several stories of a component share a distance, prefer the variant whose name signals it renders the changed surface."}
1358
+
1359
+ Never invent IDs from file names, feature names, or memory; title strings can be overridden by story authors, so only IDs returned by discovery tools resolve. If a component has no matches here, it has no stories yet (say so, don't fabricate).
1360
+
1361
+ Backed by Storybook's live reverse dependency graph, available only when the dev server runs a builder that supports change detection (e.g. Vite) \u2014 otherwise returns a typed error.`;
1362
+ }
1363
+ var GetStoriesByComponentInput = v4.object({
1364
+ componentPaths: v4.pipe(
1365
+ v4.array(v4.string()),
1366
+ v4.minLength(1),
1367
+ v4.description(
1368
+ `Absolute paths to component source files (e.g. "/repo/src/Button.tsx").
1369
+ Pass the components you actually want stories for \u2014 typically files you just read, edited, or that the user mentioned.
1370
+ Relative paths are also accepted and resolved against the Storybook working directory, but absolute paths are preferred for unambiguous results.
1371
+ Story files (\`*.stories.*\`) are accepted too: they appear at distance 0 as self-matches, plus any reverse-graph hits (other stories that import them).`
1372
+ )
1373
+ ),
1374
+ maxDistance: v4.pipe(
1375
+ v4.optional(v4.pipe(v4.number(), v4.minValue(1), v4.integer())),
1376
+ v4.description(
1377
+ `Ceiling on the import depth to include in results. Must be a positive integer.
1378
+ - 1: only stories that directly import the component.
1379
+ - 2+: also include stories that reach the component through N hops.
1380
+ Defaults to ${DEFAULT_MAX_DISTANCE}; raise it to widen recall, lower it to tighten precision. Shared components (Button, Icon, \u2026) accumulate noisy indirect matches at distance \u2265 3, so the default cap protects against runaway results.`
1381
+ )
1382
+ )
1383
+ }), StoryMatch = v4.object({
1384
+ storyId: v4.string(),
1385
+ title: v4.string(),
1386
+ name: v4.string(),
1387
+ importPath: v4.string(),
1388
+ distance: v4.pipe(
1389
+ v4.number(),
1390
+ v4.description(
1391
+ "Import-graph depth from the story file to the component (lower = stronger). 0: the path you passed is itself a story file (self-match). 1: story file directly imports the component. 2+: reached through N hops."
1392
+ )
1393
+ )
1394
+ }), ClippedByMaxDistanceSchema = v4.pipe(
1395
+ v4.object({
1396
+ count: v4.number(),
1397
+ distances: v4.array(v4.number())
1398
+ }),
1399
+ v4.description(
1400
+ "Present only when `maxDistance` filtered out one or more matches. `count` is how many were dropped; `distances` lists the (sorted, distinct) distances those dropped matches sat at \u2014 widen `maxDistance` to include them."
1401
+ )
1402
+ ), GetStoriesByComponentOutput = v4.object({
1403
+ results: v4.array(
1404
+ v4.object({
1405
+ componentPath: v4.string(),
1406
+ matches: v4.array(StoryMatch),
1407
+ clipped: v4.optional(ClippedByMaxDistanceSchema),
1408
+ pathNotFound: v4.pipe(
1409
+ v4.optional(v4.boolean()),
1410
+ v4.description(
1411
+ '`true` when no file exists at the resolved absolute path. Distinguishes a typo from "this component has no stories yet". The agent should re-check the path it sent.'
1412
+ )
1413
+ )
1414
+ })
1415
+ )
1416
+ });
1417
+ function serializeMatch(match) {
1418
+ return ` - \`${match.storyId}\`: ${match.title} / ${match.name} (\`${match.importPath}\`)`;
1419
+ }
1420
+ function pluralize(n, singular, plural = `${singular}s`) {
1421
+ return n === 1 ? singular : plural;
1422
+ }
1423
+ function formatClippedTail(clipped, maxDistance) {
1424
+ let dists = clipped.distances, rangeText = dists.length === 1 ? `distance ${dists[0]}` : `distances ${dists[0]}..${dists[dists.length - 1]}`;
1425
+ return `+${clipped.count} more ${pluralize(clipped.count, "story", "stories")} at ${rangeText} hidden by \`maxDistance: ${maxDistance}\``;
1426
+ }
1427
+ function serializeComponentSection(componentPath, matches, options = {}) {
1428
+ let { maxDistance, clipped, pathNotFound } = options;
1429
+ if (pathNotFound)
1430
+ return `${componentPath}: path does not exist on disk \u2014 re-check the path you sent.`;
1431
+ if (matches.length === 0)
1432
+ return clipped && clipped.count > 0 && maxDistance !== void 0 ? `${componentPath}: no stories within \`maxDistance: ${maxDistance}\` \u2014 ${formatClippedTail(clipped, maxDistance)}.` : `${componentPath}: no stories found`;
1433
+ let byDistance = /* @__PURE__ */ new Map();
1434
+ for (let m of matches) {
1435
+ let bucket = byDistance.get(m.distance) ?? [];
1436
+ bucket.push(m), byDistance.set(m.distance, bucket);
1437
+ }
1438
+ let distances = [...byDistance.keys()].sort((a, b) => a - b), minDist = distances[0], maxDist = distances[distances.length - 1], componentCount = new Set(matches.map((m) => m.title)).size, bucketSummary = distances.map((d) => `d${d}=${byDistance.get(d).length}`).join(", "), summary = `\u2192 ${matches.length} ${pluralize(matches.length, "story", "stories")} across ${componentCount} ${pluralize(componentCount, "component")}, distances ${minDist}..${maxDist} (${bucketSummary})`, lines = [`${componentPath}:`, summary];
1439
+ for (let d of distances) {
1440
+ lines.push(`distance ${d}:`);
1441
+ for (let m of byDistance.get(d)) lines.push(serializeMatch(m));
1442
+ }
1443
+ return clipped && clipped.count > 0 && maxDistance !== void 0 && lines.push(` (${formatClippedTail(clipped, maxDistance)}.)`), lines.join(`
1444
+ `);
1445
+ }
1446
+ function applyMaxDistance(depths, maxDistance) {
1447
+ if (maxDistance === void 0) return { kept: depths };
1448
+ let kept = [], clippedDistances = /* @__PURE__ */ new Set(), clippedCount = 0;
1449
+ for (let d of depths)
1450
+ d.depth <= maxDistance ? kept.push(d) : (clippedCount++, clippedDistances.add(d.depth));
1451
+ let clipped = clippedCount > 0 ? {
1452
+ count: clippedCount,
1453
+ distances: [...clippedDistances].sort((a, b) => a - b)
1454
+ } : void 0;
1455
+ return { kept, clipped };
1456
+ }
1457
+ function getStoriesByComponentToolMetadata({
1458
+ reviewEnabled = !1
1459
+ } = {}) {
1460
+ return {
1461
+ name: GET_STORIES_BY_COMPONENT_TOOL_NAME,
1462
+ title: "Get stories for component files",
1463
+ description: getStoriesByComponentToolDescription({ reviewEnabled }),
1464
+ schema: GetStoriesByComponentInput,
1465
+ outputSchema: GetStoriesByComponentOutput
1466
+ };
1467
+ }
1468
+ async function addGetStoriesByComponentTool(server, enabled = () => server.ctx.custom?.toolsets?.dev ?? !0, { reviewEnabled = !1 } = {}) {
1469
+ server.tool(
1470
+ {
1471
+ ...getStoriesByComponentToolMetadata({ reviewEnabled }),
1472
+ enabled
1473
+ },
1474
+ async (input) => {
1475
+ try {
1476
+ let { options, disableTelemetry: disableTelemetry2 } = server.ctx.custom ?? {};
1477
+ if (!options)
1478
+ throw new Error("Storybook options are required in addon context");
1479
+ let index = await getStoryIndex(options), lookup = await resolveComponentStories(
1480
+ { componentPaths: input.componentPaths },
1481
+ { getStoryIndex: async () => index }
1482
+ );
1483
+ if (!lookup.available)
1484
+ return {
1485
+ content: [
1486
+ {
1487
+ type: "text",
1488
+ text: lookup.reason ?? "Storybook's story dependency graph is unavailable. Make sure the dev server is running with a builder that supports change detection."
1489
+ }
1490
+ ],
1491
+ isError: !0
1492
+ };
1493
+ let effectiveMaxDistance = input.maxDistance ?? DEFAULT_MAX_DISTANCE, results = (lookup.results ?? []).map((entry) => {
1494
+ if (entry.pathNotFound)
1495
+ return { componentPath: entry.componentPath, matches: [], pathNotFound: !0 };
1496
+ let { kept, clipped } = applyMaxDistance(entry.matches, effectiveMaxDistance), matches = [];
1497
+ for (let { storyId, depth } of kept) {
1498
+ let indexEntry = index.entries[storyId];
1499
+ !indexEntry || indexEntry.type !== "story" || matches.push({
1500
+ storyId: indexEntry.id,
1501
+ title: indexEntry.title,
1502
+ name: indexEntry.name,
1503
+ importPath: indexEntry.importPath,
1504
+ distance: depth
1505
+ });
1506
+ }
1507
+ return { componentPath: entry.componentPath, matches, clipped };
1508
+ }), totalMatches = results.reduce((sum, r) => sum + r.matches.length, 0), unmatchedCount = results.filter(
1509
+ (r) => !r.pathNotFound && r.matches.length === 0
1510
+ ).length, textSections = results.map(
1511
+ ({ componentPath, matches, clipped, pathNotFound }) => serializeComponentSection(componentPath, matches, {
1512
+ maxDistance: effectiveMaxDistance,
1513
+ clipped,
1514
+ pathNotFound
1515
+ })
1516
+ ), text = textSections.length > 0 ? textSections.join(`
1517
+
1518
+ `) : "No component paths provided.";
1519
+ return disableTelemetry2 || await collectTelemetry({
1520
+ event: "tool:getStoriesByComponent",
1521
+ server,
1522
+ toolset: "dev",
1523
+ componentCount: input.componentPaths.length,
1524
+ matchedComponentCount: input.componentPaths.length - unmatchedCount,
1525
+ totalMatchCount: totalMatches,
1526
+ maxDistance: effectiveMaxDistance
1527
+ }), {
1528
+ content: [{ type: "text", text }],
1529
+ structuredContent: { results }
1530
+ };
1531
+ } catch (error) {
1532
+ return errorToMCPContent(error);
1533
+ }
1534
+ }
1535
+ );
1536
+ }
1537
+
1538
+ // src/instructions/storybook-story-instructions.md
1539
+ var storybook_story_instructions_default = `# Writing User Interfaces
1540
+
1541
+ When writing UI, prefer breaking larger components up into smaller parts.
1542
+
1543
+ ALWAYS write a Storybook story for any component written. If editing a component, ensure appropriate changes have been made to stories for that component.
1544
+ {{DOCS_WORKFLOW_GUIDANCE}}
1545
+
1546
+ ## How to write good stories
1547
+
1548
+ Goal: Cover every distinct piece of business logic and state the component can reach (happy paths, error/edge states, loading, permissions/roles, empty states, variations from props/context). Avoid redundant stories that show the same logic.
1549
+
1550
+ Interactivity: If the component is interactive, add Interaction tests using play functions that drive the UI with storybook/test utilities (e.g., fn, userEvent, expect). Simulate key user flows: clicking buttons/links, typing, focus/blur, keyboard nav, form submit, async responses, toggle/selection changes, pagination/filters, etc. When passing \`fn\` functions as \`args\` for callback functions, make sure to add a play function which interacts with the component and assert whether the callback function was actually called.
1551
+
1552
+ Data/setup: Provide realistic props, state, and mocked data. Include meaningful labels/text to make behaviors observable. Stub network/services with deterministic fixtures; keep stories reliable.
1553
+
1554
+ Assertions: In play functions, assert the visible outcome of the interaction (text, aria state, enabled/disabled, class/state changes, emitted events). Prefer role/label-based queries.
1555
+
1556
+ Variants to consider (pick only those that change behavior): default vs. alternate themes; loading vs. loaded vs. empty vs. error; validated vs. invalid input; permissions/roles/capabilities; feature flags; size/density/layout variants that alter logic.
1557
+
1558
+ Accessibility: Use semantic roles/labels; ensure focusable/keyboard interactions are test-covered where relevant.
1559
+
1560
+ Naming/structure: Use clear story names that describe the scenario (\u201CError state after failed submit\u201D). Group related variants logically; don\u2019t duplicate.
1561
+
1562
+ Imports/format: Import Meta/StoryObj from the framework package; import test helpers from storybook/test (not @storybook/test). Keep stories minimal\u2014only what's needed to demonstrate behavior.
1563
+
1564
+ ## Storybook 9 Essential Changes for Story Writing
1565
+
1566
+ ### Package Consolidation
1567
+
1568
+ #### \`Meta\` and \`StoryObj\` imports
1569
+
1570
+ Update story imports to use the framework package:
1571
+
1572
+ \`\`\`diff
1573
+ - import { Meta, StoryObj } from '{{RENDERER}}';
1574
+ + import { Meta, StoryObj } from '{{FRAMEWORK}}';
1575
+ \`\`\`
1576
+
1577
+ #### Test utility imports
1578
+
1579
+ Update test imports to use \`storybook/test\` instead of \`@storybook/test\`
1580
+
1581
+ \`\`\`diff
1582
+ - import { fn } from '@storybook/test';
1583
+ + import { fn } from 'storybook/test';
1584
+ \`\`\`
1585
+
1586
+ ### Global State Changes
1587
+
1588
+ The \`globals\` annotation has be renamed to \`initialGlobals\`:
1589
+
1590
+ \`\`\`diff
1591
+ // .storybook/preview.js
1592
+ export default {
1593
+ - globals: { theme: 'light' }
1594
+ + initialGlobals: { theme: 'light' }
1595
+ };
1596
+ \`\`\`
1597
+
1598
+ ### Autodocs Configuration
1599
+
1600
+ Instead of \`parameters.docs.autodocs\` in main.js, use tags:
1601
+
1602
+ \`\`\`js
1603
+ // .storybook/preview.js or in individual stories
1604
+ export default {
1605
+ tags: ['autodocs'], // generates autodocs for all stories
1606
+ };
1607
+ \`\`\`
1608
+
1609
+ ### Mocking imports in Storybook
1610
+
1611
+ To mock imports in Storybook, use Storybook's mocking features. ALWAYS mock external dependencies to ensure stories render consistently.
1612
+
1613
+ 1. **Register in the mock in Storybook's preview file**:
1614
+ To mock dependendencies, you MUST register a module mock in \`.storybook/preview.ts\` (or equivalent):
1615
+
1616
+ \`\`\`js
1617
+ import { sb } from 'storybook/test';
1618
+
1619
+ // Prefer spy mocks (keeps functions, but allows to override them and spy on them)
1620
+ sb.mock(import('some-library'), { spy: true });
1621
+ \`\`\`
1622
+
1623
+ **Important: Use file extensions when referring to relative files!**
1624
+
1625
+ \`\`\`js
1626
+ sb.mock(import('./relative/module.ts'), { spy: true });
1627
+ \`\`\`
1628
+
1629
+ 2. **Specify mock values in stories**:
1630
+ You can override the behaviour of the mocks per-story using \`beforeEach\` and the \`mocked()\` type function:
1631
+
1632
+ \`\`\`js
1633
+ import { expect, mocked, fn } from 'storybook/test';
1634
+ import { library } from 'some-library';
1635
+
1636
+ const meta = {
1637
+ component: AuthButton,
1638
+ beforeEach: async () => {
1639
+ mocked(library).mockResolvedValue({ user: 'data' });
1640
+ },
1641
+ };
1642
+
1643
+ export const LoggedIn: Story = {
1644
+ play: async ({ canvas }) => {
1645
+ await expect(library).toHaveBeenCalled();
1646
+ },
1647
+ };
1648
+ \`\`\`
1649
+
1650
+ Before doing this ensure you have mocked the import in the preview file.
1651
+
1652
+ ### Play Function Parameters
1653
+
1654
+ - The play function has a \`canvas\` parameter that can be used directly with testing-library-like query methods.
1655
+ - It also has a \`canvasElement\` which is the actual DOM element.
1656
+ - The \`within\`-function imported from \`storybook/test\` transforms a DOM element to an object with query methods, similar to \`canvas\`.
1657
+
1658
+ **DO NOT** use \`within(canvas)\` - it is redundant because \`canvas\` already has the query methods, \`canvas\` is not a DOM element.
1659
+
1660
+ \`\`\`ts
1661
+ // \u2705 Correct: Use canvas directly
1662
+ play: async ({ canvas }) => {
1663
+ await canvas.getByLabelText('Submit').click();
1664
+ };
1665
+
1666
+ // \u26A0\uFE0F Also acceptable: Use \`canvasElement\` with \`within\`
1667
+ import { within } from 'storybook/test';
1668
+
1669
+ play: async ({ canvasElement }) => {
1670
+ const canvas = within(canvasElement);
1671
+ await canvas.getByLabelText('Submit').click();
1672
+ };
1673
+
1674
+ // \u274C Wrong: Do NOT use within(canvas)
1675
+ play: async ({ canvas }) => {
1676
+ const screen = within(canvas); // Error!
1677
+ };
1678
+ \`\`\`
1679
+
1680
+ ### Key Requirements
1681
+
1682
+ - **Node.js 20+**, **TypeScript 4.9+**
1683
+ - React Native uses \`.rnstorybook\` directory
1684
+
1685
+ ## Story Linking Agent Behavior
1686
+
1687
+ - ALWAYS provide story links after any changes to stories files, including changes to existing stories.
1688
+ - {{STORY_LINKING_WORKFLOW}}
1689
+ - {{FINAL_LINKS_GUIDANCE}}
1690
+ - When you will share preview/story links (i.e. when you are not collapsing everything into a single review section), pass only the most relevant story IDs into **preview-stories** (generally no more than 5) so the returned URL list stays manageable. Include every URL returned by that call in your final response \u2014 do not drop links there.
1691
+ - {{CHANGED_STORY_FALLBACK_LINK_GUIDANCE}}
1692
+ - After changing any UI components, ALWAYS search for related stories that might cover the changes you've made. If you find any, provide the story links to the user. THIS IS VERY IMPORTANT, as it allows the user to visually inspect the changes you've made. Even later in a session when changing UI components or stories that have already been linked to previously, YOU MUST PROVIDE THE LINKS AGAIN.
1693
+ `;
1694
+
1695
+ // src/instructions/story-testing-instructions.md
1696
+ var story_testing_instructions_default = `## Story Testing Requirements
1697
+
1698
+ **Run \`{{RUN_STORY_TESTS_TOOL_NAME}}\` after EVERY component or story change.** This includes creating, modifying, or refactoring components, stories, or their dependencies. It is the only way to run story tests \u2014 never run package.json test scripts (like \`npm run test:stories\`) instead.
1699
+
1700
+ ### Workflow
1701
+
1702
+ 1. Make your change
1703
+ 2. Run \`{{RUN_STORY_TESTS_TOOL_NAME}}\` with related stories for focused feedback (faster while iterating)
1704
+ 3. If tests fail: analyze, fix{{A11Y_FIX_SUFFIX}}, re-run
1705
+ 4. Repeat until all tests pass
1706
+
1707
+ Do not skip tests, ignore failures, or move on with failing tests. If stuck after multiple attempts, report to user.
1708
+
1709
+ ### Focused vs. full-suite test runs
1710
+
1711
+ - Prefer focused runs (\`stories\` input) during development to validate the parts you changed quickly.
1712
+ - Run all tests (omit \`stories\`) before final handoff, after broad/refactor changes, or when impact is unclear and you need project-wide verification.
1713
+ `;
1714
+
1715
+ // src/instructions/a11y-instructions.md
1716
+ var a11y_instructions_default = `### Accessibility Violations
1717
+
1718
+ **Fix automatically** (semantic/structural, no visual change):
1719
+
1720
+ - ARIA attributes, roles, labels, alt text
1721
+ - Heading hierarchy, landmarks, table structure
1722
+ - Keyboard access (tabindex, focus, handlers)
1723
+ - Document-level: lang attr, frame titles, duplicate IDs
1724
+
1725
+ **Confirm with user first** (visual/design changes):
1726
+
1727
+ - Color contrast ratios
1728
+ - Font sizes, spacing, layout
1729
+ - Focus indicator styling
1730
+
1731
+ Describe the issue, ask how the user wants to proceed, and provide 2-3 concrete options.
1732
+ Do not auto-apply visual changes before user confirmation, and do not claim visual issues are fixed until they approve an option.
1733
+ `;
1734
+
1735
+ // src/tools/get-storybook-story-instructions.ts
1736
+ var docsWorkflowGuidance = "\n\n## Using library components\n\nThis Storybook exposes component documentation tools. Before creating or changing any UI, call **list-all-documentation** once to see what the design system already provides \u2014 build on existing components instead of hand-rolling duplicates \u2014 then call **get-documentation** with the `id` of each component you build on or get asked about, for its real props and usage examples. When multiple Storybook sources are configured, pass the `storybookId` from **list-all-documentation** on follow-up calls. Do this instead of reading the library's source or type definitions out of `node_modules` \u2014 stories show intended usage, raw types don't \u2014 and answer props/usage questions from these tools too. Never assume or invent props.";
1737
+ async function addGetUIBuildingInstructionsTool(server, enabled = () => server.ctx.custom?.toolsets?.dev ?? !0, { docsAvailable = !1 } = {}) {
1738
+ let addonVitestAvailable = !!await getAddonVitestConstants();
1739
+ server.tool(
1740
+ {
1741
+ name: GET_UI_BUILDING_INSTRUCTIONS_TOOL_NAME,
1742
+ title: "Storybook Story Development Instructions",
1743
+ get description() {
1744
+ let testToolsetAvailable = (server.ctx.custom?.toolsets?.test ?? !0) && addonVitestAvailable, a11yAvailable = testToolsetAvailable && (server.ctx.custom?.a11yEnabled ?? !1);
1745
+ return getStorybookStoryInstructionsDescription({
1746
+ testToolsetAvailable,
1747
+ a11yAvailable
1748
+ });
1749
+ },
1750
+ enabled
1751
+ },
1752
+ async () => {
1753
+ try {
1754
+ let { options, disableTelemetry: disableTelemetry2 } = server.ctx.custom ?? {};
1755
+ if (!options)
1756
+ throw new Error("Options are required in addon context");
1757
+ return disableTelemetry2 || await collectTelemetry({
1758
+ event: "tool:getUIBuildingInstructions",
1759
+ server,
1760
+ toolset: "dev"
1761
+ }), {
1762
+ content: [{ type: "text", text: await buildStorybookStoryInstructions(options, {
1763
+ toolsets: server.ctx.custom?.toolsets,
1764
+ a11yEnabled: server.ctx.custom?.a11yEnabled,
1765
+ addonVitestAvailable,
1766
+ docsAvailable,
1767
+ reviewEnabled: server.ctx.custom?.reviewEnabled
1768
+ }) }]
1769
+ };
1770
+ } catch (error) {
1771
+ return errorToMCPContent(error);
1772
+ }
1773
+ }
1774
+ );
1775
+ }
1776
+ function getStorybookStoryInstructionsDescription({
1777
+ testToolsetAvailable,
1778
+ a11yAvailable
1779
+ }) {
1780
+ return `Get comprehensive instructions for writing, testing, and fixing Storybook stories (.stories.tsx, .stories.ts, .stories.jsx, .stories.js, .stories.svelte, .stories.vue files).
695
1781
 
696
1782
  CRITICAL: You MUST call this tool before:
697
1783
  - Creating new Storybook stories or story files
698
1784
  - Updating or modifying existing Storybook stories
699
1785
  - Adding new story variants or exports to story files
700
1786
  - Editing any file matching *.stories.* patterns
701
- - Writing components that will need stories${testToolsetAvailable ? `
1787
+ - Writing components that will need stories
1788
+ - Editing anything that changes how the UI looks \u2014 components, styles, CSS, themes, colors, or design tokens; a shared file with no stories of its own still changes its consumers' stories${testToolsetAvailable ? `
702
1789
  - Running story tests or fixing test failures` : ""}${a11yAvailable ? `
703
1790
  - Handling accessibility (a11y) violations in stories (fix semantic issues directly; ask before visual/design changes)` : ""}
704
1791
 
@@ -713,655 +1800,1489 @@ This tool provides essential Storybook-specific guidance including:
713
1800
  - How to handle test failures${a11yAvailable ? " and accessibility violations" : ""}` : ""}
714
1801
 
715
1802
  Even if you're familiar with Storybook, call this tool to ensure you're following the correct patterns, import paths, and conventions for this specific Storybook setup.`;
716
- },
717
- enabled: () => server.ctx.custom?.toolsets?.dev ?? true
718
- }, async () => {
719
- try {
720
- const { options, disableTelemetry } = server.ctx.custom ?? {};
721
- if (!options) throw new Error("Options are required in addon context");
722
- if (!disableTelemetry) await collectTelemetry({
723
- event: "tool:getUIBuildingInstructions",
724
- server,
725
- toolset: "dev"
726
- });
727
- const frameworkPreset = await options.presets.apply("framework");
728
- const framework = typeof frameworkPreset === "string" ? frameworkPreset : frameworkPreset?.name;
729
- const renderer = frameworkToRendererMap[framework];
730
- let uiInstructions = storybook_story_instructions_default.replace("{{FRAMEWORK}}", framework).replace("{{RENDERER}}", renderer ?? framework).replace("{{PREVIEW_STORIES_TOOL_NAME}}", PREVIEW_STORIES_TOOL_NAME);
731
- if ((server.ctx.custom?.toolsets?.test ?? true) && !!await getAddonVitestConstants()) {
732
- const a11yEnabled = server.ctx.custom?.a11yEnabled ?? false;
733
- const a11yFixSuffix = a11yEnabled ? " (see a11y guidelines below)" : "";
734
- const storyTestingInstructions = story_testing_instructions_default.replaceAll("{{RUN_STORY_TESTS_TOOL_NAME}}", RUN_STORY_TESTS_TOOL_NAME).replace("{{A11Y_FIX_SUFFIX}}", a11yFixSuffix);
735
- uiInstructions += `\n\n${storyTestingInstructions}`;
736
- if (a11yEnabled) uiInstructions += `\n${a11y_instructions_default}`;
737
- }
738
- return { content: [{
739
- type: "text",
740
- text: uiInstructions
741
- }] };
742
- } catch (error) {
743
- return errorToMCPContent(error);
744
- }
745
- });
746
- }
747
- const frameworkToRendererMap = {
748
- "@storybook/react-vite": "@storybook/react",
749
- "@storybook/react-webpack5": "@storybook/react",
750
- "@storybook/nextjs": "@storybook/react",
751
- "@storybook/nextjs-vite": "@storybook/react",
752
- "@storybook/react-native-web-vite": "@storybook/react",
753
- "@storybook/vue3-vite": "@storybook/vue3",
754
- "@nuxtjs/storybook": "@storybook/vue3",
755
- "@storybook/angular": "@storybook/angular",
756
- "@storybook/svelte-vite": "@storybook/svelte",
757
- "@storybook/sveltekit": "@storybook/svelte",
758
- "@storybook/preact-vite": "@storybook/preact",
759
- "@storybook/web-components-vite": "@storybook/web-components",
760
- "@storybook/html-vite": "@storybook/html"
761
- };
1803
+ }
1804
+ function getStorybookStoryInstructionsToolMetadata(options) {
1805
+ return {
1806
+ name: GET_UI_BUILDING_INSTRUCTIONS_TOOL_NAME,
1807
+ title: "Storybook Story Development Instructions",
1808
+ description: getStorybookStoryInstructionsDescription(options)
1809
+ };
1810
+ }
1811
+ async function buildStorybookStoryInstructions(options, {
1812
+ toolsets,
1813
+ a11yEnabled: a11yEnabled2 = !1,
1814
+ addonVitestAvailable,
1815
+ docsAvailable = !1,
1816
+ reviewEnabled: reviewEnabledOverride
1817
+ } = {}) {
1818
+ let frameworkPreset = await options.presets.apply("framework"), featuresPreset = await options.presets.apply("features", {}), changeDetectionEnabled = featuresPreset?.changeDetection ?? !1, reviewStatus = await getReviewStatus(options, { features: featuresPreset }), reviewEnabled = reviewEnabledOverride ?? reviewStatus.available, framework = typeof frameworkPreset == "string" ? frameworkPreset : frameworkPreset?.name, renderer = frameworkToRendererMap[framework], storyLinkingWorkflow = changeDetectionEnabled ? reviewEnabled ? `After changing any component or story, call \`${GET_CHANGED_STORIES_TOOL_NAME}\` to discover the new, modified, and related stories affected by your change. Story IDs must come from that call (or a fallback discovery tool such as get-stories-by-component for shared-infrastructure changes) \u2014 never construct them from file names, export names, or memory. Feed the discovered IDs into **display-review** when the change is visually observable; use \`${PREVIEW_STORIES_TOOL_NAME}\` only while iterating on a specific story.` : `After changing UI, call \`${GET_CHANGED_STORIES_TOOL_NAME}\` first, then use \`${PREVIEW_STORIES_TOOL_NAME}\` with selected \`storyId\` values from those results.` : `After changing UI, call \`${PREVIEW_STORIES_TOOL_NAME}\` and share the most relevant links for the changes.`, changedStoryFallbackLinkGuidance = changeDetectionEnabled ? `When sharing preview/story links (not when ending with a review section): if you did not pass every changed story into \`${PREVIEW_STORIES_TOOL_NAME}\`, include this Storybook fallback link so the user can view the complete changed list: \`/?statuses=affected;modified;new\`.` : `When sharing preview/story links (not when ending with a review section) and you passed only a subset into \`${PREVIEW_STORIES_TOOL_NAME}\`, mention that additional relevant stories may exist in Storybook.`, docsToolsAvailable = (toolsets?.docs ?? !0) && docsAvailable, uiInstructions = storybook_story_instructions_default.replace("{{FRAMEWORK}}", framework).replace("{{RENDERER}}", renderer ?? framework).replace(`
1819
+ {{DOCS_WORKFLOW_GUIDANCE}}`, docsToolsAvailable ? docsWorkflowGuidance : "").replace("{{STORY_LINKING_WORKFLOW}}", storyLinkingWorkflow).replace("{{FINAL_LINKS_GUIDANCE}}", getFinalLinksGuidance(reviewEnabled)).replace("{{CHANGED_STORY_FALLBACK_LINK_GUIDANCE}}", changedStoryFallbackLinkGuidance), resolvedAddonVitestAvailable = addonVitestAvailable ?? !!await getAddonVitestConstants();
1820
+ if ((toolsets?.test ?? !0) && resolvedAddonVitestAvailable) {
1821
+ let a11yFixSuffix = a11yEnabled2 ? " (see a11y guidelines below)" : "", storyTestingInstructions = story_testing_instructions_default.replaceAll("{{RUN_STORY_TESTS_TOOL_NAME}}", RUN_STORY_TESTS_TOOL_NAME).replace("{{A11Y_FIX_SUFFIX}}", a11yFixSuffix);
1822
+ uiInstructions += `
762
1823
 
763
- //#endregion
764
- //#region src/tools/is-manifest-available.ts
765
- const getManifestStatus = async (options) => {
766
- const [features, manifests, legacyComponentManifestGenerator] = await Promise.all([
767
- options.presets.apply("features"),
768
- options.presets.apply("experimental_manifests", void 0, { manifestEntries: [] }),
769
- options.presets.apply("experimental_componentManifestGenerator")
770
- ]);
771
- const hasManifests = manifests && "components" in manifests || !!legacyComponentManifestGenerator;
772
- const hasFeatureFlag = !!(features?.componentsManifest ?? features?.experimentalComponentsManifest);
773
- return {
774
- available: hasFeatureFlag && hasManifests,
775
- hasManifests,
776
- hasFeatureFlag
777
- };
1824
+ ${storyTestingInstructions}`, a11yEnabled2 && (uiInstructions += `
1825
+ ${a11y_instructions_default}`);
1826
+ }
1827
+ return uiInstructions;
1828
+ }
1829
+ var frameworkToRendererMap = {
1830
+ "@storybook/react-vite": "@storybook/react",
1831
+ "@storybook/react-webpack5": "@storybook/react",
1832
+ "@storybook/nextjs": "@storybook/react",
1833
+ "@storybook/nextjs-vite": "@storybook/react",
1834
+ "@storybook/react-native-web-vite": "@storybook/react",
1835
+ "@storybook/vue3-vite": "@storybook/vue3",
1836
+ "@nuxtjs/storybook": "@storybook/vue3",
1837
+ "@storybook/angular": "@storybook/angular",
1838
+ "@storybook/svelte-vite": "@storybook/svelte",
1839
+ "@storybook/sveltekit": "@storybook/svelte",
1840
+ "@storybook/preact-vite": "@storybook/preact",
1841
+ "@storybook/web-components-vite": "@storybook/web-components",
1842
+ "@storybook/html-vite": "@storybook/html"
778
1843
  };
779
1844
 
780
- //#endregion
781
- //#region src/utils/estimate-tokens.ts
782
- /**
783
- * Checks if a character code is whitespace (space, tab, newline, carriage return)
784
- *
785
- * Checking char codes is slightly faster than using regex or string methods.
786
- */
787
- function isWhitespace(code) {
788
- return code === 32 || code === 9 || code === 10 || code === 13;
789
- }
790
- /**
791
- * Checks if a character code is alphanumeric or underscore
792
- * 0-9 (48-57), A-Z (65-90), a-z (97-122), underscore (95)
793
- *
794
- * Checking char codes is slightly faster than using regex or string methods.
795
- */
796
- function isAlphanumeric(code) {
797
- return code >= 48 && code <= 57 || code >= 65 && code <= 90 || code >= 97 && code <= 122 || code === 95;
798
- }
799
- /**
800
- * Estimates token count from text using a fast approximation.
801
- * Counts:
802
- * - Continuous whitespace as a single token
803
- * - Continuous alphanumeric sequences as single tokens
804
- * - Each special character as an individual token
805
- *
806
- * This is a cheap approximation suitable for telemetry purposes.
807
- *
808
- * @param text - The text to estimate token count for
809
- * @returns Estimated token count
810
- */
811
- function estimateTokens(text) {
812
- if (!text) return 0;
813
- let tokenCount = 0;
814
- let i = 0;
815
- const len = text.length;
816
- while (i < len) {
817
- const code = text.charCodeAt(i);
818
- if (isWhitespace(code)) {
819
- tokenCount++;
820
- i++;
821
- while (i < len && isWhitespace(text.charCodeAt(i))) i++;
822
- } else if (isAlphanumeric(code)) {
823
- tokenCount++;
824
- i++;
825
- while (i < len && isAlphanumeric(text.charCodeAt(i))) i++;
826
- } else {
827
- tokenCount++;
828
- i++;
829
- }
830
- }
831
- return tokenCount;
832
- }
833
-
834
- //#endregion
835
- //#region src/instructions/dev-instructions.md
836
- var dev_instructions_default = "## UI Building and Story Writing Workflow\n\n- Before creating or editing components or stories, call **get-storybook-story-instructions**.\n- Treat that tool's output as the source of truth for framework-specific imports, story patterns, and testing conventions.\n- After changing any component or story, call **preview-stories**.\n- Always include every returned preview URL in your user-facing response so the user can verify the visual result.\n";
837
-
838
- //#endregion
839
- //#region src/instructions/test-instructions.md
840
- var test_instructions_default = "## Validation Workflow\n\n- After each component or story change, run **run-story-tests**.\n- Use focused runs while iterating, then run a broad pass before final handoff when scope is unclear or wide.\n- Fix failing tests before reporting success. Do not report completion while story tests are failing.\n";
841
-
842
- //#endregion
843
- //#region src/instructions/build-server-instructions.ts
844
- function buildServerInstructions(options) {
845
- const sections = ["Follow these workflows when working with UI and/or Storybook."];
846
- if (options.devEnabled) sections.push(dev_instructions_default.trim());
847
- if (options.testEnabled) sections.push(test_instructions_default.trim());
848
- if (options.docsEnabled) sections.push(STORYBOOK_MCP_INSTRUCTIONS.trim());
849
- if (sections.length === 1) return "";
850
- return sections.join("\n\n");
851
- }
852
-
853
- //#endregion
854
- //#region src/mcp-handler.ts
855
- let transport;
856
- let origin;
857
- let initialize;
858
- let disableTelemetry;
859
- let a11yEnabled;
860
- const initializeMCPServer = async (options, multiSource) => {
861
- disableTelemetry = (await options.presets.apply("core", {}))?.disableTelemetry ?? false;
862
- const addonVitestConstants = await getAddonVitestConstants();
863
- const manifestStatus = await getManifestStatus(options);
864
- a11yEnabled = await isAddonA11yEnabled(options);
865
- let server;
866
- const serverOptions = {
867
- adapter: new ValibotJsonSchemaAdapter(),
868
- get instructions() {
869
- return buildServerInstructions({
870
- devEnabled: server?.ctx.custom?.toolsets?.dev ?? true,
871
- testEnabled: (server?.ctx.custom?.toolsets?.test ?? true) && !!addonVitestConstants,
872
- docsEnabled: (server?.ctx.custom?.toolsets?.docs ?? true) && manifestStatus.available
873
- });
874
- },
875
- capabilities: {
876
- tools: { listChanged: true },
877
- resources: { listChanged: true }
878
- }
879
- };
880
- server = new McpServer({
881
- name,
882
- version,
883
- description
884
- }, serverOptions).withContext();
885
- if (!disableTelemetry) server.on("initialize", async () => {
886
- await collectTelemetry({
887
- event: "session:initialized",
888
- server
889
- });
890
- });
891
- await addPreviewStoriesTool(server);
892
- await addGetUIBuildingInstructionsTool(server);
893
- await addRunStoryTestsTool(server, { a11yEnabled });
894
- if (manifestStatus.available) {
895
- logger.info("Experimental components manifest feature detected - registering component tools");
896
- const contextAwareEnabled = () => server.ctx.custom?.toolsets?.docs ?? true;
897
- await addListAllDocumentationTool(server, contextAwareEnabled);
898
- await addGetDocumentationTool(server, contextAwareEnabled, { multiSource });
899
- await addGetStoryDocumentationTool(server, contextAwareEnabled, { multiSource });
900
- }
901
- transport = new HttpTransport(server, { path: null });
902
- origin = `http://localhost:${options.port}`;
903
- logger.debug(`MCP server origin: ${origin}`);
904
- return server;
905
- };
906
- const mcpServerHandler = async ({ req, res, options, addonOptions, sources, manifestProvider, compositionAuth }) => {
907
- if (!initialize) initialize = initializeMCPServer(options, sources?.some((s) => s.url));
908
- const server = await initialize;
909
- const webRequest = await incomingMessageToWebRequest(req);
910
- const addonContext = {
911
- options,
912
- toolsets: getToolsets(webRequest, addonOptions),
913
- origin,
914
- disableTelemetry,
915
- a11yEnabled,
916
- request: webRequest,
917
- sources,
918
- manifestProvider,
919
- ...!disableTelemetry && {
920
- onListAllDocumentation: async ({ manifests, resultText, sources: sourceManifests }) => {
921
- await collectTelemetry({
922
- event: "tool:listAllDocumentation",
923
- server,
924
- toolset: "docs",
925
- componentCount: Object.keys(manifests.componentManifest.components).length,
926
- docsCount: Object.keys(manifests.docsManifest?.docs || {}).length,
927
- resultTokenCount: estimateTokens(resultText),
928
- sourceCount: sourceManifests?.length
929
- });
930
- },
931
- onGetDocumentation: async ({ input, foundDocumentation, resultText }) => {
932
- await collectTelemetry({
933
- event: "tool:getDocumentation",
934
- server,
935
- toolset: "docs",
936
- componentId: input.id,
937
- found: !!foundDocumentation,
938
- resultTokenCount: estimateTokens(resultText ?? "")
939
- });
940
- }
941
- }
942
- };
943
- const response = await transport.respond(webRequest, addonContext);
944
- if (response) {
945
- const body = await response.arrayBuffer();
946
- await webResponseToServerResponse(compositionAuth.hadAuthError(webRequest) ? new Response("401 - Unauthorized", {
947
- status: 401,
948
- headers: {
949
- "Content-Type": "text/plain",
950
- "WWW-Authenticate": compositionAuth.buildWwwAuthenticate(origin)
951
- }
952
- }) : new Response(body, {
953
- status: response.status,
954
- headers: response.headers
955
- }), res);
956
- }
1845
+ // src/tools/preview-stories.ts
1846
+ import url from "node:url";
1847
+ import * as v5 from "valibot";
1848
+
1849
+ // src/utils/build-args-param.ts
1850
+ import { stringify } from "picoquery";
1851
+ var HEX_REGEXP = /^#([a-f0-9]{3,4}|[a-f0-9]{6}|[a-f0-9]{8})$/i, COLOR_REGEXP = /^(rgba?|hsla?)\(([0-9]{1,3}),\s?([0-9]{1,3})%?,\s?([0-9]{1,3})%?,?\s?([0-9](\.[0-9]{1,2})?)?\)$/i;
1852
+ function encodeSpecialValues(value) {
1853
+ return value === void 0 ? "!undefined" : value === null ? "!null" : typeof value == "string" ? HEX_REGEXP.test(value) ? `!hex(${value.slice(1)})` : COLOR_REGEXP.test(value) ? `!${value.replace(/[\s%]/g, "")}` : value : typeof value == "boolean" ? `!${value}` : value instanceof Date ? `!date(${value.toISOString()})` : Array.isArray(value) ? value.map(encodeSpecialValues) : typeof value == "object" && value !== null ? Object.entries(value).reduce(
1854
+ (acc, [key, val]) => Object.assign(acc, { [key]: encodeSpecialValues(val) }),
1855
+ {}
1856
+ ) : value;
1857
+ }
1858
+ function decodeKnownQueryChar(chr) {
1859
+ switch (chr) {
1860
+ case "%20":
1861
+ return "+";
1862
+ case "%5B":
1863
+ return "[";
1864
+ case "%5D":
1865
+ return "]";
1866
+ case "%2C":
1867
+ return ",";
1868
+ case "%3A":
1869
+ return ":";
1870
+ }
1871
+ return chr;
1872
+ }
1873
+ var KNOWN_QUERY_CHAR_REGEXP = /%[0-9A-F]{2}/g;
1874
+ function buildArgsParam(args) {
1875
+ return !args || Object.keys(args).length === 0 ? "" : stringify(encodeSpecialValues(args), {
1876
+ delimiter: ";",
1877
+ nesting: !0,
1878
+ nestingSyntax: "js"
1879
+ }).replace(KNOWN_QUERY_CHAR_REGEXP, decodeKnownQueryChar).split(";").map((part) => part.replace("=", ":")).join(";");
1880
+ }
1881
+
1882
+ // src/tools/preview-stories/preview-stories-app-template.html
1883
+ var preview_stories_app_template_default = `<!doctype html>
1884
+ <html>
1885
+ <head>
1886
+ <meta charset="utf-8" />
1887
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
1888
+ <style>
1889
+ * {
1890
+ margin: 0;
1891
+ padding: 0;
1892
+ box-sizing: border-box;
1893
+ }
1894
+ html[data-theme='light'] {
1895
+ color-scheme: light;
1896
+ }
1897
+ html[data-theme='dark'] {
1898
+ color-scheme: dark;
1899
+ }
1900
+ html,
1901
+ body {
1902
+ width: 100%;
1903
+ margin: 0;
1904
+ padding: 0;
1905
+ background-color: var(--color-background-secondary);
1906
+ }
1907
+ body {
1908
+ display: flex;
1909
+ flex-direction: column;
1910
+ gap: 1rem;
1911
+ }
1912
+ :root {
1913
+ /*
1914
+ These are fallback values, if the MCP client doesn't set them.
1915
+ See https://github.com/modelcontextprotocol/ext-apps/blob/main/specification/draft/apps.mdx#theming
1916
+ */
1917
+ --color-text-primary: light-dark(black, white);
1918
+ --color-border-primary: light-dark(#ccc, #444);
1919
+ --color-background-secondary: light-dark(#f9f9f9, #1e1e1e);
1920
+ --font-sans:
1921
+ -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Oxygen-Sans', Ubuntu, Cantarell,
1922
+ 'Helvetica Neue', sans-serif;
1923
+ --font-heading-xs-size: 1rem;
1924
+ --font-heading-xs-line-height: 1.25;
1925
+ --border-width-regular: 1px;
1926
+ }
1927
+ .story-heading {
1928
+ font-family: var(--font-sans);
1929
+ font-size: var(--font-heading-xs-size);
1930
+ line-height: var(--font-heading-xs-line-height);
1931
+ color: var(--color-text-primary);
1932
+ padding: 0.5rem 0;
1933
+ }
1934
+ .story-iframe {
1935
+ background-color: white;
1936
+ border: var(--border-width-regular) solid var(--color-border-primary);
1937
+ }
1938
+ body:has(> article:only-child) h1 {
1939
+ /* if there is only one story rendered, hide its heading */
1940
+ display: none;
1941
+ }
1942
+ </style>
1943
+ <template id="preview-template">
1944
+ <article>
1945
+ <h1 class="story-heading"></h1>
1946
+ <iframe class="story-iframe"></iframe>
1947
+ </article>
1948
+ </template>
1949
+ <script type="module">
1950
+ // APP_SCRIPT_PLACEHOLDER
1951
+ </script>
1952
+ </head>
1953
+ <body></body>
1954
+ </html>
1955
+ `;
1956
+
1957
+ // src/tools/preview-stories.ts
1958
+ import fs2 from "node:fs/promises";
1959
+ var PREVIEW_STORIES_RESOURCE_URI = `ui://${PREVIEW_STORIES_TOOL_NAME}/preview.html`;
1960
+ function getPreviewStoriesToolDescription({
1961
+ reviewEnabled = !1
1962
+ } = {}) {
1963
+ return reviewEnabled ? `Use this tool to get Storybook preview URLs while iterating on a specific story, or when the user asks for a direct link to one.
1964
+ Do not end visual work or browse requests with these links \u2014 publish a curated review with display-review instead (passing changedFiles: [] when no code changed) and link that.` : `Use this tool to get one or more Storybook preview URLs.
1965
+ Call it after editing anything that changes how the UI looks \u2014 components, stories, styles, CSS, themes, colors, or design tokens \u2014 no exceptions. A shared file has no stories of its own: preview the stories of the components that consume it.
1966
+ Include each returned preview URL in your final user-facing response so users can open them directly.`;
1967
+ }
1968
+ var PreviewStoriesInput = v5.object({
1969
+ stories: v5.pipe(
1970
+ StoryInputArray,
1971
+ v5.description(
1972
+ `Stories to preview.
1973
+ Prefer { storyId } when you don't already have story file context, since this avoids filesystem discovery.
1974
+ Use { storyId } when IDs were discovered from documentation tools.
1975
+ Use { absoluteStoryPath + exportName } only when you're already working in a specific .stories.* file and already have that context.`
1976
+ )
1977
+ )
1978
+ }), PreviewStoriesOutput = v5.object({
1979
+ stories: v5.array(
1980
+ v5.union([
1981
+ v5.object({
1982
+ title: v5.string(),
1983
+ name: v5.string(),
1984
+ previewUrl: v5.pipe(
1985
+ v5.string(),
1986
+ v5.description(
1987
+ "Direct URL to open the story preview. Include this URL in the final user-facing response so users can open it directly \u2014 unless a curated review page is being published via display-review, in which case link the review page instead of listing individual URLs."
1988
+ )
1989
+ )
1990
+ }),
1991
+ v5.object({
1992
+ input: StoryInput,
1993
+ error: v5.string()
1994
+ })
1995
+ ])
1996
+ )
1997
+ });
1998
+ function getPreviewStoriesToolMetadata({
1999
+ reviewEnabled = !1
2000
+ } = {}) {
2001
+ return {
2002
+ name: PREVIEW_STORIES_TOOL_NAME,
2003
+ title: "Get story preview URLs",
2004
+ description: getPreviewStoriesToolDescription({ reviewEnabled }),
2005
+ schema: PreviewStoriesInput,
2006
+ outputSchema: PreviewStoriesOutput,
2007
+ _meta: { ui: { resourceUri: PREVIEW_STORIES_RESOURCE_URI } }
2008
+ };
2009
+ }
2010
+ async function addPreviewStoriesTool(server, enabled = () => server.ctx.custom?.toolsets?.dev ?? !0, { reviewEnabled = !1 } = {}) {
2011
+ let previewStoryAppScript = await fs2.readFile(
2012
+ url.fileURLToPath(
2013
+ import.meta.resolve("@storybook/addon-mcp/internal/preview-stories-app-script")
2014
+ ),
2015
+ "utf-8"
2016
+ ), appHtml = preview_stories_app_template_default.replace("// APP_SCRIPT_PLACEHOLDER", previewStoryAppScript);
2017
+ server.resource(
2018
+ {
2019
+ name: PREVIEW_STORIES_RESOURCE_URI,
2020
+ description: "App resource for the Preview Stories tool",
2021
+ uri: PREVIEW_STORIES_RESOURCE_URI,
2022
+ mimeType: "text/html;profile=mcp-app"
2023
+ },
2024
+ () => {
2025
+ let origin2 = server.ctx.custom.origin;
2026
+ return {
2027
+ contents: [
2028
+ {
2029
+ uri: PREVIEW_STORIES_RESOURCE_URI,
2030
+ mimeType: "text/html;profile=mcp-app",
2031
+ text: appHtml,
2032
+ _meta: {
2033
+ ui: {
2034
+ prefersBorder: !1,
2035
+ domain: origin2,
2036
+ csp: {
2037
+ connectDomains: [origin2],
2038
+ resourceDomains: [origin2],
2039
+ frameDomains: [origin2],
2040
+ baseUriDomains: [origin2]
2041
+ }
2042
+ }
2043
+ }
2044
+ }
2045
+ ]
2046
+ };
2047
+ }
2048
+ ), server.tool(
2049
+ {
2050
+ ...getPreviewStoriesToolMetadata({ reviewEnabled }),
2051
+ enabled
2052
+ },
2053
+ async (input) => {
2054
+ try {
2055
+ let { origin: origin2, options, disableTelemetry: disableTelemetry2 } = server.ctx.custom ?? {};
2056
+ if (!origin2)
2057
+ throw new Error("Origin is required in addon context");
2058
+ if (!options)
2059
+ throw new Error("Storybook options are required in addon context");
2060
+ let index = await getStoryIndex(options), resolvedStories = findStoryIds(index, input.stories), structuredResult = [], textResult = [];
2061
+ for (let story of resolvedStories) {
2062
+ if ("errorMessage" in story) {
2063
+ structuredResult.push({
2064
+ input: story.input,
2065
+ error: story.errorMessage
2066
+ }), textResult.push(story.errorMessage);
2067
+ continue;
2068
+ }
2069
+ let indexEntry = index.entries[story.id];
2070
+ if (!indexEntry) {
2071
+ structuredResult.push({
2072
+ input: story.input,
2073
+ error: `No story found for story ID "${story.id}"`
2074
+ }), textResult.push(`No story found for story ID "${story.id}"`);
2075
+ continue;
2076
+ }
2077
+ let previewUrl = `${origin2}/?path=/story/${story.id}`, argsParam = buildArgsParam(story.input.props ?? {});
2078
+ argsParam && (previewUrl += `&args=${argsParam}`);
2079
+ let globalsParam = buildArgsParam(story.input.globals ?? {});
2080
+ globalsParam && (previewUrl += `&globals=${globalsParam}`), structuredResult.push({
2081
+ title: indexEntry.title,
2082
+ name: indexEntry.name,
2083
+ previewUrl
2084
+ }), textResult.push(previewUrl);
2085
+ }
2086
+ disableTelemetry2 || await collectTelemetry({
2087
+ event: "tool:previewStories",
2088
+ server,
2089
+ toolset: "dev",
2090
+ inputStoryCount: input.stories.length,
2091
+ outputStoryCount: structuredResult.length
2092
+ });
2093
+ let content = textResult.map((text) => ({
2094
+ type: "text",
2095
+ text
2096
+ })), resolvedAnyStory = structuredResult.some((story) => "previewUrl" in story);
2097
+ return reviewEnabled && resolvedAnyStory && content.push({
2098
+ type: "text",
2099
+ text: "These preview links are for iterating or sharing a specific story \u2014 they are not how visual work or a browse request ends. The display-review tool is available in this session: if you are finishing visually observable work or showing a set of stories, publish the review with **display-review** and link that instead."
2100
+ }), {
2101
+ content,
2102
+ structuredContent: {
2103
+ stories: structuredResult
2104
+ }
2105
+ };
2106
+ } catch (error) {
2107
+ return errorToMCPContent(error);
2108
+ }
2109
+ }
2110
+ );
2111
+ }
2112
+
2113
+ // src/tools/tool-registry.ts
2114
+ var isToolsetEnabled = (toolset, toolsets) => toolsets?.[toolset] ?? !0, isToolAvailable = (definition, context) => definition.available?.(context) ?? !0, isMetadataToolEnabled = (definition, context) => isToolsetEnabled(definition.toolset, context.toolsets) && isToolAvailable(definition, context), createToolsetEnabled = (server, toolset) => () => server.ctx.custom?.toolsets?.[toolset] ?? !0, addonToolDefinitions = [
2115
+ {
2116
+ name: PREVIEW_STORIES_TOOL_NAME,
2117
+ toolset: "dev",
2118
+ getMetadata: ({ availability }) => getPreviewStoriesToolMetadata({ reviewEnabled: availability.reviewEnabled }),
2119
+ register: (server, { availability }, enabled) => addPreviewStoriesTool(server, enabled, { reviewEnabled: availability.reviewEnabled })
2120
+ },
2121
+ {
2122
+ name: GET_UI_BUILDING_INSTRUCTIONS_TOOL_NAME,
2123
+ toolset: "dev",
2124
+ getMetadata: ({ availability, toolsets }) => {
2125
+ let testToolsetAvailable = isToolsetEnabled("test", toolsets) && availability.testSupported;
2126
+ return getStorybookStoryInstructionsToolMetadata({
2127
+ testToolsetAvailable,
2128
+ a11yAvailable: testToolsetAvailable && availability.a11yEnabled
2129
+ });
2130
+ },
2131
+ register: (server, { availability, toolsets }, enabled) => addGetUIBuildingInstructionsTool(server, enabled, {
2132
+ docsAvailable: isToolsetEnabled("docs", toolsets) && availability.docsEnabled
2133
+ }),
2134
+ getLocalTool: ({ availability, toolsets, options }) => ({
2135
+ call: async () => ({ content: [{ type: "text", text: await buildStorybookStoryInstructions(options, {
2136
+ toolsets,
2137
+ a11yEnabled: availability.a11yEnabled,
2138
+ addonVitestAvailable: availability.testSupported,
2139
+ docsAvailable: isToolsetEnabled("docs", toolsets) && availability.docsEnabled,
2140
+ reviewEnabled: availability.reviewEnabled
2141
+ }) }] })
2142
+ })
2143
+ },
2144
+ {
2145
+ name: GET_CHANGED_STORIES_TOOL_NAME,
2146
+ toolset: "dev",
2147
+ available: ({ availability }) => availability.changeDetectionEnabled,
2148
+ getMetadata: () => getChangedStoriesToolMetadata(),
2149
+ register: (server, { availability }, enabled) => addGetChangedStoriesTool(server, enabled, { reviewEnabled: availability.reviewEnabled })
2150
+ },
2151
+ {
2152
+ name: GET_STORIES_BY_COMPONENT_TOOL_NAME,
2153
+ toolset: "dev",
2154
+ available: ({ availability }) => availability.moduleGraphSupported,
2155
+ getMetadata: ({ availability }) => getStoriesByComponentToolMetadata({ reviewEnabled: availability.reviewEnabled }),
2156
+ register: (server, { availability }, enabled) => addGetStoriesByComponentTool(server, enabled, {
2157
+ reviewEnabled: availability.reviewEnabled
2158
+ })
2159
+ },
2160
+ {
2161
+ name: DISPLAY_REVIEW_TOOL_NAME,
2162
+ toolset: "dev",
2163
+ // Registered whenever the CLI default could turn review on; the per-request
2164
+ // `reviewEnabled` context (explicit flag, or the trusted local-client header)
2165
+ // decides whether a given MCP client actually sees the tool.
2166
+ available: ({ availability }) => availability.reviewEnabledForCli,
2167
+ getMetadata: () => getDisplayReviewToolMetadata(),
2168
+ register: (server, { availability }, enabled) => addDisplayReviewTool(
2169
+ server,
2170
+ async () => (await enabled?.() ?? !0) && (server.ctx.custom?.reviewEnabled ?? availability.reviewEnabled)
2171
+ )
2172
+ },
2173
+ {
2174
+ name: RUN_STORY_TESTS_TOOL_NAME,
2175
+ toolset: "test",
2176
+ available: ({ availability }) => availability.testSupported,
2177
+ getMetadata: ({ availability }) => getRunStoryTestsToolMetadata({ a11yEnabled: availability.a11yEnabled }),
2178
+ register: (server, { availability }, enabled) => addRunStoryTestsTool(server, { a11yEnabled: availability.a11yEnabled }, enabled)
2179
+ },
2180
+ {
2181
+ name: LIST_TOOL_NAME2,
2182
+ toolset: "docs",
2183
+ available: ({ availability }) => availability.docsEnabled,
2184
+ getMetadata: () => getListAllDocumentationToolMetadata(),
2185
+ register: async (server, _context, enabled) => {
2186
+ logger5.info(
2187
+ "Experimental components manifest feature detected - registering component tools"
2188
+ ), await addListAllDocumentationTool(server, enabled);
2189
+ }
2190
+ },
2191
+ {
2192
+ name: GET_TOOL_NAME2,
2193
+ toolset: "docs",
2194
+ available: ({ availability }) => availability.docsEnabled,
2195
+ getMetadata: ({ multiSource }) => getDocumentationToolMetadata({ multiSource }),
2196
+ register: (server, { multiSource }, enabled) => addGetDocumentationTool(server, enabled, {
2197
+ multiSource
2198
+ })
2199
+ },
2200
+ {
2201
+ name: GET_STORY_TOOL_NAME,
2202
+ toolset: "docs",
2203
+ available: ({ availability }) => availability.docsEnabled,
2204
+ getMetadata: ({ multiSource }) => getStoryDocumentationToolMetadata({ multiSource }),
2205
+ register: (server, { multiSource }, enabled) => addGetStoryDocumentationTool(server, enabled, {
2206
+ multiSource
2207
+ })
2208
+ }
2209
+ ];
2210
+ function getAddonToolMetadata(context) {
2211
+ return addonToolDefinitions.filter((definition) => isMetadataToolEnabled(definition, context)).map((definition) => definition.getMetadata(context));
2212
+ }
2213
+ function getAddonLocalTools(context) {
2214
+ return Object.fromEntries(
2215
+ addonToolDefinitions.filter((definition) => isMetadataToolEnabled(definition, context)).flatMap((definition) => {
2216
+ let localTool = definition.getLocalTool?.(context);
2217
+ return localTool ? [[definition.name, localTool]] : [];
2218
+ })
2219
+ );
2220
+ }
2221
+ async function registerAddonMcpTools(server, context) {
2222
+ for (let definition of addonToolDefinitions)
2223
+ isToolsetEnabled(definition.toolset, context.toolsets) && isToolAvailable(definition, context) && await definition.register(server, context, createToolsetEnabled(server, definition.toolset));
2224
+ }
2225
+
2226
+ // src/mcp-handler.ts
2227
+ var transport, origin, initialize, disableTelemetry, a11yEnabled, reviewGates, initializeMCPServer = async (options, multiSource) => {
2228
+ let core = await options.presets.apply("core", {}), features2 = await options.presets.apply("features", {});
2229
+ disableTelemetry = core?.disableTelemetry ?? !1;
2230
+ let rawAvailability = await getToolAvailability(options, { features: features2 }), availability = getEffectiveToolAvailability(rawAvailability, { multiSource });
2231
+ a11yEnabled = availability.a11yEnabled, reviewGates = {
2232
+ reviewEnabled: availability.reviewEnabled,
2233
+ reviewEnabledForCli: availability.reviewEnabledForCli
2234
+ };
2235
+ let server, serverOptions = {
2236
+ adapter: new ValibotJsonSchemaAdapter(),
2237
+ get instructions() {
2238
+ return buildServerInstructions({
2239
+ devEnabled: server?.ctx.custom?.toolsets?.dev ?? !0,
2240
+ testEnabled: (server?.ctx.custom?.toolsets?.test ?? !0) && availability.testSupported,
2241
+ docsEnabled: (server?.ctx.custom?.toolsets?.docs ?? !0) && availability.docsEnabled,
2242
+ changeDetectionEnabled: availability.changeDetectionEnabled,
2243
+ moduleGraphSupported: availability.moduleGraphSupported,
2244
+ reviewEnabled: server?.ctx.custom?.reviewEnabled ?? availability.reviewEnabled
2245
+ });
2246
+ },
2247
+ capabilities: {
2248
+ tools: { listChanged: !0 },
2249
+ resources: { listChanged: !0 }
2250
+ }
2251
+ };
2252
+ return server = new McpServer(
2253
+ {
2254
+ name: package_default.name,
2255
+ version: package_default.version,
2256
+ description: package_default.description
2257
+ },
2258
+ serverOptions
2259
+ ).withContext(), disableTelemetry || server.on("initialize", async () => {
2260
+ await collectTelemetry({ event: "session:initialized", server });
2261
+ }), await registerAddonMcpTools(server, { availability, multiSource }), transport = new HttpTransport(server, { path: null }), origin = `http://localhost:${options.port}`, logger6.debug(`MCP server origin: ${origin}`), server;
2262
+ }, mcpServerHandler = async ({
2263
+ req,
2264
+ res,
2265
+ options,
2266
+ addonOptions,
2267
+ endpoint = DEFAULT_MCP_ENDPOINT,
2268
+ sources,
2269
+ manifestProvider,
2270
+ resolveEntry,
2271
+ compositionAuth
2272
+ }) => {
2273
+ initialize || (initialize = initializeMCPServer(
2274
+ options,
2275
+ sources?.some((s) => s.url)
2276
+ ));
2277
+ let server = await initialize, webRequest = await incomingMessageToWebRequest(req), addonContext = {
2278
+ options,
2279
+ endpoint,
2280
+ toolsets: getToolsets(webRequest, addonOptions),
2281
+ reviewEnabled: isReviewEnabledForRequest(webRequest, reviewGates),
2282
+ origin,
2283
+ disableTelemetry,
2284
+ a11yEnabled,
2285
+ request: webRequest,
2286
+ sources,
2287
+ manifestProvider,
2288
+ resolveEntry,
2289
+ // Telemetry handlers for component manifest tools
2290
+ ...!disableTelemetry && {
2291
+ onListAllDocumentation: async ({ manifests, resultText, sources: sourceManifests }) => {
2292
+ await collectTelemetry({
2293
+ event: "tool:listAllDocumentation",
2294
+ server,
2295
+ toolset: "docs",
2296
+ componentCount: Object.keys(manifests.componentManifest.components).length,
2297
+ docsCount: Object.keys(manifests.docsManifest?.docs || {}).length,
2298
+ resultTokenCount: estimateTokens(resultText),
2299
+ sourceCount: sourceManifests?.length
2300
+ });
2301
+ },
2302
+ onGetDocumentation: async ({ input, foundDocumentation, resultText }) => {
2303
+ await collectTelemetry({
2304
+ event: "tool:getDocumentation",
2305
+ server,
2306
+ toolset: "docs",
2307
+ componentId: input.id,
2308
+ found: !!foundDocumentation,
2309
+ resultTokenCount: estimateTokens(resultText ?? "")
2310
+ });
2311
+ }
2312
+ }
2313
+ }, response = await transport.respond(webRequest, addonContext);
2314
+ if (response) {
2315
+ let body = await response.arrayBuffer(), finalResponse = compositionAuth.hadAuthError(webRequest) ? new Response("401 - Unauthorized", {
2316
+ status: 401,
2317
+ headers: {
2318
+ "Content-Type": "text/plain",
2319
+ "WWW-Authenticate": compositionAuth.buildWwwAuthenticate(origin)
2320
+ }
2321
+ }) : new Response(body, { status: response.status, headers: response.headers });
2322
+ await webResponseToServerResponse(finalResponse, res);
2323
+ }
957
2324
  };
958
- /**
959
- * Converts a Node.js IncomingMessage to a Web Request.
960
- */
961
2325
  async function incomingMessageToWebRequest(req) {
962
- const host = req.headers.host || "localhost";
963
- const protocol = "encrypted" in req.socket && req.socket.encrypted ? "https" : "http";
964
- const url = new URL(req.url || "/", `${protocol}://${host}`);
965
- const bodyBuffer = await buffer(req);
966
- return new Request(url, {
967
- method: req.method,
968
- headers: req.headers,
969
- body: bodyBuffer.length > 0 ? new Uint8Array(bodyBuffer) : void 0
970
- });
971
- }
972
- /**
973
- * Converts a Web Response to a Node.js ServerResponse.
974
- */
2326
+ let host = req.headers.host || "localhost", protocol = "encrypted" in req.socket && req.socket.encrypted ? "https" : "http", url2 = new URL(req.url || "/", `${protocol}://${host}`), bodyBuffer = await buffer(req);
2327
+ return new Request(url2, {
2328
+ method: req.method,
2329
+ headers: req.headers,
2330
+ body: bodyBuffer.length > 0 ? new Uint8Array(bodyBuffer) : void 0
2331
+ });
2332
+ }
975
2333
  async function webResponseToServerResponse(webResponse, nodeResponse) {
976
- nodeResponse.statusCode = webResponse.status;
977
- webResponse.headers.forEach((value, key) => {
978
- nodeResponse.setHeader(key, value);
979
- });
980
- if (webResponse.body) {
981
- const reader = webResponse.body.getReader();
982
- try {
983
- while (true) {
984
- const { done, value } = await reader.read();
985
- if (done) break;
986
- nodeResponse.write(value);
987
- }
988
- } finally {
989
- reader.releaseLock();
990
- }
991
- }
992
- nodeResponse.end();
2334
+ if (nodeResponse.statusCode = webResponse.status, webResponse.headers.forEach((value, key) => {
2335
+ nodeResponse.setHeader(key, value);
2336
+ }), webResponse.body) {
2337
+ let reader = webResponse.body.getReader();
2338
+ try {
2339
+ for (; ; ) {
2340
+ let { done, value } = await reader.read();
2341
+ if (done) break;
2342
+ nodeResponse.write(value);
2343
+ }
2344
+ } finally {
2345
+ reader.releaseLock();
2346
+ }
2347
+ }
2348
+ nodeResponse.end();
2349
+ }
2350
+ function isReviewEnabledForRequest(request, gates) {
2351
+ return gates.reviewEnabled || gates.reviewEnabledForCli && request.headers.get(STORYBOOK_MCP_PROXY_HEADER) === "true";
993
2352
  }
994
2353
  function getToolsets(request, addonOptions) {
995
- const toolsetHeader = request.headers.get("X-MCP-Toolsets");
996
- if (!toolsetHeader || toolsetHeader.trim() === "") return addonOptions.toolsets;
997
- const toolsets = {
998
- dev: false,
999
- docs: false,
1000
- test: false
1001
- };
1002
- const enabledToolsets = toolsetHeader.split(",");
1003
- for (const enabledToolset of enabledToolsets) {
1004
- const trimmedToolset = enabledToolset.trim();
1005
- if (trimmedToolset in toolsets) toolsets[trimmedToolset] = true;
1006
- }
1007
- return toolsets;
1008
- }
1009
-
1010
- //#endregion
1011
- //#region src/template.html
1012
- var template_default = "<!doctype html>\n<html>\n <head>\n <style>\n @font-face {\n font-family: 'Nunito Sans';\n font-style: normal;\n font-weight: 400;\n font-display: swap;\n src: url('./sb-common-assets/nunito-sans-regular.woff2') format('woff2');\n }\n\n * {\n margin: 0;\n padding: 0;\n box-sizing: border-box;\n }\n\n html,\n body {\n height: 100%;\n font-family:\n 'Nunito Sans',\n -apple-system,\n BlinkMacSystemFont,\n 'Segoe UI',\n Roboto,\n Oxygen,\n Ubuntu,\n Cantarell,\n sans-serif;\n }\n\n body {\n display: flex;\n flex-direction: column;\n justify-content: center;\n align-items: center;\n text-align: center;\n padding: 2rem;\n background-color: #ffffff;\n color: rgb(46, 52, 56);\n line-height: 1.6;\n }\n\n p {\n margin-bottom: 1rem;\n }\n\n code {\n font-family: 'Monaco', 'Courier New', monospace;\n background: #f5f5f5;\n padding: 0.2em 0.4em;\n border-radius: 3px;\n }\n\n a {\n color: #1ea7fd;\n }\n\n .container {\n display: flex;\n flex-direction: column;\n align-items: center;\n }\n\n .toolsets {\n margin: 1.5rem 0;\n text-align: left;\n max-width: 500px;\n }\n\n .toolsets h3 {\n font-size: 1rem;\n margin-bottom: 0.75rem;\n text-align: center;\n }\n\n .toolset {\n margin-bottom: 1rem;\n padding: 0.75rem 1rem;\n border-radius: 6px;\n background: #f8f9fa;\n border: 1px solid #e9ecef;\n }\n\n .toolset-header {\n display: flex;\n align-items: center;\n gap: 0.5rem;\n font-weight: 600;\n margin-bottom: 0.5rem;\n }\n\n .toolset-status {\n display: inline-block;\n padding: 0.15em 0.5em;\n border-radius: 3px;\n font-size: 0.75rem;\n font-weight: 500;\n text-transform: uppercase;\n }\n\n .toolset-status.enabled {\n background: #d4edda;\n color: #155724;\n }\n\n .toolset-status.disabled {\n background: #f8d7da;\n color: #721c24;\n }\n\n .toolset-tools {\n font-size: 0.875rem;\n color: #6c757d;\n padding-left: 1.5rem;\n margin: 0;\n }\n\n .toolset-tools li {\n margin-bottom: 0.25rem;\n }\n\n .toolset-tools code {\n font-size: 0.8rem;\n }\n\n .toolset-notice {\n font-size: 0.8rem;\n color: #856404;\n background: #fff3cd;\n padding: 0.5rem;\n border-radius: 4px;\n margin-top: 0.5rem;\n }\n\n .toolset-notice a {\n color: #533f03;\n }\n\n @media (prefers-color-scheme: dark) {\n body {\n background-color: rgb(34, 36, 37);\n color: rgb(201, 205, 207);\n }\n\n code {\n background: rgba(255, 255, 255, 0.1);\n }\n\n .toolset {\n background: rgba(255, 255, 255, 0.05);\n border-color: rgba(255, 255, 255, 0.1);\n }\n\n .toolset-tools {\n color: #adb5bd;\n }\n\n .toolset-status.enabled {\n background: rgba(40, 167, 69, 0.2);\n color: #75d67e;\n }\n\n .toolset-status.disabled {\n background: rgba(220, 53, 69, 0.2);\n color: #f5a6ad;\n }\n\n .toolset-notice {\n background: rgba(255, 193, 7, 0.15);\n color: #ffc107;\n }\n\n .toolset-notice a {\n color: #ffe066;\n }\n }\n </style>\n </head>\n <body>\n <div class=\"container\">\n <p>\n Storybook MCP server successfully running via\n <code>@storybook/addon-mcp</code>.\n </p>\n <p>\n See how to connect to it from your coding agent in\n <a\n target=\"_blank\"\n href=\"https://github.com/storybookjs/mcp/tree/main/packages/addon-mcp#configuring-your-agent\"\n >the addon's README</a\n >.\n </p>\n\n <div class=\"toolsets\">\n <h3>Available Toolsets</h3>\n\n <div class=\"toolset\">\n <div class=\"toolset-header\">\n <span>dev</span>\n <span class=\"toolset-status {{DEV_STATUS}}\">{{DEV_STATUS}}</span>\n </div>\n <ul class=\"toolset-tools\">\n <li><code>preview-stories</code></li>\n <li><code>get-storybook-story-instructions</code></li>\n </ul>\n </div>\n\n <div class=\"toolset\">\n <div class=\"toolset-header\">\n <span>docs</span>\n <span class=\"toolset-status {{DOCS_STATUS}}\">{{DOCS_STATUS}}</span>\n </div>\n <ul class=\"toolset-tools\">\n <li><code>list-all-documentation</code></li>\n <li><code>get-documentation</code></li>\n </ul>\n {{DOCS_NOTICE}}\n </div>\n\n <div class=\"toolset\">\n <div class=\"toolset-header\">\n <span>test</span>\n <span class=\"toolset-status {{TEST_STATUS}}\">{{TEST_STATUS}}</span>\n </div>\n <ul class=\"toolset-tools\">\n <li><code>run-story-tests</code>{{A11Y_BADGE}}</li>\n </ul>\n {{TEST_NOTICE}}\n </div>\n </div>\n\n {{MANIFEST_DEBUGGER_LINK}}\n </div>\n </body>\n</html>\n";
1013
-
1014
- //#endregion
1015
- //#region src/auth/composition-auth.ts
1016
- /**
1017
- * Composition authentication for fetching manifests from private Storybooks.
1018
- *
1019
- * This class handles OAuth discovery and token-based manifest fetching for
1020
- * composed Storybooks (refs). It acts as a proxy for OAuth metadata, allowing
1021
- * MCP clients like VS Code to handle the OAuth flow with Chromatic.
1022
- */
1023
- const OAuthResourceMetadata = v.object({
1024
- resource: v.optional(v.string()),
1025
- authorization_servers: v.pipe(v.array(v.string()), v.minLength(1)),
1026
- scopes_supported: v.optional(v.array(v.string()))
1027
- });
1028
- const OAuthServerMetadata = v.object({
1029
- issuer: v.string(),
1030
- authorization_endpoint: v.string(),
1031
- token_endpoint: v.string(),
1032
- scopes_supported: v.optional(v.array(v.string()))
1033
- });
1034
- const MANIFEST_CACHE_TTL = 3600 * 1e3;
1035
- const REVALIDATION_TTL = 60 * 1e3;
1036
- var AuthenticationError = class extends Error {
1037
- constructor(url) {
1038
- super(`Authentication failed for ${url}. Your token may be invalid or expired.`);
1039
- this.name = "AuthenticationError";
1040
- }
1041
- };
1042
- var CompositionAuth = class {
1043
- #authRequirement = null;
1044
- #authRequiredUrls = [];
1045
- #refsWithManifests = [];
1046
- #manifestCache = /* @__PURE__ */ new Map();
1047
- #lastToken = null;
1048
- #authErrors = /* @__PURE__ */ new WeakMap();
1049
- /** Initialize by checking which refs require authentication and have manifests. */
1050
- async initialize(refs) {
1051
- for (const ref of refs) try {
1052
- const result = await this.#checkRef(ref.url);
1053
- if (result === "no-manifest") continue;
1054
- this.#refsWithManifests.push(ref);
1055
- if (result === "public") continue;
1056
- this.#authRequiredUrls.push(ref.url);
1057
- if (!this.#authRequirement) this.#authRequirement = result;
1058
- else {
1059
- const existingServer = this.#authRequirement.resourceMetadata.authorization_servers[0];
1060
- const newServer = result.resourceMetadata.authorization_servers[0];
1061
- if (existingServer !== newServer) console.warn(`[addon-mcp] Composed ref "${ref.title}" uses a different OAuth server (${newServer}) than the first authenticated ref (${existingServer}). Only the first OAuth server will be used for authentication.`);
1062
- }
1063
- } catch (error) {
1064
- console.warn(`[addon-mcp] Failed to check auth for composed ref "${ref.title}" (${ref.url}): ${error instanceof Error ? error.message : String(error)}. Skipping this ref.`);
1065
- }
1066
- }
1067
- get requiresAuth() {
1068
- return this.#authRequiredUrls.length > 0;
1069
- }
1070
- get authUrls() {
1071
- return this.#authRequiredUrls;
1072
- }
1073
- /** Check if a request encountered an auth error during manifest fetching. */
1074
- hadAuthError(request) {
1075
- return this.#authErrors.has(request);
1076
- }
1077
- /** Check if a URL requires authentication based on discovered auth requirements. */
1078
- #isAuthRequiredUrl(url) {
1079
- return this.#authRequiredUrls.some((authUrl) => url.startsWith(authUrl));
1080
- }
1081
- /** Build .well-known/oauth-protected-resource response. */
1082
- buildWellKnown(origin) {
1083
- if (!this.#authRequirement) return null;
1084
- return {
1085
- resource: `${origin}/mcp`,
1086
- authorization_servers: this.#authRequirement.resourceMetadata.authorization_servers,
1087
- scopes_supported: this.#authRequirement.resourceMetadata.scopes_supported
1088
- };
1089
- }
1090
- /** Build WWW-Authenticate header for 401 responses */
1091
- buildWwwAuthenticate(origin) {
1092
- return `Bearer error="unauthorized", error_description="Authorization needed for composed Storybooks", resource_metadata="${origin}/.well-known/oauth-protected-resource"`;
1093
- }
1094
- /** Build sources configuration: local first, then refs that have manifests. */
1095
- buildSources() {
1096
- return [{
1097
- id: "local",
1098
- title: "Local"
1099
- }, ...this.#refsWithManifests.map((ref) => ({
1100
- id: ref.id,
1101
- title: ref.title,
1102
- url: ref.url
1103
- }))];
1104
- }
1105
- /** Create a manifest provider for multi-source mode. */
1106
- createManifestProvider(localOrigin) {
1107
- return async (request, path, source) => {
1108
- const token = extractBearerToken(request?.headers.get("Authorization"));
1109
- const baseUrl = source?.url ?? localOrigin;
1110
- const manifestUrl = `${baseUrl}${path.replace("./", "/")}`;
1111
- const isRemote = !!source?.url;
1112
- const tokenForRequest = isRemote && this.#isAuthRequiredUrl(baseUrl) ? token : null;
1113
- if (token && token !== this.#lastToken) {
1114
- this.#manifestCache.clear();
1115
- this.#lastToken = token;
1116
- }
1117
- if (isRemote) {
1118
- const cached = this.#manifestCache.get(manifestUrl);
1119
- if (cached) if (Date.now() - cached.timestamp > MANIFEST_CACHE_TTL) this.#manifestCache.delete(manifestUrl);
1120
- else {
1121
- if (!cached.lastRevalidatedAt || Date.now() - cached.lastRevalidatedAt > REVALIDATION_TTL) {
1122
- cached.lastRevalidatedAt = Date.now();
1123
- this.#fetchManifest(manifestUrl, tokenForRequest).then((text) => this.#manifestCache.set(manifestUrl, {
1124
- text,
1125
- timestamp: Date.now(),
1126
- lastRevalidatedAt: Date.now()
1127
- })).catch(() => {});
1128
- }
1129
- return cached.text;
1130
- }
1131
- }
1132
- try {
1133
- const text = await this.#fetchManifest(manifestUrl, tokenForRequest);
1134
- if (isRemote) this.#manifestCache.set(manifestUrl, {
1135
- text,
1136
- timestamp: Date.now()
1137
- });
1138
- return text;
1139
- } catch (error) {
1140
- if (error instanceof AuthenticationError && request) this.#authErrors.set(request, error);
1141
- throw error;
1142
- }
1143
- };
1144
- }
1145
- /**
1146
- * Fetch a manifest with optional auth token.
1147
- * If the response is 200 but not a valid manifest, checks /mcp for auth issues.
1148
- */
1149
- async #fetchManifest(url, token) {
1150
- const headers = { Accept: "application/json" };
1151
- if (token) headers["Authorization"] = `Bearer ${token}`;
1152
- const response = await fetch(url, { headers });
1153
- if (response.status === 401) throw new AuthenticationError(url);
1154
- if (!response.ok) throw new Error(`Failed to fetch ${url}: ${response.status}`);
1155
- const text = await response.text();
1156
- const schema = url.includes("docs.json") ? DocsManifestMap : ComponentManifestMap;
1157
- if (v.safeParse(v.pipe(v.string(), v.parseJson(), schema), text).success) return text;
1158
- if (await this.#isMcpUnauthorized(new URL(url).origin)) throw new AuthenticationError(url);
1159
- throw new Error(`Invalid manifest response from ${url}: expected valid JSON manifest but got unexpected content.`);
1160
- }
1161
- /**
1162
- * Check a ref to determine if it has a manifest and whether it requires auth.
1163
- * Returns 'public' if the ref has a valid manifest without auth,
1164
- * 'no-manifest' if no manifest is available, or an AuthRequirement if auth is needed.
1165
- */
1166
- async #checkRef(refUrl) {
1167
- const response = await fetch(`${refUrl}/manifests/components.json`, { headers: { Accept: "application/json" } });
1168
- const authReq = await this.#parseAuthFromResponse(response);
1169
- if (authReq) return authReq;
1170
- if (response.ok) {
1171
- const text = await response.text();
1172
- if (v.safeParse(v.pipe(v.string(), v.parseJson(), ComponentManifestMap), text).success) return "public";
1173
- }
1174
- const mcpAuth = await this.#checkMcpAuth(refUrl);
1175
- if (mcpAuth) return mcpAuth;
1176
- return "no-manifest";
1177
- }
1178
- /** Check /mcp endpoint for 401 auth requirement. */
1179
- async #checkMcpAuth(refUrl) {
1180
- const response = await fetch(`${refUrl}/mcp`, {
1181
- method: "POST",
1182
- headers: { "Content-Type": "application/json" },
1183
- body: JSON.stringify({
1184
- jsonrpc: "2.0",
1185
- id: 1,
1186
- method: "tools/list"
1187
- })
1188
- });
1189
- return this.#parseAuthFromResponse(response);
1190
- }
1191
- /** Quick check: does the remote /mcp return 401? */
1192
- async #isMcpUnauthorized(origin) {
1193
- try {
1194
- return (await fetch(`${origin}/mcp`, {
1195
- method: "POST",
1196
- headers: { "Content-Type": "application/json" },
1197
- body: JSON.stringify({
1198
- jsonrpc: "2.0",
1199
- id: 1,
1200
- method: "tools/list"
1201
- })
1202
- })).status === 401;
1203
- } catch {
1204
- return false;
1205
- }
1206
- }
1207
- /** Extract auth requirement from a 401 response's WWW-Authenticate header. */
1208
- async #parseAuthFromResponse(response) {
1209
- if (response.status !== 401) return null;
1210
- const wwwAuth = response.headers.get("WWW-Authenticate");
1211
- if (!wwwAuth) return null;
1212
- const match = wwwAuth.match(/resource_metadata="([^"]+)"/);
1213
- if (!match?.[1]) return null;
1214
- const resourceMetadataUrl = match[1];
1215
- const resourceResponse = await fetch(resourceMetadataUrl);
1216
- if (!resourceResponse.ok) {
1217
- console.warn(`[addon-mcp] Failed to fetch OAuth resource metadata from ${resourceMetadataUrl}: ${resourceResponse.status}`);
1218
- return null;
1219
- }
1220
- const resourceResult = v.safeParse(OAuthResourceMetadata, await resourceResponse.json());
1221
- if (!resourceResult.success) {
1222
- console.warn(`[addon-mcp] Invalid OAuth resource metadata from ${resourceMetadataUrl}: ${resourceResult.issues.map((i) => i.message).join(", ")}`);
1223
- return null;
1224
- }
1225
- const serverMetadataUrl = `${resourceResult.output.authorization_servers[0]}/.well-known/oauth-authorization-server`;
1226
- const serverResponse = await fetch(serverMetadataUrl);
1227
- if (!serverResponse.ok) {
1228
- console.warn(`[addon-mcp] Failed to fetch OAuth server metadata from ${serverMetadataUrl}: ${serverResponse.status}`);
1229
- return null;
1230
- }
1231
- const serverResult = v.safeParse(OAuthServerMetadata, await serverResponse.json());
1232
- if (!serverResult.success) {
1233
- console.warn(`[addon-mcp] Invalid OAuth server metadata from ${serverMetadataUrl}: ${serverResult.issues.map((i) => i.message).join(", ")}`);
1234
- return null;
1235
- }
1236
- return {
1237
- resourceMetadataUrl,
1238
- resourceMetadata: resourceResult.output,
1239
- serverMetadata: serverResult.output
1240
- };
1241
- }
2354
+ let toolsetHeader = request.headers.get("X-MCP-Toolsets");
2355
+ if (!toolsetHeader || toolsetHeader.trim() === "")
2356
+ return addonOptions.toolsets;
2357
+ let toolsets = {
2358
+ dev: !1,
2359
+ docs: !1,
2360
+ test: !1
2361
+ }, enabledToolsets = toolsetHeader.split(",");
2362
+ for (let enabledToolset of enabledToolsets) {
2363
+ let trimmedToolset = enabledToolset.trim();
2364
+ trimmedToolset in toolsets && (toolsets[trimmedToolset] = !0);
2365
+ }
2366
+ return toolsets;
2367
+ }
2368
+
2369
+ // src/preset.ts
2370
+ import * as v9 from "valibot";
2371
+
2372
+ // src/template.html
2373
+ var template_default = `<!doctype html>
2374
+ <html>
2375
+ <head>
2376
+ <style>
2377
+ @font-face {
2378
+ font-family: 'Nunito Sans';
2379
+ font-style: normal;
2380
+ font-weight: 400;
2381
+ font-display: swap;
2382
+ src: url('./sb-common-assets/nunito-sans-regular.woff2') format('woff2');
2383
+ }
2384
+
2385
+ * {
2386
+ margin: 0;
2387
+ padding: 0;
2388
+ box-sizing: border-box;
2389
+ }
2390
+
2391
+ html,
2392
+ body {
2393
+ height: 100%;
2394
+ font-family:
2395
+ 'Nunito Sans',
2396
+ -apple-system,
2397
+ BlinkMacSystemFont,
2398
+ 'Segoe UI',
2399
+ Roboto,
2400
+ Oxygen,
2401
+ Ubuntu,
2402
+ Cantarell,
2403
+ sans-serif;
2404
+ }
2405
+
2406
+ body {
2407
+ display: flex;
2408
+ flex-direction: column;
2409
+ justify-content: center;
2410
+ align-items: center;
2411
+ text-align: center;
2412
+ padding: 2rem;
2413
+ background-color: #ffffff;
2414
+ color: rgb(46, 52, 56);
2415
+ line-height: 1.6;
2416
+ }
2417
+
2418
+ p {
2419
+ margin-bottom: 1rem;
2420
+ }
2421
+
2422
+ code {
2423
+ font-family: 'Monaco', 'Courier New', monospace;
2424
+ background: #f5f5f5;
2425
+ padding: 0.2em 0.4em;
2426
+ border-radius: 3px;
2427
+ }
2428
+
2429
+ a {
2430
+ color: #1ea7fd;
2431
+ }
2432
+
2433
+ .container {
2434
+ display: flex;
2435
+ flex-direction: column;
2436
+ align-items: center;
2437
+ }
2438
+
2439
+ .toolsets {
2440
+ margin: 1.5rem 0;
2441
+ text-align: left;
2442
+ max-width: 500px;
2443
+ }
2444
+
2445
+ .toolsets h3 {
2446
+ font-size: 1rem;
2447
+ margin-bottom: 0.75rem;
2448
+ text-align: center;
2449
+ }
2450
+
2451
+ .toolset {
2452
+ margin-bottom: 1rem;
2453
+ padding: 0.75rem 1rem;
2454
+ border-radius: 6px;
2455
+ background: #f8f9fa;
2456
+ border: 1px solid #e9ecef;
2457
+ }
2458
+
2459
+ .toolset-header {
2460
+ display: flex;
2461
+ align-items: center;
2462
+ gap: 0.5rem;
2463
+ font-weight: 600;
2464
+ margin-bottom: 0.5rem;
2465
+ }
2466
+
2467
+ .toolset-status {
2468
+ display: inline-block;
2469
+ padding: 0.15em 0.5em;
2470
+ border-radius: 3px;
2471
+ font-size: 0.75rem;
2472
+ font-weight: 500;
2473
+ text-transform: uppercase;
2474
+ }
2475
+
2476
+ .toolset-status.enabled {
2477
+ background: #d4edda;
2478
+ color: #155724;
2479
+ }
2480
+
2481
+ .toolset-status.disabled {
2482
+ background: #f8d7da;
2483
+ color: #721c24;
2484
+ }
2485
+
2486
+ .toolset-tools {
2487
+ font-size: 0.875rem;
2488
+ color: #6c757d;
2489
+ padding-left: 1.5rem;
2490
+ margin: 0;
2491
+ }
2492
+
2493
+ .toolset-tools li {
2494
+ margin-bottom: 0.25rem;
2495
+ }
2496
+
2497
+ .toolset-tools code {
2498
+ font-size: 0.8rem;
2499
+ }
2500
+
2501
+ .toolset-notice {
2502
+ font-size: 0.8rem;
2503
+ color: #856404;
2504
+ background: #fff3cd;
2505
+ padding: 0.5rem;
2506
+ border-radius: 4px;
2507
+ margin-top: 0.5rem;
2508
+ }
2509
+
2510
+ .toolset-notice a {
2511
+ color: #533f03;
2512
+ }
2513
+
2514
+ @media (prefers-color-scheme: dark) {
2515
+ body {
2516
+ background-color: rgb(34, 36, 37);
2517
+ color: rgb(201, 205, 207);
2518
+ }
2519
+
2520
+ code {
2521
+ background: rgba(255, 255, 255, 0.1);
2522
+ }
2523
+
2524
+ .toolset {
2525
+ background: rgba(255, 255, 255, 0.05);
2526
+ border-color: rgba(255, 255, 255, 0.1);
2527
+ }
2528
+
2529
+ .toolset-tools {
2530
+ color: #adb5bd;
2531
+ }
2532
+
2533
+ .toolset-status.enabled {
2534
+ background: rgba(40, 167, 69, 0.2);
2535
+ color: #75d67e;
2536
+ }
2537
+
2538
+ .toolset-status.disabled {
2539
+ background: rgba(220, 53, 69, 0.2);
2540
+ color: #f5a6ad;
2541
+ }
2542
+
2543
+ .toolset-notice {
2544
+ background: rgba(255, 193, 7, 0.15);
2545
+ color: #ffc107;
2546
+ }
2547
+
2548
+ .toolset-notice a {
2549
+ color: #ffe066;
2550
+ }
2551
+ }
2552
+ </style>
2553
+ </head>
2554
+ <body>
2555
+ <div class="container">
2556
+ <p>
2557
+ Storybook MCP server successfully running via
2558
+ <code>@storybook/addon-mcp</code>.
2559
+ </p>
2560
+ <p>
2561
+ See how to connect to it from your coding agent in
2562
+ <a target="_blank" href="https://github.com/storybookjs/storybook/tree/next/code/addons/mcp"
2563
+ >the addon's README</a
2564
+ >.
2565
+ </p>
2566
+
2567
+ <div class="toolsets">
2568
+ <h3>Available Toolsets</h3>
2569
+
2570
+ <div class="toolset">
2571
+ <div class="toolset-header">
2572
+ <span>dev</span>
2573
+ <span class="toolset-status {{DEV_STATUS}}">{{DEV_STATUS}}</span>
2574
+ </div>
2575
+ <ul class="toolset-tools">
2576
+ <li><code>preview-stories</code></li>
2577
+ <li><code>get-storybook-story-instructions</code></li>
2578
+ <li>
2579
+ <code>get-changed-stories</code>
2580
+ <span class="toolset-status {{CHANGE_DETECTION_STATUS}}"
2581
+ >{{CHANGE_DETECTION_STATUS}}</span
2582
+ >
2583
+ </li>
2584
+ <li>
2585
+ <code>get-stories-by-component</code>
2586
+ <span class="toolset-status {{STORIES_BY_COMPONENT_STATUS}}"
2587
+ >{{STORIES_BY_COMPONENT_STATUS}}</span
2588
+ >
2589
+ </li>
2590
+ <li>
2591
+ <code>display-review</code>
2592
+ <span class="toolset-status {{REVIEW_STATUS}}">{{REVIEW_STATUS}}</span>
2593
+ </li>
2594
+ </ul>
2595
+ {{DEV_NOTICE}}
2596
+ </div>
2597
+
2598
+ <div class="toolset">
2599
+ <div class="toolset-header">
2600
+ <span>docs</span>
2601
+ <span class="toolset-status {{DOCS_STATUS}}">{{DOCS_STATUS}}</span>
2602
+ </div>
2603
+ <ul class="toolset-tools">
2604
+ <li><code>list-all-documentation</code></li>
2605
+ <li><code>get-documentation</code></li>
2606
+ <li><code>get-documentation-for-story</code></li>
2607
+ </ul>
2608
+ {{DOCS_NOTICE}}
2609
+ </div>
2610
+
2611
+ <div class="toolset">
2612
+ <div class="toolset-header">
2613
+ <span>test</span>
2614
+ <span class="toolset-status {{TEST_STATUS}}">{{TEST_STATUS}}</span>
2615
+ </div>
2616
+ <ul class="toolset-tools">
2617
+ <li><code>run-story-tests</code>{{A11Y_BADGE}}</li>
2618
+ </ul>
2619
+ {{TEST_NOTICE}}
2620
+ </div>
2621
+ </div>
2622
+
2623
+ {{MANIFEST_DEBUGGER_LINK}}
2624
+ </div>
2625
+ </body>
2626
+ </html>
2627
+ `;
2628
+
2629
+ // src/preset.ts
2630
+ import path4 from "node:path";
2631
+
2632
+ // src/auth/composition-auth.ts
2633
+ import { ComponentManifestMap, DocsManifestMap } from "@storybook/mcp";
2634
+ import { logger as logger7 } from "storybook/internal/node-logger";
2635
+ import * as v6 from "valibot";
2636
+ var OAuthResourceMetadata = v6.object({
2637
+ resource: v6.optional(v6.string()),
2638
+ authorization_servers: v6.pipe(v6.array(v6.string()), v6.minLength(1)),
2639
+ scopes_supported: v6.optional(v6.array(v6.string()))
2640
+ }), OAuthServerMetadata = v6.object({
2641
+ issuer: v6.string(),
2642
+ authorization_endpoint: v6.string(),
2643
+ token_endpoint: v6.string(),
2644
+ scopes_supported: v6.optional(v6.array(v6.string()))
2645
+ }), MANIFEST_CACHE_TTL = 3600 * 1e3, REVALIDATION_TTL = 60 * 1e3, AuthenticationError = class extends Error {
2646
+ constructor(url2) {
2647
+ super(`Authentication failed for ${url2}. Your token may be invalid or expired.`), this.name = "AuthenticationError";
2648
+ }
2649
+ }, CompositionAuth = class {
2650
+ #authRequirement = null;
2651
+ #authRequiredUrls = [];
2652
+ #refsWithManifests = [];
2653
+ #manifestCache = /* @__PURE__ */ new Map();
2654
+ #lastToken = null;
2655
+ #authErrors = /* @__PURE__ */ new WeakMap();
2656
+ /** Initialize by checking which refs require authentication and have manifests. */
2657
+ async initialize(refs) {
2658
+ for (let ref of refs)
2659
+ try {
2660
+ let result = await this.#checkRef(ref.url);
2661
+ if (result === "no-manifest" || (this.#refsWithManifests.push(ref), result === "public")) continue;
2662
+ if (this.#authRequiredUrls.push(ref.url), !this.#authRequirement)
2663
+ this.#authRequirement = result;
2664
+ else {
2665
+ let existingServer = this.#authRequirement.resourceMetadata.authorization_servers[0], newServer = result.resourceMetadata.authorization_servers[0];
2666
+ existingServer !== newServer && logger7.warn(
2667
+ `[addon-mcp] Composed ref "${ref.title}" uses a different OAuth server (${newServer}) than the first authenticated ref (${existingServer}). Only the first OAuth server will be used for authentication.`
2668
+ );
2669
+ }
2670
+ } catch (error) {
2671
+ logger7.warn(
2672
+ `[addon-mcp] Failed to check auth for composed ref "${ref.title}" (${ref.url}): ${error instanceof Error ? error.message : String(error)}. Skipping this ref.`
2673
+ );
2674
+ }
2675
+ }
2676
+ get requiresAuth() {
2677
+ return this.#authRequiredUrls.length > 0;
2678
+ }
2679
+ get authUrls() {
2680
+ return this.#authRequiredUrls;
2681
+ }
2682
+ /** Check if a request encountered an auth error during manifest fetching. */
2683
+ hadAuthError(request) {
2684
+ return this.#authErrors.has(request);
2685
+ }
2686
+ /** Check if a URL requires authentication based on discovered auth requirements. */
2687
+ #isAuthRequiredUrl(url2) {
2688
+ return this.#authRequiredUrls.some((authUrl) => url2.startsWith(authUrl));
2689
+ }
2690
+ /** Build .well-known/oauth-protected-resource response. */
2691
+ buildWellKnown(origin2) {
2692
+ return this.#authRequirement ? {
2693
+ resource: `${origin2}/mcp`,
2694
+ authorization_servers: this.#authRequirement.resourceMetadata.authorization_servers,
2695
+ scopes_supported: this.#authRequirement.resourceMetadata.scopes_supported
2696
+ } : null;
2697
+ }
2698
+ /** Build WWW-Authenticate header for 401 responses */
2699
+ buildWwwAuthenticate(origin2) {
2700
+ return `Bearer error="unauthorized", error_description="Authorization needed for composed Storybooks", resource_metadata="${origin2}/.well-known/oauth-protected-resource"`;
2701
+ }
2702
+ /** Build sources configuration: local first, then refs that have manifests. */
2703
+ buildSources() {
2704
+ return [
2705
+ { id: "local", title: "Local" },
2706
+ ...this.#refsWithManifests.map((ref) => ({
2707
+ id: ref.id,
2708
+ title: ref.title,
2709
+ url: ref.url
2710
+ }))
2711
+ ];
2712
+ }
2713
+ /**
2714
+ * Create a manifest provider for multi-source mode.
2715
+ *
2716
+ * Remote sources are always fetched over HTTP (with auth + caching). The local
2717
+ * source normally fetches from `localOrigin`, but in `experimentalDocgenServer`
2718
+ * mode core 404s `/manifests/*.json` (the data lives in the open services), so
2719
+ * callers pass `localManifestProvider` to read the local source in-process
2720
+ * instead. When omitted, the local source keeps its HTTP behavior.
2721
+ */
2722
+ createManifestProvider(localOrigin, localManifestProvider) {
2723
+ return async (request, path5, source) => {
2724
+ let token = extractBearerToken(request?.headers.get("Authorization")), remoteSource = source?.url ? { ...source, url: source.url } : void 0;
2725
+ if (!remoteSource && localManifestProvider)
2726
+ return localManifestProvider(request, path5, source);
2727
+ let baseUrl = remoteSource?.url ?? localOrigin, manifestUrl = `${baseUrl}${path5.replace("./", "/")}`, isRemote = !!remoteSource, tokenForRequest = isRemote && this.#isAuthRequiredUrl(baseUrl) ? token : null;
2728
+ if (token && token !== this.#lastToken && (this.#manifestCache.clear(), this.#lastToken = token), isRemote) {
2729
+ let cached = this.#manifestCache.get(manifestUrl);
2730
+ if (cached)
2731
+ if (Date.now() - cached.timestamp > MANIFEST_CACHE_TTL)
2732
+ this.#manifestCache.delete(manifestUrl);
2733
+ else
2734
+ return (!cached.lastRevalidatedAt || Date.now() - cached.lastRevalidatedAt > REVALIDATION_TTL) && (cached.lastRevalidatedAt = Date.now(), this.#fetchManifest(manifestUrl, tokenForRequest).then(
2735
+ (text) => this.#manifestCache.set(manifestUrl, {
2736
+ text,
2737
+ timestamp: Date.now(),
2738
+ lastRevalidatedAt: Date.now()
2739
+ })
2740
+ ).catch(() => {
2741
+ })), cached.text;
2742
+ }
2743
+ try {
2744
+ let text = await this.#fetchManifest(manifestUrl, tokenForRequest);
2745
+ return isRemote && this.#manifestCache.set(manifestUrl, { text, timestamp: Date.now() }), text;
2746
+ } catch (error) {
2747
+ throw error instanceof AuthenticationError && request && this.#authErrors.set(request, error), error;
2748
+ }
2749
+ };
2750
+ }
2751
+ /**
2752
+ * Fetch a manifest with optional auth token.
2753
+ * If the response is 200 but not a valid manifest, checks /mcp for auth issues.
2754
+ */
2755
+ async #fetchManifest(url2, token) {
2756
+ let headers = { Accept: "application/json" };
2757
+ token && (headers.Authorization = `Bearer ${token}`);
2758
+ let response = await fetch(url2, { headers });
2759
+ if (response.status === 401)
2760
+ throw new AuthenticationError(url2);
2761
+ if (!response.ok)
2762
+ throw new Error(`Failed to fetch ${url2}: ${response.status}`);
2763
+ let text = await response.text(), { pathname } = new URL(url2), isComponentsManifest = pathname.endsWith("/manifests/components.json"), isDocsManifest = pathname.endsWith("/manifests/docs.json"), schema = isComponentsManifest ? ComponentManifestMap : isDocsManifest ? DocsManifestMap : v6.unknown();
2764
+ if (v6.safeParse(v6.pipe(v6.string(), v6.parseJson(), schema), text).success)
2765
+ return text;
2766
+ throw await this.#isMcpUnauthorized(new URL(url2).origin) ? new AuthenticationError(url2) : new Error(
2767
+ `Invalid manifest response from ${url2}: expected valid JSON manifest but got unexpected content.`
2768
+ );
2769
+ }
2770
+ /**
2771
+ * Check a ref to determine if it has a manifest and whether it requires auth.
2772
+ * Returns 'public' if the ref has a valid manifest without auth,
2773
+ * 'no-manifest' if no manifest is available, or an AuthRequirement if auth is needed.
2774
+ */
2775
+ async #checkRef(refUrl) {
2776
+ let response = await fetch(`${refUrl}/manifests/components.json`, {
2777
+ headers: { Accept: "application/json" }
2778
+ }), authReq = await this.#parseAuthFromResponse(response);
2779
+ if (authReq) return authReq;
2780
+ if (response.ok) {
2781
+ let text = await response.text();
2782
+ if (v6.safeParse(v6.pipe(v6.string(), v6.parseJson(), ComponentManifestMap), text).success)
2783
+ return "public";
2784
+ }
2785
+ let mcpAuth = await this.#checkMcpAuth(refUrl);
2786
+ return mcpAuth || "no-manifest";
2787
+ }
2788
+ /** Check /mcp endpoint for 401 auth requirement. */
2789
+ async #checkMcpAuth(refUrl) {
2790
+ let response = await fetch(`${refUrl}/mcp`, {
2791
+ method: "POST",
2792
+ headers: { "Content-Type": "application/json" },
2793
+ body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/list" })
2794
+ });
2795
+ return this.#parseAuthFromResponse(response);
2796
+ }
2797
+ /** Quick check: does the remote /mcp return 401? */
2798
+ async #isMcpUnauthorized(origin2) {
2799
+ try {
2800
+ return (await fetch(`${origin2}/mcp`, {
2801
+ method: "POST",
2802
+ headers: { "Content-Type": "application/json" },
2803
+ body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/list" })
2804
+ })).status === 401;
2805
+ } catch {
2806
+ return !1;
2807
+ }
2808
+ }
2809
+ /** Extract auth requirement from a 401 response's WWW-Authenticate header. */
2810
+ async #parseAuthFromResponse(response) {
2811
+ if (response.status !== 401) return null;
2812
+ let wwwAuth = response.headers.get("WWW-Authenticate");
2813
+ if (!wwwAuth) return null;
2814
+ let match = wwwAuth.match(/resource_metadata="([^"]+)"/);
2815
+ if (!match?.[1]) return null;
2816
+ let resourceMetadataUrl = match[1], resourceResponse = await fetch(resourceMetadataUrl);
2817
+ if (!resourceResponse.ok)
2818
+ return logger7.warn(
2819
+ `[addon-mcp] Failed to fetch OAuth resource metadata from ${resourceMetadataUrl}: ${resourceResponse.status}`
2820
+ ), null;
2821
+ let resourceResult = v6.safeParse(OAuthResourceMetadata, await resourceResponse.json());
2822
+ if (!resourceResult.success)
2823
+ return logger7.warn(
2824
+ `[addon-mcp] Invalid OAuth resource metadata from ${resourceMetadataUrl}: ${resourceResult.issues.map((i) => i.message).join(", ")}`
2825
+ ), null;
2826
+ let serverMetadataUrl = `${resourceResult.output.authorization_servers[0]}/.well-known/oauth-authorization-server`, serverResponse = await fetch(serverMetadataUrl);
2827
+ if (!serverResponse.ok)
2828
+ return logger7.warn(
2829
+ `[addon-mcp] Failed to fetch OAuth server metadata from ${serverMetadataUrl}: ${serverResponse.status}`
2830
+ ), null;
2831
+ let serverResult = v6.safeParse(OAuthServerMetadata, await serverResponse.json());
2832
+ return serverResult.success ? {
2833
+ resourceMetadataUrl,
2834
+ resourceMetadata: resourceResult.output,
2835
+ serverMetadata: serverResult.output
2836
+ } : (logger7.warn(
2837
+ `[addon-mcp] Invalid OAuth server metadata from ${serverMetadataUrl}: ${serverResult.issues.map((i) => i.message).join(", ")}`
2838
+ ), null);
2839
+ }
1242
2840
  };
1243
- /**
1244
- * Extract Bearer token from Authorization header.
1245
- * Handles both Node.js (string | string[] | undefined) and Web API (string | null) headers.
1246
- */
1247
2841
  function extractBearerToken(authHeader) {
1248
- const bearer = (Array.isArray(authHeader) ? authHeader : [authHeader]).find((value) => typeof value === "string" && value.startsWith("Bearer "));
1249
- return bearer ? bearer.slice(7) : null;
2842
+ let bearer = (Array.isArray(authHeader) ? authHeader : [authHeader]).find((value) => typeof value == "string" && value.startsWith("Bearer "));
2843
+ return bearer ? bearer.slice(7) : null;
1250
2844
  }
1251
2845
 
1252
- //#endregion
1253
- //#region src/preset.ts
1254
- const previewAnnotations = async (existingAnnotations = []) => {
1255
- return [...existingAnnotations, path.join(import.meta.dirname, "preview.js")];
1256
- };
1257
- const experimental_devServer = async (app, options) => {
1258
- const addonOptions = v.parse(AddonOptions, { toolsets: "toolsets" in options ? options.toolsets : {} });
1259
- const origin = `http://localhost:${options.port}`;
1260
- const refs = await getRefsFromConfig(options);
1261
- const compositionAuth = new CompositionAuth();
1262
- let sources;
1263
- let manifestProvider;
1264
- if (refs.length > 0) {
1265
- logger.info(`Initializing composition with ${refs.length} remote Storybook(s)`);
1266
- await compositionAuth.initialize(refs);
1267
- if (compositionAuth.requiresAuth) logger.info(`Auth required for: ${compositionAuth.authUrls.join(", ")}`);
1268
- sources = compositionAuth.buildSources();
1269
- logger.info(`Sources: ${sources.map((s) => s.id).join(", ")}`);
1270
- manifestProvider = compositionAuth.createManifestProvider(origin);
1271
- }
1272
- app.get("/.well-known/oauth-protected-resource", (_req, res) => {
1273
- const wellKnown = compositionAuth.buildWellKnown(origin);
1274
- if (!wellKnown) {
1275
- res.writeHead(404);
1276
- res.end("Not found");
1277
- return;
1278
- }
1279
- res.writeHead(200, { "Content-Type": "application/json" });
1280
- res.end(JSON.stringify(wellKnown));
1281
- });
1282
- const requireAuth = (req, res) => {
1283
- const token = extractBearerToken(req.headers["authorization"]);
1284
- if (compositionAuth.requiresAuth && !token) {
1285
- res.writeHead(401, {
1286
- "Content-Type": "text/plain",
1287
- "WWW-Authenticate": compositionAuth.buildWwwAuthenticate(origin)
1288
- });
1289
- res.end("401 - Unauthorized");
1290
- return true;
1291
- }
1292
- return false;
1293
- };
1294
- app.post("/mcp", (req, res) => {
1295
- if (requireAuth(req, res)) return;
1296
- return mcpServerHandler({
1297
- req,
1298
- res,
1299
- options,
1300
- addonOptions,
1301
- sources,
1302
- manifestProvider,
1303
- compositionAuth
1304
- });
1305
- });
1306
- const manifestStatus = await getManifestStatus(options);
1307
- const addonVitestConstants = await getAddonVitestConstants();
1308
- const a11yEnabled = await isAddonA11yEnabled(options);
1309
- const isDevEnabled = addonOptions.toolsets?.dev ?? true;
1310
- const isDocsEnabled = manifestStatus.available && (addonOptions.toolsets?.docs ?? true);
1311
- const isTestEnabled = !!addonVitestConstants && (addonOptions.toolsets?.test ?? true);
1312
- app.get("/mcp", (req, res) => {
1313
- if (!req.headers["accept"]?.includes("text/html")) {
1314
- if (requireAuth(req, res)) return;
1315
- return mcpServerHandler({
1316
- req,
1317
- res,
1318
- options,
1319
- addonOptions,
1320
- sources,
1321
- manifestProvider,
1322
- compositionAuth
1323
- });
1324
- }
1325
- res.writeHead(200, { "Content-Type": "text/html" });
1326
- let docsNotice = "";
1327
- if (!manifestStatus.hasManifests) docsNotice = `<div class="toolset-notice">
1328
- This toolset is only supported in React-based setups.
1329
- </div>`;
1330
- else if (!manifestStatus.hasFeatureFlag) docsNotice = `<div class="toolset-notice">
2846
+ // src/auth/resolve-composition-sources.ts
2847
+ import { ComponentManifestMap as ComponentManifestMap2 } from "@storybook/mcp";
2848
+ import * as v7 from "valibot";
2849
+
2850
+ // src/auth/get-refs-from-config.ts
2851
+ async function getRefsFromConfig(options) {
2852
+ try {
2853
+ let refs = await options.presets.apply("refs", {});
2854
+ return !refs || typeof refs != "object" ? [] : Object.entries(refs).flatMap(([key, value]) => {
2855
+ if (!value || typeof value != "object")
2856
+ return [];
2857
+ let { title, url: url2 } = value;
2858
+ return typeof url2 != "string" || url2.length === 0 ? [] : [
2859
+ {
2860
+ id: key,
2861
+ title: typeof title == "string" && title.length > 0 ? title : key,
2862
+ url: url2
2863
+ }
2864
+ ];
2865
+ });
2866
+ } catch {
2867
+ return [];
2868
+ }
2869
+ }
2870
+
2871
+ // src/auth/resolve-composition-sources.ts
2872
+ var MANIFEST_PROBE_TIMEOUT_MS = 3e3;
2873
+ async function resolveCompositionSources(options) {
2874
+ let refs = await getRefsFromConfig(options), compositionAuth = new CompositionAuth();
2875
+ if (refs.length === 0)
2876
+ return { refs, compositionAuth, sources: void 0, multiSource: !1 };
2877
+ await compositionAuth.initialize(refs);
2878
+ let sources = compositionAuth.buildSources();
2879
+ return {
2880
+ refs,
2881
+ compositionAuth,
2882
+ sources,
2883
+ multiSource: sources.some((source) => !!source.url)
2884
+ };
2885
+ }
2886
+ async function resolveServerlessCompositionSources(options) {
2887
+ let refs = await getRefsFromConfig(options), refsWithManifests = await Promise.all(
2888
+ refs.map(
2889
+ async (ref) => await hasServerlessComponentManifestSource(ref.url) ? ref : void 0
2890
+ )
2891
+ ), sources = [
2892
+ { id: "local", title: "Local" },
2893
+ ...refsWithManifests.filter((ref) => !!ref).map((ref) => ({
2894
+ id: ref.id,
2895
+ title: ref.title,
2896
+ url: ref.url
2897
+ }))
2898
+ ];
2899
+ return {
2900
+ refs,
2901
+ sources,
2902
+ multiSource: sources.some((source) => !!source.url)
2903
+ };
2904
+ }
2905
+ async function hasServerlessComponentManifestSource(refUrl) {
2906
+ let controller = new AbortController(), timeout = setTimeout(() => controller.abort(), MANIFEST_PROBE_TIMEOUT_MS);
2907
+ try {
2908
+ let response = await fetch(
2909
+ new URL("manifests/components.json", `${refUrl.replace(/\/$/, "")}/`),
2910
+ {
2911
+ headers: { Accept: "application/json" },
2912
+ signal: controller.signal
2913
+ }
2914
+ );
2915
+ if (response.status === 401 && hasOAuthResourceMetadataChallenge(response))
2916
+ return !0;
2917
+ if (!response.ok)
2918
+ return !1;
2919
+ let text = await response.text();
2920
+ return v7.safeParse(v7.pipe(v7.string(), v7.parseJson(), ComponentManifestMap2), text).success;
2921
+ } catch {
2922
+ return !1;
2923
+ } finally {
2924
+ clearTimeout(timeout);
2925
+ }
2926
+ }
2927
+ function hasOAuthResourceMetadataChallenge(response) {
2928
+ return /resource_metadata="[^"]+"/.test(response.headers.get("WWW-Authenticate") ?? "");
2929
+ }
2930
+
2931
+ // src/preset.ts
2932
+ import { logger as logger8 } from "storybook/internal/node-logger";
2933
+
2934
+ // src/storybook-ai-metadata.ts
2935
+ import { ValibotJsonSchemaAdapter as ValibotJsonSchemaAdapter2 } from "@tmcp/adapter-valibot";
2936
+ import * as v8 from "valibot";
2937
+ var createEmptyInputSchema = () => ({ type: "object", properties: {} });
2938
+ async function buildStorybookAiMetadata(options, existingMetadata) {
2939
+ let toolsets = v8.parse(AddonOptions, {
2940
+ endpoint: options.endpoint,
2941
+ toolsets: options.toolsets ?? {}
2942
+ }).toolsets, features2 = await options.presets.apply("features", {}), devEnabled = toolsets?.dev ?? !0, moduleGraphSupported = await isModuleGraphSupportedByBuilder(options), rawAvailability = await getToolAvailability(options, {
2943
+ features: features2,
2944
+ moduleGraphSupported
2945
+ }), availability = {
2946
+ ...rawAvailability,
2947
+ reviewEnabled: rawAvailability.reviewEnabledForCli
2948
+ }, testEnabled = (toolsets?.test ?? !0) && availability.testSupported, docsToolsetEnabled = toolsets?.docs ?? !0, multiSource = docsToolsetEnabled ? (await resolveServerlessCompositionSources(options)).multiSource : !1, registryAvailability = getEffectiveToolAvailability(availability, { multiSource }), docsEnabled = docsToolsetEnabled && registryAvailability.docsEnabled, registryContext = { availability: registryAvailability, multiSource, toolsets }, toolMetadata = getAddonToolMetadata(registryContext), localTools = {
2949
+ ...existingMetadata?.localTools,
2950
+ ...getAddonLocalTools({ ...registryContext, options })
2951
+ };
2952
+ return {
2953
+ instructions: joinInstructions(
2954
+ existingMetadata?.instructions,
2955
+ buildServerInstructions({
2956
+ devEnabled,
2957
+ testEnabled,
2958
+ docsEnabled,
2959
+ changeDetectionEnabled: availability.changeDetectionEnabled,
2960
+ moduleGraphSupported: availability.moduleGraphSupported,
2961
+ reviewEnabled: availability.reviewEnabled
2962
+ })
2963
+ ),
2964
+ tools: mergeToolDescriptors(
2965
+ existingMetadata?.tools ?? [],
2966
+ await toToolDescriptors(toolMetadata)
2967
+ ),
2968
+ localTools
2969
+ };
2970
+ }
2971
+ async function toToolDescriptors(toolMetadata) {
2972
+ let adapter = new ValibotJsonSchemaAdapter2();
2973
+ return Promise.all(
2974
+ toolMetadata.map(async ({ schema, outputSchema, ...metadata }) => ({
2975
+ ...metadata,
2976
+ inputSchema: schema ? await toJsonSchema(adapter, schema) : createEmptyInputSchema(),
2977
+ ...outputSchema ? { outputSchema: await toJsonSchema(adapter, outputSchema) } : {}
2978
+ }))
2979
+ );
2980
+ }
2981
+ async function toJsonSchema(adapter, schema) {
2982
+ return await adapter.toJsonSchema(
2983
+ schema
2984
+ );
2985
+ }
2986
+ function joinInstructions(...sections) {
2987
+ let uniqueSections = [], seen = /* @__PURE__ */ new Set();
2988
+ for (let section of sections) {
2989
+ let trimmed = section?.trim();
2990
+ trimmed && !seen.has(trimmed) && (seen.add(trimmed), uniqueSections.push(trimmed));
2991
+ }
2992
+ return uniqueSections.join(`
2993
+
2994
+ `);
2995
+ }
2996
+ function mergeToolDescriptors(...groups) {
2997
+ let toolsByName = /* @__PURE__ */ new Map();
2998
+ for (let tool of groups.flat())
2999
+ toolsByName.has(tool.name) && toolsByName.delete(tool.name), toolsByName.set(tool.name, tool);
3000
+ return [...toolsByName.values()];
3001
+ }
3002
+
3003
+ // src/manifests/in-process-provider.ts
3004
+ import {
3005
+ adaptCoreComponent,
3006
+ adaptCoreDoc
3007
+ } from "@storybook/mcp";
3008
+
3009
+ // src/manifests/vendored.ts
3010
+ var Tag = {
3011
+ ATTACHED_MDX: "attached-mdx",
3012
+ UNATTACHED_MDX: "unattached-mdx",
3013
+ MANIFEST: "manifest"
3014
+ }, DOCGEN_SERVICE_ID = "core/docgen", STORY_DOCS_SERVICE_ID = "core/story-docs", MDX_SERVICE_ID = "addon-docs/mdx";
3015
+ function getComponentIdFromEntry(entry) {
3016
+ return entry.id.split("--")[0] ?? entry.id;
3017
+ }
3018
+ function isAttachedDocsEntry(entry) {
3019
+ return entry.type === "docs" && entry.tags?.includes(Tag.ATTACHED_MDX) === !0 && entry.storiesImports.length > 0;
3020
+ }
3021
+ function isEligibleStoryEntry(entry) {
3022
+ return entry.type === "story" && entry.subtype === "story";
3023
+ }
3024
+ function selectComponentEntriesByComponentId(indexEntries) {
3025
+ let entriesByComponentId = /* @__PURE__ */ new Map();
3026
+ for (let entry of indexEntries)
3027
+ isEligibleStoryEntry(entry) && entriesByComponentId.set(getComponentIdFromEntry(entry), entry);
3028
+ for (let entry of indexEntries) {
3029
+ if (!isAttachedDocsEntry(entry))
3030
+ continue;
3031
+ let componentId = getComponentIdFromEntry(entry);
3032
+ entriesByComponentId.has(componentId) || entriesByComponentId.set(componentId, entry);
3033
+ }
3034
+ return entriesByComponentId;
3035
+ }
3036
+ function storyDocsManifestRef(id) {
3037
+ return `../services/${STORY_DOCS_SERVICE_ID}/${id}.json#/components/${id}`;
3038
+ }
3039
+
3040
+ // src/manifests/service-access.ts
3041
+ var cachedGetService;
3042
+ async function loadGetService() {
3043
+ if (cachedGetService !== void 0)
3044
+ return cachedGetService ?? void 0;
3045
+ try {
3046
+ let getService = (await import("storybook/internal/core-server")).getService;
3047
+ return cachedGetService = getService ?? null, getService;
3048
+ } catch {
3049
+ cachedGetService = null;
3050
+ return;
3051
+ }
3052
+ }
3053
+ async function getServiceSafely(id) {
3054
+ let getService = await loadGetService();
3055
+ if (getService)
3056
+ try {
3057
+ return getService(id, { internal: !0 });
3058
+ } catch {
3059
+ return;
3060
+ }
3061
+ }
3062
+ function getDocgenService() {
3063
+ return getServiceSafely(DOCGEN_SERVICE_ID);
3064
+ }
3065
+ function getStoryDocsService() {
3066
+ return getServiceSafely(STORY_DOCS_SERVICE_ID);
3067
+ }
3068
+ function getMdxService() {
3069
+ return getServiceSafely(MDX_SERVICE_ID);
3070
+ }
3071
+
3072
+ // src/manifests/in-process-provider.ts
3073
+ function classifyIndex(index) {
3074
+ let entries = Object.values(index.entries).filter(
3075
+ (entry) => entry.tags?.includes(Tag.MANIFEST) ?? !1
3076
+ ), selected = selectComponentEntriesByComponentId(entries), storyBasedIds = /* @__PURE__ */ new Set();
3077
+ for (let [id, entry] of selected)
3078
+ entry.type === "story" && storyBasedIds.add(id);
3079
+ let attachedDocsByComponent = /* @__PURE__ */ new Map(), unattachedDocs = /* @__PURE__ */ new Map();
3080
+ for (let entry of entries)
3081
+ if (entry.type === "docs") {
3082
+ if (entry.tags?.includes(Tag.UNATTACHED_MDX))
3083
+ unattachedDocs.set(entry.id, entry);
3084
+ else if (entry.tags?.includes(Tag.ATTACHED_MDX)) {
3085
+ let componentId = getComponentIdFromEntry(entry), list = attachedDocsByComponent.get(componentId) ?? [];
3086
+ list.push(entry), attachedDocsByComponent.set(componentId, list);
3087
+ }
3088
+ }
3089
+ return {
3090
+ componentIds: [...selected.keys()],
3091
+ storyBasedIds,
3092
+ attachedDocsByComponent,
3093
+ unattachedDocs
3094
+ };
3095
+ }
3096
+ async function buildComponentsManifest(cls) {
3097
+ let docgenService = await getDocgenService(), allDocgen = docgenService ? await docgenService.queries.docgenForAllComponents.loaded() : {}, components = {};
3098
+ for (let id of cls.componentIds) {
3099
+ let payload = allDocgen[id];
3100
+ components[id] = {
3101
+ id,
3102
+ name: payload?.name ?? id,
3103
+ ...payload?.description !== void 0 ? { description: payload.description } : {},
3104
+ ...payload?.summary !== void 0 ? { summary: payload.summary } : {},
3105
+ ...cls.storyBasedIds.has(id) ? { stories: { $ref: storyDocsManifestRef(id) } } : {}
3106
+ };
3107
+ }
3108
+ return JSON.stringify({ v: 1, components });
3109
+ }
3110
+ async function buildDocsManifest(cls) {
3111
+ if (cls.unattachedDocs.size === 0)
3112
+ return;
3113
+ let mdxService = await getMdxService(), allMdx = mdxService ? await mdxService.queries.mdxForAllComponents.loaded() : {}, docs = {};
3114
+ for (let [docId, entry] of cls.unattachedDocs) {
3115
+ let payload = allMdx[docId]?.docs?.[docId];
3116
+ docs[docId] = {
3117
+ id: docId,
3118
+ name: entry.name,
3119
+ ...payload?.summary !== void 0 ? { summary: payload.summary } : {}
3120
+ };
3121
+ }
3122
+ return JSON.stringify({ v: 1, docs });
3123
+ }
3124
+ var STORY_DOCS_SERVICE_PREFIX = `services/${STORY_DOCS_SERVICE_ID}/`;
3125
+ function matchStoryDocsServicePath(normalizedPath) {
3126
+ if (normalizedPath.startsWith(STORY_DOCS_SERVICE_PREFIX) && normalizedPath.endsWith(".json"))
3127
+ return normalizedPath.slice(STORY_DOCS_SERVICE_PREFIX.length, -5);
3128
+ }
3129
+ async function buildStoryDocsServiceFile(id) {
3130
+ let storyDocsService = await getStoryDocsService(), payload = storyDocsService ? await storyDocsService.queries.storyDocs.loaded({ id }) : void 0;
3131
+ return JSON.stringify({ components: payload === void 0 ? {} : { [id]: payload } });
3132
+ }
3133
+ async function resolveComponent(id, cls) {
3134
+ let [docgenService, storyDocsService, mdxService] = await Promise.all([
3135
+ getDocgenService(),
3136
+ getStoryDocsService(),
3137
+ getMdxService()
3138
+ ]), [docgen, storyDocs] = await Promise.all([
3139
+ docgenService ? docgenService.queries.docgen.loaded({ id }) : void 0,
3140
+ storyDocsService ? storyDocsService.queries.storyDocs.loaded({ id }) : void 0
3141
+ ]), attached = cls.attachedDocsByComponent.get(id) ?? [], docs;
3142
+ if (attached.length > 0 && mdxService) {
3143
+ let mdxPayload = await mdxService.queries.mdxForComponent.loaded({ id });
3144
+ if (mdxPayload?.docs) {
3145
+ docs = {};
3146
+ for (let entry of attached) {
3147
+ let doc = mdxPayload.docs[entry.id];
3148
+ doc && (docs[entry.id] = doc);
3149
+ }
3150
+ }
3151
+ }
3152
+ let core = {
3153
+ ...docgen,
3154
+ id,
3155
+ name: docgen?.name ?? id,
3156
+ ...storyDocs?.stories ? { stories: storyDocs.stories } : {},
3157
+ ...storyDocs?.import ? { import: storyDocs.import } : {},
3158
+ ...docs ? { docs } : {}
3159
+ };
3160
+ return { kind: "component", component: adaptCoreComponent(core) };
3161
+ }
3162
+ async function resolveStandaloneDoc(id) {
3163
+ let mdxService = await getMdxService(), doc = (mdxService ? await mdxService.queries.mdxForComponent.loaded({ id }) : void 0)?.docs?.[id];
3164
+ if (doc)
3165
+ return { kind: "doc", doc: adaptCoreDoc(doc) };
3166
+ }
3167
+ function createDocgenServerManifestAccess(options) {
3168
+ return { manifestProvider: async (_request, path5) => {
3169
+ let normalized = path5.replace(/^\.?\//, "");
3170
+ if (normalized === "manifests/components.json") {
3171
+ let cls = classifyIndex(await getStoryIndex(options));
3172
+ return buildComponentsManifest(cls);
3173
+ }
3174
+ if (normalized === "manifests/docs.json") {
3175
+ let cls = classifyIndex(await getStoryIndex(options)), docs = await buildDocsManifest(cls);
3176
+ if (docs === void 0)
3177
+ throw new Error("No unattached docs manifest available");
3178
+ return docs;
3179
+ }
3180
+ let storyDocsId = matchStoryDocsServicePath(normalized);
3181
+ if (storyDocsId)
3182
+ return buildStoryDocsServiceFile(storyDocsId);
3183
+ throw new Error(`Unsupported in-process manifest path: ${path5}`);
3184
+ }, resolveEntry: async (id) => {
3185
+ let cls = classifyIndex(await getStoryIndex(options));
3186
+ if (cls.unattachedDocs.has(id))
3187
+ return resolveStandaloneDoc(id);
3188
+ if (cls.componentIds.includes(id))
3189
+ return resolveComponent(id, cls);
3190
+ } };
3191
+ }
3192
+
3193
+ // src/preset.ts
3194
+ var previewAnnotations = async (existingAnnotations = []) => [...existingAnnotations, path4.join(import.meta.dirname, "preview.js")], experimental_devServer = async (app, options) => {
3195
+ let addonOptions = v9.parse(AddonOptions, {
3196
+ endpoint: options.endpoint,
3197
+ toolsets: options.toolsets ?? {}
3198
+ }), origin2 = `http://localhost:${options.port}`, endpoint = addonOptions.endpoint ?? DEFAULT_MCP_ENDPOINT, { refs, compositionAuth, sources, multiSource } = await resolveCompositionSources(options), rawAvailability = await getToolAvailability(options), docgenServerAccess = rawAvailability.docgenServer ? createDocgenServerManifestAccess(options) : void 0, createManifestProvider;
3199
+ refs.length > 0 && (logger8.info(`Initialized composition with ${refs.length} remote Storybook(s)`), compositionAuth.requiresAuth && logger8.info(`Auth required for: ${compositionAuth.authUrls.join(", ")}`), logger8.info(`Sources: ${(sources ?? []).map((s) => s.id).join(", ")}`), createManifestProvider = () => compositionAuth.createManifestProvider(origin2, docgenServerAccess?.manifestProvider));
3200
+ let manifestAccessFor = (req) => ({
3201
+ manifestProvider: createManifestProvider ? createManifestProvider(req) : docgenServerAccess?.manifestProvider,
3202
+ resolveEntry: docgenServerAccess?.resolveEntry
3203
+ });
3204
+ app.get("/.well-known/oauth-protected-resource", (_req, res) => {
3205
+ let wellKnown = compositionAuth.buildWellKnown(origin2);
3206
+ if (!wellKnown) {
3207
+ res.writeHead(404), res.end("Not found");
3208
+ return;
3209
+ }
3210
+ res.writeHead(200, { "Content-Type": "application/json" }), res.end(JSON.stringify(wellKnown));
3211
+ });
3212
+ let requireAuth = (req, res) => {
3213
+ let token = extractBearerToken(req.headers.authorization);
3214
+ return compositionAuth.requiresAuth && !token ? (res.writeHead(401, {
3215
+ "Content-Type": "text/plain",
3216
+ "WWW-Authenticate": compositionAuth.buildWwwAuthenticate(origin2)
3217
+ }), res.end("401 - Unauthorized"), !0) : !1;
3218
+ };
3219
+ app.post(endpoint, (req, res) => {
3220
+ if (!requireAuth(req, res))
3221
+ return mcpServerHandler({
3222
+ req,
3223
+ res,
3224
+ options,
3225
+ addonOptions,
3226
+ endpoint,
3227
+ sources,
3228
+ ...manifestAccessFor(req),
3229
+ compositionAuth
3230
+ });
3231
+ });
3232
+ let {
3233
+ moduleGraphSupported,
3234
+ changeDetectionEnabled,
3235
+ reviewEnabled,
3236
+ reviewEnabledForCli,
3237
+ docsEnabled,
3238
+ docsHasManifests,
3239
+ docsFeatureEnabled,
3240
+ testSupported,
3241
+ a11yEnabled: a11yEnabled2
3242
+ } = getEffectiveToolAvailability(rawAvailability, { multiSource }), isDevEnabled = addonOptions.toolsets?.dev ?? !0, isDocsEnabled = docsEnabled && (addonOptions.toolsets?.docs ?? !0), isTestEnabled = testSupported && (addonOptions.toolsets?.test ?? !0);
3243
+ return app.get(endpoint, (req, res) => {
3244
+ if (!req.headers.accept?.includes("text/html"))
3245
+ return requireAuth(req, res) ? void 0 : mcpServerHandler({
3246
+ req,
3247
+ res,
3248
+ options,
3249
+ addonOptions,
3250
+ endpoint,
3251
+ sources,
3252
+ ...manifestAccessFor(req),
3253
+ compositionAuth
3254
+ });
3255
+ res.writeHead(200, { "Content-Type": "text/html" });
3256
+ let docsNotice = "";
3257
+ docsHasManifests ? docsFeatureEnabled || (docsNotice = `<div class="toolset-notice">
1331
3258
  This toolset requires enabling the component manifest feature.
1332
- <a target="_blank" href="https://github.com/storybookjs/mcp/tree/main/packages/addon-mcp#docs-tools-experimental">Learn how to enable it</a>
3259
+ <a target="_blank" href="https://github.com/storybookjs/storybook/tree/next/code/addons/mcp">Learn how to enable it</a>
3260
+ </div>`) : docsNotice = `<div class="toolset-notice">
3261
+ This toolset is only supported in React-based setups.
1333
3262
  </div>`;
1334
- const testNoticeLines = [!addonVitestConstants && `This toolset requires Storybook 10.3.0+ with <code>@storybook/addon-vitest</code>. <a target="_blank" href="https://storybook.js.org/docs/writing-tests/test-addon">Learn how to set it up</a>`, !a11yEnabled && `Add <code>@storybook/addon-a11y</code> for accessibility testing. <a target="_blank" href="https://storybook.js.org/docs/writing-tests/accessibility-testing">Learn more</a>`].filter(Boolean);
1335
- const testNotice = testNoticeLines.length ? `<div class="toolset-notice">${testNoticeLines.join("<br>")}</div>` : "";
1336
- const a11yBadge = a11yEnabled ? " <span class=\"toolset-status enabled\">+ accessibility</span>" : "";
1337
- const html = template_default.replaceAll("{{DEV_STATUS}}", isDevEnabled ? "enabled" : "disabled").replaceAll("{{DOCS_STATUS}}", isDocsEnabled ? "enabled" : "disabled").replace("{{DOCS_NOTICE}}", docsNotice).replaceAll("{{TEST_STATUS}}", isTestEnabled ? "enabled" : "disabled").replace("{{TEST_NOTICE}}", testNotice).replace("{{MANIFEST_DEBUGGER_LINK}}", manifestStatus.available ? "<p>View the <a href=\"/manifests/components.html\">component manifest debugger</a>.</p>" : "").replace("{{A11Y_BADGE}}", a11yBadge);
1338
- res.end(html);
1339
- });
1340
- return app;
1341
- };
1342
- const features = async (existingFeatures) => {
1343
- return {
1344
- ...existingFeatures,
1345
- componentsManifest: true
1346
- };
3263
+ let testNoticeLines = [
3264
+ !testSupported && 'This toolset requires Storybook 10.3.0+ with <code>@storybook/addon-vitest</code>. <a target="_blank" href="https://storybook.js.org/docs/writing-tests/integrations/vitest-addon#install-and-set-up">Learn how to set it up</a>',
3265
+ !a11yEnabled2 && 'Add <code>@storybook/addon-a11y</code> for accessibility testing. <a target="_blank" href="https://storybook.js.org/docs/writing-tests/accessibility-testing">Learn more</a>'
3266
+ ].filter(Boolean), testNotice = testNoticeLines.length ? `<div class="toolset-notice">${testNoticeLines.join("<br>")}</div>` : "", a11yBadge = a11yEnabled2 ? ' <span class="toolset-status enabled">+ accessibility</span>' : "", devNoticeLines = isDevEnabled ? [
3267
+ !moduleGraphSupported && "<code>get-stories-by-component</code> requires a dev server with a builder that supports the module graph (e.g. Vite).",
3268
+ !changeDetectionEnabled && "<code>get-changed-stories</code> requires enabling the <code>changeDetection</code> feature flag.",
3269
+ !reviewEnabled && (reviewEnabledForCli ? "<code>display-review</code> is enabled for <code>storybook ai</code> CLI clients (the Claude/Codex plugins); direct MCP clients need the <code>experimentalReview</code> feature flag." : "<code>display-review</code> requires the <code>changeDetection</code> feature flag and is off when <code>experimentalReview</code> is set to <code>false</code>.")
3270
+ ].filter(Boolean) : ["The <code>dev</code> toolset is disabled via addon options."], devNotice = devNoticeLines.length ? `<div class="toolset-notice">${devNoticeLines.join("<br>")}</div>` : "", statusWord = (enabled) => enabled ? "enabled" : "disabled", html = template_default.replaceAll("{{DEV_STATUS}}", isDevEnabled ? "enabled" : "disabled").replaceAll(
3271
+ "{{STORIES_BY_COMPONENT_STATUS}}",
3272
+ statusWord(isDevEnabled && moduleGraphSupported)
3273
+ ).replaceAll("{{CHANGE_DETECTION_STATUS}}", statusWord(isDevEnabled && changeDetectionEnabled)).replaceAll("{{REVIEW_STATUS}}", statusWord(isDevEnabled && reviewEnabledForCli)).replace("{{DEV_NOTICE}}", devNotice).replaceAll("{{DOCS_STATUS}}", isDocsEnabled ? "enabled" : "disabled").replace("{{DOCS_NOTICE}}", docsNotice).replaceAll("{{TEST_STATUS}}", isTestEnabled ? "enabled" : "disabled").replace("{{TEST_NOTICE}}", testNotice).replace(
3274
+ "{{MANIFEST_DEBUGGER_LINK}}",
3275
+ rawAvailability.docsEnabled ? '<p>View the <a href="/manifests/components.html">component manifest debugger</a>.</p>' : ""
3276
+ ).replace("{{A11Y_BADGE}}", a11yBadge);
3277
+ res.end(html);
3278
+ }), app;
3279
+ }, experimental_storybookAi = async (existingMetadata, options) => buildStorybookAiMetadata(options, existingMetadata), features = async (existingFeatures) => ({
3280
+ ...existingFeatures,
3281
+ componentsManifest: !0
3282
+ });
3283
+ export {
3284
+ experimental_devServer,
3285
+ experimental_storybookAi,
3286
+ features,
3287
+ previewAnnotations
1347
3288
  };
1348
- /**
1349
- * Get composed Storybook refs from Storybook config.
1350
- * See: https://storybook.js.org/docs/sharing/storybook-composition
1351
- */
1352
- async function getRefsFromConfig(options) {
1353
- try {
1354
- const refs = await options.presets.apply("refs", {});
1355
- if (!refs || typeof refs !== "object") return [];
1356
- return Object.entries(refs).map(([key, value]) => ({
1357
- id: key,
1358
- title: value.title || key,
1359
- url: value.url
1360
- })).filter((ref) => ref.url);
1361
- } catch {
1362
- return [];
1363
- }
1364
- }
1365
-
1366
- //#endregion
1367
- export { experimental_devServer, features, previewAnnotations };