@storybook/addon-mcp 10.6.0-alpha.5 → 10.6.0-alpha.7

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,10 +1,10 @@
1
- import CJS_COMPAT_NODE_URL_y5eqdjsbeu from 'node:url';
2
- import CJS_COMPAT_NODE_PATH_y5eqdjsbeu from 'node:path';
3
- import CJS_COMPAT_NODE_MODULE_y5eqdjsbeu from "node:module";
1
+ import CJS_COMPAT_NODE_URL_05tg55zd2fgl from 'node:url';
2
+ import CJS_COMPAT_NODE_PATH_05tg55zd2fgl from 'node:path';
3
+ import CJS_COMPAT_NODE_MODULE_05tg55zd2fgl from "node:module";
4
4
 
5
- var __filename = CJS_COMPAT_NODE_URL_y5eqdjsbeu.fileURLToPath(import.meta.url);
6
- var __dirname = CJS_COMPAT_NODE_PATH_y5eqdjsbeu.dirname(__filename);
7
- var require = CJS_COMPAT_NODE_MODULE_y5eqdjsbeu.createRequire(import.meta.url);
5
+ var __filename = CJS_COMPAT_NODE_URL_05tg55zd2fgl.fileURLToPath(import.meta.url);
6
+ var __dirname = CJS_COMPAT_NODE_PATH_05tg55zd2fgl.dirname(__filename);
7
+ var require = CJS_COMPAT_NODE_MODULE_05tg55zd2fgl.createRequire(import.meta.url);
8
8
 
9
9
  // ------------------------------------------------------------
10
10
  // end of CJS compatibility banner, injected by Storybook's esbuild configuration
@@ -18,7 +18,7 @@ import { HttpTransport } from "@tmcp/transport-http";
18
18
  // package.json
19
19
  var package_default = {
20
20
  name: "@storybook/addon-mcp",
21
- version: "10.6.0-alpha.5",
21
+ version: "10.6.0-alpha.7",
22
22
  description: "Help agents automatically write and test stories for your UI components",
23
23
  keywords: [
24
24
  "ai",
@@ -54,10 +54,8 @@ var package_default = {
54
54
  "!src/**/*"
55
55
  ],
56
56
  dependencies: {
57
- "@storybook/mcp": "workspace:*",
58
57
  "@tmcp/adapter-valibot": "^0.1.5",
59
58
  "@tmcp/transport-http": "^0.8.5",
60
- picoquery: "^2.5.0",
61
59
  tmcp: "^1.19.4",
62
60
  valibot: "^1.4.0"
63
61
  },
@@ -113,6 +111,9 @@ async function collectTelemetry({
113
111
  mcpSessionId: server.ctx.sessionId,
114
112
  clientInfo: server.ctx.sessionInfo?.clientInfo,
115
113
  clientCapabilities: server.ctx.sessionInfo?.clientCapabilities,
114
+ // Which channel drove the call: the `storybook ai` CLI marks its requests with the proxy
115
+ // header; everything else is a direct MCP client.
116
+ transport: server.ctx.custom?.cliClient ? "cli" : "mcp",
116
117
  ...payload
117
118
  });
118
119
  } catch (error) {
@@ -121,762 +122,37 @@ async function collectTelemetry({
121
122
  }
122
123
 
123
124
  // 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
125
  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
216
- import path from "node:path";
217
- import { normalizeStoryPath } from "storybook/internal/common";
218
- import { storyNameFromExport } from "storybook/internal/csf";
219
- import { logger as logger3 } from "storybook/internal/node-logger";
220
-
221
- // src/utils/slash.ts
222
- function slash(path5) {
223
- return path5.replace(/\\/g, "/");
224
- }
225
-
226
- // src/utils/find-story-ids.ts
227
- function isStoryIdInput(input) {
228
- return "storyId" in input;
229
- }
230
- function normalizeImportPath(importPath) {
231
- let normalized = path.posix.normalize(slash(importPath));
232
- return slash(normalizeStoryPath(normalized));
233
- }
234
- function findStoryIds(index, stories) {
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";
294
-
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,
330
- but you want to customize some args or other props.
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.
351
- Use this path-based shape only when you're already editing a .stories.* file and know the export names in that file.
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").
382
- Prefer this shape whenever you are not already working in a specific story file.
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
391
- async function getAddonVitestConstants() {
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.
408
- Prefer running tests for specific stories while developing to get faster feedback,
409
- and only omit this when you explicitly need to run all tests for comprehensive verification.
410
- Prefer { storyId } when you don't already have story file context, since this avoids filesystem discovery.
411
- Use { storyId } when IDs were discovered from documentation tools.
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
- )
425
- });
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.
429
- Provide stories for focused runs (faster while iterating),
430
- or omit stories to run all tests for full-project verification.
431
- Use this continuously to monitor test results as you work on your UI components and stories.
432
- Results will include passing/failing status` + (a11yEnabled2 ? `, and accessibility violation reports.
433
- For visual/design accessibility violations (for example color contrast), ask the user before changing styles.` : ".");
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.
498
-
499
- ${errorMessages}`
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
- }
549
- function triggerTestRun(channel, triggerTestRunRequestEventName, triggerTestRunResponseEventName, storyIds, config) {
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
- };
616
- }
617
- function formatPassingStoriesSection(passingStories) {
618
- return `## Passing Stories
619
-
620
- - ${passingStories.map((status) => status.storyId).join(`
621
- - `)}`;
622
- }
623
- function formatFailingStoriesSection(statuses) {
624
- return `## Failing Stories
625
-
626
- ${statuses.map(
627
- (status) => `### ${status.storyId}
628
-
629
- ${status.description || "No failure details available."}`
630
- ).join(`
631
-
632
- `)}`;
633
- }
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
643
-
644
- ${report.error.message}`);
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}
657
-
658
- ${violation.description}
659
-
660
- #### Affected Elements
661
- ${nodes}`);
662
- }
663
- }
664
- if (a11yViolationSections.length !== 0)
665
- return `## Accessibility Violations
666
-
667
- ${a11yViolationSections.join(`
668
-
669
- `)}`;
670
- }
671
- function formatUnhandledErrorsSection(errors) {
672
- return `## Unhandled Errors
673
-
674
- ${errors.map(
675
- (unhandledError) => `### ${unhandledError.name || "Unknown Error"}
676
-
677
- **Error message**: ${unhandledError.message || "No message available"}
678
- **Path**: ${unhandledError.VITEST_TEST_PATH || "No path available"}
679
- **Test name**: ${unhandledError.VITEST_TEST_NAME || "No test name available"}
680
- **Stack trace**:
681
- ${unhandledError.stack || "No stack trace available"}`
682
- ).join(`
683
-
684
- `)}`;
685
- }
686
- function countA11yViolations(a11yReports) {
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;
692
- }
693
- function getA11yViolations(report) {
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
710
- async function isAddonA11yEnabled(options) {
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
- }
126
+ import { getEffectiveToolAvailability, getToolAvailability } from "storybook/internal/core-server";
127
+ import { buildServerInstructions } from "storybook/internal/skills";
842
128
 
843
129
  // 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";
130
+ var STORYBOOK_MCP_PROXY_HEADER = "X-Storybook-MCP-Proxy", DEFAULT_MCP_ENDPOINT = "/mcp";
845
131
 
846
132
  // src/tools/tool-registry.ts
847
- import { logger as logger5 } from "storybook/internal/node-logger";
133
+ import { logger as logger3 } from "storybook/internal/node-logger";
848
134
  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";
135
+ createCompositionDocsSources,
136
+ createDocsToolset
137
+ } from "storybook/internal/toolsets-docs";
862
138
 
863
139
  // src/utils/format-validation-issues.ts
864
- function formatPath(path5) {
865
- if (!path5 || path5.length === 0) return "";
140
+ function formatPath(path2) {
141
+ if (!path2 || path2.length === 0) return "";
866
142
  let out = "";
867
- for (let segment of path5) {
143
+ for (let segment of path2) {
868
144
  let key = typeof segment == "object" && segment !== null && "key" in segment ? segment.key : segment;
869
145
  typeof key == "number" ? out += `[${key}]` : key != null && (out += out === "" ? String(key) : `.${String(key)}`);
870
146
  }
871
147
  return out;
872
148
  }
873
149
  function summarizeIssue(issue) {
874
- let path5 = formatPath(issue.path);
150
+ let path2 = formatPath(issue.path);
875
151
  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
152
  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}.` };
153
+ return { path: path2, message: `Missing required field \`${field}\`${where}.` };
878
154
  }
879
- return { path: path5, message: issue.message };
155
+ return { path: path2, message: issue.message };
880
156
  }
881
157
  function withFriendlyErrors(schema) {
882
158
  let original = schema["~standard"];
@@ -891,859 +167,44 @@ function withFriendlyErrors(schema) {
891
167
  // `received` — see {@link StandardSchemaIssue}.
892
168
  r.issues ? { issues: r.issues.map(summarizeIssue) } : r
893
169
  );
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
170
+ return result instanceof Promise ? result.then(trim) : trim(result);
171
+ }
172
+ }
173
+ };
174
+ }
1724
175
 
1725
- **Confirm with user first** (visual/design changes):
176
+ // src/tools/get-storybook-story-instructions.ts
177
+ import { resolveSkillInputs } from "storybook/internal/core-server";
178
+ import { buildStoryInstructions } from "storybook/internal/skills";
1726
179
 
1727
- - Color contrast ratios
1728
- - Font sizes, spacing, layout
1729
- - Focus indicator styling
180
+ // src/utils/errors.ts
181
+ var errorToMCPContent = (error) => ({
182
+ content: [
183
+ {
184
+ type: "text",
185
+ text: `Error: ${error instanceof Error ? error.message : String(error)}`
186
+ }
187
+ ],
188
+ isError: !0
189
+ });
1730
190
 
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
- `;
191
+ // src/tools/tool-names.ts
192
+ import { toMcpToolName } from "storybook/open-service";
193
+ var PREVIEW_STORIES_TOOL_NAME = toMcpToolName("stories.preview"), GET_CHANGED_STORIES_TOOL_NAME = toMcpToolName("stories.changed"), GET_STORIES_BY_COMPONENT_TOOL_NAME = toMcpToolName("stories.findByComponent"), RUN_STORY_TESTS_TOOL_NAME = toMcpToolName("test.run"), DISPLAY_REVIEW_TOOL_NAME = toMcpToolName("review.create"), GET_UI_BUILDING_INSTRUCTIONS_TOOL_NAME = "get-storybook-story-instructions";
1734
194
 
1735
195
  // 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();
196
+ async function addGetUIBuildingInstructionsTool(server, enabled = () => server.ctx.custom?.toolsets?.dev ?? !0, {
197
+ docsEnabled = !1,
198
+ addonVitestAvailable = !1
199
+ } = {}) {
1739
200
  server.tool(
1740
201
  {
1741
202
  name: GET_UI_BUILDING_INSTRUCTIONS_TOOL_NAME,
1742
203
  title: "Storybook Story Development Instructions",
1743
204
  get description() {
1744
- let testToolsetAvailable = (server.ctx.custom?.toolsets?.test ?? !0) && addonVitestAvailable, a11yAvailable = testToolsetAvailable && (server.ctx.custom?.a11yEnabled ?? !1);
205
+ let testSupported = (server.ctx.custom?.toolsets?.test ?? !0) && addonVitestAvailable, a11yAvailable = testSupported && (server.ctx.custom?.a11yEnabled ?? !1);
1745
206
  return getStorybookStoryInstructionsDescription({
1746
- testToolsetAvailable,
207
+ testSupported,
1747
208
  a11yAvailable
1748
209
  });
1749
210
  },
@@ -1763,7 +224,7 @@ async function addGetUIBuildingInstructionsTool(server, enabled = () => server.c
1763
224
  toolsets: server.ctx.custom?.toolsets,
1764
225
  a11yEnabled: server.ctx.custom?.a11yEnabled,
1765
226
  addonVitestAvailable,
1766
- docsAvailable,
227
+ docsEnabled,
1767
228
  reviewEnabled: server.ctx.custom?.reviewEnabled
1768
229
  }) }]
1769
230
  };
@@ -1774,7 +235,7 @@ async function addGetUIBuildingInstructionsTool(server, enabled = () => server.c
1774
235
  );
1775
236
  }
1776
237
  function getStorybookStoryInstructionsDescription({
1777
- testToolsetAvailable,
238
+ testSupported,
1778
239
  a11yAvailable
1779
240
  }) {
1780
241
  return `Get comprehensive instructions for writing, testing, and fixing Storybook stories (.stories.tsx, .stories.ts, .stories.jsx, .stories.js, .stories.svelte, .stories.vue files).
@@ -1785,7 +246,7 @@ CRITICAL: You MUST call this tool before:
1785
246
  - Adding new story variants or exports to story files
1786
247
  - Editing any file matching *.stories.* patterns
1787
248
  - 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 ? `
249
+ - 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${testSupported ? `
1789
250
  - Running story tests or fixing test failures` : ""}${a11yAvailable ? `
1790
251
  - Handling accessibility (a11y) violations in stories (fix semantic issues directly; ask before visual/design changes)` : ""}
1791
252
 
@@ -1796,7 +257,7 @@ This tool provides essential Storybook-specific guidance including:
1796
257
  - Story naming conventions and best practices
1797
258
  - Play function patterns for interactive testing
1798
259
  - Mocking strategies for external dependencies
1799
- - Story variants and coverage requirements${testToolsetAvailable ? `
260
+ - Story variants and coverage requirements${testSupported ? `
1800
261
  - How to handle test failures${a11yAvailable ? " and accessibility violations" : ""}` : ""}
1801
262
 
1802
263
  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.`;
@@ -1810,74 +271,27 @@ function getStorybookStoryInstructionsToolMetadata(options) {
1810
271
  }
1811
272
  async function buildStorybookStoryInstructions(options, {
1812
273
  toolsets,
1813
- a11yEnabled: a11yEnabled2 = !1,
274
+ a11yEnabled: a11yEnabled2,
1814
275
  addonVitestAvailable,
1815
- docsAvailable = !1,
276
+ docsEnabled,
1816
277
  reviewEnabled: reviewEnabledOverride
1817
278
  } = {}) {
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 += `
1823
-
1824
- ${storyTestingInstructions}`, a11yEnabled2 && (uiInstructions += `
1825
- ${a11y_instructions_default}`);
1826
- }
1827
- return uiInstructions;
279
+ let inputs = await resolveSkillInputs(options);
280
+ return buildStoryInstructions({
281
+ transport: "mcp",
282
+ framework: inputs.framework,
283
+ renderer: inputs.renderer,
284
+ changeDetectionEnabled: inputs.changeDetectionEnabled,
285
+ reviewEnabled: reviewEnabledOverride ?? inputs.reviewEnabled,
286
+ testSupported: (toolsets?.test ?? !0) && (addonVitestAvailable ?? inputs.testSupported),
287
+ a11yEnabled: a11yEnabled2 ?? inputs.a11yEnabled,
288
+ docsEnabled: (toolsets?.docs ?? !0) && (docsEnabled ?? inputs.docsEnabled)
289
+ });
1828
290
  }
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"
1843
- };
1844
291
 
1845
292
  // src/tools/preview-stories.ts
1846
293
  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
- }
294
+ import fs from "node:fs/promises";
1881
295
 
1882
296
  // src/tools/preview-stories/preview-stories-app-template.html
1883
297
  var preview_stories_app_template_default = `<!doctype html>
@@ -1955,60 +369,9 @@ var preview_stories_app_template_default = `<!doctype html>
1955
369
  `;
1956
370
 
1957
371
  // src/tools/preview-stories.ts
1958
- import fs2 from "node:fs/promises";
1959
372
  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(
373
+ async function addPreviewStoriesResource(server) {
374
+ let previewStoryAppScript = await fs.readFile(
2012
375
  url.fileURLToPath(
2013
376
  import.meta.resolve("@storybook/addon-mcp/internal/preview-stories-app-script")
2014
377
  ),
@@ -2045,182 +408,267 @@ async function addPreviewStoriesTool(server, enabled = () => server.ctx.custom?.
2045
408
  ]
2046
409
  };
2047
410
  }
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
- }
411
+ );
412
+ }
413
+
414
+ // src/tools/tool-registry.ts
415
+ import { OpenServiceMissingToolsetError, toMcpToolName as toMcpToolName3 } from "storybook/open-service";
416
+
417
+ // src/tools/toolset-tools.ts
418
+ import { getService } from "storybook/internal/core-server";
419
+ import { logger as logger2 } from "storybook/internal/node-logger";
420
+ import { OpenServiceToolsetOutputMismatchError } from "storybook/internal/server-errors";
421
+ import {
422
+ getToolset,
423
+ resolveToolsetDescription,
424
+ toMcpToolName as toMcpToolName2
425
+ } from "storybook/open-service";
426
+
427
+ // src/tools/toolset-origin.ts
428
+ function storybookRootFromRequest(request, trustedOrigin, endpoint) {
429
+ if (request?.url)
430
+ try {
431
+ let url2 = new URL(request.url), normalizedEndpoint = endpoint.replace(/\/$/, ""), normalizedPathname = url2.pathname.replace(/\/$/, ""), rootPath = normalizedPathname.endsWith(normalizedEndpoint) ? normalizedPathname.slice(0, -normalizedEndpoint.length) : normalizedPathname.replace(/\/[^/]+$/, "");
432
+ return `${trustedOrigin.replace(/\/$/, "")}${rootPath}`;
433
+ } catch {
434
+ return;
435
+ }
436
+ }
437
+ function resolveToolsetOrigin(context) {
438
+ if (context.origin)
439
+ return context.request ? storybookRootFromRequest(
440
+ context.request,
441
+ context.origin,
442
+ context.endpoint ?? DEFAULT_MCP_ENDPOINT
443
+ ) ?? context.origin : context.origin;
444
+ }
445
+
446
+ // src/tools/toolset-tools.ts
447
+ function resolveToolset(options, server) {
448
+ if (options.resolveToolset)
449
+ return options.resolveToolset(server);
450
+ let [toolsetId] = options.method.split(".");
451
+ return getToolset(toolsetId);
452
+ }
453
+ function resolveMethod(toolset, options) {
454
+ let [, methodName] = options.method.split(".");
455
+ return toolset.methods[methodName];
456
+ }
457
+ function isAgentFacingError(error) {
458
+ return error instanceof Error && error.agentFacing === !0;
459
+ }
460
+ async function toStructuredContent(outputSchema, data) {
461
+ if (!outputSchema || data === void 0)
462
+ return;
463
+ let result = await outputSchema["~standard"].validate(data);
464
+ if (result.issues)
465
+ throw new OpenServiceToolsetOutputMismatchError({ issues: result.issues });
466
+ return result.value;
467
+ }
468
+ function buildContext(server) {
469
+ let custom = server.ctx.custom;
470
+ return {
471
+ transport: "mcp",
472
+ // The toolset origin is the complete UI base URL, including any deployment subpath.
473
+ origin: resolveToolsetOrigin(custom ?? {}),
474
+ getService: (serviceId, serviceOptions) => getService(serviceId, serviceOptions),
475
+ telemetry: custom?.disableTelemetry ? void 0 : async (event, payload) => {
476
+ await collectTelemetry({
477
+ event,
478
+ server,
479
+ ...payload
480
+ });
2109
481
  }
482
+ };
483
+ }
484
+ async function callToolsetMethod(server, options, input) {
485
+ let toolset = resolveToolset(options, server), method = resolveMethod(toolset, options), ctx = buildContext(server);
486
+ try {
487
+ let outcome = await method.handler(input, ctx), structuredContent = await toStructuredContent(method.output, outcome.data);
488
+ return {
489
+ content: (Array.isArray(outcome.markdown) ? outcome.markdown : [outcome.markdown]).map((text) => ({ type: "text", text })),
490
+ ...structuredContent !== void 0 ? { structuredContent } : {},
491
+ ...outcome.ok ? {} : { isError: !0 }
492
+ };
493
+ } catch (error) {
494
+ return isAgentFacingError(error) ? { content: [{ type: "text", text: error.message }], isError: !0 } : (logger2.error(`MCP tool "${toMcpToolName2(options.method)}" failed: ${error}`), errorToMCPContent(error));
495
+ }
496
+ }
497
+ function getToolsetToolMetadata(options) {
498
+ let method = resolveMethod(resolveToolset(options), options), descriptionCtx = {
499
+ transport: "mcp",
500
+ getService: (serviceId, serviceOptions) => getService(serviceId, serviceOptions)
501
+ }, entries = method.input.entries, hasInput = !entries || Object.keys(entries).length > 0;
502
+ return {
503
+ name: toMcpToolName2(options.method),
504
+ title: method.title,
505
+ description: resolveToolsetDescription(method.description, descriptionCtx),
506
+ ...hasInput ? { schema: options.wrapSchema ? options.wrapSchema(method.input) : method.input } : {},
507
+ ...method.output ? { outputSchema: method.output } : {},
508
+ ...options.extras
509
+ };
510
+ }
511
+ function registerToolsetTool(server, options, enabled) {
512
+ server.tool(
513
+ { ...getToolsetToolMetadata(options), enabled },
514
+ ((input) => callToolsetMethod(server, options, input))
2110
515
  );
2111
516
  }
2112
517
 
2113
518
  // 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,
519
+ 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;
520
+ function fromToolset(definition) {
521
+ let { options, available, wrapEnabled, ...rest } = definition;
522
+ return {
523
+ ...rest,
524
+ // Read from the constant, not the registry: this array is built at import time, while toolsets
525
+ // register later from their preset hooks. Each availability gate is written to match the
526
+ // condition under which its toolset registers; if they still disagree, resolution fails loudly
527
+ // (getToolset throws) and the registry drops that one tool with an error log rather than taking
528
+ // down the whole server (see resolveDefinitionOrDrop).
529
+ name: toMcpToolName3(options.method),
530
+ available: (context) => available?.(context) ?? !0,
531
+ getMetadata: () => getToolsetToolMetadata(options),
532
+ register: async (server, context, enabled) => {
533
+ registerToolsetTool(server, options, wrapEnabled?.(server, context, enabled) ?? enabled);
534
+ }
535
+ };
536
+ }
537
+ function compositionDocsToolset(server) {
538
+ let custom = server?.ctx.custom;
539
+ return createDocsToolset({
540
+ sources: createCompositionDocsSources({
541
+ sources: custom?.sources ?? [{ id: "local", title: "Local" }],
542
+ manifestProvider: custom?.manifestProvider,
543
+ getRequest: () => custom?.request,
544
+ localAccess: custom?.localAccess
545
+ })
546
+ });
547
+ }
548
+ function docsToolDefinition(method) {
549
+ let forContext = (context) => context.multiSource ? { method, resolveToolset: (server) => compositionDocsToolset(server) } : { method };
550
+ return {
551
+ name: toMcpToolName3(method),
552
+ toolset: "docs",
553
+ available: ({ availability }) => availability.docsEnabled,
554
+ getMetadata: (context) => getToolsetToolMetadata(forContext(context)),
555
+ register: async (server, context, enabled) => {
556
+ registerToolsetTool(server, forContext(context), enabled);
557
+ }
558
+ };
559
+ }
560
+ var docsToolDefinitions = [
561
+ docsToolDefinition("docs.list"),
562
+ docsToolDefinition("docs.show"),
563
+ docsToolDefinition("docs.showStory")
564
+ ], addonToolDefinitions = [
565
+ fromToolset({
2117
566
  toolset: "dev",
2118
- getMetadata: ({ availability }) => getPreviewStoriesToolMetadata({ reviewEnabled: availability.reviewEnabled }),
2119
- register: (server, { availability }, enabled) => addPreviewStoriesTool(server, enabled, { reviewEnabled: availability.reviewEnabled })
2120
- },
567
+ options: {
568
+ method: "stories.preview",
569
+ extras: { _meta: { ui: { resourceUri: PREVIEW_STORIES_RESOURCE_URI } } }
570
+ }
571
+ }),
2121
572
  {
2122
573
  name: GET_UI_BUILDING_INSTRUCTIONS_TOOL_NAME,
2123
574
  toolset: "dev",
2124
575
  getMetadata: ({ availability, toolsets }) => {
2125
- let testToolsetAvailable = isToolsetEnabled("test", toolsets) && availability.testSupported;
576
+ let testSupported = isToolsetEnabled("test", toolsets) && availability.testSupported;
2126
577
  return getStorybookStoryInstructionsToolMetadata({
2127
- testToolsetAvailable,
2128
- a11yAvailable: testToolsetAvailable && availability.a11yEnabled
578
+ testSupported,
579
+ a11yAvailable: testSupported && availability.a11yEnabled
2129
580
  });
2130
581
  },
2131
582
  register: (server, { availability, toolsets }, enabled) => addGetUIBuildingInstructionsTool(server, enabled, {
2132
- docsAvailable: isToolsetEnabled("docs", toolsets) && availability.docsEnabled
583
+ docsEnabled: isToolsetEnabled("docs", toolsets) && availability.docsEnabled,
584
+ addonVitestAvailable: availability.testSupported
2133
585
  }),
2134
586
  getLocalTool: ({ availability, toolsets, options }) => ({
2135
587
  call: async () => ({ content: [{ type: "text", text: await buildStorybookStoryInstructions(options, {
2136
588
  toolsets,
2137
589
  a11yEnabled: availability.a11yEnabled,
2138
590
  addonVitestAvailable: availability.testSupported,
2139
- docsAvailable: isToolsetEnabled("docs", toolsets) && availability.docsEnabled,
591
+ docsEnabled: isToolsetEnabled("docs", toolsets) && availability.docsEnabled,
2140
592
  reviewEnabled: availability.reviewEnabled
2141
593
  }) }] })
2142
594
  })
2143
595
  },
2144
- {
2145
- name: GET_CHANGED_STORIES_TOOL_NAME,
596
+ fromToolset({
2146
597
  toolset: "dev",
2147
598
  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,
599
+ options: { method: "stories.changed" }
600
+ }),
601
+ fromToolset({
2153
602
  toolset: "dev",
2154
603
  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,
604
+ options: { method: "stories.findByComponent" }
605
+ }),
606
+ fromToolset({
2162
607
  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.
608
+ // Registered whenever the CLI default could turn review on; the per-request `reviewEnabled`
609
+ // context (explicit flag, or the trusted local-client header) decides whether a given MCP
610
+ // client actually sees the tool.
2166
611
  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,
612
+ wrapEnabled: (server, { availability }, enabled) => async () => (await enabled?.() ?? !0) && (server.ctx.custom?.reviewEnabled ?? availability.reviewEnabled),
613
+ options: {
614
+ method: "review.create",
615
+ wrapSchema: withFriendlyErrors
616
+ }
617
+ }),
618
+ fromToolset({
2175
619
  toolset: "test",
2176
620
  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
- }
621
+ options: { method: "test.run" }
622
+ }),
623
+ // Docs run on the core docs toolset in both modes. A composition builds its toolset per request,
624
+ // because the sources it reads and the provider that fetches them belong to the request.
625
+ ...docsToolDefinitions
2209
626
  ];
627
+ function dropToolIfToolsetMissing(name, error) {
628
+ if (!(error instanceof OpenServiceMissingToolsetError))
629
+ throw error;
630
+ logger3.error(`Skipping MCP tool "${name}", its backing toolset is not registered: ${error}`);
631
+ }
632
+ function resolveDefinitionOrDrop(name, resolve) {
633
+ try {
634
+ return resolve();
635
+ } catch (error) {
636
+ return dropToolIfToolsetMissing(name, error);
637
+ }
638
+ }
2210
639
  function getAddonToolMetadata(context) {
2211
- return addonToolDefinitions.filter((definition) => isMetadataToolEnabled(definition, context)).map((definition) => definition.getMetadata(context));
640
+ return addonToolDefinitions.filter((definition) => isMetadataToolEnabled(definition, context)).flatMap((definition) => {
641
+ let metadata = resolveDefinitionOrDrop(
642
+ definition.name,
643
+ () => definition.getMetadata(context)
644
+ );
645
+ return metadata ? [metadata] : [];
646
+ });
2212
647
  }
2213
648
  function getAddonLocalTools(context) {
2214
649
  return Object.fromEntries(
2215
650
  addonToolDefinitions.filter((definition) => isMetadataToolEnabled(definition, context)).flatMap((definition) => {
2216
- let localTool = definition.getLocalTool?.(context);
651
+ let localTool = resolveDefinitionOrDrop(
652
+ definition.name,
653
+ () => definition.getLocalTool?.(context)
654
+ );
2217
655
  return localTool ? [[definition.name, localTool]] : [];
2218
656
  })
2219
657
  );
2220
658
  }
2221
659
  async function registerAddonMcpTools(server, context) {
660
+ isToolsetEnabled("dev", context.toolsets) && await addPreviewStoriesResource(server);
2222
661
  for (let definition of addonToolDefinitions)
2223
- isToolsetEnabled(definition.toolset, context.toolsets) && isToolAvailable(definition, context) && await definition.register(server, context, createToolsetEnabled(server, definition.toolset));
662
+ if (isToolsetEnabled(definition.toolset, context.toolsets) && isToolAvailable(definition, context))
663
+ try {
664
+ await definition.register(
665
+ server,
666
+ context,
667
+ createToolsetEnabled(server, definition.toolset)
668
+ );
669
+ } catch (error) {
670
+ dropToolIfToolsetMissing(definition.name, error);
671
+ }
2224
672
  }
2225
673
 
2226
674
  // src/mcp-handler.ts
@@ -2236,8 +684,9 @@ var transport, origin, initialize, disableTelemetry, a11yEnabled, reviewGates, i
2236
684
  adapter: new ValibotJsonSchemaAdapter(),
2237
685
  get instructions() {
2238
686
  return buildServerInstructions({
687
+ transport: "mcp",
2239
688
  devEnabled: server?.ctx.custom?.toolsets?.dev ?? !0,
2240
- testEnabled: (server?.ctx.custom?.toolsets?.test ?? !0) && availability.testSupported,
689
+ testSupported: (server?.ctx.custom?.toolsets?.test ?? !0) && availability.testSupported,
2241
690
  docsEnabled: (server?.ctx.custom?.toolsets?.docs ?? !0) && availability.docsEnabled,
2242
691
  changeDetectionEnabled: availability.changeDetectionEnabled,
2243
692
  moduleGraphSupported: availability.moduleGraphSupported,
@@ -2258,7 +707,7 @@ var transport, origin, initialize, disableTelemetry, a11yEnabled, reviewGates, i
2258
707
  serverOptions
2259
708
  ).withContext(), disableTelemetry || server.on("initialize", async () => {
2260
709
  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;
710
+ }), await registerAddonMcpTools(server, { availability, multiSource }), transport = new HttpTransport(server, { path: null }), origin = `http://localhost:${options.port}`, logger4.debug(`MCP server origin: ${origin}`), server;
2262
711
  }, mcpServerHandler = async ({
2263
712
  req,
2264
713
  res,
@@ -2267,49 +716,26 @@ var transport, origin, initialize, disableTelemetry, a11yEnabled, reviewGates, i
2267
716
  endpoint = DEFAULT_MCP_ENDPOINT,
2268
717
  sources,
2269
718
  manifestProvider,
2270
- resolveEntry,
719
+ localAccess,
2271
720
  compositionAuth
2272
721
  }) => {
2273
722
  initialize || (initialize = initializeMCPServer(
2274
723
  options,
2275
724
  sources?.some((s) => s.url)
2276
- ));
2277
- let server = await initialize, webRequest = await incomingMessageToWebRequest(req), addonContext = {
725
+ )), await initialize;
726
+ let webRequest = await incomingMessageToWebRequest(req), addonContext = {
2278
727
  options,
2279
728
  endpoint,
2280
729
  toolsets: getToolsets(webRequest, addonOptions),
2281
730
  reviewEnabled: isReviewEnabledForRequest(webRequest, reviewGates),
731
+ cliClient: webRequest.headers.get(STORYBOOK_MCP_PROXY_HEADER) === "true",
2282
732
  origin,
2283
733
  disableTelemetry,
2284
734
  a11yEnabled,
2285
735
  request: webRequest,
2286
736
  sources,
2287
737
  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
- }
738
+ localAccess
2313
739
  }, response = await transport.respond(webRequest, addonContext);
2314
740
  if (response) {
2315
741
  let body = await response.arrayBuffer(), finalResponse = compositionAuth.hadAuthError(webRequest) ? new Response("401 - Unauthorized", {
@@ -2366,8 +792,45 @@ function getToolsets(request, addonOptions) {
2366
792
  return toolsets;
2367
793
  }
2368
794
 
795
+ // src/types.ts
796
+ import * as v from "valibot";
797
+ var isLiteralEndpointPathname = (endpoint) => {
798
+ try {
799
+ let { pathname } = new URL(endpoint, "http://storybook.local");
800
+ return pathname === endpoint && pathname !== "/";
801
+ } catch {
802
+ return !1;
803
+ }
804
+ }, AddonOptions = v.object({
805
+ endpoint: v.optional(
806
+ v.pipe(
807
+ v.string(),
808
+ v.check(isLiteralEndpointPathname, "Endpoint must be a literal URL pathname")
809
+ )
810
+ ),
811
+ toolsets: v.optional(
812
+ v.object({
813
+ dev: v.exactOptional(v.boolean(), !0),
814
+ docs: v.exactOptional(v.boolean(), !0),
815
+ test: v.exactOptional(v.boolean(), !0)
816
+ }),
817
+ {
818
+ // Default values for toolsets
819
+ dev: !0,
820
+ docs: !0,
821
+ test: !0
822
+ }
823
+ )
824
+ });
825
+
2369
826
  // src/preset.ts
2370
- import * as v9 from "valibot";
827
+ import * as v5 from "valibot";
828
+ import {
829
+ createLocalDocsAccess,
830
+ getEffectiveToolAvailability as getEffectiveToolAvailability3,
831
+ getToolAvailability as getToolAvailability3,
832
+ loadManifests
833
+ } from "storybook/internal/core-server";
2371
834
 
2372
835
  // src/template.html
2373
836
  var template_default = `<!doctype html>
@@ -2573,22 +1036,22 @@ var template_default = `<!doctype html>
2573
1036
  <span class="toolset-status {{DEV_STATUS}}">{{DEV_STATUS}}</span>
2574
1037
  </div>
2575
1038
  <ul class="toolset-tools">
2576
- <li><code>preview-stories</code></li>
1039
+ <li><code>stories-preview</code></li>
2577
1040
  <li><code>get-storybook-story-instructions</code></li>
2578
1041
  <li>
2579
- <code>get-changed-stories</code>
1042
+ <code>stories-changed</code>
2580
1043
  <span class="toolset-status {{CHANGE_DETECTION_STATUS}}"
2581
1044
  >{{CHANGE_DETECTION_STATUS}}</span
2582
1045
  >
2583
1046
  </li>
2584
1047
  <li>
2585
- <code>get-stories-by-component</code>
1048
+ <code>stories-find-by-component</code>
2586
1049
  <span class="toolset-status {{STORIES_BY_COMPONENT_STATUS}}"
2587
1050
  >{{STORIES_BY_COMPONENT_STATUS}}</span
2588
1051
  >
2589
1052
  </li>
2590
1053
  <li>
2591
- <code>display-review</code>
1054
+ <code>review-create</code>
2592
1055
  <span class="toolset-status {{REVIEW_STATUS}}">{{REVIEW_STATUS}}</span>
2593
1056
  </li>
2594
1057
  </ul>
@@ -2601,9 +1064,9 @@ var template_default = `<!doctype html>
2601
1064
  <span class="toolset-status {{DOCS_STATUS}}">{{DOCS_STATUS}}</span>
2602
1065
  </div>
2603
1066
  <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>
1067
+ <li><code>docs-list</code></li>
1068
+ <li><code>docs-show</code></li>
1069
+ <li><code>docs-show-story</code></li>
2607
1070
  </ul>
2608
1071
  {{DOCS_NOTICE}}
2609
1072
  </div>
@@ -2614,7 +1077,7 @@ var template_default = `<!doctype html>
2614
1077
  <span class="toolset-status {{TEST_STATUS}}">{{TEST_STATUS}}</span>
2615
1078
  </div>
2616
1079
  <ul class="toolset-tools">
2617
- <li><code>run-story-tests</code>{{A11Y_BADGE}}</li>
1080
+ <li><code>test-run</code>{{A11Y_BADGE}}</li>
2618
1081
  </ul>
2619
1082
  {{TEST_NOTICE}}
2620
1083
  </div>
@@ -2627,21 +1090,24 @@ var template_default = `<!doctype html>
2627
1090
  `;
2628
1091
 
2629
1092
  // src/preset.ts
2630
- import path4 from "node:path";
1093
+ import path from "node:path";
2631
1094
 
2632
1095
  // 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()))
1096
+ import {
1097
+ ComponentManifestMap,
1098
+ DocsManifestMap
1099
+ } from "storybook/internal/toolsets-docs";
1100
+ import { logger as logger5 } from "storybook/internal/node-logger";
1101
+ import * as v2 from "valibot";
1102
+ var OAuthResourceMetadata = v2.object({
1103
+ resource: v2.optional(v2.string()),
1104
+ authorization_servers: v2.pipe(v2.array(v2.string()), v2.minLength(1)),
1105
+ scopes_supported: v2.optional(v2.array(v2.string()))
1106
+ }), OAuthServerMetadata = v2.object({
1107
+ issuer: v2.string(),
1108
+ authorization_endpoint: v2.string(),
1109
+ token_endpoint: v2.string(),
1110
+ scopes_supported: v2.optional(v2.array(v2.string()))
2645
1111
  }), MANIFEST_CACHE_TTL = 3600 * 1e3, REVALIDATION_TTL = 60 * 1e3, AuthenticationError = class extends Error {
2646
1112
  constructor(url2) {
2647
1113
  super(`Authentication failed for ${url2}. Your token may be invalid or expired.`), this.name = "AuthenticationError";
@@ -2663,12 +1129,12 @@ var OAuthResourceMetadata = v6.object({
2663
1129
  this.#authRequirement = result;
2664
1130
  else {
2665
1131
  let existingServer = this.#authRequirement.resourceMetadata.authorization_servers[0], newServer = result.resourceMetadata.authorization_servers[0];
2666
- existingServer !== newServer && logger7.warn(
1132
+ existingServer !== newServer && logger5.warn(
2667
1133
  `[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
1134
  );
2669
1135
  }
2670
1136
  } catch (error) {
2671
- logger7.warn(
1137
+ logger5.warn(
2672
1138
  `[addon-mcp] Failed to check auth for composed ref "${ref.title}" (${ref.url}): ${error instanceof Error ? error.message : String(error)}. Skipping this ref.`
2673
1139
  );
2674
1140
  }
@@ -2713,18 +1179,13 @@ var OAuthResourceMetadata = v6.object({
2713
1179
  /**
2714
1180
  * Create a manifest provider for multi-source mode.
2715
1181
  *
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.
1182
+ * Remote sources are fetched over HTTP with auth and caching; the local source fetches from
1183
+ * `localOrigin`. In `experimentalDocgenServer` mode core 404s the local `/manifests/*.json`, and
1184
+ * the composition reads that source through its own access instead of this provider.
2721
1185
  */
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;
1186
+ createManifestProvider(localOrigin) {
1187
+ return async (request, path2, source) => {
1188
+ let token = extractBearerToken(request?.headers.get("Authorization")), remoteSource = source?.url ? { ...source, url: source.url } : void 0, baseUrl = remoteSource?.url ?? localOrigin, manifestUrl = `${baseUrl}${path2.replace("./", "/")}`, isRemote = !!remoteSource, tokenForRequest = isRemote && this.#isAuthRequiredUrl(baseUrl) ? token : null;
2728
1189
  if (token && token !== this.#lastToken && (this.#manifestCache.clear(), this.#lastToken = token), isRemote) {
2729
1190
  let cached = this.#manifestCache.get(manifestUrl);
2730
1191
  if (cached)
@@ -2760,8 +1221,8 @@ var OAuthResourceMetadata = v6.object({
2760
1221
  throw new AuthenticationError(url2);
2761
1222
  if (!response.ok)
2762
1223
  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)
1224
+ 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 : v2.unknown();
1225
+ if (v2.safeParse(v2.pipe(v2.string(), v2.parseJson(), schema), text).success)
2765
1226
  return text;
2766
1227
  throw await this.#isMcpUnauthorized(new URL(url2).origin) ? new AuthenticationError(url2) : new Error(
2767
1228
  `Invalid manifest response from ${url2}: expected valid JSON manifest but got unexpected content.`
@@ -2779,7 +1240,7 @@ var OAuthResourceMetadata = v6.object({
2779
1240
  if (authReq) return authReq;
2780
1241
  if (response.ok) {
2781
1242
  let text = await response.text();
2782
- if (v6.safeParse(v6.pipe(v6.string(), v6.parseJson(), ComponentManifestMap), text).success)
1243
+ if (v2.safeParse(v2.pipe(v2.string(), v2.parseJson(), ComponentManifestMap), text).success)
2783
1244
  return "public";
2784
1245
  }
2785
1246
  let mcpAuth = await this.#checkMcpAuth(refUrl);
@@ -2815,25 +1276,25 @@ var OAuthResourceMetadata = v6.object({
2815
1276
  if (!match?.[1]) return null;
2816
1277
  let resourceMetadataUrl = match[1], resourceResponse = await fetch(resourceMetadataUrl);
2817
1278
  if (!resourceResponse.ok)
2818
- return logger7.warn(
1279
+ return logger5.warn(
2819
1280
  `[addon-mcp] Failed to fetch OAuth resource metadata from ${resourceMetadataUrl}: ${resourceResponse.status}`
2820
1281
  ), null;
2821
- let resourceResult = v6.safeParse(OAuthResourceMetadata, await resourceResponse.json());
1282
+ let resourceResult = v2.safeParse(OAuthResourceMetadata, await resourceResponse.json());
2822
1283
  if (!resourceResult.success)
2823
- return logger7.warn(
1284
+ return logger5.warn(
2824
1285
  `[addon-mcp] Invalid OAuth resource metadata from ${resourceMetadataUrl}: ${resourceResult.issues.map((i) => i.message).join(", ")}`
2825
1286
  ), null;
2826
1287
  let serverMetadataUrl = `${resourceResult.output.authorization_servers[0]}/.well-known/oauth-authorization-server`, serverResponse = await fetch(serverMetadataUrl);
2827
1288
  if (!serverResponse.ok)
2828
- return logger7.warn(
1289
+ return logger5.warn(
2829
1290
  `[addon-mcp] Failed to fetch OAuth server metadata from ${serverMetadataUrl}: ${serverResponse.status}`
2830
1291
  ), null;
2831
- let serverResult = v6.safeParse(OAuthServerMetadata, await serverResponse.json());
1292
+ let serverResult = v2.safeParse(OAuthServerMetadata, await serverResponse.json());
2832
1293
  return serverResult.success ? {
2833
1294
  resourceMetadataUrl,
2834
1295
  resourceMetadata: resourceResult.output,
2835
1296
  serverMetadata: serverResult.output
2836
- } : (logger7.warn(
1297
+ } : (logger5.warn(
2837
1298
  `[addon-mcp] Invalid OAuth server metadata from ${serverMetadataUrl}: ${serverResult.issues.map((i) => i.message).join(", ")}`
2838
1299
  ), null);
2839
1300
  }
@@ -2844,8 +1305,8 @@ function extractBearerToken(authHeader) {
2844
1305
  }
2845
1306
 
2846
1307
  // src/auth/resolve-composition-sources.ts
2847
- import { ComponentManifestMap as ComponentManifestMap2 } from "@storybook/mcp";
2848
- import * as v7 from "valibot";
1308
+ import { ComponentManifestMap as ComponentManifestMap2 } from "storybook/internal/toolsets-docs";
1309
+ import * as v3 from "valibot";
2849
1310
 
2850
1311
  // src/auth/get-refs-from-config.ts
2851
1312
  async function getRefsFromConfig(options) {
@@ -2917,7 +1378,7 @@ async function hasServerlessComponentManifestSource(refUrl) {
2917
1378
  if (!response.ok)
2918
1379
  return !1;
2919
1380
  let text = await response.text();
2920
- return v7.safeParse(v7.pipe(v7.string(), v7.parseJson(), ComponentManifestMap2), text).success;
1381
+ return v3.safeParse(v3.pipe(v3.string(), v3.parseJson(), ComponentManifestMap2), text).success;
2921
1382
  } catch {
2922
1383
  return !1;
2923
1384
  } finally {
@@ -2929,32 +1390,39 @@ function hasOAuthResourceMetadataChallenge(response) {
2929
1390
  }
2930
1391
 
2931
1392
  // src/preset.ts
2932
- import { logger as logger8 } from "storybook/internal/node-logger";
1393
+ import { logger as logger7 } from "storybook/internal/node-logger";
2933
1394
 
2934
1395
  // src/storybook-ai-metadata.ts
2935
1396
  import { ValibotJsonSchemaAdapter as ValibotJsonSchemaAdapter2 } from "@tmcp/adapter-valibot";
2936
- import * as v8 from "valibot";
1397
+ import * as v4 from "valibot";
1398
+ import {
1399
+ getEffectiveToolAvailability as getEffectiveToolAvailability2,
1400
+ getToolAvailability as getToolAvailability2,
1401
+ isModuleGraphSupportedByBuilder
1402
+ } from "storybook/internal/core-server";
1403
+ import { buildServerInstructions as buildServerInstructions2 } from "storybook/internal/skills";
2937
1404
  var createEmptyInputSchema = () => ({ type: "object", properties: {} });
2938
1405
  async function buildStorybookAiMetadata(options, existingMetadata) {
2939
- let toolsets = v8.parse(AddonOptions, {
1406
+ let toolsets = v4.parse(AddonOptions, {
2940
1407
  endpoint: options.endpoint,
2941
1408
  toolsets: options.toolsets ?? {}
2942
- }).toolsets, features2 = await options.presets.apply("features", {}), devEnabled = toolsets?.dev ?? !0, moduleGraphSupported = await isModuleGraphSupportedByBuilder(options), rawAvailability = await getToolAvailability(options, {
1409
+ }).toolsets, features2 = await options.presets.apply("features", {}), devEnabled = toolsets?.dev ?? !0, moduleGraphSupported = await isModuleGraphSupportedByBuilder(options), rawAvailability = await getToolAvailability2(options, {
2943
1410
  features: features2,
2944
1411
  moduleGraphSupported
2945
1412
  }), availability = {
2946
1413
  ...rawAvailability,
2947
1414
  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 = {
1415
+ }, testSupported = (toolsets?.test ?? !0) && availability.testSupported, docsToolsetEnabled = toolsets?.docs ?? !0, multiSource = docsToolsetEnabled ? (await resolveServerlessCompositionSources(options)).multiSource : !1, registryAvailability = getEffectiveToolAvailability2(availability, { multiSource }), docsEnabled = docsToolsetEnabled && registryAvailability.docsEnabled, registryContext = { availability: registryAvailability, multiSource, toolsets }, toolMetadata = getAddonToolMetadata(registryContext), localTools = {
2949
1416
  ...existingMetadata?.localTools,
2950
1417
  ...getAddonLocalTools({ ...registryContext, options })
2951
1418
  };
2952
1419
  return {
2953
1420
  instructions: joinInstructions(
2954
1421
  existingMetadata?.instructions,
2955
- buildServerInstructions({
1422
+ buildServerInstructions2({
1423
+ transport: "mcp",
2956
1424
  devEnabled,
2957
- testEnabled,
1425
+ testSupported,
2958
1426
  docsEnabled,
2959
1427
  changeDetectionEnabled: availability.changeDetectionEnabled,
2960
1428
  moduleGraphSupported: availability.moduleGraphSupported,
@@ -3000,206 +1468,33 @@ function mergeToolDescriptors(...groups) {
3000
1468
  return [...toolsByName.values()];
3001
1469
  }
3002
1470
 
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
- } };
1471
+ // src/utils/get-story-index.ts
1472
+ import { logger as logger6 } from "storybook/internal/node-logger";
1473
+ async function getStoryIndex(options) {
1474
+ let generator = await options.presets.apply(
1475
+ "storyIndexGenerator"
1476
+ );
1477
+ if (!generator)
1478
+ throw new Error(
1479
+ "Storybook story index generator is unavailable. These MCP tools require a running Storybook dev server with a builder that exposes the story index."
1480
+ );
1481
+ let index = await generator.getIndex();
1482
+ return logger6.debug(`Story index entries found: ${Object.keys(index.entries).length}`), index;
3191
1483
  }
3192
1484
 
3193
1485
  // 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, {
1486
+ var previewAnnotations = async (existingAnnotations = []) => [...existingAnnotations, path.join(import.meta.dirname, "preview.js")], experimental_devServer = async (app, options) => {
1487
+ let addonOptions = v5.parse(AddonOptions, {
3196
1488
  endpoint: options.endpoint,
3197
1489
  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));
1490
+ }), origin2 = `http://localhost:${options.port}`, endpoint = addonOptions.endpoint ?? DEFAULT_MCP_ENDPOINT, { refs, compositionAuth, sources, multiSource } = await resolveCompositionSources(options), rawAvailability = await getToolAvailability3(options), localAccess = rawAvailability.docgenServer && refs.length > 0 ? createLocalDocsAccess({
1491
+ storyIndex: { getIndex: () => getStoryIndex(options) },
1492
+ getManifests: () => loadManifests(options.presets)
1493
+ }) : void 0, createManifestProvider;
1494
+ refs.length > 0 && (logger7.info(`Initialized composition with ${refs.length} remote Storybook(s)`), compositionAuth.requiresAuth && logger7.info(`Auth required for: ${compositionAuth.authUrls.join(", ")}`), logger7.info(`Sources: ${(sources ?? []).map((s) => s.id).join(", ")}`), createManifestProvider = () => compositionAuth.createManifestProvider(origin2));
3200
1495
  let manifestAccessFor = (req) => ({
3201
- manifestProvider: createManifestProvider ? createManifestProvider(req) : docgenServerAccess?.manifestProvider,
3202
- resolveEntry: docgenServerAccess?.resolveEntry
1496
+ manifestProvider: createManifestProvider?.(req),
1497
+ localAccess
3203
1498
  });
3204
1499
  app.get("/.well-known/oauth-protected-resource", (_req, res) => {
3205
1500
  let wellKnown = compositionAuth.buildWellKnown(origin2);
@@ -3239,7 +1534,7 @@ var previewAnnotations = async (existingAnnotations = []) => [...existingAnnotat
3239
1534
  docsFeatureEnabled,
3240
1535
  testSupported,
3241
1536
  a11yEnabled: a11yEnabled2
3242
- } = getEffectiveToolAvailability(rawAvailability, { multiSource }), isDevEnabled = addonOptions.toolsets?.dev ?? !0, isDocsEnabled = docsEnabled && (addonOptions.toolsets?.docs ?? !0), isTestEnabled = testSupported && (addonOptions.toolsets?.test ?? !0);
1537
+ } = getEffectiveToolAvailability3(rawAvailability, { multiSource }), isDevEnabled = addonOptions.toolsets?.dev ?? !0, isDocsEnabled = docsEnabled && (addonOptions.toolsets?.docs ?? !0), isTestEnabled = testSupported && (addonOptions.toolsets?.test ?? !0);
3243
1538
  return app.get(endpoint, (req, res) => {
3244
1539
  if (!req.headers.accept?.includes("text/html"))
3245
1540
  return requireAuth(req, res) ? void 0 : mcpServerHandler({
@@ -3257,16 +1552,20 @@ var previewAnnotations = async (existingAnnotations = []) => [...existingAnnotat
3257
1552
  docsHasManifests ? docsFeatureEnabled || (docsNotice = `<div class="toolset-notice">
3258
1553
  This toolset requires enabling the component manifest feature.
3259
1554
  <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.
1555
+ </div>`) : docsNotice = docsFeatureEnabled ? `<div class="toolset-notice">
1556
+ This toolset requires a components manifest, which your framework does not generate. On <code>@storybook/vue3-vite</code>, also enable <code>experimentalDocgenServer</code>.
1557
+ <a target="_blank" href="https://storybook.js.org/docs/ai/mcp/overview#framework-support">See which frameworks are supported</a>
1558
+ </div>` : `<div class="toolset-notice">
1559
+ This toolset requires a components manifest, which is generated by the React frameworks, <code>@storybook/angular-vite</code> and <code>@storybook/vue3-vite</code>. Enable the <code>componentsManifest</code> feature, plus <code>experimentalDocgenServer</code> on <code>@storybook/vue3-vite</code>.
1560
+ <a target="_blank" href="https://storybook.js.org/docs/ai/mcp/overview#framework-support">Learn how to enable it</a>
3262
1561
  </div>`;
3263
1562
  let testNoticeLines = [
3264
1563
  !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
1564
  !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
1565
  ].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>.")
1566
+ !moduleGraphSupported && "<code>stories-find-by-component</code> requires a dev server with a builder that supports the module graph (Vite or Webpack 5).",
1567
+ !changeDetectionEnabled && "<code>stories-changed</code> requires enabling the <code>changeDetection</code> feature flag.",
1568
+ !reviewEnabled && (reviewEnabledForCli ? "<code>review-create</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>review-create</code> requires the <code>changeDetection</code> feature flag and is off when <code>experimentalReview</code> is set to <code>false</code>.")
3270
1569
  ].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
1570
  "{{STORIES_BY_COMPONENT_STATUS}}",
3272
1571
  statusWord(isDevEnabled && moduleGraphSupported)