@storybook/addon-mcp 0.6.0 → 0.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +20 -0
- package/dist/preset.js +1981 -412
- package/dist/preview-stories-app-script.js +1 -1
- package/package.json +8 -8
package/dist/preset.js
CHANGED
|
@@ -1,21 +1,24 @@
|
|
|
1
1
|
import { McpServer } from "tmcp";
|
|
2
2
|
import { ValibotJsonSchemaAdapter } from "@tmcp/adapter-valibot";
|
|
3
3
|
import { HttpTransport } from "@tmcp/transport-http";
|
|
4
|
-
import
|
|
5
|
-
import * as v from "valibot";
|
|
4
|
+
import { buffer } from "node:stream/consumers";
|
|
6
5
|
import { logger } from "storybook/internal/node-logger";
|
|
7
6
|
import { telemetry } from "storybook/internal/telemetry";
|
|
8
|
-
import {
|
|
7
|
+
import { importModule, normalizeStoryPath } from "storybook/internal/common";
|
|
8
|
+
import * as v from "valibot";
|
|
9
9
|
import path from "node:path";
|
|
10
|
-
import { normalizeStoryPath } from "storybook/internal/common";
|
|
11
10
|
import { storyNameFromExport } from "storybook/internal/csf";
|
|
12
|
-
import { ComponentManifestMap, DocsManifestMap, GET_TOOL_NAME, LIST_TOOL_NAME, STORYBOOK_MCP_INSTRUCTIONS, addGetDocumentationTool, addGetStoryDocumentationTool, addListAllDocumentationTool } from "@storybook/mcp";
|
|
13
|
-
import
|
|
14
|
-
import {
|
|
11
|
+
import { ComponentManifestMap, DocsManifestMap, GET_STORY_TOOL_NAME, GET_TOOL_NAME, LIST_TOOL_NAME, STORYBOOK_MCP_INSTRUCTIONS, adaptCoreComponent, adaptCoreDoc, addGetDocumentationTool, addGetStoryDocumentationTool, addListAllDocumentationTool, getDocumentationToolMetadata, getListAllDocumentationToolMetadata, getStoryDocumentationToolMetadata } from "@storybook/mcp";
|
|
12
|
+
import { experimental_getStatusStore } from "storybook/internal/core-server";
|
|
13
|
+
import { execSync } from "node:child_process";
|
|
14
|
+
import fs from "node:fs";
|
|
15
|
+
import url from "node:url";
|
|
16
|
+
import { stringify } from "picoquery";
|
|
17
|
+
import fs$1 from "node:fs/promises";
|
|
15
18
|
|
|
16
19
|
//#region package.json
|
|
17
20
|
var name = "@storybook/addon-mcp";
|
|
18
|
-
var version = "0.
|
|
21
|
+
var version = "0.7.0";
|
|
19
22
|
var description = "Help agents automatically write and test stories for your UI components";
|
|
20
23
|
|
|
21
24
|
//#endregion
|
|
@@ -35,75 +38,120 @@ async function collectTelemetry({ event, server, ...payload }) {
|
|
|
35
38
|
}
|
|
36
39
|
|
|
37
40
|
//#endregion
|
|
38
|
-
//#region src/utils/
|
|
39
|
-
const HEX_REGEXP = /^#([a-f0-9]{3,4}|[a-f0-9]{6}|[a-f0-9]{8})$/i;
|
|
40
|
-
const COLOR_REGEXP = /^(rgba?|hsla?)\(([0-9]{1,3}),\s?([0-9]{1,3})%?,\s?([0-9]{1,3})%?,?\s?([0-9](\.[0-9]{1,2})?)?\)$/i;
|
|
41
|
+
//#region src/utils/module-graph.ts
|
|
41
42
|
/**
|
|
42
|
-
*
|
|
43
|
-
*
|
|
43
|
+
* Access helper for Storybook's `core/module-graph` open service — the reverse index from source
|
|
44
|
+
* files to the story files that (transitively) import them. Replaces the removed
|
|
45
|
+
* `experimental_getDependencyGraphService` compatibility API.
|
|
46
|
+
*
|
|
47
|
+
* Older Storybook versions don't ship the open-service runtime; we dynamically import and treat a
|
|
48
|
+
* missing `getService` export (or an unregistered service) as "unsupported".
|
|
49
|
+
*
|
|
50
|
+
* The generic open-service query type (`Query`) is imported from core. The
|
|
51
|
+
* module-graph-specific data shapes below (`ModuleGraphStatus`, `ModuleGraphStoryHit`, etc.) are
|
|
52
|
+
* baked into the service's runtime definition and aren't part of core's public type surface, so we
|
|
53
|
+
* mirror them here; keep them in sync with `core/module-graph` if it changes.
|
|
44
54
|
*/
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
if (
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
55
|
+
const MODULE_GRAPH_SERVICE_ID = "core/module-graph";
|
|
56
|
+
let probed;
|
|
57
|
+
async function probe() {
|
|
58
|
+
if (probed !== void 0) return probed;
|
|
59
|
+
try {
|
|
60
|
+
const fn = (await import("storybook/internal/core-server")).getService;
|
|
61
|
+
probed = typeof fn === "function" ? fn : null;
|
|
62
|
+
} catch {
|
|
63
|
+
probed = null;
|
|
52
64
|
}
|
|
53
|
-
|
|
54
|
-
if (value instanceof Date) return `!date(${value.toISOString()})`;
|
|
55
|
-
if (Array.isArray(value)) return value.map(encodeSpecialValues);
|
|
56
|
-
if (typeof value === "object" && value !== null) return Object.entries(value).reduce((acc, [key, val]) => Object.assign(acc, { [key]: encodeSpecialValues(val) }), {});
|
|
57
|
-
return value;
|
|
65
|
+
return probed;
|
|
58
66
|
}
|
|
59
67
|
/**
|
|
60
|
-
*
|
|
61
|
-
*
|
|
62
|
-
*
|
|
68
|
+
* True iff the `core/module-graph` service is actually resolvable — i.e. Storybook ships the
|
|
69
|
+
* open-service runtime AND the service is registered in this process. Reflects registration rather
|
|
70
|
+
* than mere runtime presence so tool gating/badging can't drift from {@link getModuleGraphService}
|
|
71
|
+
* (a builder may ship the runtime but not register the service, e.g. without change detection).
|
|
63
72
|
*/
|
|
64
|
-
function
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
73
|
+
async function isModuleGraphSupported() {
|
|
74
|
+
return await getModuleGraphService() !== void 0;
|
|
75
|
+
}
|
|
76
|
+
async function isModuleGraphSupportedByBuilder(options) {
|
|
77
|
+
const builder = (await options.presets.apply("core", {}))?.builder;
|
|
78
|
+
const builderName = typeof builder === "string" ? builder : builder?.name;
|
|
79
|
+
if (!builderName) return false;
|
|
80
|
+
try {
|
|
81
|
+
return typeof (await importModule(builderName)).changeDetectionAdapter === "function";
|
|
82
|
+
} catch {
|
|
83
|
+
return false;
|
|
71
84
|
}
|
|
72
|
-
return chr;
|
|
73
85
|
}
|
|
74
|
-
const KNOWN_QUERY_CHAR_REGEXP = /%[0-9A-F]{2}/g;
|
|
75
86
|
/**
|
|
76
|
-
*
|
|
77
|
-
*
|
|
78
|
-
*
|
|
79
|
-
*
|
|
80
|
-
*
|
|
81
|
-
* Example output: "disabled:!true;label:Hello+World;count:42"
|
|
87
|
+
* Resolves the `core/module-graph` runtime service, or `undefined` when Storybook doesn't ship the
|
|
88
|
+
* open-service API or the service isn't registered (e.g. a builder without change detection, or the
|
|
89
|
+
* dev server isn't running). A non-undefined result doesn't mean the graph is built — await
|
|
90
|
+
* `queries.status.loaded(undefined)` and check for the `ready` status.
|
|
82
91
|
*/
|
|
83
|
-
function
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
92
|
+
async function getModuleGraphService() {
|
|
93
|
+
const getService = await probe();
|
|
94
|
+
if (!getService) return void 0;
|
|
95
|
+
try {
|
|
96
|
+
return getService(MODULE_GRAPH_SERVICE_ID);
|
|
97
|
+
} catch {
|
|
98
|
+
return;
|
|
99
|
+
}
|
|
90
100
|
}
|
|
91
101
|
|
|
92
102
|
//#endregion
|
|
93
|
-
//#region src/utils/
|
|
103
|
+
//#region src/utils/is-review-available.ts
|
|
104
|
+
const getReviewStatus = async (options, { features } = {}) => {
|
|
105
|
+
const resolvedFeatures = features ?? await options.presets.apply("features", {});
|
|
106
|
+
const hasFeatureFlag = !!resolvedFeatures?.experimentalReview;
|
|
107
|
+
const changeDetection = !!resolvedFeatures?.changeDetection;
|
|
108
|
+
return {
|
|
109
|
+
available: hasFeatureFlag && changeDetection,
|
|
110
|
+
availableForCli: resolvedFeatures?.experimentalReview !== false && changeDetection,
|
|
111
|
+
hasFeatureFlag
|
|
112
|
+
};
|
|
113
|
+
};
|
|
114
|
+
|
|
115
|
+
//#endregion
|
|
116
|
+
//#region src/tools/is-manifest-available.ts
|
|
117
|
+
const hasComponentManifestFeature = (features) => !!(features?.componentsManifest ?? features?.experimentalComponentsManifest);
|
|
118
|
+
const isDocgenServerMode = (features) => !!(features?.experimentalDocgenServer && features?.componentsManifest);
|
|
119
|
+
const getManifestStatus = async (options) => {
|
|
120
|
+
const [features, manifests, legacyComponentManifestGenerator] = await Promise.all([
|
|
121
|
+
options.presets.apply("features"),
|
|
122
|
+
options.presets.apply("experimental_manifests", void 0, { manifestEntries: [] }),
|
|
123
|
+
options.presets.apply("experimental_componentManifestGenerator")
|
|
124
|
+
]);
|
|
125
|
+
const hasFeatureFlag = hasComponentManifestFeature(features);
|
|
126
|
+
const docgenServer = isDocgenServerMode(features);
|
|
127
|
+
const hasManifests = docgenServer || manifests && "components" in manifests || !!legacyComponentManifestGenerator;
|
|
128
|
+
return {
|
|
129
|
+
available: hasFeatureFlag && hasManifests,
|
|
130
|
+
hasManifests,
|
|
131
|
+
hasFeatureFlag,
|
|
132
|
+
docgenServer
|
|
133
|
+
};
|
|
134
|
+
};
|
|
135
|
+
|
|
136
|
+
//#endregion
|
|
137
|
+
//#region src/utils/get-story-index.ts
|
|
94
138
|
/**
|
|
95
|
-
*
|
|
139
|
+
* Resolves the Storybook story index in-process via the `storyIndexGenerator` preset, rather than
|
|
140
|
+
* fetching `/index.json` over loopback HTTP.
|
|
96
141
|
*
|
|
97
|
-
*
|
|
98
|
-
*
|
|
99
|
-
*
|
|
142
|
+
* The dev-server registers and memoises a single `StoryIndexGenerator` (see Storybook's
|
|
143
|
+
* `common-preset`); applying the preset here returns that same live instance, so `getIndex()`
|
|
144
|
+
* hands back the up-to-date, internally-cached index without a network round-trip. This also keeps
|
|
145
|
+
* the index in lock-step with HMR — the generator's watcher refreshes `lastIndex` as files change.
|
|
146
|
+
*
|
|
147
|
+
* @param options - The Storybook options object carrying the resolved presets.
|
|
148
|
+
* @returns A promise that resolves to the StoryIndex.
|
|
149
|
+
* @throws If the generator preset is unavailable (e.g. not running inside a dev server).
|
|
100
150
|
*/
|
|
101
|
-
async function
|
|
102
|
-
const
|
|
103
|
-
|
|
104
|
-
const
|
|
105
|
-
if (!response.ok) throw new Error(`Failed to fetch story index: ${response.status} ${response.statusText}`);
|
|
106
|
-
const index = await response.json();
|
|
151
|
+
async function getStoryIndex(options) {
|
|
152
|
+
const generator = await options.presets.apply("storyIndexGenerator");
|
|
153
|
+
if (!generator) throw new Error("Storybook story index generator is unavailable. These MCP tools require a running Storybook dev server with a builder that exposes the story index.");
|
|
154
|
+
const index = await generator.getIndex();
|
|
107
155
|
logger.debug(`Story index entries found: ${Object.keys(index.entries).length}`);
|
|
108
156
|
return index;
|
|
109
157
|
}
|
|
@@ -209,20 +257,34 @@ const errorToMCPContent = (error) => {
|
|
|
209
257
|
* Tool name constants extracted to avoid circular dependencies.
|
|
210
258
|
*/
|
|
211
259
|
const PREVIEW_STORIES_TOOL_NAME = "preview-stories";
|
|
260
|
+
const GET_CHANGED_STORIES_TOOL_NAME = "get-changed-stories";
|
|
261
|
+
const GET_STORIES_BY_COMPONENT_TOOL_NAME = "get-stories-by-component";
|
|
212
262
|
const GET_UI_BUILDING_INSTRUCTIONS_TOOL_NAME = "get-storybook-story-instructions";
|
|
213
263
|
const RUN_STORY_TESTS_TOOL_NAME = "run-story-tests";
|
|
264
|
+
const DISPLAY_REVIEW_TOOL_NAME = "display-review";
|
|
214
265
|
|
|
215
266
|
//#endregion
|
|
216
267
|
//#region src/types.ts
|
|
217
|
-
const
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
}
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
268
|
+
const isLiteralEndpointPathname = (endpoint) => {
|
|
269
|
+
try {
|
|
270
|
+
const { pathname } = new URL(endpoint, "http://storybook.local");
|
|
271
|
+
return pathname === endpoint && pathname !== "/";
|
|
272
|
+
} catch {
|
|
273
|
+
return false;
|
|
274
|
+
}
|
|
275
|
+
};
|
|
276
|
+
const AddonOptions = v.object({
|
|
277
|
+
endpoint: v.optional(v.pipe(v.string(), v.check(isLiteralEndpointPathname, "Endpoint must be a literal URL pathname"))),
|
|
278
|
+
toolsets: v.optional(v.object({
|
|
279
|
+
dev: v.exactOptional(v.boolean(), true),
|
|
280
|
+
docs: v.exactOptional(v.boolean(), true),
|
|
281
|
+
test: v.exactOptional(v.boolean(), true)
|
|
282
|
+
}), {
|
|
283
|
+
dev: true,
|
|
284
|
+
docs: true,
|
|
285
|
+
test: true
|
|
286
|
+
})
|
|
287
|
+
});
|
|
226
288
|
const StoryInputProps = {
|
|
227
289
|
props: v.pipe(v.optional(v.record(v.string(), v.any())), v.description(`Optional custom props to pass to the story for rendering. Use this when you don't want to render the default story,
|
|
228
290
|
but you want to customize some args or other props.
|
|
@@ -252,118 +314,6 @@ Use IDs discovered from ${LIST_TOOL_NAME} (withStoryIds=true) or ${GET_TOOL_NAME
|
|
|
252
314
|
*/
|
|
253
315
|
const StoryInputArray = v.array(StoryInput);
|
|
254
316
|
|
|
255
|
-
//#endregion
|
|
256
|
-
//#region src/tools/preview-stories/preview-stories-app-template.html
|
|
257
|
-
var preview_stories_app_template_default = "<!doctype html>\n<html>\n <head>\n <meta charset=\"utf-8\" />\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\" />\n <style>\n * {\n margin: 0;\n padding: 0;\n box-sizing: border-box;\n }\n html[data-theme='light'] {\n color-scheme: light;\n }\n html[data-theme='dark'] {\n color-scheme: dark;\n }\n html,\n body {\n width: 100%;\n margin: 0;\n padding: 0;\n background-color: var(--color-background-secondary);\n }\n body {\n display: flex;\n flex-direction: column;\n gap: 1rem;\n }\n :root {\n /*\n These are fallback values, if the MCP client doesn't set them.\n See https://github.com/modelcontextprotocol/ext-apps/blob/main/specification/draft/apps.mdx#theming\n */\n --color-text-primary: light-dark(black, white);\n --color-border-primary: light-dark(#ccc, #444);\n --color-background-secondary: light-dark(#f9f9f9, #1e1e1e);\n --font-sans:\n -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Oxygen-Sans', Ubuntu, Cantarell,\n 'Helvetica Neue', sans-serif;\n --font-heading-xs-size: 1rem;\n --font-heading-xs-line-height: 1.25;\n --border-width-regular: 1px;\n }\n .story-heading {\n font-family: var(--font-sans);\n font-size: var(--font-heading-xs-size);\n line-height: var(--font-heading-xs-line-height);\n color: var(--color-text-primary);\n padding: 0.5rem 0;\n }\n .story-iframe {\n background-color: white;\n border: var(--border-width-regular) solid var(--color-border-primary);\n }\n body:has(> article:only-child) h1 {\n /* if there is only one story rendered, hide its heading */\n display: none;\n }\n </style>\n <template id=\"preview-template\">\n <article>\n <h1 class=\"story-heading\"></h1>\n <iframe class=\"story-iframe\"></iframe>\n </article>\n </template>\n <script type=\"module\">\n // APP_SCRIPT_PLACEHOLDER\n <\/script>\n </head>\n <body></body>\n</html>\n";
|
|
258
|
-
|
|
259
|
-
//#endregion
|
|
260
|
-
//#region src/tools/preview-stories.ts
|
|
261
|
-
const PREVIEW_STORIES_RESOURCE_URI = `ui://${PREVIEW_STORIES_TOOL_NAME}/preview.html`;
|
|
262
|
-
const PreviewStoriesInput = v.object({ stories: v.pipe(StoryInputArray, v.description(`Stories to preview.
|
|
263
|
-
Prefer { storyId } when you don't already have story file context, since this avoids filesystem discovery.
|
|
264
|
-
Use { storyId } when IDs were discovered from documentation tools.
|
|
265
|
-
Use { absoluteStoryPath + exportName } only when you're already working in a specific .stories.* file and already have that context.`)) });
|
|
266
|
-
const PreviewStoriesOutput = v.object({ stories: v.array(v.union([v.object({
|
|
267
|
-
title: v.string(),
|
|
268
|
-
name: v.string(),
|
|
269
|
-
previewUrl: v.pipe(v.string(), v.description("Direct URL to open the story preview. Always include this URL in the final user-facing response so users can open it directly."))
|
|
270
|
-
}), v.object({
|
|
271
|
-
input: StoryInput,
|
|
272
|
-
error: v.string()
|
|
273
|
-
})])) });
|
|
274
|
-
async function addPreviewStoriesTool(server) {
|
|
275
|
-
const previewStoryAppScript = await fs.readFile(url.fileURLToPath(import.meta.resolve("@storybook/addon-mcp/internal/preview-stories-app-script")), "utf-8");
|
|
276
|
-
const appHtml = preview_stories_app_template_default.replace("// APP_SCRIPT_PLACEHOLDER", previewStoryAppScript);
|
|
277
|
-
server.resource({
|
|
278
|
-
name: PREVIEW_STORIES_RESOURCE_URI,
|
|
279
|
-
description: "App resource for the Preview Stories tool",
|
|
280
|
-
uri: PREVIEW_STORIES_RESOURCE_URI,
|
|
281
|
-
mimeType: "text/html;profile=mcp-app"
|
|
282
|
-
}, () => {
|
|
283
|
-
const origin = server.ctx.custom.origin;
|
|
284
|
-
return { contents: [{
|
|
285
|
-
uri: PREVIEW_STORIES_RESOURCE_URI,
|
|
286
|
-
mimeType: "text/html;profile=mcp-app",
|
|
287
|
-
text: appHtml,
|
|
288
|
-
_meta: { ui: {
|
|
289
|
-
prefersBorder: false,
|
|
290
|
-
domain: origin,
|
|
291
|
-
csp: {
|
|
292
|
-
connectDomains: [origin],
|
|
293
|
-
resourceDomains: [origin],
|
|
294
|
-
frameDomains: [origin],
|
|
295
|
-
baseUriDomains: [origin]
|
|
296
|
-
}
|
|
297
|
-
} }
|
|
298
|
-
}] };
|
|
299
|
-
});
|
|
300
|
-
server.tool({
|
|
301
|
-
name: PREVIEW_STORIES_TOOL_NAME,
|
|
302
|
-
title: "Get story preview URLs",
|
|
303
|
-
description: `Use this tool to get one or more Storybook preview URLs.
|
|
304
|
-
Always include each returned preview URL in your final user-facing response so users can open them directly.`,
|
|
305
|
-
schema: PreviewStoriesInput,
|
|
306
|
-
outputSchema: PreviewStoriesOutput,
|
|
307
|
-
enabled: () => server.ctx.custom?.toolsets?.dev ?? true,
|
|
308
|
-
_meta: { ui: { resourceUri: PREVIEW_STORIES_RESOURCE_URI } }
|
|
309
|
-
}, async (input) => {
|
|
310
|
-
try {
|
|
311
|
-
const { origin, disableTelemetry } = server.ctx.custom ?? {};
|
|
312
|
-
if (!origin) throw new Error("Origin is required in addon context");
|
|
313
|
-
const index = await fetchStoryIndex(origin);
|
|
314
|
-
const resolvedStories = findStoryIds(index, input.stories);
|
|
315
|
-
const structuredResult = [];
|
|
316
|
-
const textResult = [];
|
|
317
|
-
for (const story of resolvedStories) {
|
|
318
|
-
if ("errorMessage" in story) {
|
|
319
|
-
structuredResult.push({
|
|
320
|
-
input: story.input,
|
|
321
|
-
error: story.errorMessage
|
|
322
|
-
});
|
|
323
|
-
textResult.push(story.errorMessage);
|
|
324
|
-
continue;
|
|
325
|
-
}
|
|
326
|
-
const indexEntry = index.entries[story.id];
|
|
327
|
-
if (!indexEntry) {
|
|
328
|
-
structuredResult.push({
|
|
329
|
-
input: story.input,
|
|
330
|
-
error: `No story found for story ID "${story.id}"`
|
|
331
|
-
});
|
|
332
|
-
textResult.push(`No story found for story ID "${story.id}"`);
|
|
333
|
-
continue;
|
|
334
|
-
}
|
|
335
|
-
let previewUrl = `${origin}/?path=/story/${story.id}`;
|
|
336
|
-
const argsParam = buildArgsParam(story.input.props ?? {});
|
|
337
|
-
if (argsParam) previewUrl += `&args=${argsParam}`;
|
|
338
|
-
const globalsParam = buildArgsParam(story.input.globals ?? {});
|
|
339
|
-
if (globalsParam) previewUrl += `&globals=${globalsParam}`;
|
|
340
|
-
structuredResult.push({
|
|
341
|
-
title: indexEntry.title,
|
|
342
|
-
name: indexEntry.name,
|
|
343
|
-
previewUrl
|
|
344
|
-
});
|
|
345
|
-
textResult.push(previewUrl);
|
|
346
|
-
}
|
|
347
|
-
if (!disableTelemetry) await collectTelemetry({
|
|
348
|
-
event: "tool:previewStories",
|
|
349
|
-
server,
|
|
350
|
-
toolset: "dev",
|
|
351
|
-
inputStoryCount: input.stories.length,
|
|
352
|
-
outputStoryCount: structuredResult.length
|
|
353
|
-
});
|
|
354
|
-
return {
|
|
355
|
-
content: textResult.map((text) => ({
|
|
356
|
-
type: "text",
|
|
357
|
-
text
|
|
358
|
-
})),
|
|
359
|
-
structuredContent: { stories: structuredResult }
|
|
360
|
-
};
|
|
361
|
-
} catch (error) {
|
|
362
|
-
return errorToMCPContent(error);
|
|
363
|
-
}
|
|
364
|
-
});
|
|
365
|
-
}
|
|
366
|
-
|
|
367
317
|
//#endregion
|
|
368
318
|
//#region src/tools/run-story-tests.ts
|
|
369
319
|
/**
|
|
@@ -390,6 +340,23 @@ Use { storyId } when IDs were discovered from documentation tools.
|
|
|
390
340
|
Use { absoluteStoryPath + exportName } only when you're currently working in a story file and already know those values.`))),
|
|
391
341
|
a11y: v.optional(v.pipe(v.boolean(), v.description("Whether to run accessibility tests. Defaults to true. Disable if you only need component test results.")), true)
|
|
392
342
|
});
|
|
343
|
+
function getRunStoryTestsToolDescription(a11yEnabled) {
|
|
344
|
+
return `Run story tests.
|
|
345
|
+
Run them after editing anything that changes how the UI looks — components, stories, styles, CSS, themes, colors, or design tokens — shell-level substitutes like typecheck, lint, or package.json test scripts do not replace this.
|
|
346
|
+
Provide stories for focused runs (faster while iterating),
|
|
347
|
+
or omit stories to run all tests for full-project verification.
|
|
348
|
+
Use this continuously to monitor test results as you work on your UI components and stories.
|
|
349
|
+
Results will include passing/failing status` + (a11yEnabled ? `, and accessibility violation reports.
|
|
350
|
+
For visual/design accessibility violations (for example color contrast), ask the user before changing styles.` : ".");
|
|
351
|
+
}
|
|
352
|
+
function getRunStoryTestsToolMetadata({ a11yEnabled }) {
|
|
353
|
+
return {
|
|
354
|
+
name: RUN_STORY_TESTS_TOOL_NAME,
|
|
355
|
+
title: "Storybook Tests",
|
|
356
|
+
description: getRunStoryTestsToolDescription(a11yEnabled),
|
|
357
|
+
schema: RunStoryTestsInput
|
|
358
|
+
};
|
|
359
|
+
}
|
|
393
360
|
/**
|
|
394
361
|
* Creates a queue that ensures concurrent calls are executed in sequence.
|
|
395
362
|
* Call `wait()` to wait for your turn, then call the
|
|
@@ -413,23 +380,14 @@ function createAsyncQueue() {
|
|
|
413
380
|
}
|
|
414
381
|
return { wait };
|
|
415
382
|
}
|
|
416
|
-
async function addRunStoryTestsTool(server, { a11yEnabled }) {
|
|
383
|
+
async function addRunStoryTestsTool(server, { a11yEnabled }, enabled = () => server.ctx.custom?.toolsets?.test ?? true) {
|
|
417
384
|
const addonVitestConstants = await getAddonVitestConstants();
|
|
418
385
|
const testRunQueue = createAsyncQueue();
|
|
419
|
-
const description = `Run story tests.
|
|
420
|
-
Provide stories for focused runs (faster while iterating),
|
|
421
|
-
or omit stories to run all tests for full-project verification.
|
|
422
|
-
Use this continuously to monitor test results as you work on your UI components and stories.
|
|
423
|
-
Results will include passing/failing status` + (a11yEnabled ? `, and accessibility violation reports.
|
|
424
|
-
For visual/design accessibility violations (for example color contrast), ask the user before changing styles.` : ".");
|
|
425
386
|
server.tool({
|
|
426
|
-
|
|
427
|
-
title: "Storybook Tests",
|
|
428
|
-
description,
|
|
429
|
-
schema: RunStoryTestsInput,
|
|
387
|
+
...getRunStoryTestsToolMetadata({ a11yEnabled }),
|
|
430
388
|
enabled: () => {
|
|
431
389
|
if (!addonVitestConstants) return false;
|
|
432
|
-
return
|
|
390
|
+
return typeof enabled === "function" ? enabled() : enabled;
|
|
433
391
|
}
|
|
434
392
|
}, async (input) => {
|
|
435
393
|
let done;
|
|
@@ -444,7 +402,7 @@ For visual/design accessibility violations (for example color contrast), ask the
|
|
|
444
402
|
let storyIds;
|
|
445
403
|
let inputStoryCount = 0;
|
|
446
404
|
if (input.stories) {
|
|
447
|
-
const resolvedStories = findStoryIds(await
|
|
405
|
+
const resolvedStories = findStoryIds(await getStoryIndex(options), input.stories);
|
|
448
406
|
storyIds = resolvedStories.filter((story) => "id" in story).map((story) => story.id);
|
|
449
407
|
inputStoryCount = input.stories.length;
|
|
450
408
|
if (storyIds.length === 0) {
|
|
@@ -656,18 +614,6 @@ function getA11yViolations(report) {
|
|
|
656
614
|
}));
|
|
657
615
|
}
|
|
658
616
|
|
|
659
|
-
//#endregion
|
|
660
|
-
//#region src/instructions/storybook-story-instructions.md
|
|
661
|
-
var storybook_story_instructions_default = "# Writing User Interfaces\n\nWhen writing UI, prefer breaking larger components up into smaller parts.\n\nALWAYS write a Storybook story for any component written. If editing a component, ensure appropriate changes have been made to stories for that component.\n\n## How to write good stories\n\nGoal: Cover every distinct piece of business logic and state the component can reach (happy paths, error/edge states, loading, permissions/roles, empty states, variations from props/context). Avoid redundant stories that show the same logic.\n\nInteractivity: If the component is interactive, add Interaction tests using play functions that drive the UI with storybook/test utilities (e.g., fn, userEvent, expect). Simulate key user flows: clicking buttons/links, typing, focus/blur, keyboard nav, form submit, async responses, toggle/selection changes, pagination/filters, etc. When passing `fn` functions as `args` for callback functions, make sure to add a play function which interacts with the component and assert whether the callback function was actually called.\n\nData/setup: Provide realistic props, state, and mocked data. Include meaningful labels/text to make behaviors observable. Stub network/services with deterministic fixtures; keep stories reliable.\n\nAssertions: In play functions, assert the visible outcome of the interaction (text, aria state, enabled/disabled, class/state changes, emitted events). Prefer role/label-based queries.\n\nVariants to consider (pick only those that change behavior): default vs. alternate themes; loading vs. loaded vs. empty vs. error; validated vs. invalid input; permissions/roles/capabilities; feature flags; size/density/layout variants that alter logic.\n\nAccessibility: Use semantic roles/labels; ensure focusable/keyboard interactions are test-covered where relevant.\n\nNaming/structure: Use clear story names that describe the scenario (“Error state after failed submit”). Group related variants logically; don’t duplicate.\n\nImports/format: Import Meta/StoryObj from the framework package; import test helpers from storybook/test (not @storybook/test). Keep stories minimal—only what's needed to demonstrate behavior.\n\n## Storybook 9 Essential Changes for Story Writing\n\n### Package Consolidation\n\n#### `Meta` and `StoryObj` imports\n\nUpdate story imports to use the framework package:\n\n```diff\n- import { Meta, StoryObj } from '{{RENDERER}}';\n+ import { Meta, StoryObj } from '{{FRAMEWORK}}';\n```\n\n#### Test utility imports\n\nUpdate test imports to use `storybook/test` instead of `@storybook/test`\n\n```diff\n- import { fn } from '@storybook/test';\n+ import { fn } from 'storybook/test';\n```\n\n### Global State Changes\n\nThe `globals` annotation has be renamed to `initialGlobals`:\n\n```diff\n// .storybook/preview.js\nexport default {\n- globals: { theme: 'light' }\n+ initialGlobals: { theme: 'light' }\n};\n```\n\n### Autodocs Configuration\n\nInstead of `parameters.docs.autodocs` in main.js, use tags:\n\n```js\n// .storybook/preview.js or in individual stories\nexport default {\n tags: ['autodocs'], // generates autodocs for all stories\n};\n```\n\n### Mocking imports in Storybook\n\nTo mock imports in Storybook, use Storybook's mocking features. ALWAYS mock external dependencies to ensure stories render consistently.\n\n1. **Register in the mock in Storybook's preview file**:\n To mock dependendencies, you MUST register a module mock in `.storybook/preview.ts` (or equivalent):\n\n```js\nimport { sb } from 'storybook/test';\n\n// Prefer spy mocks (keeps functions, but allows to override them and spy on them)\nsb.mock(import('some-library'), { spy: true });\n```\n\n**Important: Use file extensions when referring to relative files!**\n\n```js\nsb.mock(import('./relative/module.ts'), { spy: true });\n```\n\n2. **Specify mock values in stories**:\n You can override the behaviour of the mocks per-story using `beforeEach` and the `mocked()` type function:\n\n```js\nimport { expect, mocked, fn } from 'storybook/test';\nimport { library } from 'some-library';\n\nconst meta = {\n component: AuthButton,\n beforeEach: async () => {\n mocked(library).mockResolvedValue({ user: 'data' });\n },\n};\n\nexport const LoggedIn: Story = {\n play: async ({ canvas }) => {\n await expect(library).toHaveBeenCalled();\n },\n};\n```\n\nBefore doing this ensure you have mocked the import in the preview file.\n\n### Play Function Parameters\n\n- The play function has a `canvas` parameter that can be used directly with testing-library-like query methods.\n- It also has a `canvasElement` which is the actual DOM element.\n- The `within`-function imported from `storybook/test` transforms a DOM element to an object with query methods, similar to `canvas`.\n\n**DO NOT** use `within(canvas)` - it is redundant because `canvas` already has the query methods, `canvas` is not a DOM element.\n\n```ts\n// ✅ Correct: Use canvas directly\nplay: async ({ canvas }) => {\n await canvas.getByLabelText('Submit').click();\n};\n\n// ⚠️ Also acceptable: Use `canvasElement` with `within`\nimport { within } from 'storybook/test';\n\nplay: async ({ canvasElement }) => {\n const canvas = within(canvasElement);\n await canvas.getByLabelText('Submit').click();\n};\n\n// ❌ Wrong: Do NOT use within(canvas)\nplay: async ({ canvas }) => {\n const screen = within(canvas); // Error!\n};\n```\n\n### Key Requirements\n\n- **Node.js 20+**, **TypeScript 4.9+**\n- React Native uses `.rnstorybook` directory\n\n## Story Linking Agent Behavior\n\n- ALWAYS provide story links after any changes to stories files, including changes to existing stories.\n- After changing any UI components, ALWAYS search for related stories that might cover the changes you've made. If you find any, provide the story links to the user. THIS IS VERY IMPORTANT, as it allows the user to visually inspect the changes you've made. Even later in a session when changing UI components or stories that have already been linked to previously, YOU MUST PROVIDE THE LINKS AGAIN.\n- Use the {{PREVIEW_STORIES_TOOL_NAME}} tool to get the correct URLs for links to stories.\n";
|
|
662
|
-
|
|
663
|
-
//#endregion
|
|
664
|
-
//#region src/instructions/story-testing-instructions.md
|
|
665
|
-
var story_testing_instructions_default = "## Story Testing Requirements\n\n**Run `{{RUN_STORY_TESTS_TOOL_NAME}}` after EVERY component or story change.** This includes creating, modifying, or refactoring components, stories, or their dependencies.\n\n### Workflow\n\n1. Make your change\n2. Run `{{RUN_STORY_TESTS_TOOL_NAME}}` with affected stories for focused feedback (faster while iterating)\n3. If tests fail: analyze, fix{{A11Y_FIX_SUFFIX}}, re-run\n4. Repeat until all tests pass\n\nDo not skip tests, ignore failures, or move on with failing tests. If stuck after multiple attempts, report to user.\n\n### Focused vs. full-suite test runs\n\n- Prefer focused runs (`stories` input) during development to validate the parts you changed quickly.\n- Run all tests (omit `stories`) before final handoff, after broad/refactor changes, or when impact is unclear and you need project-wide verification.\n";
|
|
666
|
-
|
|
667
|
-
//#endregion
|
|
668
|
-
//#region src/instructions/a11y-instructions.md
|
|
669
|
-
var a11y_instructions_default = "### Accessibility Violations\n\n**Fix automatically** (semantic/structural, no visual change):\n\n- ARIA attributes, roles, labels, alt text\n- Heading hierarchy, landmarks, table structure\n- Keyboard access (tabindex, focus, handlers)\n- Document-level: lang attr, frame titles, duplicate IDs\n\n**Confirm with user first** (visual/design changes):\n\n- Color contrast ratios\n- Font sizes, spacing, layout\n- Focus indicator styling\n\nDescribe the issue, ask how the user wants to proceed, and provide 2-3 concrete options.\nDo not auto-apply visual changes before user confirmation, and do not claim visual issues are fixed until they approve an option.\n";
|
|
670
|
-
|
|
671
617
|
//#endregion
|
|
672
618
|
//#region src/utils/is-addon-a11y-enabled.ts
|
|
673
619
|
/**
|
|
@@ -682,39 +628,983 @@ async function isAddonA11yEnabled(options) {
|
|
|
682
628
|
}
|
|
683
629
|
|
|
684
630
|
//#endregion
|
|
685
|
-
//#region src/
|
|
686
|
-
|
|
687
|
-
|
|
688
|
-
|
|
689
|
-
|
|
690
|
-
|
|
691
|
-
|
|
692
|
-
|
|
693
|
-
|
|
694
|
-
|
|
695
|
-
|
|
696
|
-
|
|
697
|
-
|
|
698
|
-
|
|
699
|
-
|
|
700
|
-
|
|
701
|
-
|
|
702
|
-
|
|
703
|
-
|
|
631
|
+
//#region src/utils/get-tool-availability.ts
|
|
632
|
+
/**
|
|
633
|
+
* Composed Storybooks with component manifests can back docs tools even when the
|
|
634
|
+
* local Storybook has no component manifest. Use this before feeding
|
|
635
|
+
* availability into the shared tool registry so live MCP registration and
|
|
636
|
+
* serverless AI metadata make the same docs-tool decision.
|
|
637
|
+
*/
|
|
638
|
+
function getEffectiveToolAvailability(availability, { multiSource = false } = {}) {
|
|
639
|
+
if (!multiSource) return availability;
|
|
640
|
+
return {
|
|
641
|
+
...availability,
|
|
642
|
+
docsEnabled: true,
|
|
643
|
+
docsHasManifests: true,
|
|
644
|
+
docsFeatureEnabled: true
|
|
645
|
+
};
|
|
646
|
+
}
|
|
647
|
+
/**
|
|
648
|
+
* Single source of truth for the runtime gates that decide whether each tool is
|
|
649
|
+
* registered (and how the landing page badges it).
|
|
650
|
+
*
|
|
651
|
+
* Every dynamic gate lives here — the dependency graph, the change-detection
|
|
652
|
+
* pipeline, review, the component manifest (docs), addon-vitest (test) and the
|
|
653
|
+
* accessibility sub-feature — so the MCP server (which registers the tools) and
|
|
654
|
+
* the browser landing page (which shows enabled/disabled badges) can never drift
|
|
655
|
+
* apart. Add new gates here rather than computing them ad-hoc at a call site.
|
|
656
|
+
*/
|
|
657
|
+
async function getToolAvailability(options, { features, moduleGraphSupported: moduleGraphSupportedOverride } = {}) {
|
|
658
|
+
const resolvedFeatures = features ?? await options.presets.apply("features", {});
|
|
659
|
+
const [moduleGraphSupported, reviewStatus, manifestStatus, addonVitestConstants, a11yEnabled] = await Promise.all([
|
|
660
|
+
moduleGraphSupportedOverride ?? isModuleGraphSupported(),
|
|
661
|
+
getReviewStatus(options, { features: resolvedFeatures }),
|
|
662
|
+
getManifestStatus(options),
|
|
663
|
+
getAddonVitestConstants(),
|
|
664
|
+
isAddonA11yEnabled(options)
|
|
665
|
+
]);
|
|
666
|
+
return {
|
|
667
|
+
moduleGraphSupported,
|
|
668
|
+
changeDetectionEnabled: resolvedFeatures?.changeDetection ?? false,
|
|
669
|
+
reviewEnabled: reviewStatus.available,
|
|
670
|
+
reviewEnabledForCli: reviewStatus.availableForCli,
|
|
671
|
+
docsEnabled: manifestStatus.available,
|
|
672
|
+
docsHasManifests: manifestStatus.hasManifests,
|
|
673
|
+
docsFeatureEnabled: manifestStatus.hasFeatureFlag,
|
|
674
|
+
testSupported: !!addonVitestConstants,
|
|
675
|
+
a11yEnabled,
|
|
676
|
+
docgenServer: manifestStatus.docgenServer
|
|
677
|
+
};
|
|
678
|
+
}
|
|
704
679
|
|
|
705
|
-
|
|
706
|
-
-
|
|
707
|
-
|
|
708
|
-
|
|
709
|
-
|
|
710
|
-
|
|
711
|
-
|
|
712
|
-
|
|
713
|
-
|
|
680
|
+
//#endregion
|
|
681
|
+
//#region src/utils/estimate-tokens.ts
|
|
682
|
+
/**
|
|
683
|
+
* Checks if a character code is whitespace (space, tab, newline, carriage return)
|
|
684
|
+
*
|
|
685
|
+
* Checking char codes is slightly faster than using regex or string methods.
|
|
686
|
+
*/
|
|
687
|
+
function isWhitespace(code) {
|
|
688
|
+
return code === 32 || code === 9 || code === 10 || code === 13;
|
|
689
|
+
}
|
|
690
|
+
/**
|
|
691
|
+
* Checks if a character code is alphanumeric or underscore
|
|
692
|
+
* 0-9 (48-57), A-Z (65-90), a-z (97-122), underscore (95)
|
|
693
|
+
*
|
|
694
|
+
* Checking char codes is slightly faster than using regex or string methods.
|
|
695
|
+
*/
|
|
696
|
+
function isAlphanumeric(code) {
|
|
697
|
+
return code >= 48 && code <= 57 || code >= 65 && code <= 90 || code >= 97 && code <= 122 || code === 95;
|
|
698
|
+
}
|
|
699
|
+
/**
|
|
700
|
+
* Estimates token count from text using a fast approximation.
|
|
701
|
+
* Counts:
|
|
702
|
+
* - Continuous whitespace as a single token
|
|
703
|
+
* - Continuous alphanumeric sequences as single tokens
|
|
704
|
+
* - Each special character as an individual token
|
|
705
|
+
*
|
|
706
|
+
* This is a cheap approximation suitable for telemetry purposes.
|
|
707
|
+
*
|
|
708
|
+
* @param text - The text to estimate token count for
|
|
709
|
+
* @returns Estimated token count
|
|
710
|
+
*/
|
|
711
|
+
function estimateTokens(text) {
|
|
712
|
+
if (!text) return 0;
|
|
713
|
+
let tokenCount = 0;
|
|
714
|
+
let i = 0;
|
|
715
|
+
const len = text.length;
|
|
716
|
+
while (i < len) {
|
|
717
|
+
const code = text.charCodeAt(i);
|
|
718
|
+
if (isWhitespace(code)) {
|
|
719
|
+
tokenCount++;
|
|
720
|
+
i++;
|
|
721
|
+
while (i < len && isWhitespace(text.charCodeAt(i))) i++;
|
|
722
|
+
} else if (isAlphanumeric(code)) {
|
|
723
|
+
tokenCount++;
|
|
724
|
+
i++;
|
|
725
|
+
while (i < len && isAlphanumeric(text.charCodeAt(i))) i++;
|
|
726
|
+
} else {
|
|
727
|
+
tokenCount++;
|
|
728
|
+
i++;
|
|
729
|
+
}
|
|
730
|
+
}
|
|
731
|
+
return tokenCount;
|
|
732
|
+
}
|
|
733
|
+
|
|
734
|
+
//#endregion
|
|
735
|
+
//#region src/instructions/dev-instructions.md
|
|
736
|
+
var dev_instructions_default = "## UI Building and Story Writing Workflow\n\n- 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.\n- {{PREVIEW_STORIES_STEP}}\n- {{FINAL_LINKS_STEP}}{{DISPLAY_REVIEW_STEP}}\n- Only use story IDs returned by tools — 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 — say so.\n";
|
|
737
|
+
|
|
738
|
+
//#endregion
|
|
739
|
+
//#region src/instructions/legacy-dev-instructions.md
|
|
740
|
+
var legacy_dev_instructions_default = "## UI Building and Story Writing Workflow\n\n- Before creating or editing components or stories, call **get-storybook-story-instructions**.\n- Treat its output as the source of truth for imports, story patterns, and testing conventions.\n- After editing anything that changes how the UI looks — components, stories, styles, themes, colors, design tokens — call **preview-stories**, no exceptions; a shared file has no stories of its own, so preview its consumers' stories.\n- Include every returned preview URL in your final response.\n";
|
|
741
|
+
|
|
742
|
+
//#endregion
|
|
743
|
+
//#region src/instructions/legacy-test-instructions.md
|
|
744
|
+
var legacy_test_instructions_default = "## Validation Workflow\n\n- After editing anything that changes how the UI looks, run **run-story-tests** — never a package.json test script.\n- Use focused runs while iterating, then a broad pass before handoff when scope is unclear or wide.\n- Fix failing tests; never report completion while they are failing.\n";
|
|
745
|
+
|
|
746
|
+
//#endregion
|
|
747
|
+
//#region src/instructions/review-docs-instructions.md
|
|
748
|
+
var review_docs_instructions_default = "## Documentation Workflow\n\n**CRITICAL: Never hallucinate component properties!** Undocumented props do not exist — never assume them from naming or other libraries; verify every prop via these tools, not source or types in node_modules.\n\n1. Call **list-all-documentation** once at task start for component and docs IDs.\n2. Call **get-documentation** with an `id` from that list for props and usage examples.\n\nOnly reference IDs returned by these tools — never guess; scope multi-source requests with `storybookId`.\n";
|
|
749
|
+
|
|
750
|
+
//#endregion
|
|
751
|
+
//#region src/instructions/test-instructions.md
|
|
752
|
+
var test_instructions_default = "## Validation Workflow\n\n- After editing anything that changes how the UI looks, run **run-story-tests** — never a package.json test script.\n- Never report completion while story tests are failing.\n";
|
|
753
|
+
|
|
754
|
+
//#endregion
|
|
755
|
+
//#region src/instructions/build-server-instructions.ts
|
|
756
|
+
/**
|
|
757
|
+
* The full rule for how the agent should present links in its final
|
|
758
|
+
* user-facing response, delivered through the
|
|
759
|
+
* `get-storybook-story-instructions` output. The server instructions only
|
|
760
|
+
* carry a terse pointer to the same rule: MCP clients truncate server
|
|
761
|
+
* instructions (Claude Code cuts them at 2,048 chars), so anything beyond
|
|
762
|
+
* the workflow trigger must live in tool descriptions and tool results.
|
|
763
|
+
*
|
|
764
|
+
* Keyed on whether `display-review` is available in this Storybook setup.
|
|
765
|
+
* When available, the guidance covers both paths: ending with a review section
|
|
766
|
+
* after publishing, or falling back to preview URLs when no review was published
|
|
767
|
+
* (e.g. non-visual refactors).
|
|
768
|
+
*/
|
|
769
|
+
function getFinalLinksGuidance(reviewToolAvailable) {
|
|
770
|
+
return reviewToolAvailable ? "In your final user-facing response, show one set of links — 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 `## 👀 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 👉 so it is easy to spot, using the returned `reviewUrl` (for example `👉 [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 — 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 — 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).";
|
|
771
|
+
}
|
|
772
|
+
function buildServerInstructions(options) {
|
|
773
|
+
const sections = [options.docsEnabled ? "Follow these workflows when working with UI and/or Storybook. Answer questions about component props, API, or usage with the documentation tools — never from source or type definitions." : "Follow these workflows when working with UI and/or Storybook."];
|
|
774
|
+
const reviewEnabled = options.reviewEnabled ?? false;
|
|
775
|
+
if (options.devEnabled && !reviewEnabled) sections.push(legacy_dev_instructions_default.trim());
|
|
776
|
+
else if (options.devEnabled) {
|
|
777
|
+
const changeDetection = options.changeDetectionEnabled ?? false;
|
|
778
|
+
const graphSupported = options.moduleGraphSupported ?? false;
|
|
779
|
+
const previewStoriesStep = changeDetection ? "After editing anything that changes how the UI looks — components, stories, styles, themes, tokens — 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.";
|
|
780
|
+
sections.push(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 — never substitute preview URLs. **preview-stories** is only for mid-loop iteration or a requested direct link. If nothing visually changed, say so.").replace("{{DISPLAY_REVIEW_STEP}}", "\n- 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.").trim());
|
|
781
|
+
}
|
|
782
|
+
if (options.testEnabled) sections.push((reviewEnabled ? test_instructions_default : legacy_test_instructions_default).trim());
|
|
783
|
+
if (options.docsEnabled) sections.push((reviewEnabled ? review_docs_instructions_default : STORYBOOK_MCP_INSTRUCTIONS).trim());
|
|
784
|
+
if (sections.length === 1) return "";
|
|
785
|
+
return sections.join("\n\n");
|
|
786
|
+
}
|
|
787
|
+
|
|
788
|
+
//#endregion
|
|
789
|
+
//#region src/constants.ts
|
|
790
|
+
/**
|
|
791
|
+
* Channel event shared with Storybook core's review subsystem
|
|
792
|
+
* Emitted by the `display-review` tool to hand the agent's payload off to the
|
|
793
|
+
* core-server review channel.
|
|
794
|
+
*/
|
|
795
|
+
const PUSH_REVIEW_EVENT = "storybook/review/push-review";
|
|
796
|
+
/** Storybook manager route the review page is registered at. */
|
|
797
|
+
const REVIEW_PAGE_PATH = "/review/";
|
|
798
|
+
/**
|
|
799
|
+
* Request header the `storybook ai` CLI (and the Claude/Codex plugins built on
|
|
800
|
+
* it) sends on every MCP request to mark itself as a trusted local Storybook
|
|
801
|
+
* client. Mirrors `STORYBOOK_MCP_PROXY_HEADER` in Storybook core's
|
|
802
|
+
* `cli/ai/mcp/client.ts` — the two must stay in sync.
|
|
803
|
+
*/
|
|
804
|
+
const STORYBOOK_MCP_PROXY_HEADER = "X-Storybook-MCP-Proxy";
|
|
805
|
+
/**
|
|
806
|
+
* Default path the MCP server is mounted at on the Storybook dev server.
|
|
807
|
+
* The user can override this via the addon's `endpoint` option; everywhere
|
|
808
|
+
* else in the codebase that needs to compare against or fall back to the
|
|
809
|
+
* default should import this constant rather than hard-coding `'/mcp'`.
|
|
810
|
+
*/
|
|
811
|
+
const DEFAULT_MCP_ENDPOINT = "/mcp";
|
|
812
|
+
|
|
813
|
+
//#endregion
|
|
814
|
+
//#region src/utils/format-validation-issues.ts
|
|
815
|
+
function formatPath(path) {
|
|
816
|
+
if (!path || path.length === 0) return "";
|
|
817
|
+
let out = "";
|
|
818
|
+
for (const segment of path) {
|
|
819
|
+
const key = typeof segment === "object" && segment !== null && "key" in segment ? segment.key : segment;
|
|
820
|
+
if (typeof key === "number") out += `[${key}]`;
|
|
821
|
+
else if (key !== void 0 && key !== null) out += out === "" ? String(key) : `.${String(key)}`;
|
|
822
|
+
}
|
|
823
|
+
return out;
|
|
824
|
+
}
|
|
825
|
+
function summarizeIssue(issue) {
|
|
826
|
+
const path = formatPath(issue.path);
|
|
827
|
+
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") {
|
|
828
|
+
const field = issue.expected.slice(1, -1);
|
|
829
|
+
const parentPathStr = formatPath((issue.path ?? []).slice(0, -1));
|
|
830
|
+
return {
|
|
831
|
+
path,
|
|
832
|
+
message: `Missing required field \`${field}\`${parentPathStr ? ` at \`${parentPathStr}\`` : ""}.`
|
|
833
|
+
};
|
|
834
|
+
}
|
|
835
|
+
return {
|
|
836
|
+
path,
|
|
837
|
+
message: issue.message
|
|
838
|
+
};
|
|
839
|
+
}
|
|
840
|
+
/**
|
|
841
|
+
* Wrap a standard-schema validator so that validation failures contain
|
|
842
|
+
* trimmed, agent-readable issue objects instead of raw valibot metadata.
|
|
843
|
+
*
|
|
844
|
+
* Successful inputs pass through unchanged (we don't touch the parsed value).
|
|
845
|
+
*
|
|
846
|
+
* Standard Schema validators are POJOs by convention (data fields + a
|
|
847
|
+
* `~standard` slot, no prototype methods), so spread-and-replace is enough
|
|
848
|
+
* — no Proxy required.
|
|
849
|
+
*/
|
|
850
|
+
function withFriendlyErrors(schema) {
|
|
851
|
+
const original = schema["~standard"];
|
|
852
|
+
return {
|
|
853
|
+
...schema,
|
|
854
|
+
"~standard": {
|
|
855
|
+
...original,
|
|
856
|
+
validate(input) {
|
|
857
|
+
const result = original.validate(input);
|
|
858
|
+
const trim = (r) => r.issues ? { issues: r.issues.map(summarizeIssue) } : r;
|
|
859
|
+
return result instanceof Promise ? result.then(trim) : trim(result);
|
|
860
|
+
}
|
|
861
|
+
}
|
|
862
|
+
};
|
|
863
|
+
}
|
|
864
|
+
|
|
865
|
+
//#endregion
|
|
866
|
+
//#region src/tools/display-review.ts
|
|
867
|
+
const 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 — call it again whenever the user iterates on the changes.
|
|
868
|
+
|
|
869
|
+
## When to call
|
|
870
|
+
- **Trigger 1 — visual change** (components, stories, CSS, themes, colors, design tokens, i18n — 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 — 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\`.
|
|
871
|
+
- **Trigger 2 — 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: []\` — no code changed.
|
|
872
|
+
|
|
873
|
+
## Hard rules
|
|
874
|
+
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.
|
|
875
|
+
2. Every story you CREATED in this change MUST appear in the review — including interaction/play-function stories. Showing the stories you modified is encouraged too. Curate by grouping, never by omission.
|
|
876
|
+
3. Prefer 2-5 collections; avoid one-story collections unless truly isolated.
|
|
877
|
+
4. Follow-up reviews: stabilize collection/story order to avoid disorientation from reshuffling.
|
|
878
|
+
5. Apply the field formatting rules from each schema property. Do not use em-dashes in review payload field values (title, rationale, description, etc.).
|
|
879
|
+
6. Do not instruct or tell the user what to do unless they explicitly ask for guidance.
|
|
880
|
+
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.
|
|
881
|
+
|
|
882
|
+
## Curating (Trigger 1)
|
|
883
|
+
Trace the **visual cascade** up the **import graph** to **page-level UI surfaces** — one collection per layer (\`distance 0\` → direct importers → 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 → **usage locations** → outer surfaces. **Larger features:** central page/module → lower-level pieces → outer **usage locations**.
|
|
884
|
+
|
|
885
|
+
## Curating (Trigger 2)
|
|
886
|
+
Exactly what the user asked for — **no more, no less**. Group logically or follow **story index hierarchy**.`;
|
|
887
|
+
/**
|
|
888
|
+
* Canonical schema for the agent-pushed review payload.
|
|
889
|
+
*
|
|
890
|
+
* Server-side state caching and git-branch enrichment live on the
|
|
891
|
+
* core server preset, not here — this tool just
|
|
892
|
+
* validates the agent's input and forwards it over the channel.
|
|
893
|
+
*/
|
|
894
|
+
const ReviewCollectionSchema = v.object({
|
|
895
|
+
title: v.pipe(v.string(), v.description("Title describing **what** this collection consists of, phrased the way a person would say it. Avoid typographic marks and CamelCase. Plain text, no markdown.")),
|
|
896
|
+
rationale: v.pipe(v.string(), v.description("Rationale explaining **why** this collection is relevant to the user. Shown alongside the title. One or two sentences. Plain text, no markdown.")),
|
|
897
|
+
storyIds: v.pipe(v.array(v.string()), v.description("Story IDs that represent this collection (e.g. \"button--primary\"). The page renders exactly these."))
|
|
898
|
+
});
|
|
899
|
+
const ReviewStateSchema = v.object({
|
|
900
|
+
title: v.pipe(v.string(), v.description("Terse, human-readable title for the overall review. What is this review about? Avoid typographic marks and CamelCase. Plain text, no markdown.")),
|
|
901
|
+
description: v.pipe(v.string(), v.description("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.")),
|
|
902
|
+
collections: v.pipe(v.array(ReviewCollectionSchema), v.description("Groups of stories to show in the review, most relevant first. Prefer 2-5 groups.")),
|
|
903
|
+
changedFiles: v.pipe(v.array(v.string()), v.description("Paths of the files you changed, most central first. Pass an empty array `[]` only when no code changed (browse requests, Trigger 2)."))
|
|
904
|
+
});
|
|
905
|
+
const DisplayReviewOutput = v.object({ reviewUrl: v.pipe(v.string(), v.description("URL of the Storybook review page. Always include this URL in your final user-facing response so the user can open it directly.")) });
|
|
906
|
+
function storybookRootFromRequest(request, trustedOrigin, endpoint) {
|
|
907
|
+
if (!request?.url) return void 0;
|
|
908
|
+
try {
|
|
909
|
+
const url = new URL(request.url);
|
|
910
|
+
const normalizedEndpoint = endpoint.replace(/\/$/, "");
|
|
911
|
+
const normalizedPathname = url.pathname.replace(/\/$/, "");
|
|
912
|
+
const rootPath = normalizedPathname.endsWith(normalizedEndpoint) ? normalizedPathname.slice(0, -normalizedEndpoint.length) : normalizedPathname.replace(/\/[^/]+$/, "");
|
|
913
|
+
return `${trustedOrigin.replace(/\/$/, "")}${rootPath}`;
|
|
914
|
+
} catch {
|
|
915
|
+
return;
|
|
916
|
+
}
|
|
917
|
+
}
|
|
918
|
+
function buildReviewUrl(ctx) {
|
|
919
|
+
const trustedOrigin = ctx.origin;
|
|
920
|
+
if (!trustedOrigin) throw new Error("Cannot resolve the Storybook URL: missing trusted origin in addon context.");
|
|
921
|
+
return `${(ctx.request ? storybookRootFromRequest(ctx.request, trustedOrigin, ctx.endpoint ?? DEFAULT_MCP_ENDPOINT) ?? trustedOrigin : trustedOrigin).replace(/\/$/, "")}/?path=${REVIEW_PAGE_PATH}`;
|
|
922
|
+
}
|
|
923
|
+
function getDisplayReviewToolMetadata() {
|
|
924
|
+
return {
|
|
925
|
+
name: DISPLAY_REVIEW_TOOL_NAME,
|
|
926
|
+
title: "Display Storybook review",
|
|
927
|
+
description: DISPLAY_REVIEW_TOOL_DESCRIPTION,
|
|
928
|
+
schema: withFriendlyErrors(ReviewStateSchema),
|
|
929
|
+
outputSchema: DisplayReviewOutput
|
|
930
|
+
};
|
|
931
|
+
}
|
|
932
|
+
/**
|
|
933
|
+
* Returns the storyIds the agent passed that don't resolve against the live
|
|
934
|
+
* Storybook index. Order-preserving and deduplicated so the error message
|
|
935
|
+
* lists each fabricated ID once, in the order the agent provided them.
|
|
936
|
+
*/
|
|
937
|
+
async function collectUnknownStoryIds(collections, options) {
|
|
938
|
+
const requested = /* @__PURE__ */ new Set();
|
|
939
|
+
const inOrder = [];
|
|
940
|
+
for (const collection of collections) for (const id of collection.storyIds) if (!requested.has(id)) {
|
|
941
|
+
requested.add(id);
|
|
942
|
+
inOrder.push(id);
|
|
943
|
+
}
|
|
944
|
+
if (inOrder.length === 0) return [];
|
|
945
|
+
const index = await getStoryIndex(options);
|
|
946
|
+
return inOrder.filter((id) => !index.entries[id]);
|
|
947
|
+
}
|
|
948
|
+
function formatUnknownStoryIdsError(unknownIds) {
|
|
949
|
+
const list = unknownIds.map((id) => `- \`${id}\``).join("\n");
|
|
950
|
+
const plural = unknownIds.length === 1 ? "ID is" : "IDs are";
|
|
951
|
+
return `Refusing to publish review: ${unknownIds.length} story ${plural} not in the live Storybook index:\n${list}\n\nThis 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.`;
|
|
952
|
+
}
|
|
953
|
+
async function addDisplayReviewTool(server, enabled = () => server.ctx.custom?.toolsets?.dev ?? true) {
|
|
954
|
+
server.tool({
|
|
955
|
+
...getDisplayReviewToolMetadata(),
|
|
956
|
+
enabled
|
|
957
|
+
}, async (input) => {
|
|
958
|
+
try {
|
|
959
|
+
const customContext = server.ctx.custom;
|
|
960
|
+
if (!customContext?.origin) throw new Error("Cannot resolve the Storybook URL: missing trusted origin in addon context.");
|
|
961
|
+
if (!customContext.options) throw new Error("Storybook options are required in addon context.");
|
|
962
|
+
const unknownIds = await collectUnknownStoryIds(input.collections, customContext.options);
|
|
963
|
+
if (unknownIds.length > 0) throw new Error(formatUnknownStoryIdsError(unknownIds));
|
|
964
|
+
const reviewUrl = buildReviewUrl({
|
|
965
|
+
origin: customContext.origin,
|
|
966
|
+
request: customContext.request,
|
|
967
|
+
endpoint: customContext.endpoint
|
|
968
|
+
});
|
|
969
|
+
server.ctx.custom?.options?.channel?.emit(PUSH_REVIEW_EVENT, input);
|
|
970
|
+
const collectionCount = input.collections.length;
|
|
971
|
+
const storyCount = input.collections.reduce((n, c) => n + c.storyIds.length, 0);
|
|
972
|
+
if (!customContext.disableTelemetry) await collectTelemetry({
|
|
973
|
+
event: "tool:displayReview",
|
|
974
|
+
server,
|
|
975
|
+
toolset: "dev",
|
|
976
|
+
collectionCount,
|
|
977
|
+
storyCount,
|
|
978
|
+
changedFileCount: input.changedFiles.length
|
|
979
|
+
});
|
|
980
|
+
return {
|
|
981
|
+
content: [{
|
|
982
|
+
type: "text",
|
|
983
|
+
text: `Review applied: ${collectionCount} collection${collectionCount === 1 ? "" : "s"}, ${storyCount} stor${storyCount === 1 ? "y" : "ies"}. Storybook is already running at ${customContext.origin} — reuse it. Do NOT start another Storybook or change its port to view this review; the running instance already serves it.
|
|
984
|
+
|
|
985
|
+
Two things you must do now, both of them:
|
|
986
|
+
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 — actually open it.
|
|
987
|
+
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. \`## 👀 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 👉 so it's easy to spot: \`👉 [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 — not a trailing sentence the user has to hunt for. The user needs to see this link even after you've opened it yourself.`
|
|
988
|
+
}],
|
|
989
|
+
structuredContent: { reviewUrl }
|
|
990
|
+
};
|
|
991
|
+
} catch (error) {
|
|
992
|
+
return errorToMCPContent(error);
|
|
993
|
+
}
|
|
994
|
+
});
|
|
995
|
+
}
|
|
996
|
+
|
|
997
|
+
//#endregion
|
|
998
|
+
//#region src/utils/detect-unreachable-changes.ts
|
|
999
|
+
const SOURCE_EXT_RE = /\.(?:tsx?|jsx?|mjs|cjs)$/i;
|
|
1000
|
+
/**
|
|
1001
|
+
* Module-graph query batch size. Bounds the per-call file list so a large working tree doesn't
|
|
1002
|
+
* issue one oversized reverse-index query; we early-exit between chunks once `maxFiles` is reached.
|
|
1003
|
+
*/
|
|
1004
|
+
const CHUNK_SIZE = 50;
|
|
1005
|
+
/**
|
|
1006
|
+
* git status --porcelain produces lines like `XY filename`, where XY are two
|
|
1007
|
+
* status characters (M, A, ?, etc). The pattern is rigid; we slice the prefix.
|
|
1008
|
+
* Rename lines are formatted as `R old -> new` — keep only the new path.
|
|
1009
|
+
*/
|
|
1010
|
+
function parsePorcelain(output) {
|
|
1011
|
+
return output.split("\n").filter(Boolean).map((line) => {
|
|
1012
|
+
const rest = line.slice(3);
|
|
1013
|
+
const arrow = rest.indexOf(" -> ");
|
|
1014
|
+
return arrow >= 0 ? rest.slice(arrow + 4).trim() : rest.trim();
|
|
1015
|
+
});
|
|
1016
|
+
}
|
|
1017
|
+
/**
|
|
1018
|
+
* Lists working-tree modified files that are NOT reached from any story file
|
|
1019
|
+
* via Storybook's reverse dependency graph. This is the "your edit isn't in
|
|
1020
|
+
* the graph; you'll need to grep" case — typical for theme tokens, decorator
|
|
1021
|
+
* config, and other infrastructure files consumed via Storybook's preview
|
|
1022
|
+
* runtime rather than story-file imports.
|
|
1023
|
+
*
|
|
1024
|
+
* Returns workspace-relative paths, suitable for inlining into a tool
|
|
1025
|
+
* response. Empty when:
|
|
1026
|
+
* - change detection is inactive,
|
|
1027
|
+
* - the working tree is clean,
|
|
1028
|
+
* - or every modified file IS in the graph (the caller should use the
|
|
1029
|
+
* status-store result directly).
|
|
1030
|
+
*/
|
|
1031
|
+
async function detectUnreachableChanges(maxFiles = 10) {
|
|
1032
|
+
const moduleGraph = await getModuleGraphService();
|
|
1033
|
+
if (!moduleGraph) return [];
|
|
1034
|
+
if ((await moduleGraph.queries.status.loaded(void 0)).value !== "ready") return [];
|
|
1035
|
+
const workingDir = process.cwd();
|
|
1036
|
+
let porcelain;
|
|
1037
|
+
try {
|
|
1038
|
+
porcelain = execSync("git status --porcelain", {
|
|
1039
|
+
cwd: workingDir,
|
|
1040
|
+
encoding: "utf-8",
|
|
1041
|
+
stdio: [
|
|
1042
|
+
"ignore",
|
|
1043
|
+
"pipe",
|
|
1044
|
+
"ignore"
|
|
1045
|
+
]
|
|
1046
|
+
});
|
|
1047
|
+
} catch {
|
|
1048
|
+
return [];
|
|
1049
|
+
}
|
|
1050
|
+
const relFiles = parsePorcelain(porcelain).filter((f) => SOURCE_EXT_RE.test(f));
|
|
1051
|
+
if (relFiles.length === 0) return [];
|
|
1052
|
+
const unreachable = [];
|
|
1053
|
+
for (let start = 0; start < relFiles.length && unreachable.length < maxFiles; start += CHUNK_SIZE) {
|
|
1054
|
+
const chunk = relFiles.slice(start, start + CHUNK_SIZE);
|
|
1055
|
+
const absChunk = chunk.map((rel) => slash(path.resolve(workingDir, rel)));
|
|
1056
|
+
const hits = await moduleGraph.queries.storiesForFiles.loaded({ files: absChunk });
|
|
1057
|
+
for (const [i, rel] of chunk.entries()) {
|
|
1058
|
+
if (unreachable.length >= maxFiles) break;
|
|
1059
|
+
if ((hits[i]?.length ?? 0) === 0) unreachable.push(rel);
|
|
1060
|
+
}
|
|
1061
|
+
}
|
|
1062
|
+
return unreachable;
|
|
1063
|
+
}
|
|
1064
|
+
/**
|
|
1065
|
+
* Maximum unreachable files listed inline in the short header banner. Beyond
|
|
1066
|
+
* this we summarise the overflow as `+N more` to keep the banner one-line-ish.
|
|
1067
|
+
*/
|
|
1068
|
+
const BANNER_INLINE_LIMIT = 3;
|
|
1069
|
+
/**
|
|
1070
|
+
* Short "front-loaded" version of {@link formatPartialCoverageHint}, designed
|
|
1071
|
+
* to survive truncation and compaction. The full hint still trails the
|
|
1072
|
+
* response body unchanged — this banner is purely a salience aid for the
|
|
1073
|
+
* non-empty case where 1000+ story bullets would otherwise bury the tail.
|
|
1074
|
+
*
|
|
1075
|
+
* Empty when no unreachable files were detected.
|
|
1076
|
+
*/
|
|
1077
|
+
function formatPartialCoverageBanner(unreachable) {
|
|
1078
|
+
if (unreachable.length === 0) return "";
|
|
1079
|
+
const fileList = unreachable.length <= BANNER_INLINE_LIMIT ? unreachable.join(", ") : `${unreachable.slice(0, BANNER_INLINE_LIMIT).join(", ")}, +${unreachable.length - BANNER_INLINE_LIMIT} more`;
|
|
1080
|
+
const noun = unreachable.length === 1 ? "file" : "files";
|
|
1081
|
+
return `⚠ Coverage gap: ${unreachable.length} modified ${noun} unreachable from any story (${fileList}) — full sanity-check note at end of this response.\n\n`;
|
|
1082
|
+
}
|
|
1083
|
+
/**
|
|
1084
|
+
* Formats the unreachable-files list into a hint appended to
|
|
1085
|
+
* `get-changed-stories`' empty response. Empty string when no hint applies.
|
|
1086
|
+
*/
|
|
1087
|
+
function formatUnreachableHint(unreachable) {
|
|
1088
|
+
if (unreachable.length === 0) return "";
|
|
1089
|
+
return `\n\nThe following working-tree file(s) are modified but unreachable from any story (no static import path connects them — they are likely theme tokens, decorators, or other Storybook-preview-runtime files):\n${unreachable.map((f) => `- ${f}`).join("\n")}\n\nFor 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.`;
|
|
1090
|
+
}
|
|
1091
|
+
/**
|
|
1092
|
+
* Formats a sanity-check hint for the *non-empty* response case: there ARE
|
|
1093
|
+
* changed stories, but the working tree also contains modified files that
|
|
1094
|
+
* aren't reachable from any story (typically because the diff bundles a prior
|
|
1095
|
+
* sub-change on a component with a follow-up edit to shared infrastructure).
|
|
1096
|
+
* In that situation, the changed-stories list is real but incomplete w.r.t.
|
|
1097
|
+
* the agent's most recent sub-edit — the agent has to actively check coverage
|
|
1098
|
+
* rather than trust the list.
|
|
1099
|
+
*
|
|
1100
|
+
* Empty string when no hint applies.
|
|
1101
|
+
*/
|
|
1102
|
+
function formatPartialCoverageHint(unreachable) {
|
|
1103
|
+
if (unreachable.length === 0) return "";
|
|
1104
|
+
return `\n\nCoverage sanity check: the working tree also contains modified file(s) that aren't reachable from any story above (no static import path connects them — typically theme tokens, decorators, or other preview-runtime files):\n${unreachable.map((f) => `- ${f}`).join("\n")}\n\nThe list above is real but may be stale w.r.t. these files — 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.`;
|
|
1105
|
+
}
|
|
1106
|
+
|
|
1107
|
+
//#endregion
|
|
1108
|
+
//#region src/tools/get-changed-stories.ts
|
|
1109
|
+
const GET_CHANGED_STORIES_TOOL_DESCRIPTION = `Get Storybook stories marked as new, modified, or related. Returns story metadata only (no URLs).
|
|
1110
|
+
|
|
1111
|
+
The result reflects the cumulative working-tree diff, not just your latest edit — 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.`;
|
|
1112
|
+
const CHANGE_DETECTION_TYPE = "storybook/change-detection";
|
|
1113
|
+
const INCLUDED_STATUS_VALUES = new Set([
|
|
1114
|
+
"status-value:new",
|
|
1115
|
+
"status-value:modified",
|
|
1116
|
+
"status-value:affected"
|
|
1117
|
+
]);
|
|
1118
|
+
function statusPriority(statusValue) {
|
|
1119
|
+
if (statusValue === "status-value:new") return 0;
|
|
1120
|
+
if (statusValue === "status-value:modified") return 1;
|
|
1121
|
+
return 2;
|
|
1122
|
+
}
|
|
1123
|
+
function getChangedStoriesToolMetadata() {
|
|
1124
|
+
return {
|
|
1125
|
+
name: GET_CHANGED_STORIES_TOOL_NAME,
|
|
1126
|
+
title: "Get changed stories metadata",
|
|
1127
|
+
description: GET_CHANGED_STORIES_TOOL_DESCRIPTION
|
|
1128
|
+
};
|
|
1129
|
+
}
|
|
1130
|
+
async function addGetChangedStoriesTool(server, enabled = () => server.ctx.custom?.toolsets?.dev ?? true, { reviewEnabled = false } = {}) {
|
|
1131
|
+
server.tool({
|
|
1132
|
+
...getChangedStoriesToolMetadata(),
|
|
1133
|
+
enabled
|
|
1134
|
+
}, async () => {
|
|
1135
|
+
try {
|
|
1136
|
+
const { options, disableTelemetry } = server.ctx.custom ?? {};
|
|
1137
|
+
if (!options) throw new Error("Storybook options are required in addon context");
|
|
1138
|
+
const allStatuses = experimental_getStatusStore(CHANGE_DETECTION_TYPE).getAll();
|
|
1139
|
+
const changedStoriesFromStatusStore = [];
|
|
1140
|
+
for (const byType of Object.values(allStatuses)) {
|
|
1141
|
+
const status = byType?.[CHANGE_DETECTION_TYPE];
|
|
1142
|
+
if (status?.value && INCLUDED_STATUS_VALUES.has(status.value)) changedStoriesFromStatusStore.push(status);
|
|
1143
|
+
}
|
|
1144
|
+
if (changedStoriesFromStatusStore.length === 0) {
|
|
1145
|
+
if (!disableTelemetry) await collectTelemetry({
|
|
1146
|
+
event: "tool:getChangedStories",
|
|
1147
|
+
server,
|
|
1148
|
+
toolset: "dev",
|
|
1149
|
+
storyCount: 0,
|
|
1150
|
+
newStoryCount: 0,
|
|
1151
|
+
modifiedStoryCount: 0,
|
|
1152
|
+
affectedStoryCount: 0
|
|
1153
|
+
});
|
|
1154
|
+
return { content: [{
|
|
1155
|
+
type: "text",
|
|
1156
|
+
text: `No new, modified, or related stories detected.${formatUnreachableHint(await detectUnreachableChanges())}`
|
|
1157
|
+
}] };
|
|
1158
|
+
}
|
|
1159
|
+
const index = await getStoryIndex(options);
|
|
1160
|
+
const stories = changedStoriesFromStatusStore.flatMap(({ storyId, value }) => {
|
|
1161
|
+
const entry = index.entries[storyId];
|
|
1162
|
+
if (!entry) return [];
|
|
1163
|
+
return [{
|
|
1164
|
+
storyId,
|
|
1165
|
+
statusValue: value,
|
|
1166
|
+
title: entry.title,
|
|
1167
|
+
name: entry.name,
|
|
1168
|
+
importPath: entry.importPath
|
|
1169
|
+
}];
|
|
1170
|
+
});
|
|
1171
|
+
stories.sort((a, b) => {
|
|
1172
|
+
const priorityDelta = statusPriority(a.statusValue) - statusPriority(b.statusValue);
|
|
1173
|
+
return priorityDelta !== 0 ? priorityDelta : a.storyId.localeCompare(b.storyId);
|
|
1174
|
+
});
|
|
1175
|
+
const buckets = {
|
|
1176
|
+
new: stories.filter((story) => story.statusValue === "status-value:new"),
|
|
1177
|
+
modified: stories.filter((story) => story.statusValue === "status-value:modified"),
|
|
1178
|
+
affected: stories.filter((story) => story.statusValue === "status-value:affected")
|
|
1179
|
+
};
|
|
1180
|
+
const counts = {
|
|
1181
|
+
new: buckets.new.length,
|
|
1182
|
+
modified: buckets.modified.length,
|
|
1183
|
+
affected: buckets.affected.length
|
|
1184
|
+
};
|
|
1185
|
+
if (!disableTelemetry) await collectTelemetry({
|
|
1186
|
+
event: "tool:getChangedStories",
|
|
1187
|
+
server,
|
|
1188
|
+
toolset: "dev",
|
|
1189
|
+
storyCount: stories.length,
|
|
1190
|
+
newStoryCount: counts.new,
|
|
1191
|
+
modifiedStoryCount: counts.modified,
|
|
1192
|
+
affectedStoryCount: counts.affected
|
|
1193
|
+
});
|
|
1194
|
+
const unreachable = await detectUnreachableChanges();
|
|
1195
|
+
let text = `${formatPartialCoverageBanner(unreachable)}Detected ${stories.length} changed stor${stories.length === 1 ? "y" : "ies"} (${counts.new} new, ${counts.modified} modified, ${counts.affected} related).`;
|
|
1196
|
+
if (reviewEnabled && stories.length > 0) text += `\n\nNext: if the change is visually observable, publish the review now — call **display-review** curating these story IDs. That review link is how you finish; do not substitute individual preview URLs for it.`;
|
|
1197
|
+
const serializeStory = ({ storyId, title, name, importPath }) => `- \`${storyId}\`: ${title} / ${name} (\`${importPath}\`)`;
|
|
1198
|
+
if (buckets.new.length > 0) {
|
|
1199
|
+
text += `\n\nNew stories:\n`;
|
|
1200
|
+
text += buckets.new.map(serializeStory).join("\n");
|
|
1201
|
+
}
|
|
1202
|
+
if (buckets.modified.length > 0) {
|
|
1203
|
+
text += `\n\nModified stories:\n`;
|
|
1204
|
+
text += buckets.modified.map(serializeStory).join("\n");
|
|
1205
|
+
}
|
|
1206
|
+
if (buckets.affected.length > 0) {
|
|
1207
|
+
text += `\n\nRelated stories:\n`;
|
|
1208
|
+
text += buckets.affected.map(serializeStory).join("\n");
|
|
1209
|
+
}
|
|
1210
|
+
text += formatPartialCoverageHint(unreachable);
|
|
1211
|
+
return { content: [{
|
|
1212
|
+
type: "text",
|
|
1213
|
+
text
|
|
1214
|
+
}] };
|
|
1215
|
+
} catch (error) {
|
|
1216
|
+
return errorToMCPContent(error);
|
|
1217
|
+
}
|
|
1218
|
+
});
|
|
1219
|
+
}
|
|
1220
|
+
|
|
1221
|
+
//#endregion
|
|
1222
|
+
//#region src/utils/resolve-component-stories.ts
|
|
1223
|
+
const SOURCE_EXTENSIONS = [
|
|
1224
|
+
".ts",
|
|
1225
|
+
".tsx",
|
|
1226
|
+
".js",
|
|
1227
|
+
".jsx",
|
|
1228
|
+
".mjs",
|
|
1229
|
+
".cjs"
|
|
1230
|
+
];
|
|
1231
|
+
const INDEX_BASENAMES = SOURCE_EXTENSIONS.map((ext) => `index${ext}`);
|
|
1232
|
+
/**
|
|
1233
|
+
* Expands `Foo/Foo.tsx` ↔ `Foo/index.tsx` so a query against either form hits stories that
|
|
1234
|
+
* imported the other. Only expands when filename or dirname clearly names the directory's
|
|
1235
|
+
* main export.
|
|
1236
|
+
*/
|
|
1237
|
+
function expandBarrelTargets(absoluteComponentPath) {
|
|
1238
|
+
const targets = new Set([absoluteComponentPath]);
|
|
1239
|
+
const dir = path.dirname(absoluteComponentPath);
|
|
1240
|
+
const ext = path.extname(absoluteComponentPath);
|
|
1241
|
+
const base = path.basename(absoluteComponentPath, ext);
|
|
1242
|
+
const dirName = path.basename(dir);
|
|
1243
|
+
if (base.toLowerCase() === "index") for (const candidateExt of SOURCE_EXTENSIONS) {
|
|
1244
|
+
const candidate = path.join(dir, `${dirName}${candidateExt}`);
|
|
1245
|
+
if (fs.existsSync(candidate)) targets.add(candidate);
|
|
1246
|
+
}
|
|
1247
|
+
else if (base.toLowerCase() === dirName.toLowerCase()) for (const indexBasename of INDEX_BASENAMES) {
|
|
1248
|
+
const candidate = path.join(dir, indexBasename);
|
|
1249
|
+
if (fs.existsSync(candidate)) targets.add(candidate);
|
|
1250
|
+
}
|
|
1251
|
+
return [...targets].map((p) => slash(path.normalize(p)));
|
|
1252
|
+
}
|
|
1253
|
+
/**
|
|
1254
|
+
* Canonicalises a path via `realpath`. Fixes silent misses on case-insensitive filesystems
|
|
1255
|
+
* (macOS APFS) where `BUTTON/Button.tsx` and `Button/Button.tsx` resolve to the same file but
|
|
1256
|
+
* only the canonical form is in the reverse-index keyset.
|
|
1257
|
+
*
|
|
1258
|
+
* Returns `undefined` if the path doesn't exist on disk — the caller surfaces that as a
|
|
1259
|
+
* distinct "path not found" outcome rather than a generic "no stories".
|
|
1260
|
+
*/
|
|
1261
|
+
function canonicalise(absolutePath) {
|
|
1262
|
+
try {
|
|
1263
|
+
return fs.realpathSync.native(absolutePath);
|
|
1264
|
+
} catch (err) {
|
|
1265
|
+
if (err.code === "ENOENT") return void 0;
|
|
1266
|
+
throw err;
|
|
1267
|
+
}
|
|
1268
|
+
}
|
|
1269
|
+
/**
|
|
1270
|
+
* Normalizes a story-index `importPath` to the `./`-prefixed, forward-slash form the module graph
|
|
1271
|
+
* returns for its story files (e.g. `./src/Button.stories.tsx`). The module graph keys story files
|
|
1272
|
+
* this way, so we match on it instead of the absolute path.
|
|
1273
|
+
*/
|
|
1274
|
+
function toStoryIndexPath(importPath) {
|
|
1275
|
+
const normalized = slash(importPath);
|
|
1276
|
+
if (normalized.startsWith("./") || normalized.startsWith("../")) return normalized;
|
|
1277
|
+
return `./${normalized}`;
|
|
1278
|
+
}
|
|
1279
|
+
/**
|
|
1280
|
+
* Map story-index-relative story-file path → story IDs declared in that file. Skips virtual entries.
|
|
1281
|
+
* Keys match the `storyFile` values returned by the module graph's `storiesForFiles`.
|
|
1282
|
+
*/
|
|
1283
|
+
function buildStoryIdsByFile(storyIndex) {
|
|
1284
|
+
const storyIdsByFile = /* @__PURE__ */ new Map();
|
|
1285
|
+
for (const entry of Object.values(storyIndex.entries)) {
|
|
1286
|
+
if (entry.type !== "story" || entry.importPath.startsWith("virtual:")) continue;
|
|
1287
|
+
const filePath = toStoryIndexPath(entry.importPath);
|
|
1288
|
+
let ids = storyIdsByFile.get(filePath);
|
|
1289
|
+
if (!ids) {
|
|
1290
|
+
ids = /* @__PURE__ */ new Set();
|
|
1291
|
+
storyIdsByFile.set(filePath, ids);
|
|
1292
|
+
}
|
|
1293
|
+
ids.add(entry.id);
|
|
1294
|
+
}
|
|
1295
|
+
return storyIdsByFile;
|
|
1296
|
+
}
|
|
1297
|
+
/** Builds the unavailable reason for a non-`ready` module-graph status. */
|
|
1298
|
+
function reasonForStatus(status) {
|
|
1299
|
+
switch (status.value) {
|
|
1300
|
+
case "booting": return "Storybook's story module graph hasn't built yet — it is still being constructed. Retry shortly.";
|
|
1301
|
+
case "unavailable": return `Storybook's story module graph is unavailable: ${status.reason}`;
|
|
1302
|
+
case "error": return `Storybook's story module graph failed to build: ${status.error.message}`;
|
|
1303
|
+
case "ready": return "Storybook's story module graph is ready.";
|
|
1304
|
+
default: return status;
|
|
1305
|
+
}
|
|
1306
|
+
}
|
|
1307
|
+
/**
|
|
1308
|
+
* Looks up stories that consume each component path via Storybook's `core/module-graph` reverse
|
|
1309
|
+
* index. Returns `{ available: false }` when the graph isn't ready; otherwise per-path results.
|
|
1310
|
+
*/
|
|
1311
|
+
async function resolveComponentStories(request, deps) {
|
|
1312
|
+
const moduleGraph = await getModuleGraphService();
|
|
1313
|
+
if (!moduleGraph) return {
|
|
1314
|
+
available: false,
|
|
1315
|
+
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."
|
|
1316
|
+
};
|
|
1317
|
+
const status = await moduleGraph.queries.status.loaded(void 0);
|
|
1318
|
+
if (status.value !== "ready") return {
|
|
1319
|
+
available: false,
|
|
1320
|
+
reason: reasonForStatus(status)
|
|
1321
|
+
};
|
|
1322
|
+
const workingDir = deps.workingDir ?? process.cwd();
|
|
1323
|
+
const storyIdsByFile = buildStoryIdsByFile(await deps.getStoryIndex());
|
|
1324
|
+
const resolved = [...new Set(request.componentPaths)].map((componentPath) => {
|
|
1325
|
+
const absolute = path.resolve(workingDir, componentPath);
|
|
1326
|
+
const canonical = canonicalise(absolute);
|
|
1327
|
+
const echo = path.normalize(componentPath);
|
|
1328
|
+
if (!canonical) return {
|
|
1329
|
+
componentPath: echo,
|
|
1330
|
+
targets: [],
|
|
1331
|
+
pathNotFound: true
|
|
1332
|
+
};
|
|
1333
|
+
const targets = new Set(expandBarrelTargets(absolute));
|
|
1334
|
+
if (canonical !== absolute) for (const t of expandBarrelTargets(canonical)) targets.add(t);
|
|
1335
|
+
return {
|
|
1336
|
+
componentPath: echo,
|
|
1337
|
+
targets: [...targets]
|
|
1338
|
+
};
|
|
1339
|
+
});
|
|
1340
|
+
const allTargets = [...new Set(resolved.flatMap((c) => c.targets))];
|
|
1341
|
+
const hitsByTarget = /* @__PURE__ */ new Map();
|
|
1342
|
+
if (allTargets.length > 0) {
|
|
1343
|
+
const batched = await moduleGraph.queries.storiesForFiles.loaded({ files: allTargets });
|
|
1344
|
+
allTargets.forEach((target, i) => {
|
|
1345
|
+
hitsByTarget.set(target, batched[i] ?? []);
|
|
1346
|
+
});
|
|
1347
|
+
}
|
|
1348
|
+
return {
|
|
1349
|
+
available: true,
|
|
1350
|
+
results: resolved.map((component) => {
|
|
1351
|
+
if (component.pathNotFound) return {
|
|
1352
|
+
componentPath: component.componentPath,
|
|
1353
|
+
matches: [],
|
|
1354
|
+
pathNotFound: true
|
|
1355
|
+
};
|
|
1356
|
+
const byStoryId = /* @__PURE__ */ new Map();
|
|
1357
|
+
for (const target of component.targets) {
|
|
1358
|
+
const hits = hitsByTarget.get(target) ?? [];
|
|
1359
|
+
for (const { storyFile, depth } of hits) {
|
|
1360
|
+
const storyIds = storyIdsByFile.get(storyFile);
|
|
1361
|
+
if (!storyIds) continue;
|
|
1362
|
+
for (const storyId of storyIds) {
|
|
1363
|
+
const existing = byStoryId.get(storyId);
|
|
1364
|
+
if (existing === void 0 || depth < existing) byStoryId.set(storyId, depth);
|
|
1365
|
+
}
|
|
1366
|
+
}
|
|
1367
|
+
}
|
|
1368
|
+
const matches = [...byStoryId.entries()].map(([storyId, depth]) => ({
|
|
1369
|
+
storyId,
|
|
1370
|
+
depth
|
|
1371
|
+
})).sort((a, b) => {
|
|
1372
|
+
if (a.depth !== b.depth) return a.depth - b.depth;
|
|
1373
|
+
return a.storyId.localeCompare(b.storyId);
|
|
1374
|
+
});
|
|
1375
|
+
return {
|
|
1376
|
+
componentPath: component.componentPath,
|
|
1377
|
+
matches
|
|
1378
|
+
};
|
|
1379
|
+
})
|
|
1380
|
+
};
|
|
1381
|
+
}
|
|
1382
|
+
|
|
1383
|
+
//#endregion
|
|
1384
|
+
//#region src/tools/get-stories-by-component.ts
|
|
1385
|
+
/** When omitted by the caller, applied internally to keep result sets actionable on real codebases. */
|
|
1386
|
+
const DEFAULT_MAX_DISTANCE = 3;
|
|
1387
|
+
/**
|
|
1388
|
+
* Review-conditional like the preview-stories description: with the
|
|
1389
|
+
* `experimentalReview` flag off, display-review is not registered, so the
|
|
1390
|
+
* review-off variant must not point agents at a tool that doesn't exist.
|
|
1391
|
+
*/
|
|
1392
|
+
function getStoriesByComponentToolDescription({ reviewEnabled = false } = {}) {
|
|
1393
|
+
return `Map component source files to the stories that render them, returning grounded \`storyId\` values from the live Storybook index — hand these to ${reviewEnabled ? `${PREVIEW_STORIES_TOOL_NAME} or display-review` : PREVIEW_STORIES_TOOL_NAME} instead of guessing.
|
|
1394
|
+
|
|
1395
|
+
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 — 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 — 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 — 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.
|
|
1396
|
+
|
|
1397
|
+
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 — 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 → direct importers → page-level context) — 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 → direct importers → page-level context) — 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.`}
|
|
1398
|
+
|
|
1399
|
+
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).
|
|
1400
|
+
|
|
1401
|
+
Backed by Storybook's live reverse dependency graph, available only when the dev server runs a builder that supports change detection (e.g. Vite) — otherwise returns a typed error.`;
|
|
1402
|
+
}
|
|
1403
|
+
const GetStoriesByComponentInput = v.object({
|
|
1404
|
+
componentPaths: v.pipe(v.array(v.string()), v.minLength(1), v.description(`Absolute paths to component source files (e.g. "/repo/src/Button.tsx").
|
|
1405
|
+
Pass the components you actually want stories for — typically files you just read, edited, or that the user mentioned.
|
|
1406
|
+
Relative paths are also accepted and resolved against the Storybook working directory, but absolute paths are preferred for unambiguous results.
|
|
1407
|
+
Story files (\`*.stories.*\`) are accepted too: they appear at distance 0 as self-matches, plus any reverse-graph hits (other stories that import them).`)),
|
|
1408
|
+
maxDistance: v.pipe(v.optional(v.pipe(v.number(), v.minValue(1), v.integer())), v.description(`Ceiling on the import depth to include in results. Must be a positive integer.
|
|
1409
|
+
- 1: only stories that directly import the component.
|
|
1410
|
+
- 2+: also include stories that reach the component through N hops.
|
|
1411
|
+
Defaults to ${DEFAULT_MAX_DISTANCE}; raise it to widen recall, lower it to tighten precision. Shared components (Button, Icon, …) accumulate noisy indirect matches at distance ≥ 3, so the default cap protects against runaway results.`))
|
|
1412
|
+
});
|
|
1413
|
+
const StoryMatch = v.object({
|
|
1414
|
+
storyId: v.string(),
|
|
1415
|
+
title: v.string(),
|
|
1416
|
+
name: v.string(),
|
|
1417
|
+
importPath: v.string(),
|
|
1418
|
+
distance: v.pipe(v.number(), v.description("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."))
|
|
1419
|
+
});
|
|
1420
|
+
const ClippedByMaxDistanceSchema = v.pipe(v.object({
|
|
1421
|
+
count: v.number(),
|
|
1422
|
+
distances: v.array(v.number())
|
|
1423
|
+
}), v.description("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 — widen `maxDistance` to include them."));
|
|
1424
|
+
const GetStoriesByComponentOutput = v.object({ results: v.array(v.object({
|
|
1425
|
+
componentPath: v.string(),
|
|
1426
|
+
matches: v.array(StoryMatch),
|
|
1427
|
+
clipped: v.optional(ClippedByMaxDistanceSchema),
|
|
1428
|
+
pathNotFound: v.pipe(v.optional(v.boolean()), v.description("`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."))
|
|
1429
|
+
})) });
|
|
1430
|
+
function serializeMatch(match) {
|
|
1431
|
+
return ` - \`${match.storyId}\`: ${match.title} / ${match.name} (\`${match.importPath}\`)`;
|
|
1432
|
+
}
|
|
1433
|
+
function pluralize(n, singular, plural = `${singular}s`) {
|
|
1434
|
+
return n === 1 ? singular : plural;
|
|
1435
|
+
}
|
|
1436
|
+
function formatClippedTail(clipped, maxDistance) {
|
|
1437
|
+
const dists = clipped.distances;
|
|
1438
|
+
const rangeText = dists.length === 1 ? `distance ${dists[0]}` : `distances ${dists[0]}..${dists[dists.length - 1]}`;
|
|
1439
|
+
return `+${clipped.count} more ${pluralize(clipped.count, "story", "stories")} at ${rangeText} hidden by \`maxDistance: ${maxDistance}\``;
|
|
1440
|
+
}
|
|
1441
|
+
function serializeComponentSection(componentPath, matches, options = {}) {
|
|
1442
|
+
const { maxDistance, clipped, pathNotFound } = options;
|
|
1443
|
+
if (pathNotFound) return `${componentPath}: path does not exist on disk — re-check the path you sent.`;
|
|
1444
|
+
if (matches.length === 0) {
|
|
1445
|
+
if (clipped && clipped.count > 0 && maxDistance !== void 0) return `${componentPath}: no stories within \`maxDistance: ${maxDistance}\` — ${formatClippedTail(clipped, maxDistance)}.`;
|
|
1446
|
+
return `${componentPath}: no stories found`;
|
|
1447
|
+
}
|
|
1448
|
+
const byDistance = /* @__PURE__ */ new Map();
|
|
1449
|
+
for (const m of matches) {
|
|
1450
|
+
const bucket = byDistance.get(m.distance) ?? [];
|
|
1451
|
+
bucket.push(m);
|
|
1452
|
+
byDistance.set(m.distance, bucket);
|
|
1453
|
+
}
|
|
1454
|
+
const distances = [...byDistance.keys()].sort((a, b) => a - b);
|
|
1455
|
+
const minDist = distances[0];
|
|
1456
|
+
const maxDist = distances[distances.length - 1];
|
|
1457
|
+
const componentCount = new Set(matches.map((m) => m.title)).size;
|
|
1458
|
+
const bucketSummary = distances.map((d) => `d${d}=${byDistance.get(d).length}`).join(", ");
|
|
1459
|
+
const summary = `→ ${matches.length} ${pluralize(matches.length, "story", "stories")} across ${componentCount} ${pluralize(componentCount, "component")}, distances ${minDist}..${maxDist} (${bucketSummary})`;
|
|
1460
|
+
const lines = [`${componentPath}:`, summary];
|
|
1461
|
+
for (const d of distances) {
|
|
1462
|
+
lines.push(`distance ${d}:`);
|
|
1463
|
+
for (const m of byDistance.get(d)) lines.push(serializeMatch(m));
|
|
1464
|
+
}
|
|
1465
|
+
if (clipped && clipped.count > 0 && maxDistance !== void 0) lines.push(` (${formatClippedTail(clipped, maxDistance)}.)`);
|
|
1466
|
+
return lines.join("\n");
|
|
1467
|
+
}
|
|
1468
|
+
function applyMaxDistance(depths, maxDistance) {
|
|
1469
|
+
if (maxDistance === void 0) return { kept: depths };
|
|
1470
|
+
const kept = [];
|
|
1471
|
+
const clippedDistances = /* @__PURE__ */ new Set();
|
|
1472
|
+
let clippedCount = 0;
|
|
1473
|
+
for (const d of depths) if (d.depth <= maxDistance) kept.push(d);
|
|
1474
|
+
else {
|
|
1475
|
+
clippedCount++;
|
|
1476
|
+
clippedDistances.add(d.depth);
|
|
1477
|
+
}
|
|
1478
|
+
return {
|
|
1479
|
+
kept,
|
|
1480
|
+
clipped: clippedCount > 0 ? {
|
|
1481
|
+
count: clippedCount,
|
|
1482
|
+
distances: [...clippedDistances].sort((a, b) => a - b)
|
|
1483
|
+
} : void 0
|
|
1484
|
+
};
|
|
1485
|
+
}
|
|
1486
|
+
function getStoriesByComponentToolMetadata({ reviewEnabled = false } = {}) {
|
|
1487
|
+
return {
|
|
1488
|
+
name: GET_STORIES_BY_COMPONENT_TOOL_NAME,
|
|
1489
|
+
title: "Get stories for component files",
|
|
1490
|
+
description: getStoriesByComponentToolDescription({ reviewEnabled }),
|
|
1491
|
+
schema: GetStoriesByComponentInput,
|
|
1492
|
+
outputSchema: GetStoriesByComponentOutput
|
|
1493
|
+
};
|
|
1494
|
+
}
|
|
1495
|
+
async function addGetStoriesByComponentTool(server, enabled = () => server.ctx.custom?.toolsets?.dev ?? true, { reviewEnabled = false } = {}) {
|
|
1496
|
+
server.tool({
|
|
1497
|
+
...getStoriesByComponentToolMetadata({ reviewEnabled }),
|
|
1498
|
+
enabled
|
|
1499
|
+
}, async (input) => {
|
|
1500
|
+
try {
|
|
1501
|
+
const { options, disableTelemetry } = server.ctx.custom ?? {};
|
|
1502
|
+
if (!options) throw new Error("Storybook options are required in addon context");
|
|
1503
|
+
const index = await getStoryIndex(options);
|
|
1504
|
+
const lookup = await resolveComponentStories({ componentPaths: input.componentPaths }, { getStoryIndex: async () => index });
|
|
1505
|
+
if (!lookup.available) return {
|
|
1506
|
+
content: [{
|
|
1507
|
+
type: "text",
|
|
1508
|
+
text: lookup.reason ?? "Storybook's story dependency graph is unavailable. Make sure the dev server is running with a builder that supports change detection."
|
|
1509
|
+
}],
|
|
1510
|
+
isError: true
|
|
1511
|
+
};
|
|
1512
|
+
const effectiveMaxDistance = input.maxDistance ?? DEFAULT_MAX_DISTANCE;
|
|
1513
|
+
const results = (lookup.results ?? []).map((entry) => {
|
|
1514
|
+
if (entry.pathNotFound) return {
|
|
1515
|
+
componentPath: entry.componentPath,
|
|
1516
|
+
matches: [],
|
|
1517
|
+
pathNotFound: true
|
|
1518
|
+
};
|
|
1519
|
+
const { kept, clipped } = applyMaxDistance(entry.matches, effectiveMaxDistance);
|
|
1520
|
+
const matches = [];
|
|
1521
|
+
for (const { storyId, depth } of kept) {
|
|
1522
|
+
const indexEntry = index.entries[storyId];
|
|
1523
|
+
if (!indexEntry || indexEntry.type !== "story") continue;
|
|
1524
|
+
matches.push({
|
|
1525
|
+
storyId: indexEntry.id,
|
|
1526
|
+
title: indexEntry.title,
|
|
1527
|
+
name: indexEntry.name,
|
|
1528
|
+
importPath: indexEntry.importPath,
|
|
1529
|
+
distance: depth
|
|
1530
|
+
});
|
|
1531
|
+
}
|
|
1532
|
+
return {
|
|
1533
|
+
componentPath: entry.componentPath,
|
|
1534
|
+
matches,
|
|
1535
|
+
clipped
|
|
1536
|
+
};
|
|
1537
|
+
});
|
|
1538
|
+
const totalMatches = results.reduce((sum, r) => sum + r.matches.length, 0);
|
|
1539
|
+
const unmatchedCount = results.filter((r) => !r.pathNotFound && r.matches.length === 0).length;
|
|
1540
|
+
const textSections = results.map(({ componentPath, matches, clipped, pathNotFound }) => serializeComponentSection(componentPath, matches, {
|
|
1541
|
+
maxDistance: effectiveMaxDistance,
|
|
1542
|
+
clipped,
|
|
1543
|
+
pathNotFound
|
|
1544
|
+
}));
|
|
1545
|
+
const text = textSections.length > 0 ? textSections.join("\n\n") : "No component paths provided.";
|
|
1546
|
+
if (!disableTelemetry) await collectTelemetry({
|
|
1547
|
+
event: "tool:getStoriesByComponent",
|
|
1548
|
+
server,
|
|
1549
|
+
toolset: "dev",
|
|
1550
|
+
componentCount: input.componentPaths.length,
|
|
1551
|
+
matchedComponentCount: input.componentPaths.length - unmatchedCount,
|
|
1552
|
+
totalMatchCount: totalMatches,
|
|
1553
|
+
maxDistance: effectiveMaxDistance
|
|
1554
|
+
});
|
|
1555
|
+
return {
|
|
1556
|
+
content: [{
|
|
1557
|
+
type: "text",
|
|
1558
|
+
text
|
|
1559
|
+
}],
|
|
1560
|
+
structuredContent: { results }
|
|
1561
|
+
};
|
|
1562
|
+
} catch (error) {
|
|
1563
|
+
return errorToMCPContent(error);
|
|
1564
|
+
}
|
|
1565
|
+
});
|
|
1566
|
+
}
|
|
714
1567
|
|
|
715
|
-
|
|
1568
|
+
//#endregion
|
|
1569
|
+
//#region src/instructions/storybook-story-instructions.md
|
|
1570
|
+
var storybook_story_instructions_default = "# Writing User Interfaces\n\nWhen writing UI, prefer breaking larger components up into smaller parts.\n\nALWAYS write a Storybook story for any component written. If editing a component, ensure appropriate changes have been made to stories for that component.\n{{DOCS_WORKFLOW_GUIDANCE}}\n\n## How to write good stories\n\nGoal: Cover every distinct piece of business logic and state the component can reach (happy paths, error/edge states, loading, permissions/roles, empty states, variations from props/context). Avoid redundant stories that show the same logic.\n\nInteractivity: If the component is interactive, add Interaction tests using play functions that drive the UI with storybook/test utilities (e.g., fn, userEvent, expect). Simulate key user flows: clicking buttons/links, typing, focus/blur, keyboard nav, form submit, async responses, toggle/selection changes, pagination/filters, etc. When passing `fn` functions as `args` for callback functions, make sure to add a play function which interacts with the component and assert whether the callback function was actually called.\n\nData/setup: Provide realistic props, state, and mocked data. Include meaningful labels/text to make behaviors observable. Stub network/services with deterministic fixtures; keep stories reliable.\n\nAssertions: In play functions, assert the visible outcome of the interaction (text, aria state, enabled/disabled, class/state changes, emitted events). Prefer role/label-based queries.\n\nVariants to consider (pick only those that change behavior): default vs. alternate themes; loading vs. loaded vs. empty vs. error; validated vs. invalid input; permissions/roles/capabilities; feature flags; size/density/layout variants that alter logic.\n\nAccessibility: Use semantic roles/labels; ensure focusable/keyboard interactions are test-covered where relevant.\n\nNaming/structure: Use clear story names that describe the scenario (“Error state after failed submit”). Group related variants logically; don’t duplicate.\n\nImports/format: Import Meta/StoryObj from the framework package; import test helpers from storybook/test (not @storybook/test). Keep stories minimal—only what's needed to demonstrate behavior.\n\n## Storybook 9 Essential Changes for Story Writing\n\n### Package Consolidation\n\n#### `Meta` and `StoryObj` imports\n\nUpdate story imports to use the framework package:\n\n```diff\n- import { Meta, StoryObj } from '{{RENDERER}}';\n+ import { Meta, StoryObj } from '{{FRAMEWORK}}';\n```\n\n#### Test utility imports\n\nUpdate test imports to use `storybook/test` instead of `@storybook/test`\n\n```diff\n- import { fn } from '@storybook/test';\n+ import { fn } from 'storybook/test';\n```\n\n### Global State Changes\n\nThe `globals` annotation has be renamed to `initialGlobals`:\n\n```diff\n// .storybook/preview.js\nexport default {\n- globals: { theme: 'light' }\n+ initialGlobals: { theme: 'light' }\n};\n```\n\n### Autodocs Configuration\n\nInstead of `parameters.docs.autodocs` in main.js, use tags:\n\n```js\n// .storybook/preview.js or in individual stories\nexport default {\n tags: ['autodocs'], // generates autodocs for all stories\n};\n```\n\n### Mocking imports in Storybook\n\nTo mock imports in Storybook, use Storybook's mocking features. ALWAYS mock external dependencies to ensure stories render consistently.\n\n1. **Register in the mock in Storybook's preview file**:\n To mock dependendencies, you MUST register a module mock in `.storybook/preview.ts` (or equivalent):\n\n```js\nimport { sb } from 'storybook/test';\n\n// Prefer spy mocks (keeps functions, but allows to override them and spy on them)\nsb.mock(import('some-library'), { spy: true });\n```\n\n**Important: Use file extensions when referring to relative files!**\n\n```js\nsb.mock(import('./relative/module.ts'), { spy: true });\n```\n\n2. **Specify mock values in stories**:\n You can override the behaviour of the mocks per-story using `beforeEach` and the `mocked()` type function:\n\n```js\nimport { expect, mocked, fn } from 'storybook/test';\nimport { library } from 'some-library';\n\nconst meta = {\n component: AuthButton,\n beforeEach: async () => {\n mocked(library).mockResolvedValue({ user: 'data' });\n },\n};\n\nexport const LoggedIn: Story = {\n play: async ({ canvas }) => {\n await expect(library).toHaveBeenCalled();\n },\n};\n```\n\nBefore doing this ensure you have mocked the import in the preview file.\n\n### Play Function Parameters\n\n- The play function has a `canvas` parameter that can be used directly with testing-library-like query methods.\n- It also has a `canvasElement` which is the actual DOM element.\n- The `within`-function imported from `storybook/test` transforms a DOM element to an object with query methods, similar to `canvas`.\n\n**DO NOT** use `within(canvas)` - it is redundant because `canvas` already has the query methods, `canvas` is not a DOM element.\n\n```ts\n// ✅ Correct: Use canvas directly\nplay: async ({ canvas }) => {\n await canvas.getByLabelText('Submit').click();\n};\n\n// ⚠️ Also acceptable: Use `canvasElement` with `within`\nimport { within } from 'storybook/test';\n\nplay: async ({ canvasElement }) => {\n const canvas = within(canvasElement);\n await canvas.getByLabelText('Submit').click();\n};\n\n// ❌ Wrong: Do NOT use within(canvas)\nplay: async ({ canvas }) => {\n const screen = within(canvas); // Error!\n};\n```\n\n### Key Requirements\n\n- **Node.js 20+**, **TypeScript 4.9+**\n- React Native uses `.rnstorybook` directory\n\n## Story Linking Agent Behavior\n\n- ALWAYS provide story links after any changes to stories files, including changes to existing stories.\n- {{STORY_LINKING_WORKFLOW}}\n- {{FINAL_LINKS_GUIDANCE}}\n- 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 — do not drop links there.\n- {{CHANGED_STORY_FALLBACK_LINK_GUIDANCE}}\n- After changing any UI components, ALWAYS search for related stories that might cover the changes you've made. If you find any, provide the story links to the user. THIS IS VERY IMPORTANT, as it allows the user to visually inspect the changes you've made. Even later in a session when changing UI components or stories that have already been linked to previously, YOU MUST PROVIDE THE LINKS AGAIN.\n";
|
|
1571
|
+
|
|
1572
|
+
//#endregion
|
|
1573
|
+
//#region src/instructions/story-testing-instructions.md
|
|
1574
|
+
var story_testing_instructions_default = "## Story Testing Requirements\n\n**Run `{{RUN_STORY_TESTS_TOOL_NAME}}` after EVERY component or story change.** This includes creating, modifying, or refactoring components, stories, or their dependencies. It is the only way to run story tests — never run package.json test scripts (like `npm run test:stories`) instead.\n\n### Workflow\n\n1. Make your change\n2. Run `{{RUN_STORY_TESTS_TOOL_NAME}}` with related stories for focused feedback (faster while iterating)\n3. If tests fail: analyze, fix{{A11Y_FIX_SUFFIX}}, re-run\n4. Repeat until all tests pass\n\nDo not skip tests, ignore failures, or move on with failing tests. If stuck after multiple attempts, report to user.\n\n### Focused vs. full-suite test runs\n\n- Prefer focused runs (`stories` input) during development to validate the parts you changed quickly.\n- Run all tests (omit `stories`) before final handoff, after broad/refactor changes, or when impact is unclear and you need project-wide verification.\n";
|
|
1575
|
+
|
|
1576
|
+
//#endregion
|
|
1577
|
+
//#region src/instructions/a11y-instructions.md
|
|
1578
|
+
var a11y_instructions_default = "### Accessibility Violations\n\n**Fix automatically** (semantic/structural, no visual change):\n\n- ARIA attributes, roles, labels, alt text\n- Heading hierarchy, landmarks, table structure\n- Keyboard access (tabindex, focus, handlers)\n- Document-level: lang attr, frame titles, duplicate IDs\n\n**Confirm with user first** (visual/design changes):\n\n- Color contrast ratios\n- Font sizes, spacing, layout\n- Focus indicator styling\n\nDescribe the issue, ask how the user wants to proceed, and provide 2-3 concrete options.\nDo not auto-apply visual changes before user confirmation, and do not claim visual issues are fixed until they approve an option.\n";
|
|
1579
|
+
|
|
1580
|
+
//#endregion
|
|
1581
|
+
//#region src/tools/get-storybook-story-instructions.ts
|
|
1582
|
+
/**
|
|
1583
|
+
* Injected into the story instructions when the documentation toolset is
|
|
1584
|
+
* available. This tool output is the one channel every agent reads before
|
|
1585
|
+
* writing UI (on both the MCP and the CLI/plugin path) and is never
|
|
1586
|
+
* truncated, so it must carry the docs-workflow trigger — the server
|
|
1587
|
+
* instructions only have room for a terse pointer, and agents otherwise
|
|
1588
|
+
* default to reading library sources out of node_modules.
|
|
1589
|
+
*/
|
|
1590
|
+
const docsWorkflowGuidance = `
|
|
1591
|
+
|
|
1592
|
+
## Using library components
|
|
1593
|
+
|
|
1594
|
+
This Storybook exposes component documentation tools. Before creating or changing any UI, call **list-all-documentation** once to see what the design system already provides — build on existing components instead of hand-rolling duplicates — 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\` — stories show intended usage, raw types don't — and answer props/usage questions from these tools too. Never assume or invent props.`;
|
|
1595
|
+
async function addGetUIBuildingInstructionsTool(server, enabled = () => server.ctx.custom?.toolsets?.dev ?? true, { docsAvailable = false } = {}) {
|
|
1596
|
+
const addonVitestAvailable = !!await getAddonVitestConstants();
|
|
1597
|
+
server.tool({
|
|
1598
|
+
name: GET_UI_BUILDING_INSTRUCTIONS_TOOL_NAME,
|
|
1599
|
+
title: "Storybook Story Development Instructions",
|
|
1600
|
+
get description() {
|
|
1601
|
+
const testToolsetAvailable = (server.ctx.custom?.toolsets?.test ?? true) && addonVitestAvailable;
|
|
1602
|
+
return getStorybookStoryInstructionsDescription({
|
|
1603
|
+
testToolsetAvailable,
|
|
1604
|
+
a11yAvailable: testToolsetAvailable && (server.ctx.custom?.a11yEnabled ?? false)
|
|
1605
|
+
});
|
|
716
1606
|
},
|
|
717
|
-
enabled
|
|
1607
|
+
enabled
|
|
718
1608
|
}, async () => {
|
|
719
1609
|
try {
|
|
720
1610
|
const { options, disableTelemetry } = server.ctx.custom ?? {};
|
|
@@ -724,130 +1614,376 @@ Even if you're familiar with Storybook, call this tool to ensure you're followin
|
|
|
724
1614
|
server,
|
|
725
1615
|
toolset: "dev"
|
|
726
1616
|
});
|
|
727
|
-
const frameworkPreset = await options.presets.apply("framework");
|
|
728
|
-
const framework = typeof frameworkPreset === "string" ? frameworkPreset : frameworkPreset?.name;
|
|
729
|
-
const renderer = frameworkToRendererMap[framework];
|
|
730
|
-
let uiInstructions = storybook_story_instructions_default.replace("{{FRAMEWORK}}", framework).replace("{{RENDERER}}", renderer ?? framework).replace("{{PREVIEW_STORIES_TOOL_NAME}}", PREVIEW_STORIES_TOOL_NAME);
|
|
731
|
-
if ((server.ctx.custom?.toolsets?.test ?? true) && !!await getAddonVitestConstants()) {
|
|
732
|
-
const a11yEnabled = server.ctx.custom?.a11yEnabled ?? false;
|
|
733
|
-
const a11yFixSuffix = a11yEnabled ? " (see a11y guidelines below)" : "";
|
|
734
|
-
const storyTestingInstructions = story_testing_instructions_default.replaceAll("{{RUN_STORY_TESTS_TOOL_NAME}}", RUN_STORY_TESTS_TOOL_NAME).replace("{{A11Y_FIX_SUFFIX}}", a11yFixSuffix);
|
|
735
|
-
uiInstructions += `\n\n${storyTestingInstructions}`;
|
|
736
|
-
if (a11yEnabled) uiInstructions += `\n${a11y_instructions_default}`;
|
|
737
|
-
}
|
|
738
1617
|
return { content: [{
|
|
739
1618
|
type: "text",
|
|
740
|
-
text:
|
|
1619
|
+
text: await buildStorybookStoryInstructions(options, {
|
|
1620
|
+
toolsets: server.ctx.custom?.toolsets,
|
|
1621
|
+
a11yEnabled: server.ctx.custom?.a11yEnabled,
|
|
1622
|
+
addonVitestAvailable,
|
|
1623
|
+
docsAvailable,
|
|
1624
|
+
reviewEnabled: server.ctx.custom?.reviewEnabled
|
|
1625
|
+
})
|
|
741
1626
|
}] };
|
|
742
1627
|
} catch (error) {
|
|
743
1628
|
return errorToMCPContent(error);
|
|
744
1629
|
}
|
|
745
1630
|
});
|
|
746
1631
|
}
|
|
747
|
-
|
|
748
|
-
|
|
749
|
-
|
|
750
|
-
|
|
751
|
-
|
|
752
|
-
|
|
753
|
-
|
|
754
|
-
|
|
755
|
-
|
|
756
|
-
|
|
757
|
-
|
|
758
|
-
|
|
759
|
-
|
|
760
|
-
|
|
761
|
-
|
|
762
|
-
|
|
763
|
-
|
|
764
|
-
|
|
765
|
-
|
|
766
|
-
|
|
767
|
-
|
|
768
|
-
|
|
769
|
-
|
|
770
|
-
|
|
771
|
-
|
|
772
|
-
|
|
773
|
-
return {
|
|
774
|
-
|
|
775
|
-
|
|
776
|
-
|
|
777
|
-
};
|
|
778
|
-
}
|
|
1632
|
+
function getStorybookStoryInstructionsDescription({ testToolsetAvailable, a11yAvailable }) {
|
|
1633
|
+
return `Get comprehensive instructions for writing, testing, and fixing Storybook stories (.stories.tsx, .stories.ts, .stories.jsx, .stories.js, .stories.svelte, .stories.vue files).
|
|
1634
|
+
|
|
1635
|
+
CRITICAL: You MUST call this tool before:
|
|
1636
|
+
- Creating new Storybook stories or story files
|
|
1637
|
+
- Updating or modifying existing Storybook stories
|
|
1638
|
+
- Adding new story variants or exports to story files
|
|
1639
|
+
- Editing any file matching *.stories.* patterns
|
|
1640
|
+
- Writing components that will need stories
|
|
1641
|
+
- Editing anything that changes how the UI looks — components, styles, CSS, themes, colors, or design tokens; a shared file with no stories of its own still changes its consumers' stories${testToolsetAvailable ? `
|
|
1642
|
+
- Running story tests or fixing test failures` : ""}${a11yAvailable ? `
|
|
1643
|
+
- Handling accessibility (a11y) violations in stories (fix semantic issues directly; ask before visual/design changes)` : ""}
|
|
1644
|
+
|
|
1645
|
+
This tool provides essential Storybook-specific guidance including:
|
|
1646
|
+
- How to structure stories correctly for Storybook 9
|
|
1647
|
+
- Required imports (Meta, StoryObj from framework package)
|
|
1648
|
+
- Test utility imports (from 'storybook/test')
|
|
1649
|
+
- Story naming conventions and best practices
|
|
1650
|
+
- Play function patterns for interactive testing
|
|
1651
|
+
- Mocking strategies for external dependencies
|
|
1652
|
+
- Story variants and coverage requirements${testToolsetAvailable ? `
|
|
1653
|
+
- How to handle test failures${a11yAvailable ? " and accessibility violations" : ""}` : ""}
|
|
1654
|
+
|
|
1655
|
+
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.`;
|
|
1656
|
+
}
|
|
1657
|
+
function getStorybookStoryInstructionsToolMetadata(options) {
|
|
1658
|
+
return {
|
|
1659
|
+
name: GET_UI_BUILDING_INSTRUCTIONS_TOOL_NAME,
|
|
1660
|
+
title: "Storybook Story Development Instructions",
|
|
1661
|
+
description: getStorybookStoryInstructionsDescription(options)
|
|
1662
|
+
};
|
|
1663
|
+
}
|
|
1664
|
+
async function buildStorybookStoryInstructions(options, { toolsets, a11yEnabled = false, addonVitestAvailable, docsAvailable = false, reviewEnabled: reviewEnabledOverride } = {}) {
|
|
1665
|
+
const frameworkPreset = await options.presets.apply("framework");
|
|
1666
|
+
const featuresPreset = await options.presets.apply("features", {});
|
|
1667
|
+
const changeDetectionEnabled = featuresPreset?.changeDetection ?? false;
|
|
1668
|
+
const reviewStatus = await getReviewStatus(options, { features: featuresPreset });
|
|
1669
|
+
const reviewEnabled = reviewEnabledOverride ?? reviewStatus.available;
|
|
1670
|
+
const framework = typeof frameworkPreset === "string" ? frameworkPreset : frameworkPreset?.name;
|
|
1671
|
+
const renderer = frameworkToRendererMap[framework];
|
|
1672
|
+
const 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) — 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.`;
|
|
1673
|
+
const 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.`;
|
|
1674
|
+
const docsToolsAvailable = (toolsets?.docs ?? true) && docsAvailable;
|
|
1675
|
+
let uiInstructions = storybook_story_instructions_default.replace("{{FRAMEWORK}}", framework).replace("{{RENDERER}}", renderer ?? framework).replace("\n{{DOCS_WORKFLOW_GUIDANCE}}", docsToolsAvailable ? docsWorkflowGuidance : "").replace("{{STORY_LINKING_WORKFLOW}}", storyLinkingWorkflow).replace("{{FINAL_LINKS_GUIDANCE}}", getFinalLinksGuidance(reviewEnabled)).replace("{{CHANGED_STORY_FALLBACK_LINK_GUIDANCE}}", changedStoryFallbackLinkGuidance);
|
|
1676
|
+
const resolvedAddonVitestAvailable = addonVitestAvailable ?? !!await getAddonVitestConstants();
|
|
1677
|
+
if ((toolsets?.test ?? true) && resolvedAddonVitestAvailable) {
|
|
1678
|
+
const a11yFixSuffix = a11yEnabled ? " (see a11y guidelines below)" : "";
|
|
1679
|
+
const storyTestingInstructions = story_testing_instructions_default.replaceAll("{{RUN_STORY_TESTS_TOOL_NAME}}", RUN_STORY_TESTS_TOOL_NAME).replace("{{A11Y_FIX_SUFFIX}}", a11yFixSuffix);
|
|
1680
|
+
uiInstructions += `\n\n${storyTestingInstructions}`;
|
|
1681
|
+
if (a11yEnabled) uiInstructions += `\n${a11y_instructions_default}`;
|
|
1682
|
+
}
|
|
1683
|
+
return uiInstructions;
|
|
1684
|
+
}
|
|
1685
|
+
const frameworkToRendererMap = {
|
|
1686
|
+
"@storybook/react-vite": "@storybook/react",
|
|
1687
|
+
"@storybook/react-webpack5": "@storybook/react",
|
|
1688
|
+
"@storybook/nextjs": "@storybook/react",
|
|
1689
|
+
"@storybook/nextjs-vite": "@storybook/react",
|
|
1690
|
+
"@storybook/react-native-web-vite": "@storybook/react",
|
|
1691
|
+
"@storybook/vue3-vite": "@storybook/vue3",
|
|
1692
|
+
"@nuxtjs/storybook": "@storybook/vue3",
|
|
1693
|
+
"@storybook/angular": "@storybook/angular",
|
|
1694
|
+
"@storybook/svelte-vite": "@storybook/svelte",
|
|
1695
|
+
"@storybook/sveltekit": "@storybook/svelte",
|
|
1696
|
+
"@storybook/preact-vite": "@storybook/preact",
|
|
1697
|
+
"@storybook/web-components-vite": "@storybook/web-components",
|
|
1698
|
+
"@storybook/html-vite": "@storybook/html"
|
|
1699
|
+
};
|
|
1700
|
+
|
|
1701
|
+
//#endregion
|
|
1702
|
+
//#region src/utils/build-args-param.ts
|
|
1703
|
+
const HEX_REGEXP = /^#([a-f0-9]{3,4}|[a-f0-9]{6}|[a-f0-9]{8})$/i;
|
|
1704
|
+
const COLOR_REGEXP = /^(rgba?|hsla?)\(([0-9]{1,3}),\s?([0-9]{1,3})%?,\s?([0-9]{1,3})%?,?\s?([0-9](\.[0-9]{1,2})?)?\)$/i;
|
|
1705
|
+
/**
|
|
1706
|
+
* Encodes special values for Storybook's args URL format.
|
|
1707
|
+
* Handles undefined, null, booleans, dates, hex colors, and rgba/hsla colors.
|
|
1708
|
+
*/
|
|
1709
|
+
function encodeSpecialValues(value) {
|
|
1710
|
+
if (value === void 0) return "!undefined";
|
|
1711
|
+
if (value === null) return "!null";
|
|
1712
|
+
if (typeof value === "string") {
|
|
1713
|
+
if (HEX_REGEXP.test(value)) return `!hex(${value.slice(1)})`;
|
|
1714
|
+
if (COLOR_REGEXP.test(value)) return `!${value.replace(/[\s%]/g, "")}`;
|
|
1715
|
+
return value;
|
|
1716
|
+
}
|
|
1717
|
+
if (typeof value === "boolean") return `!${value}`;
|
|
1718
|
+
if (value instanceof Date) return `!date(${value.toISOString()})`;
|
|
1719
|
+
if (Array.isArray(value)) return value.map(encodeSpecialValues);
|
|
1720
|
+
if (typeof value === "object" && value !== null) return Object.entries(value).reduce((acc, [key, val]) => Object.assign(acc, { [key]: encodeSpecialValues(val) }), {});
|
|
1721
|
+
return value;
|
|
1722
|
+
}
|
|
1723
|
+
/**
|
|
1724
|
+
* Replaces some url-encoded characters with their decoded equivalents.
|
|
1725
|
+
* The URI RFC specifies these should be encoded, but all browsers will
|
|
1726
|
+
* tolerate them being decoded, so we opt to go with it for cleaner looking URIs.
|
|
1727
|
+
*/
|
|
1728
|
+
function decodeKnownQueryChar(chr) {
|
|
1729
|
+
switch (chr) {
|
|
1730
|
+
case "%20": return "+";
|
|
1731
|
+
case "%5B": return "[";
|
|
1732
|
+
case "%5D": return "]";
|
|
1733
|
+
case "%2C": return ",";
|
|
1734
|
+
case "%3A": return ":";
|
|
1735
|
+
}
|
|
1736
|
+
return chr;
|
|
1737
|
+
}
|
|
1738
|
+
const KNOWN_QUERY_CHAR_REGEXP = /%[0-9A-F]{2}/g;
|
|
1739
|
+
/**
|
|
1740
|
+
* Builds a Storybook args query parameter string from an object of props.
|
|
1741
|
+
*
|
|
1742
|
+
* The format uses semicolons as delimiters and colons for key:value pairs,
|
|
1743
|
+
* with special encoding for booleans, null, undefined, dates, and colors.
|
|
1744
|
+
*
|
|
1745
|
+
* Example output: "disabled:!true;label:Hello+World;count:42"
|
|
1746
|
+
*/
|
|
1747
|
+
function buildArgsParam(args) {
|
|
1748
|
+
if (!args || Object.keys(args).length === 0) return "";
|
|
1749
|
+
return stringify(encodeSpecialValues(args), {
|
|
1750
|
+
delimiter: ";",
|
|
1751
|
+
nesting: true,
|
|
1752
|
+
nestingSyntax: "js"
|
|
1753
|
+
}).replace(KNOWN_QUERY_CHAR_REGEXP, decodeKnownQueryChar).split(";").map((part) => part.replace("=", ":")).join(";");
|
|
1754
|
+
}
|
|
1755
|
+
|
|
1756
|
+
//#endregion
|
|
1757
|
+
//#region src/tools/preview-stories/preview-stories-app-template.html
|
|
1758
|
+
var preview_stories_app_template_default = "<!doctype html>\n<html>\n <head>\n <meta charset=\"utf-8\" />\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\" />\n <style>\n * {\n margin: 0;\n padding: 0;\n box-sizing: border-box;\n }\n html[data-theme='light'] {\n color-scheme: light;\n }\n html[data-theme='dark'] {\n color-scheme: dark;\n }\n html,\n body {\n width: 100%;\n margin: 0;\n padding: 0;\n background-color: var(--color-background-secondary);\n }\n body {\n display: flex;\n flex-direction: column;\n gap: 1rem;\n }\n :root {\n /*\n These are fallback values, if the MCP client doesn't set them.\n See https://github.com/modelcontextprotocol/ext-apps/blob/main/specification/draft/apps.mdx#theming\n */\n --color-text-primary: light-dark(black, white);\n --color-border-primary: light-dark(#ccc, #444);\n --color-background-secondary: light-dark(#f9f9f9, #1e1e1e);\n --font-sans:\n -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Oxygen-Sans', Ubuntu, Cantarell,\n 'Helvetica Neue', sans-serif;\n --font-heading-xs-size: 1rem;\n --font-heading-xs-line-height: 1.25;\n --border-width-regular: 1px;\n }\n .story-heading {\n font-family: var(--font-sans);\n font-size: var(--font-heading-xs-size);\n line-height: var(--font-heading-xs-line-height);\n color: var(--color-text-primary);\n padding: 0.5rem 0;\n }\n .story-iframe {\n background-color: white;\n border: var(--border-width-regular) solid var(--color-border-primary);\n }\n body:has(> article:only-child) h1 {\n /* if there is only one story rendered, hide its heading */\n display: none;\n }\n </style>\n <template id=\"preview-template\">\n <article>\n <h1 class=\"story-heading\"></h1>\n <iframe class=\"story-iframe\"></iframe>\n </article>\n </template>\n <script type=\"module\">\n // APP_SCRIPT_PLACEHOLDER\n <\/script>\n </head>\n <body></body>\n</html>\n";
|
|
1759
|
+
|
|
1760
|
+
//#endregion
|
|
1761
|
+
//#region src/tools/preview-stories.ts
|
|
1762
|
+
const PREVIEW_STORIES_RESOURCE_URI = `ui://${PREVIEW_STORIES_TOOL_NAME}/preview.html`;
|
|
1763
|
+
function getPreviewStoriesToolDescription({ reviewEnabled = false } = {}) {
|
|
1764
|
+
if (!reviewEnabled) return `Use this tool to get one or more Storybook preview URLs.
|
|
1765
|
+
Call it after editing anything that changes how the UI looks — components, stories, styles, CSS, themes, colors, or design tokens — no exceptions. A shared file has no stories of its own: preview the stories of the components that consume it.
|
|
1766
|
+
Include each returned preview URL in your final user-facing response so users can open them directly.`;
|
|
1767
|
+
return `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.
|
|
1768
|
+
Do not end visual work or browse requests with these links — publish a curated review with display-review instead (passing changedFiles: [] when no code changed) and link that.`;
|
|
1769
|
+
}
|
|
1770
|
+
const PreviewStoriesInput = v.object({ stories: v.pipe(StoryInputArray, v.description(`Stories to preview.
|
|
1771
|
+
Prefer { storyId } when you don't already have story file context, since this avoids filesystem discovery.
|
|
1772
|
+
Use { storyId } when IDs were discovered from documentation tools.
|
|
1773
|
+
Use { absoluteStoryPath + exportName } only when you're already working in a specific .stories.* file and already have that context.`)) });
|
|
1774
|
+
const PreviewStoriesOutput = v.object({ stories: v.array(v.union([v.object({
|
|
1775
|
+
title: v.string(),
|
|
1776
|
+
name: v.string(),
|
|
1777
|
+
previewUrl: v.pipe(v.string(), v.description("Direct URL to open the story preview. Include this URL in the final user-facing response so users can open it directly — unless a curated review page is being published via display-review, in which case link the review page instead of listing individual URLs."))
|
|
1778
|
+
}), v.object({
|
|
1779
|
+
input: StoryInput,
|
|
1780
|
+
error: v.string()
|
|
1781
|
+
})])) });
|
|
1782
|
+
function getPreviewStoriesToolMetadata({ reviewEnabled = false } = {}) {
|
|
1783
|
+
return {
|
|
1784
|
+
name: PREVIEW_STORIES_TOOL_NAME,
|
|
1785
|
+
title: "Get story preview URLs",
|
|
1786
|
+
description: getPreviewStoriesToolDescription({ reviewEnabled }),
|
|
1787
|
+
schema: PreviewStoriesInput,
|
|
1788
|
+
outputSchema: PreviewStoriesOutput,
|
|
1789
|
+
_meta: { ui: { resourceUri: PREVIEW_STORIES_RESOURCE_URI } }
|
|
1790
|
+
};
|
|
1791
|
+
}
|
|
1792
|
+
async function addPreviewStoriesTool(server, enabled = () => server.ctx.custom?.toolsets?.dev ?? true, { reviewEnabled = false } = {}) {
|
|
1793
|
+
const previewStoryAppScript = await fs$1.readFile(url.fileURLToPath(import.meta.resolve("@storybook/addon-mcp/internal/preview-stories-app-script")), "utf-8");
|
|
1794
|
+
const appHtml = preview_stories_app_template_default.replace("// APP_SCRIPT_PLACEHOLDER", previewStoryAppScript);
|
|
1795
|
+
server.resource({
|
|
1796
|
+
name: PREVIEW_STORIES_RESOURCE_URI,
|
|
1797
|
+
description: "App resource for the Preview Stories tool",
|
|
1798
|
+
uri: PREVIEW_STORIES_RESOURCE_URI,
|
|
1799
|
+
mimeType: "text/html;profile=mcp-app"
|
|
1800
|
+
}, () => {
|
|
1801
|
+
const origin = server.ctx.custom.origin;
|
|
1802
|
+
return { contents: [{
|
|
1803
|
+
uri: PREVIEW_STORIES_RESOURCE_URI,
|
|
1804
|
+
mimeType: "text/html;profile=mcp-app",
|
|
1805
|
+
text: appHtml,
|
|
1806
|
+
_meta: { ui: {
|
|
1807
|
+
prefersBorder: false,
|
|
1808
|
+
domain: origin,
|
|
1809
|
+
csp: {
|
|
1810
|
+
connectDomains: [origin],
|
|
1811
|
+
resourceDomains: [origin],
|
|
1812
|
+
frameDomains: [origin],
|
|
1813
|
+
baseUriDomains: [origin]
|
|
1814
|
+
}
|
|
1815
|
+
} }
|
|
1816
|
+
}] };
|
|
1817
|
+
});
|
|
1818
|
+
server.tool({
|
|
1819
|
+
...getPreviewStoriesToolMetadata({ reviewEnabled }),
|
|
1820
|
+
enabled
|
|
1821
|
+
}, async (input) => {
|
|
1822
|
+
try {
|
|
1823
|
+
const { origin, options, disableTelemetry } = server.ctx.custom ?? {};
|
|
1824
|
+
if (!origin) throw new Error("Origin is required in addon context");
|
|
1825
|
+
if (!options) throw new Error("Storybook options are required in addon context");
|
|
1826
|
+
const index = await getStoryIndex(options);
|
|
1827
|
+
const resolvedStories = findStoryIds(index, input.stories);
|
|
1828
|
+
const structuredResult = [];
|
|
1829
|
+
const textResult = [];
|
|
1830
|
+
for (const story of resolvedStories) {
|
|
1831
|
+
if ("errorMessage" in story) {
|
|
1832
|
+
structuredResult.push({
|
|
1833
|
+
input: story.input,
|
|
1834
|
+
error: story.errorMessage
|
|
1835
|
+
});
|
|
1836
|
+
textResult.push(story.errorMessage);
|
|
1837
|
+
continue;
|
|
1838
|
+
}
|
|
1839
|
+
const indexEntry = index.entries[story.id];
|
|
1840
|
+
if (!indexEntry) {
|
|
1841
|
+
structuredResult.push({
|
|
1842
|
+
input: story.input,
|
|
1843
|
+
error: `No story found for story ID "${story.id}"`
|
|
1844
|
+
});
|
|
1845
|
+
textResult.push(`No story found for story ID "${story.id}"`);
|
|
1846
|
+
continue;
|
|
1847
|
+
}
|
|
1848
|
+
let previewUrl = `${origin}/?path=/story/${story.id}`;
|
|
1849
|
+
const argsParam = buildArgsParam(story.input.props ?? {});
|
|
1850
|
+
if (argsParam) previewUrl += `&args=${argsParam}`;
|
|
1851
|
+
const globalsParam = buildArgsParam(story.input.globals ?? {});
|
|
1852
|
+
if (globalsParam) previewUrl += `&globals=${globalsParam}`;
|
|
1853
|
+
structuredResult.push({
|
|
1854
|
+
title: indexEntry.title,
|
|
1855
|
+
name: indexEntry.name,
|
|
1856
|
+
previewUrl
|
|
1857
|
+
});
|
|
1858
|
+
textResult.push(previewUrl);
|
|
1859
|
+
}
|
|
1860
|
+
if (!disableTelemetry) await collectTelemetry({
|
|
1861
|
+
event: "tool:previewStories",
|
|
1862
|
+
server,
|
|
1863
|
+
toolset: "dev",
|
|
1864
|
+
inputStoryCount: input.stories.length,
|
|
1865
|
+
outputStoryCount: structuredResult.length
|
|
1866
|
+
});
|
|
1867
|
+
const content = textResult.map((text) => ({
|
|
1868
|
+
type: "text",
|
|
1869
|
+
text
|
|
1870
|
+
}));
|
|
1871
|
+
const resolvedAnyStory = structuredResult.some((story) => "previewUrl" in story);
|
|
1872
|
+
if (reviewEnabled && resolvedAnyStory) content.push({
|
|
1873
|
+
type: "text",
|
|
1874
|
+
text: `These preview links are for iterating or sharing a specific story — 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.`
|
|
1875
|
+
});
|
|
1876
|
+
return {
|
|
1877
|
+
content,
|
|
1878
|
+
structuredContent: { stories: structuredResult }
|
|
1879
|
+
};
|
|
1880
|
+
} catch (error) {
|
|
1881
|
+
return errorToMCPContent(error);
|
|
1882
|
+
}
|
|
1883
|
+
});
|
|
1884
|
+
}
|
|
779
1885
|
|
|
780
1886
|
//#endregion
|
|
781
|
-
//#region src/
|
|
782
|
-
|
|
783
|
-
|
|
784
|
-
|
|
785
|
-
|
|
786
|
-
|
|
787
|
-
|
|
788
|
-
|
|
789
|
-
|
|
790
|
-
|
|
791
|
-
|
|
792
|
-
|
|
793
|
-
|
|
794
|
-
|
|
795
|
-
|
|
796
|
-
|
|
797
|
-
|
|
798
|
-
|
|
799
|
-
|
|
800
|
-
|
|
801
|
-
|
|
802
|
-
|
|
803
|
-
|
|
804
|
-
|
|
805
|
-
|
|
806
|
-
|
|
807
|
-
|
|
808
|
-
|
|
809
|
-
|
|
810
|
-
|
|
811
|
-
|
|
812
|
-
|
|
813
|
-
|
|
814
|
-
|
|
815
|
-
|
|
816
|
-
|
|
817
|
-
|
|
818
|
-
|
|
819
|
-
|
|
820
|
-
|
|
821
|
-
|
|
822
|
-
}
|
|
823
|
-
|
|
824
|
-
|
|
825
|
-
|
|
826
|
-
|
|
827
|
-
|
|
828
|
-
|
|
1887
|
+
//#region src/tools/tool-registry.ts
|
|
1888
|
+
const isToolsetEnabled = (toolset, toolsets) => toolsets?.[toolset] ?? true;
|
|
1889
|
+
const isToolAvailable = (definition, context) => definition.available?.(context) ?? true;
|
|
1890
|
+
const isMetadataToolEnabled = (definition, context) => isToolsetEnabled(definition.toolset, context.toolsets) && isToolAvailable(definition, context);
|
|
1891
|
+
const createToolsetEnabled = (server, toolset) => () => server.ctx.custom?.toolsets?.[toolset] ?? true;
|
|
1892
|
+
const addonToolDefinitions = [
|
|
1893
|
+
{
|
|
1894
|
+
name: PREVIEW_STORIES_TOOL_NAME,
|
|
1895
|
+
toolset: "dev",
|
|
1896
|
+
getMetadata: ({ availability }) => getPreviewStoriesToolMetadata({ reviewEnabled: availability.reviewEnabled }),
|
|
1897
|
+
register: (server, { availability }, enabled) => addPreviewStoriesTool(server, enabled, { reviewEnabled: availability.reviewEnabled })
|
|
1898
|
+
},
|
|
1899
|
+
{
|
|
1900
|
+
name: GET_UI_BUILDING_INSTRUCTIONS_TOOL_NAME,
|
|
1901
|
+
toolset: "dev",
|
|
1902
|
+
getMetadata: ({ availability, toolsets }) => {
|
|
1903
|
+
const testToolsetAvailable = isToolsetEnabled("test", toolsets) && availability.testSupported;
|
|
1904
|
+
return getStorybookStoryInstructionsToolMetadata({
|
|
1905
|
+
testToolsetAvailable,
|
|
1906
|
+
a11yAvailable: testToolsetAvailable && availability.a11yEnabled
|
|
1907
|
+
});
|
|
1908
|
+
},
|
|
1909
|
+
register: (server, { availability, toolsets }, enabled) => addGetUIBuildingInstructionsTool(server, enabled, { docsAvailable: isToolsetEnabled("docs", toolsets) && availability.docsEnabled }),
|
|
1910
|
+
getLocalTool: ({ availability, toolsets, options }) => ({ call: async () => {
|
|
1911
|
+
return { content: [{
|
|
1912
|
+
type: "text",
|
|
1913
|
+
text: await buildStorybookStoryInstructions(options, {
|
|
1914
|
+
toolsets,
|
|
1915
|
+
a11yEnabled: availability.a11yEnabled,
|
|
1916
|
+
addonVitestAvailable: availability.testSupported,
|
|
1917
|
+
docsAvailable: isToolsetEnabled("docs", toolsets) && availability.docsEnabled,
|
|
1918
|
+
reviewEnabled: availability.reviewEnabled
|
|
1919
|
+
})
|
|
1920
|
+
}] };
|
|
1921
|
+
} })
|
|
1922
|
+
},
|
|
1923
|
+
{
|
|
1924
|
+
name: GET_CHANGED_STORIES_TOOL_NAME,
|
|
1925
|
+
toolset: "dev",
|
|
1926
|
+
available: ({ availability }) => availability.changeDetectionEnabled,
|
|
1927
|
+
getMetadata: () => getChangedStoriesToolMetadata(),
|
|
1928
|
+
register: (server, { availability }, enabled) => addGetChangedStoriesTool(server, enabled, { reviewEnabled: availability.reviewEnabled })
|
|
1929
|
+
},
|
|
1930
|
+
{
|
|
1931
|
+
name: GET_STORIES_BY_COMPONENT_TOOL_NAME,
|
|
1932
|
+
toolset: "dev",
|
|
1933
|
+
available: ({ availability }) => availability.moduleGraphSupported,
|
|
1934
|
+
getMetadata: ({ availability }) => getStoriesByComponentToolMetadata({ reviewEnabled: availability.reviewEnabled }),
|
|
1935
|
+
register: (server, { availability }, enabled) => addGetStoriesByComponentTool(server, enabled, { reviewEnabled: availability.reviewEnabled })
|
|
1936
|
+
},
|
|
1937
|
+
{
|
|
1938
|
+
name: DISPLAY_REVIEW_TOOL_NAME,
|
|
1939
|
+
toolset: "dev",
|
|
1940
|
+
available: ({ availability }) => availability.reviewEnabledForCli,
|
|
1941
|
+
getMetadata: () => getDisplayReviewToolMetadata(),
|
|
1942
|
+
register: (server, { availability }, enabled) => addDisplayReviewTool(server, async () => (await enabled?.() ?? true) && (server.ctx.custom?.reviewEnabled ?? availability.reviewEnabled))
|
|
1943
|
+
},
|
|
1944
|
+
{
|
|
1945
|
+
name: RUN_STORY_TESTS_TOOL_NAME,
|
|
1946
|
+
toolset: "test",
|
|
1947
|
+
available: ({ availability }) => availability.testSupported,
|
|
1948
|
+
getMetadata: ({ availability }) => getRunStoryTestsToolMetadata({ a11yEnabled: availability.a11yEnabled }),
|
|
1949
|
+
register: (server, { availability }, enabled) => addRunStoryTestsTool(server, { a11yEnabled: availability.a11yEnabled }, enabled)
|
|
1950
|
+
},
|
|
1951
|
+
{
|
|
1952
|
+
name: LIST_TOOL_NAME,
|
|
1953
|
+
toolset: "docs",
|
|
1954
|
+
available: ({ availability }) => availability.docsEnabled,
|
|
1955
|
+
getMetadata: () => getListAllDocumentationToolMetadata(),
|
|
1956
|
+
register: async (server, _context, enabled) => {
|
|
1957
|
+
logger.info("Experimental components manifest feature detected - registering component tools");
|
|
1958
|
+
await addListAllDocumentationTool(server, enabled);
|
|
829
1959
|
}
|
|
1960
|
+
},
|
|
1961
|
+
{
|
|
1962
|
+
name: GET_TOOL_NAME,
|
|
1963
|
+
toolset: "docs",
|
|
1964
|
+
available: ({ availability }) => availability.docsEnabled,
|
|
1965
|
+
getMetadata: ({ multiSource }) => getDocumentationToolMetadata({ multiSource }),
|
|
1966
|
+
register: (server, { multiSource }, enabled) => addGetDocumentationTool(server, enabled, { multiSource })
|
|
1967
|
+
},
|
|
1968
|
+
{
|
|
1969
|
+
name: GET_STORY_TOOL_NAME,
|
|
1970
|
+
toolset: "docs",
|
|
1971
|
+
available: ({ availability }) => availability.docsEnabled,
|
|
1972
|
+
getMetadata: ({ multiSource }) => getStoryDocumentationToolMetadata({ multiSource }),
|
|
1973
|
+
register: (server, { multiSource }, enabled) => addGetStoryDocumentationTool(server, enabled, { multiSource })
|
|
830
1974
|
}
|
|
831
|
-
|
|
1975
|
+
];
|
|
1976
|
+
function getAddonToolMetadata(context) {
|
|
1977
|
+
return addonToolDefinitions.filter((definition) => isMetadataToolEnabled(definition, context)).map((definition) => definition.getMetadata(context));
|
|
832
1978
|
}
|
|
833
|
-
|
|
834
|
-
|
|
835
|
-
|
|
836
|
-
|
|
837
|
-
|
|
838
|
-
|
|
839
|
-
|
|
840
|
-
|
|
841
|
-
|
|
842
|
-
//#endregion
|
|
843
|
-
//#region src/instructions/build-server-instructions.ts
|
|
844
|
-
function buildServerInstructions(options) {
|
|
845
|
-
const sections = ["Follow these workflows when working with UI and/or Storybook."];
|
|
846
|
-
if (options.devEnabled) sections.push(dev_instructions_default.trim());
|
|
847
|
-
if (options.testEnabled) sections.push(test_instructions_default.trim());
|
|
848
|
-
if (options.docsEnabled) sections.push(STORYBOOK_MCP_INSTRUCTIONS.trim());
|
|
849
|
-
if (sections.length === 1) return "";
|
|
850
|
-
return sections.join("\n\n");
|
|
1979
|
+
function getAddonLocalTools(context) {
|
|
1980
|
+
return Object.fromEntries(addonToolDefinitions.filter((definition) => isMetadataToolEnabled(definition, context)).flatMap((definition) => {
|
|
1981
|
+
const localTool = definition.getLocalTool?.(context);
|
|
1982
|
+
return localTool ? [[definition.name, localTool]] : [];
|
|
1983
|
+
}));
|
|
1984
|
+
}
|
|
1985
|
+
async function registerAddonMcpTools(server, context) {
|
|
1986
|
+
for (const definition of addonToolDefinitions) if (isToolsetEnabled(definition.toolset, context.toolsets) && isToolAvailable(definition, context)) await definition.register(server, context, createToolsetEnabled(server, definition.toolset));
|
|
851
1987
|
}
|
|
852
1988
|
|
|
853
1989
|
//#endregion
|
|
@@ -857,19 +1993,28 @@ let origin;
|
|
|
857
1993
|
let initialize;
|
|
858
1994
|
let disableTelemetry;
|
|
859
1995
|
let a11yEnabled;
|
|
1996
|
+
let reviewGates;
|
|
860
1997
|
const initializeMCPServer = async (options, multiSource) => {
|
|
861
|
-
|
|
862
|
-
const
|
|
863
|
-
|
|
864
|
-
|
|
1998
|
+
const core = await options.presets.apply("core", {});
|
|
1999
|
+
const features = await options.presets.apply("features", {});
|
|
2000
|
+
disableTelemetry = core?.disableTelemetry ?? false;
|
|
2001
|
+
const availability = getEffectiveToolAvailability(await getToolAvailability(options, { features }), { multiSource });
|
|
2002
|
+
a11yEnabled = availability.a11yEnabled;
|
|
2003
|
+
reviewGates = {
|
|
2004
|
+
reviewEnabled: availability.reviewEnabled,
|
|
2005
|
+
reviewEnabledForCli: availability.reviewEnabledForCli
|
|
2006
|
+
};
|
|
865
2007
|
let server;
|
|
866
2008
|
const serverOptions = {
|
|
867
2009
|
adapter: new ValibotJsonSchemaAdapter(),
|
|
868
2010
|
get instructions() {
|
|
869
2011
|
return buildServerInstructions({
|
|
870
2012
|
devEnabled: server?.ctx.custom?.toolsets?.dev ?? true,
|
|
871
|
-
testEnabled: (server?.ctx.custom?.toolsets?.test ?? true) &&
|
|
872
|
-
docsEnabled: (server?.ctx.custom?.toolsets?.docs ?? true) &&
|
|
2013
|
+
testEnabled: (server?.ctx.custom?.toolsets?.test ?? true) && availability.testSupported,
|
|
2014
|
+
docsEnabled: (server?.ctx.custom?.toolsets?.docs ?? true) && availability.docsEnabled,
|
|
2015
|
+
changeDetectionEnabled: availability.changeDetectionEnabled,
|
|
2016
|
+
moduleGraphSupported: availability.moduleGraphSupported,
|
|
2017
|
+
reviewEnabled: server?.ctx.custom?.reviewEnabled ?? availability.reviewEnabled
|
|
873
2018
|
});
|
|
874
2019
|
},
|
|
875
2020
|
capabilities: {
|
|
@@ -888,34 +2033,31 @@ const initializeMCPServer = async (options, multiSource) => {
|
|
|
888
2033
|
server
|
|
889
2034
|
});
|
|
890
2035
|
});
|
|
891
|
-
await
|
|
892
|
-
|
|
893
|
-
|
|
894
|
-
|
|
895
|
-
logger.info("Experimental components manifest feature detected - registering component tools");
|
|
896
|
-
const contextAwareEnabled = () => server.ctx.custom?.toolsets?.docs ?? true;
|
|
897
|
-
await addListAllDocumentationTool(server, contextAwareEnabled);
|
|
898
|
-
await addGetDocumentationTool(server, contextAwareEnabled, { multiSource });
|
|
899
|
-
await addGetStoryDocumentationTool(server, contextAwareEnabled, { multiSource });
|
|
900
|
-
}
|
|
2036
|
+
await registerAddonMcpTools(server, {
|
|
2037
|
+
availability,
|
|
2038
|
+
multiSource
|
|
2039
|
+
});
|
|
901
2040
|
transport = new HttpTransport(server, { path: null });
|
|
902
2041
|
origin = `http://localhost:${options.port}`;
|
|
903
2042
|
logger.debug(`MCP server origin: ${origin}`);
|
|
904
2043
|
return server;
|
|
905
2044
|
};
|
|
906
|
-
const mcpServerHandler = async ({ req, res, options, addonOptions, sources, manifestProvider, compositionAuth }) => {
|
|
2045
|
+
const mcpServerHandler = async ({ req, res, options, addonOptions, endpoint = DEFAULT_MCP_ENDPOINT, sources, manifestProvider, resolveEntry, compositionAuth }) => {
|
|
907
2046
|
if (!initialize) initialize = initializeMCPServer(options, sources?.some((s) => s.url));
|
|
908
2047
|
const server = await initialize;
|
|
909
2048
|
const webRequest = await incomingMessageToWebRequest(req);
|
|
910
2049
|
const addonContext = {
|
|
911
2050
|
options,
|
|
2051
|
+
endpoint,
|
|
912
2052
|
toolsets: getToolsets(webRequest, addonOptions),
|
|
2053
|
+
reviewEnabled: isReviewEnabledForRequest(webRequest, reviewGates),
|
|
913
2054
|
origin,
|
|
914
2055
|
disableTelemetry,
|
|
915
2056
|
a11yEnabled,
|
|
916
2057
|
request: webRequest,
|
|
917
2058
|
sources,
|
|
918
2059
|
manifestProvider,
|
|
2060
|
+
resolveEntry,
|
|
919
2061
|
...!disableTelemetry && {
|
|
920
2062
|
onListAllDocumentation: async ({ manifests, resultText, sources: sourceManifests }) => {
|
|
921
2063
|
await collectTelemetry({
|
|
@@ -991,6 +2133,15 @@ async function webResponseToServerResponse(webResponse, nodeResponse) {
|
|
|
991
2133
|
}
|
|
992
2134
|
nodeResponse.end();
|
|
993
2135
|
}
|
|
2136
|
+
/**
|
|
2137
|
+
* Review is on for a request when the `experimentalReview` flag enables it
|
|
2138
|
+
* globally, or when the request marks itself as coming from the `storybook ai`
|
|
2139
|
+
* CLI (the Claude/Codex plugins) via {@link STORYBOOK_MCP_PROXY_HEADER} —
|
|
2140
|
+
* that channel gets review by default, direct MCP clients stay opt-in.
|
|
2141
|
+
*/
|
|
2142
|
+
function isReviewEnabledForRequest(request, gates) {
|
|
2143
|
+
return gates.reviewEnabled || gates.reviewEnabledForCli && request.headers.get(STORYBOOK_MCP_PROXY_HEADER) === "true";
|
|
2144
|
+
}
|
|
994
2145
|
function getToolsets(request, addonOptions) {
|
|
995
2146
|
const toolsetHeader = request.headers.get("X-MCP-Toolsets");
|
|
996
2147
|
if (!toolsetHeader || toolsetHeader.trim() === "") return addonOptions.toolsets;
|
|
@@ -1009,7 +2160,7 @@ function getToolsets(request, addonOptions) {
|
|
|
1009
2160
|
|
|
1010
2161
|
//#endregion
|
|
1011
2162
|
//#region src/template.html
|
|
1012
|
-
var template_default = "<!doctype html>\n<html>\n <head>\n <style>\n @font-face {\n font-family: 'Nunito Sans';\n font-style: normal;\n font-weight: 400;\n font-display: swap;\n src: url('./sb-common-assets/nunito-sans-regular.woff2') format('woff2');\n }\n\n * {\n margin: 0;\n padding: 0;\n box-sizing: border-box;\n }\n\n html,\n body {\n height: 100%;\n font-family:\n 'Nunito Sans',\n -apple-system,\n BlinkMacSystemFont,\n 'Segoe UI',\n Roboto,\n Oxygen,\n Ubuntu,\n Cantarell,\n sans-serif;\n }\n\n body {\n display: flex;\n flex-direction: column;\n justify-content: center;\n align-items: center;\n text-align: center;\n padding: 2rem;\n background-color: #ffffff;\n color: rgb(46, 52, 56);\n line-height: 1.6;\n }\n\n p {\n margin-bottom: 1rem;\n }\n\n code {\n font-family: 'Monaco', 'Courier New', monospace;\n background: #f5f5f5;\n padding: 0.2em 0.4em;\n border-radius: 3px;\n }\n\n a {\n color: #1ea7fd;\n }\n\n .container {\n display: flex;\n flex-direction: column;\n align-items: center;\n }\n\n .toolsets {\n margin: 1.5rem 0;\n text-align: left;\n max-width: 500px;\n }\n\n .toolsets h3 {\n font-size: 1rem;\n margin-bottom: 0.75rem;\n text-align: center;\n }\n\n .toolset {\n margin-bottom: 1rem;\n padding: 0.75rem 1rem;\n border-radius: 6px;\n background: #f8f9fa;\n border: 1px solid #e9ecef;\n }\n\n .toolset-header {\n display: flex;\n align-items: center;\n gap: 0.5rem;\n font-weight: 600;\n margin-bottom: 0.5rem;\n }\n\n .toolset-status {\n display: inline-block;\n padding: 0.15em 0.5em;\n border-radius: 3px;\n font-size: 0.75rem;\n font-weight: 500;\n text-transform: uppercase;\n }\n\n .toolset-status.enabled {\n background: #d4edda;\n color: #155724;\n }\n\n .toolset-status.disabled {\n background: #f8d7da;\n color: #721c24;\n }\n\n .toolset-tools {\n font-size: 0.875rem;\n color: #6c757d;\n padding-left: 1.5rem;\n margin: 0;\n }\n\n .toolset-tools li {\n margin-bottom: 0.25rem;\n }\n\n .toolset-tools code {\n font-size: 0.8rem;\n }\n\n .toolset-notice {\n font-size: 0.8rem;\n color: #856404;\n background: #fff3cd;\n padding: 0.5rem;\n border-radius: 4px;\n margin-top: 0.5rem;\n }\n\n .toolset-notice a {\n color: #533f03;\n }\n\n @media (prefers-color-scheme: dark) {\n body {\n background-color: rgb(34, 36, 37);\n color: rgb(201, 205, 207);\n }\n\n code {\n background: rgba(255, 255, 255, 0.1);\n }\n\n .toolset {\n background: rgba(255, 255, 255, 0.05);\n border-color: rgba(255, 255, 255, 0.1);\n }\n\n .toolset-tools {\n color: #adb5bd;\n }\n\n .toolset-status.enabled {\n background: rgba(40, 167, 69, 0.2);\n color: #75d67e;\n }\n\n .toolset-status.disabled {\n background: rgba(220, 53, 69, 0.2);\n color: #f5a6ad;\n }\n\n .toolset-notice {\n background: rgba(255, 193, 7, 0.15);\n color: #ffc107;\n }\n\n .toolset-notice a {\n color: #ffe066;\n }\n }\n </style>\n </head>\n <body>\n <div class=\"container\">\n <p>\n Storybook MCP server successfully running via\n <code>@storybook/addon-mcp</code>.\n </p>\n <p>\n See how to connect to it from your coding agent in\n <a\n target=\"_blank\"\n href=\"https://github.com/storybookjs/mcp/tree/main/packages/addon-mcp#configuring-your-agent\"\n >the addon's README</a\n >.\n </p>\n\n <div class=\"toolsets\">\n <h3>Available Toolsets</h3>\n\n <div class=\"toolset\">\n <div class=\"toolset-header\">\n <span>dev</span>\n <span class=\"toolset-status {{DEV_STATUS}}\">{{DEV_STATUS}}</span>\n </div>\n <ul class=\"toolset-tools\">\n <li><code>preview-stories</code></li>\n <li><code>get-storybook-story-instructions</code></li>\n </ul>\n </div>\n\n <div class=\"toolset\">\n <div class=\"toolset-header\">\n <span>docs</span>\n <span class=\"toolset-status {{DOCS_STATUS}}\">{{DOCS_STATUS}}</span>\n </div>\n <ul class=\"toolset-tools\">\n <li><code>list-all-documentation</code></li>\n <li><code>get-documentation</code></li>\n </ul>\n {{DOCS_NOTICE}}\n </div>\n\n <div class=\"toolset\">\n <div class=\"toolset-header\">\n <span>test</span>\n <span class=\"toolset-status {{TEST_STATUS}}\">{{TEST_STATUS}}</span>\n </div>\n <ul class=\"toolset-tools\">\n <li><code>run-story-tests</code>{{A11Y_BADGE}}</li>\n </ul>\n {{TEST_NOTICE}}\n </div>\n </div>\n\n {{MANIFEST_DEBUGGER_LINK}}\n </div>\n </body>\n</html>\n";
|
|
2163
|
+
var template_default = "<!doctype html>\n<html>\n <head>\n <style>\n @font-face {\n font-family: 'Nunito Sans';\n font-style: normal;\n font-weight: 400;\n font-display: swap;\n src: url('./sb-common-assets/nunito-sans-regular.woff2') format('woff2');\n }\n\n * {\n margin: 0;\n padding: 0;\n box-sizing: border-box;\n }\n\n html,\n body {\n height: 100%;\n font-family:\n 'Nunito Sans',\n -apple-system,\n BlinkMacSystemFont,\n 'Segoe UI',\n Roboto,\n Oxygen,\n Ubuntu,\n Cantarell,\n sans-serif;\n }\n\n body {\n display: flex;\n flex-direction: column;\n justify-content: center;\n align-items: center;\n text-align: center;\n padding: 2rem;\n background-color: #ffffff;\n color: rgb(46, 52, 56);\n line-height: 1.6;\n }\n\n p {\n margin-bottom: 1rem;\n }\n\n code {\n font-family: 'Monaco', 'Courier New', monospace;\n background: #f5f5f5;\n padding: 0.2em 0.4em;\n border-radius: 3px;\n }\n\n a {\n color: #1ea7fd;\n }\n\n .container {\n display: flex;\n flex-direction: column;\n align-items: center;\n }\n\n .toolsets {\n margin: 1.5rem 0;\n text-align: left;\n max-width: 500px;\n }\n\n .toolsets h3 {\n font-size: 1rem;\n margin-bottom: 0.75rem;\n text-align: center;\n }\n\n .toolset {\n margin-bottom: 1rem;\n padding: 0.75rem 1rem;\n border-radius: 6px;\n background: #f8f9fa;\n border: 1px solid #e9ecef;\n }\n\n .toolset-header {\n display: flex;\n align-items: center;\n gap: 0.5rem;\n font-weight: 600;\n margin-bottom: 0.5rem;\n }\n\n .toolset-status {\n display: inline-block;\n padding: 0.15em 0.5em;\n border-radius: 3px;\n font-size: 0.75rem;\n font-weight: 500;\n text-transform: uppercase;\n }\n\n .toolset-status.enabled {\n background: #d4edda;\n color: #155724;\n }\n\n .toolset-status.disabled {\n background: #f8d7da;\n color: #721c24;\n }\n\n .toolset-tools {\n font-size: 0.875rem;\n color: #6c757d;\n padding-left: 1.5rem;\n margin: 0;\n }\n\n .toolset-tools li {\n margin-bottom: 0.25rem;\n }\n\n .toolset-tools code {\n font-size: 0.8rem;\n }\n\n .toolset-notice {\n font-size: 0.8rem;\n color: #856404;\n background: #fff3cd;\n padding: 0.5rem;\n border-radius: 4px;\n margin-top: 0.5rem;\n }\n\n .toolset-notice a {\n color: #533f03;\n }\n\n @media (prefers-color-scheme: dark) {\n body {\n background-color: rgb(34, 36, 37);\n color: rgb(201, 205, 207);\n }\n\n code {\n background: rgba(255, 255, 255, 0.1);\n }\n\n .toolset {\n background: rgba(255, 255, 255, 0.05);\n border-color: rgba(255, 255, 255, 0.1);\n }\n\n .toolset-tools {\n color: #adb5bd;\n }\n\n .toolset-status.enabled {\n background: rgba(40, 167, 69, 0.2);\n color: #75d67e;\n }\n\n .toolset-status.disabled {\n background: rgba(220, 53, 69, 0.2);\n color: #f5a6ad;\n }\n\n .toolset-notice {\n background: rgba(255, 193, 7, 0.15);\n color: #ffc107;\n }\n\n .toolset-notice a {\n color: #ffe066;\n }\n }\n </style>\n </head>\n <body>\n <div class=\"container\">\n <p>\n Storybook MCP server successfully running via\n <code>@storybook/addon-mcp</code>.\n </p>\n <p>\n See how to connect to it from your coding agent in\n <a\n target=\"_blank\"\n href=\"https://github.com/storybookjs/mcp/tree/main/packages/addon-mcp#configuring-your-agent\"\n >the addon's README</a\n >.\n </p>\n\n <div class=\"toolsets\">\n <h3>Available Toolsets</h3>\n\n <div class=\"toolset\">\n <div class=\"toolset-header\">\n <span>dev</span>\n <span class=\"toolset-status {{DEV_STATUS}}\">{{DEV_STATUS}}</span>\n </div>\n <ul class=\"toolset-tools\">\n <li><code>preview-stories</code></li>\n <li><code>get-storybook-story-instructions</code></li>\n <li>\n <code>get-changed-stories</code>\n <span class=\"toolset-status {{CHANGE_DETECTION_STATUS}}\"\n >{{CHANGE_DETECTION_STATUS}}</span\n >\n </li>\n <li>\n <code>get-stories-by-component</code>\n <span class=\"toolset-status {{STORIES_BY_COMPONENT_STATUS}}\"\n >{{STORIES_BY_COMPONENT_STATUS}}</span\n >\n </li>\n <li>\n <code>display-review</code>\n <span class=\"toolset-status {{REVIEW_STATUS}}\">{{REVIEW_STATUS}}</span>\n </li>\n </ul>\n {{DEV_NOTICE}}\n </div>\n\n <div class=\"toolset\">\n <div class=\"toolset-header\">\n <span>docs</span>\n <span class=\"toolset-status {{DOCS_STATUS}}\">{{DOCS_STATUS}}</span>\n </div>\n <ul class=\"toolset-tools\">\n <li><code>list-all-documentation</code></li>\n <li><code>get-documentation</code></li>\n <li><code>get-documentation-for-story</code></li>\n </ul>\n {{DOCS_NOTICE}}\n </div>\n\n <div class=\"toolset\">\n <div class=\"toolset-header\">\n <span>test</span>\n <span class=\"toolset-status {{TEST_STATUS}}\">{{TEST_STATUS}}</span>\n </div>\n <ul class=\"toolset-tools\">\n <li><code>run-story-tests</code>{{A11Y_BADGE}}</li>\n </ul>\n {{TEST_NOTICE}}\n </div>\n </div>\n\n {{MANIFEST_DEBUGGER_LINK}}\n </div>\n </body>\n</html>\n";
|
|
1013
2164
|
|
|
1014
2165
|
//#endregion
|
|
1015
2166
|
//#region src/auth/composition-auth.ts
|
|
@@ -1102,13 +2253,26 @@ var CompositionAuth = class {
|
|
|
1102
2253
|
url: ref.url
|
|
1103
2254
|
}))];
|
|
1104
2255
|
}
|
|
1105
|
-
/**
|
|
1106
|
-
|
|
2256
|
+
/**
|
|
2257
|
+
* Create a manifest provider for multi-source mode.
|
|
2258
|
+
*
|
|
2259
|
+
* Remote sources are always fetched over HTTP (with auth + caching). The local
|
|
2260
|
+
* source normally fetches from `localOrigin`, but in `experimentalDocgenServer`
|
|
2261
|
+
* mode core 404s `/manifests/*.json` (the data lives in the open services), so
|
|
2262
|
+
* callers pass `localManifestProvider` to read the local source in-process
|
|
2263
|
+
* instead. When omitted, the local source keeps its HTTP behavior.
|
|
2264
|
+
*/
|
|
2265
|
+
createManifestProvider(localOrigin, localManifestProvider) {
|
|
1107
2266
|
return async (request, path, source) => {
|
|
1108
2267
|
const token = extractBearerToken(request?.headers.get("Authorization"));
|
|
1109
|
-
const
|
|
2268
|
+
const remoteSource = source?.url ? {
|
|
2269
|
+
...source,
|
|
2270
|
+
url: source.url
|
|
2271
|
+
} : void 0;
|
|
2272
|
+
if (!remoteSource && localManifestProvider) return localManifestProvider(request, path, source);
|
|
2273
|
+
const baseUrl = remoteSource?.url ?? localOrigin;
|
|
1110
2274
|
const manifestUrl = `${baseUrl}${path.replace("./", "/")}`;
|
|
1111
|
-
const isRemote = !!
|
|
2275
|
+
const isRemote = !!remoteSource;
|
|
1112
2276
|
const tokenForRequest = isRemote && this.#isAuthRequiredUrl(baseUrl) ? token : null;
|
|
1113
2277
|
if (token && token !== this.#lastToken) {
|
|
1114
2278
|
this.#manifestCache.clear();
|
|
@@ -1153,7 +2317,10 @@ var CompositionAuth = class {
|
|
|
1153
2317
|
if (response.status === 401) throw new AuthenticationError(url);
|
|
1154
2318
|
if (!response.ok) throw new Error(`Failed to fetch ${url}: ${response.status}`);
|
|
1155
2319
|
const text = await response.text();
|
|
1156
|
-
const
|
|
2320
|
+
const { pathname } = new URL(url);
|
|
2321
|
+
const isComponentsManifest = pathname.endsWith("/manifests/components.json");
|
|
2322
|
+
const isDocsManifest = pathname.endsWith("/manifests/docs.json");
|
|
2323
|
+
const schema = isComponentsManifest ? ComponentManifestMap : isDocsManifest ? DocsManifestMap : v.unknown();
|
|
1157
2324
|
if (v.safeParse(v.pipe(v.string(), v.parseJson(), schema), text).success) return text;
|
|
1158
2325
|
if (await this.#isMcpUnauthorized(new URL(url).origin)) throw new AuthenticationError(url);
|
|
1159
2326
|
throw new Error(`Invalid manifest response from ${url}: expected valid JSON manifest but got unexpected content.`);
|
|
@@ -1249,26 +2416,435 @@ function extractBearerToken(authHeader) {
|
|
|
1249
2416
|
return bearer ? bearer.slice(7) : null;
|
|
1250
2417
|
}
|
|
1251
2418
|
|
|
2419
|
+
//#endregion
|
|
2420
|
+
//#region src/auth/get-refs-from-config.ts
|
|
2421
|
+
/**
|
|
2422
|
+
* Get composed Storybook refs from Storybook config.
|
|
2423
|
+
* See: https://storybook.js.org/docs/sharing/storybook-composition
|
|
2424
|
+
*/
|
|
2425
|
+
async function getRefsFromConfig(options) {
|
|
2426
|
+
try {
|
|
2427
|
+
const refs = await options.presets.apply("refs", {});
|
|
2428
|
+
if (!refs || typeof refs !== "object") return [];
|
|
2429
|
+
return Object.entries(refs).flatMap(([key, value]) => {
|
|
2430
|
+
if (!value || typeof value !== "object") return [];
|
|
2431
|
+
const { title, url } = value;
|
|
2432
|
+
if (typeof url !== "string" || url.length === 0) return [];
|
|
2433
|
+
return [{
|
|
2434
|
+
id: key,
|
|
2435
|
+
title: typeof title === "string" && title.length > 0 ? title : key,
|
|
2436
|
+
url
|
|
2437
|
+
}];
|
|
2438
|
+
});
|
|
2439
|
+
} catch {
|
|
2440
|
+
return [];
|
|
2441
|
+
}
|
|
2442
|
+
}
|
|
2443
|
+
|
|
2444
|
+
//#endregion
|
|
2445
|
+
//#region src/auth/resolve-composition-sources.ts
|
|
2446
|
+
const MANIFEST_PROBE_TIMEOUT_MS = 3e3;
|
|
2447
|
+
async function resolveCompositionSources(options) {
|
|
2448
|
+
const refs = await getRefsFromConfig(options);
|
|
2449
|
+
const compositionAuth = new CompositionAuth();
|
|
2450
|
+
if (refs.length === 0) return {
|
|
2451
|
+
refs,
|
|
2452
|
+
compositionAuth,
|
|
2453
|
+
sources: void 0,
|
|
2454
|
+
multiSource: false
|
|
2455
|
+
};
|
|
2456
|
+
await compositionAuth.initialize(refs);
|
|
2457
|
+
const sources = compositionAuth.buildSources();
|
|
2458
|
+
return {
|
|
2459
|
+
refs,
|
|
2460
|
+
compositionAuth,
|
|
2461
|
+
sources,
|
|
2462
|
+
multiSource: sources.some((source) => !!source.url)
|
|
2463
|
+
};
|
|
2464
|
+
}
|
|
2465
|
+
async function resolveServerlessCompositionSources(options) {
|
|
2466
|
+
const refs = await getRefsFromConfig(options);
|
|
2467
|
+
const sources = [{
|
|
2468
|
+
id: "local",
|
|
2469
|
+
title: "Local"
|
|
2470
|
+
}, ...(await Promise.all(refs.map(async (ref) => await hasServerlessComponentManifestSource(ref.url) ? ref : void 0))).filter((ref) => !!ref).map((ref) => ({
|
|
2471
|
+
id: ref.id,
|
|
2472
|
+
title: ref.title,
|
|
2473
|
+
url: ref.url
|
|
2474
|
+
}))];
|
|
2475
|
+
return {
|
|
2476
|
+
refs,
|
|
2477
|
+
sources,
|
|
2478
|
+
multiSource: sources.some((source) => !!source.url)
|
|
2479
|
+
};
|
|
2480
|
+
}
|
|
2481
|
+
async function hasServerlessComponentManifestSource(refUrl) {
|
|
2482
|
+
const controller = new AbortController();
|
|
2483
|
+
const timeout = setTimeout(() => controller.abort(), MANIFEST_PROBE_TIMEOUT_MS);
|
|
2484
|
+
try {
|
|
2485
|
+
const response = await fetch(new URL("manifests/components.json", `${refUrl.replace(/\/$/, "")}/`), {
|
|
2486
|
+
headers: { Accept: "application/json" },
|
|
2487
|
+
signal: controller.signal
|
|
2488
|
+
});
|
|
2489
|
+
if (response.status === 401 && hasOAuthResourceMetadataChallenge(response)) return true;
|
|
2490
|
+
if (!response.ok) return false;
|
|
2491
|
+
const text = await response.text();
|
|
2492
|
+
return v.safeParse(v.pipe(v.string(), v.parseJson(), ComponentManifestMap), text).success;
|
|
2493
|
+
} catch {
|
|
2494
|
+
return false;
|
|
2495
|
+
} finally {
|
|
2496
|
+
clearTimeout(timeout);
|
|
2497
|
+
}
|
|
2498
|
+
}
|
|
2499
|
+
function hasOAuthResourceMetadataChallenge(response) {
|
|
2500
|
+
return /resource_metadata="[^"]+"/.test(response.headers.get("WWW-Authenticate") ?? "");
|
|
2501
|
+
}
|
|
2502
|
+
|
|
2503
|
+
//#endregion
|
|
2504
|
+
//#region src/storybook-ai-metadata.ts
|
|
2505
|
+
const createEmptyInputSchema = () => ({
|
|
2506
|
+
type: "object",
|
|
2507
|
+
properties: {}
|
|
2508
|
+
});
|
|
2509
|
+
async function buildStorybookAiMetadata(options, existingMetadata) {
|
|
2510
|
+
const toolsets = v.parse(AddonOptions, {
|
|
2511
|
+
endpoint: options.endpoint,
|
|
2512
|
+
toolsets: options.toolsets ?? {}
|
|
2513
|
+
}).toolsets;
|
|
2514
|
+
const features = await options.presets.apply("features", {});
|
|
2515
|
+
const devEnabled = toolsets?.dev ?? true;
|
|
2516
|
+
const rawAvailability = await getToolAvailability(options, {
|
|
2517
|
+
features,
|
|
2518
|
+
moduleGraphSupported: await isModuleGraphSupportedByBuilder(options)
|
|
2519
|
+
});
|
|
2520
|
+
const availability = {
|
|
2521
|
+
...rawAvailability,
|
|
2522
|
+
reviewEnabled: rawAvailability.reviewEnabledForCli
|
|
2523
|
+
};
|
|
2524
|
+
const testEnabled = (toolsets?.test ?? true) && availability.testSupported;
|
|
2525
|
+
const docsToolsetEnabled = toolsets?.docs ?? true;
|
|
2526
|
+
const multiSource = docsToolsetEnabled ? (await resolveServerlessCompositionSources(options)).multiSource : false;
|
|
2527
|
+
const registryAvailability = getEffectiveToolAvailability(availability, { multiSource });
|
|
2528
|
+
const docsEnabled = docsToolsetEnabled && registryAvailability.docsEnabled;
|
|
2529
|
+
const registryContext = {
|
|
2530
|
+
availability: registryAvailability,
|
|
2531
|
+
multiSource,
|
|
2532
|
+
toolsets
|
|
2533
|
+
};
|
|
2534
|
+
const toolMetadata = getAddonToolMetadata(registryContext);
|
|
2535
|
+
const localTools = {
|
|
2536
|
+
...existingMetadata?.localTools,
|
|
2537
|
+
...getAddonLocalTools({
|
|
2538
|
+
...registryContext,
|
|
2539
|
+
options
|
|
2540
|
+
})
|
|
2541
|
+
};
|
|
2542
|
+
return {
|
|
2543
|
+
instructions: joinInstructions(existingMetadata?.instructions, buildServerInstructions({
|
|
2544
|
+
devEnabled,
|
|
2545
|
+
testEnabled,
|
|
2546
|
+
docsEnabled,
|
|
2547
|
+
changeDetectionEnabled: availability.changeDetectionEnabled,
|
|
2548
|
+
moduleGraphSupported: availability.moduleGraphSupported,
|
|
2549
|
+
reviewEnabled: availability.reviewEnabled
|
|
2550
|
+
})),
|
|
2551
|
+
tools: mergeToolDescriptors(existingMetadata?.tools ?? [], await toToolDescriptors(toolMetadata)),
|
|
2552
|
+
localTools
|
|
2553
|
+
};
|
|
2554
|
+
}
|
|
2555
|
+
async function toToolDescriptors(toolMetadata) {
|
|
2556
|
+
const adapter = new ValibotJsonSchemaAdapter();
|
|
2557
|
+
return Promise.all(toolMetadata.map(async ({ schema, outputSchema, ...metadata }) => ({
|
|
2558
|
+
...metadata,
|
|
2559
|
+
inputSchema: schema ? await toJsonSchema(adapter, schema) : createEmptyInputSchema(),
|
|
2560
|
+
...outputSchema ? { outputSchema: await toJsonSchema(adapter, outputSchema) } : {}
|
|
2561
|
+
})));
|
|
2562
|
+
}
|
|
2563
|
+
async function toJsonSchema(adapter, schema) {
|
|
2564
|
+
return await adapter.toJsonSchema(schema);
|
|
2565
|
+
}
|
|
2566
|
+
function joinInstructions(...sections) {
|
|
2567
|
+
const uniqueSections = [];
|
|
2568
|
+
const seen = /* @__PURE__ */ new Set();
|
|
2569
|
+
for (const section of sections) {
|
|
2570
|
+
const trimmed = section?.trim();
|
|
2571
|
+
if (trimmed && !seen.has(trimmed)) {
|
|
2572
|
+
seen.add(trimmed);
|
|
2573
|
+
uniqueSections.push(trimmed);
|
|
2574
|
+
}
|
|
2575
|
+
}
|
|
2576
|
+
return uniqueSections.join("\n\n");
|
|
2577
|
+
}
|
|
2578
|
+
function mergeToolDescriptors(...groups) {
|
|
2579
|
+
const toolsByName = /* @__PURE__ */ new Map();
|
|
2580
|
+
for (const tool of groups.flat()) {
|
|
2581
|
+
if (toolsByName.has(tool.name)) toolsByName.delete(tool.name);
|
|
2582
|
+
toolsByName.set(tool.name, tool);
|
|
2583
|
+
}
|
|
2584
|
+
return [...toolsByName.values()];
|
|
2585
|
+
}
|
|
2586
|
+
|
|
2587
|
+
//#endregion
|
|
2588
|
+
//#region src/manifests/vendored.ts
|
|
2589
|
+
/** System tags used by Storybook for categorizing stories and docs entries. */
|
|
2590
|
+
const Tag = {
|
|
2591
|
+
ATTACHED_MDX: "attached-mdx",
|
|
2592
|
+
UNATTACHED_MDX: "unattached-mdx",
|
|
2593
|
+
MANIFEST: "manifest"
|
|
2594
|
+
};
|
|
2595
|
+
/** Open-service ids (also the on-disk directory names under `services/`). */
|
|
2596
|
+
const DOCGEN_SERVICE_ID = "core/docgen";
|
|
2597
|
+
const STORY_DOCS_SERVICE_ID = "core/story-docs";
|
|
2598
|
+
const MDX_SERVICE_ID = "addon-docs/mdx";
|
|
2599
|
+
/**
|
|
2600
|
+
* Derives the componentId portion of a story index entry id. Story ids have the
|
|
2601
|
+
* shape `<componentId>--<storyName>`; the prefix before the first `--` is the
|
|
2602
|
+
* stable component identifier.
|
|
2603
|
+
*/
|
|
2604
|
+
function getComponentIdFromEntry(entry) {
|
|
2605
|
+
return entry.id.split("--")[0] ?? entry.id;
|
|
2606
|
+
}
|
|
2607
|
+
function isAttachedDocsEntry(entry) {
|
|
2608
|
+
return entry.type === "docs" && entry.tags?.includes(Tag.ATTACHED_MDX) === true && entry.storiesImports.length > 0;
|
|
2609
|
+
}
|
|
2610
|
+
function isEligibleStoryEntry(entry) {
|
|
2611
|
+
return entry.type === "story" && entry.subtype === "story";
|
|
2612
|
+
}
|
|
2613
|
+
/**
|
|
2614
|
+
* Picks one index entry per componentId: story entries win; attached docs fill gaps
|
|
2615
|
+
* only where no story exists for that componentId.
|
|
2616
|
+
*/
|
|
2617
|
+
function selectComponentEntriesByComponentId(indexEntries) {
|
|
2618
|
+
const entriesByComponentId = /* @__PURE__ */ new Map();
|
|
2619
|
+
for (const entry of indexEntries) {
|
|
2620
|
+
if (!isEligibleStoryEntry(entry)) continue;
|
|
2621
|
+
entriesByComponentId.set(getComponentIdFromEntry(entry), entry);
|
|
2622
|
+
}
|
|
2623
|
+
for (const entry of indexEntries) {
|
|
2624
|
+
if (!isAttachedDocsEntry(entry)) continue;
|
|
2625
|
+
const componentId = getComponentIdFromEntry(entry);
|
|
2626
|
+
if (!entriesByComponentId.has(componentId)) entriesByComponentId.set(componentId, entry);
|
|
2627
|
+
}
|
|
2628
|
+
return entriesByComponentId;
|
|
2629
|
+
}
|
|
2630
|
+
/** `$ref` target for one component's story-docs payload, relative to `manifests/`. */
|
|
2631
|
+
function storyDocsManifestRef(id) {
|
|
2632
|
+
return `../services/${STORY_DOCS_SERVICE_ID}/${id}.json#/components/${id}`;
|
|
2633
|
+
}
|
|
2634
|
+
|
|
2635
|
+
//#endregion
|
|
2636
|
+
//#region src/manifests/service-access.ts
|
|
2637
|
+
let cachedGetService;
|
|
2638
|
+
/**
|
|
2639
|
+
* Resolves `getService` once via a dynamic import. Returns `undefined` on Storybook
|
|
2640
|
+
* versions that don't export it (so callers fall back to the fetch-based path).
|
|
2641
|
+
*/
|
|
2642
|
+
async function loadGetService() {
|
|
2643
|
+
if (cachedGetService !== void 0) return cachedGetService ?? void 0;
|
|
2644
|
+
try {
|
|
2645
|
+
const getService = (await import("storybook/internal/core-server")).getService;
|
|
2646
|
+
cachedGetService = getService ?? null;
|
|
2647
|
+
return getService;
|
|
2648
|
+
} catch {
|
|
2649
|
+
cachedGetService = null;
|
|
2650
|
+
return;
|
|
2651
|
+
}
|
|
2652
|
+
}
|
|
2653
|
+
async function getServiceSafely(id) {
|
|
2654
|
+
const getService = await loadGetService();
|
|
2655
|
+
if (!getService) return;
|
|
2656
|
+
try {
|
|
2657
|
+
return getService(id);
|
|
2658
|
+
} catch {
|
|
2659
|
+
return;
|
|
2660
|
+
}
|
|
2661
|
+
}
|
|
2662
|
+
function getDocgenService() {
|
|
2663
|
+
return getServiceSafely(DOCGEN_SERVICE_ID);
|
|
2664
|
+
}
|
|
2665
|
+
function getStoryDocsService() {
|
|
2666
|
+
return getServiceSafely(STORY_DOCS_SERVICE_ID);
|
|
2667
|
+
}
|
|
2668
|
+
function getMdxService() {
|
|
2669
|
+
return getServiceSafely(MDX_SERVICE_ID);
|
|
2670
|
+
}
|
|
2671
|
+
|
|
2672
|
+
//#endregion
|
|
2673
|
+
//#region src/manifests/in-process-provider.ts
|
|
2674
|
+
function classifyIndex(index) {
|
|
2675
|
+
const entries = Object.values(index.entries).filter((entry) => entry.tags?.includes(Tag.MANIFEST) ?? false);
|
|
2676
|
+
const selected = selectComponentEntriesByComponentId(entries);
|
|
2677
|
+
const storyBasedIds = /* @__PURE__ */ new Set();
|
|
2678
|
+
for (const [id, entry] of selected) if (entry.type === "story") storyBasedIds.add(id);
|
|
2679
|
+
const attachedDocsByComponent = /* @__PURE__ */ new Map();
|
|
2680
|
+
const unattachedDocs = /* @__PURE__ */ new Map();
|
|
2681
|
+
for (const entry of entries) {
|
|
2682
|
+
if (entry.type !== "docs") continue;
|
|
2683
|
+
if (entry.tags?.includes(Tag.UNATTACHED_MDX)) unattachedDocs.set(entry.id, entry);
|
|
2684
|
+
else if (entry.tags?.includes(Tag.ATTACHED_MDX)) {
|
|
2685
|
+
const componentId = getComponentIdFromEntry(entry);
|
|
2686
|
+
const list = attachedDocsByComponent.get(componentId) ?? [];
|
|
2687
|
+
list.push(entry);
|
|
2688
|
+
attachedDocsByComponent.set(componentId, list);
|
|
2689
|
+
}
|
|
2690
|
+
}
|
|
2691
|
+
return {
|
|
2692
|
+
componentIds: [...selected.keys()],
|
|
2693
|
+
storyBasedIds,
|
|
2694
|
+
attachedDocsByComponent,
|
|
2695
|
+
unattachedDocs
|
|
2696
|
+
};
|
|
2697
|
+
}
|
|
2698
|
+
/**
|
|
2699
|
+
* Builds the shallow `components.json` surface used by `list-all-documentation`.
|
|
2700
|
+
*
|
|
2701
|
+
* In dev, single component/doc lookups use `resolveEntry`, so this index does not
|
|
2702
|
+
* carry docgen or MDX refs. The only ref it exposes is `stories`, which
|
|
2703
|
+
* `list-all-documentation --withStoryIds` follows to avoid running full docgen.
|
|
2704
|
+
*/
|
|
2705
|
+
async function buildComponentsManifest(cls) {
|
|
2706
|
+
const docgenService = await getDocgenService();
|
|
2707
|
+
const allDocgen = docgenService ? await docgenService.queries.docgenForAllComponents.loaded() : {};
|
|
2708
|
+
const components = {};
|
|
2709
|
+
for (const id of cls.componentIds) {
|
|
2710
|
+
const payload = allDocgen[id];
|
|
2711
|
+
components[id] = {
|
|
2712
|
+
id,
|
|
2713
|
+
name: payload?.name ?? id,
|
|
2714
|
+
...payload?.description !== void 0 ? { description: payload.description } : {},
|
|
2715
|
+
...payload?.summary !== void 0 ? { summary: payload.summary } : {},
|
|
2716
|
+
...cls.storyBasedIds.has(id) ? { stories: { $ref: storyDocsManifestRef(id) } } : {}
|
|
2717
|
+
};
|
|
2718
|
+
}
|
|
2719
|
+
return JSON.stringify({
|
|
2720
|
+
v: 1,
|
|
2721
|
+
components
|
|
2722
|
+
});
|
|
2723
|
+
}
|
|
2724
|
+
/** Builds the ref-based unattached `docs.json` index, or `undefined` when there are none. */
|
|
2725
|
+
async function buildDocsManifest(cls) {
|
|
2726
|
+
if (cls.unattachedDocs.size === 0) return;
|
|
2727
|
+
const mdxService = await getMdxService();
|
|
2728
|
+
const allMdx = mdxService ? await mdxService.queries.mdxForAllComponents.loaded() : {};
|
|
2729
|
+
const docs = {};
|
|
2730
|
+
for (const [docId, entry] of cls.unattachedDocs) {
|
|
2731
|
+
const payload = allMdx[docId]?.docs?.[docId];
|
|
2732
|
+
docs[docId] = {
|
|
2733
|
+
id: docId,
|
|
2734
|
+
name: entry.name,
|
|
2735
|
+
...payload?.summary !== void 0 ? { summary: payload.summary } : {}
|
|
2736
|
+
};
|
|
2737
|
+
}
|
|
2738
|
+
return JSON.stringify({
|
|
2739
|
+
v: 1,
|
|
2740
|
+
docs
|
|
2741
|
+
});
|
|
2742
|
+
}
|
|
2743
|
+
const STORY_DOCS_SERVICE_PREFIX = `services/${STORY_DOCS_SERVICE_ID}/`;
|
|
2744
|
+
function matchStoryDocsServicePath(normalizedPath) {
|
|
2745
|
+
if (normalizedPath.startsWith(STORY_DOCS_SERVICE_PREFIX) && normalizedPath.endsWith(".json")) return normalizedPath.slice(STORY_DOCS_SERVICE_PREFIX.length, -5);
|
|
2746
|
+
}
|
|
2747
|
+
/** Wraps one story-docs payload as `{ components: { [id]: payload } }`. */
|
|
2748
|
+
async function buildStoryDocsServiceFile(id) {
|
|
2749
|
+
const storyDocsService = await getStoryDocsService();
|
|
2750
|
+
const payload = storyDocsService ? await storyDocsService.queries.storyDocs.loaded({ id }) : void 0;
|
|
2751
|
+
return JSON.stringify({ components: payload === void 0 ? {} : { [id]: payload } });
|
|
2752
|
+
}
|
|
2753
|
+
async function resolveComponent(id, cls) {
|
|
2754
|
+
const [docgenService, storyDocsService, mdxService] = await Promise.all([
|
|
2755
|
+
getDocgenService(),
|
|
2756
|
+
getStoryDocsService(),
|
|
2757
|
+
getMdxService()
|
|
2758
|
+
]);
|
|
2759
|
+
const [docgen, storyDocs] = await Promise.all([docgenService ? docgenService.queries.docgen.loaded({ id }) : void 0, storyDocsService ? storyDocsService.queries.storyDocs.loaded({ id }) : void 0]);
|
|
2760
|
+
const attached = cls.attachedDocsByComponent.get(id) ?? [];
|
|
2761
|
+
let docs;
|
|
2762
|
+
if (attached.length > 0 && mdxService) {
|
|
2763
|
+
const mdxPayload = await mdxService.queries.mdxForComponent.loaded({ id });
|
|
2764
|
+
if (mdxPayload?.docs) {
|
|
2765
|
+
docs = {};
|
|
2766
|
+
for (const entry of attached) {
|
|
2767
|
+
const doc = mdxPayload.docs[entry.id];
|
|
2768
|
+
if (doc) docs[entry.id] = doc;
|
|
2769
|
+
}
|
|
2770
|
+
}
|
|
2771
|
+
}
|
|
2772
|
+
return {
|
|
2773
|
+
kind: "component",
|
|
2774
|
+
component: adaptCoreComponent({
|
|
2775
|
+
...docgen,
|
|
2776
|
+
id,
|
|
2777
|
+
name: docgen?.name ?? id,
|
|
2778
|
+
...storyDocs?.stories ? { stories: storyDocs.stories } : {},
|
|
2779
|
+
...storyDocs?.import ? { import: storyDocs.import } : {},
|
|
2780
|
+
...docs ? { docs } : {}
|
|
2781
|
+
})
|
|
2782
|
+
};
|
|
2783
|
+
}
|
|
2784
|
+
async function resolveStandaloneDoc(id) {
|
|
2785
|
+
const mdxService = await getMdxService();
|
|
2786
|
+
const doc = (mdxService ? await mdxService.queries.mdxForComponent.loaded({ id }) : void 0)?.docs?.[id];
|
|
2787
|
+
if (!doc) return;
|
|
2788
|
+
return {
|
|
2789
|
+
kind: "doc",
|
|
2790
|
+
doc: adaptCoreDoc(doc)
|
|
2791
|
+
};
|
|
2792
|
+
}
|
|
2793
|
+
/**
|
|
2794
|
+
* Builds the in-process manifest provider and single-entry resolver for
|
|
2795
|
+
* docgen-server mode. The closures read the live story index and services on each
|
|
2796
|
+
* call (both internally cached), so they stay in lock-step with HMR.
|
|
2797
|
+
*/
|
|
2798
|
+
function createDocgenServerManifestAccess(options) {
|
|
2799
|
+
const manifestProvider = async (_request, path) => {
|
|
2800
|
+
const normalized = path.replace(/^\.?\//, "");
|
|
2801
|
+
if (normalized === "manifests/components.json") return buildComponentsManifest(classifyIndex(await getStoryIndex(options)));
|
|
2802
|
+
if (normalized === "manifests/docs.json") {
|
|
2803
|
+
const docs = await buildDocsManifest(classifyIndex(await getStoryIndex(options)));
|
|
2804
|
+
if (docs === void 0) throw new Error("No unattached docs manifest available");
|
|
2805
|
+
return docs;
|
|
2806
|
+
}
|
|
2807
|
+
const storyDocsId = matchStoryDocsServicePath(normalized);
|
|
2808
|
+
if (storyDocsId) return buildStoryDocsServiceFile(storyDocsId);
|
|
2809
|
+
throw new Error(`Unsupported in-process manifest path: ${path}`);
|
|
2810
|
+
};
|
|
2811
|
+
const resolveEntry = async (id) => {
|
|
2812
|
+
const cls = classifyIndex(await getStoryIndex(options));
|
|
2813
|
+
if (cls.unattachedDocs.has(id)) return resolveStandaloneDoc(id);
|
|
2814
|
+
if (cls.componentIds.includes(id)) return resolveComponent(id, cls);
|
|
2815
|
+
};
|
|
2816
|
+
return {
|
|
2817
|
+
manifestProvider,
|
|
2818
|
+
resolveEntry
|
|
2819
|
+
};
|
|
2820
|
+
}
|
|
2821
|
+
|
|
1252
2822
|
//#endregion
|
|
1253
2823
|
//#region src/preset.ts
|
|
1254
2824
|
const previewAnnotations = async (existingAnnotations = []) => {
|
|
1255
2825
|
return [...existingAnnotations, path.join(import.meta.dirname, "preview.js")];
|
|
1256
2826
|
};
|
|
1257
2827
|
const experimental_devServer = async (app, options) => {
|
|
1258
|
-
const addonOptions = v.parse(AddonOptions, {
|
|
2828
|
+
const addonOptions = v.parse(AddonOptions, {
|
|
2829
|
+
endpoint: options.endpoint,
|
|
2830
|
+
toolsets: options.toolsets ?? {}
|
|
2831
|
+
});
|
|
1259
2832
|
const origin = `http://localhost:${options.port}`;
|
|
1260
|
-
const
|
|
1261
|
-
const compositionAuth =
|
|
1262
|
-
|
|
1263
|
-
|
|
2833
|
+
const endpoint = addonOptions.endpoint ?? DEFAULT_MCP_ENDPOINT;
|
|
2834
|
+
const { refs, compositionAuth, sources, multiSource } = await resolveCompositionSources(options);
|
|
2835
|
+
const rawAvailability = await getToolAvailability(options);
|
|
2836
|
+
const docgenServerAccess = rawAvailability.docgenServer ? createDocgenServerManifestAccess(options) : void 0;
|
|
2837
|
+
let createManifestProvider;
|
|
1264
2838
|
if (refs.length > 0) {
|
|
1265
|
-
logger.info(`
|
|
1266
|
-
await compositionAuth.initialize(refs);
|
|
2839
|
+
logger.info(`Initialized composition with ${refs.length} remote Storybook(s)`);
|
|
1267
2840
|
if (compositionAuth.requiresAuth) logger.info(`Auth required for: ${compositionAuth.authUrls.join(", ")}`);
|
|
1268
|
-
sources
|
|
1269
|
-
|
|
1270
|
-
manifestProvider = compositionAuth.createManifestProvider(origin);
|
|
2841
|
+
logger.info(`Sources: ${(sources ?? []).map((s) => s.id).join(", ")}`);
|
|
2842
|
+
createManifestProvider = () => compositionAuth.createManifestProvider(origin, docgenServerAccess?.manifestProvider);
|
|
1271
2843
|
}
|
|
2844
|
+
const manifestAccessFor = (req) => ({
|
|
2845
|
+
manifestProvider: createManifestProvider ? createManifestProvider(req) : docgenServerAccess?.manifestProvider,
|
|
2846
|
+
resolveEntry: docgenServerAccess?.resolveEntry
|
|
2847
|
+
});
|
|
1272
2848
|
app.get("/.well-known/oauth-protected-resource", (_req, res) => {
|
|
1273
2849
|
const wellKnown = compositionAuth.buildWellKnown(origin);
|
|
1274
2850
|
if (!wellKnown) {
|
|
@@ -1291,25 +2867,24 @@ const experimental_devServer = async (app, options) => {
|
|
|
1291
2867
|
}
|
|
1292
2868
|
return false;
|
|
1293
2869
|
};
|
|
1294
|
-
app.post(
|
|
2870
|
+
app.post(endpoint, (req, res) => {
|
|
1295
2871
|
if (requireAuth(req, res)) return;
|
|
1296
2872
|
return mcpServerHandler({
|
|
1297
2873
|
req,
|
|
1298
2874
|
res,
|
|
1299
2875
|
options,
|
|
1300
2876
|
addonOptions,
|
|
2877
|
+
endpoint,
|
|
1301
2878
|
sources,
|
|
1302
|
-
|
|
2879
|
+
...manifestAccessFor(req),
|
|
1303
2880
|
compositionAuth
|
|
1304
2881
|
});
|
|
1305
2882
|
});
|
|
1306
|
-
const
|
|
1307
|
-
const addonVitestConstants = await getAddonVitestConstants();
|
|
1308
|
-
const a11yEnabled = await isAddonA11yEnabled(options);
|
|
2883
|
+
const { moduleGraphSupported, changeDetectionEnabled, reviewEnabled, reviewEnabledForCli, docsEnabled, docsHasManifests, docsFeatureEnabled, testSupported, a11yEnabled } = getEffectiveToolAvailability(rawAvailability, { multiSource });
|
|
1309
2884
|
const isDevEnabled = addonOptions.toolsets?.dev ?? true;
|
|
1310
|
-
const isDocsEnabled =
|
|
1311
|
-
const isTestEnabled =
|
|
1312
|
-
app.get(
|
|
2885
|
+
const isDocsEnabled = docsEnabled && (addonOptions.toolsets?.docs ?? true);
|
|
2886
|
+
const isTestEnabled = testSupported && (addonOptions.toolsets?.test ?? true);
|
|
2887
|
+
app.get(endpoint, (req, res) => {
|
|
1313
2888
|
if (!req.headers["accept"]?.includes("text/html")) {
|
|
1314
2889
|
if (requireAuth(req, res)) return;
|
|
1315
2890
|
return mcpServerHandler({
|
|
@@ -1317,51 +2892,45 @@ const experimental_devServer = async (app, options) => {
|
|
|
1317
2892
|
res,
|
|
1318
2893
|
options,
|
|
1319
2894
|
addonOptions,
|
|
2895
|
+
endpoint,
|
|
1320
2896
|
sources,
|
|
1321
|
-
|
|
2897
|
+
...manifestAccessFor(req),
|
|
1322
2898
|
compositionAuth
|
|
1323
2899
|
});
|
|
1324
2900
|
}
|
|
1325
2901
|
res.writeHead(200, { "Content-Type": "text/html" });
|
|
1326
2902
|
let docsNotice = "";
|
|
1327
|
-
if (!
|
|
2903
|
+
if (!docsHasManifests) docsNotice = `<div class="toolset-notice">
|
|
1328
2904
|
This toolset is only supported in React-based setups.
|
|
1329
2905
|
</div>`;
|
|
1330
|
-
else if (!
|
|
2906
|
+
else if (!docsFeatureEnabled) docsNotice = `<div class="toolset-notice">
|
|
1331
2907
|
This toolset requires enabling the component manifest feature.
|
|
1332
2908
|
<a target="_blank" href="https://github.com/storybookjs/mcp/tree/main/packages/addon-mcp#docs-tools-experimental">Learn how to enable it</a>
|
|
1333
2909
|
</div>`;
|
|
1334
|
-
const testNoticeLines = [!
|
|
2910
|
+
const testNoticeLines = [!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>`, !a11yEnabled && `Add <code>@storybook/addon-a11y</code> for accessibility testing. <a target="_blank" href="https://storybook.js.org/docs/writing-tests/accessibility-testing">Learn more</a>`].filter(Boolean);
|
|
1335
2911
|
const testNotice = testNoticeLines.length ? `<div class="toolset-notice">${testNoticeLines.join("<br>")}</div>` : "";
|
|
1336
2912
|
const a11yBadge = a11yEnabled ? " <span class=\"toolset-status enabled\">+ accessibility</span>" : "";
|
|
1337
|
-
const
|
|
2913
|
+
const devNoticeLines = !isDevEnabled ? [`The <code>dev</code> toolset is disabled via addon options.`] : [
|
|
2914
|
+
!moduleGraphSupported && `<code>get-stories-by-component</code> requires a dev server with a builder that supports the module graph (e.g. Vite).`,
|
|
2915
|
+
!changeDetectionEnabled && `<code>get-changed-stories</code> requires enabling the <code>changeDetection</code> feature flag.`,
|
|
2916
|
+
!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>.`)
|
|
2917
|
+
].filter(Boolean);
|
|
2918
|
+
const devNotice = devNoticeLines.length ? `<div class="toolset-notice">${devNoticeLines.join("<br>")}</div>` : "";
|
|
2919
|
+
const statusWord = (enabled) => enabled ? "enabled" : "disabled";
|
|
2920
|
+
const html = template_default.replaceAll("{{DEV_STATUS}}", isDevEnabled ? "enabled" : "disabled").replaceAll("{{STORIES_BY_COMPONENT_STATUS}}", statusWord(isDevEnabled && moduleGraphSupported)).replaceAll("{{CHANGE_DETECTION_STATUS}}", statusWord(isDevEnabled && changeDetectionEnabled)).replaceAll("{{REVIEW_STATUS}}", statusWord(isDevEnabled && reviewEnabledForCli)).replace("{{DEV_NOTICE}}", devNotice).replaceAll("{{DOCS_STATUS}}", isDocsEnabled ? "enabled" : "disabled").replace("{{DOCS_NOTICE}}", docsNotice).replaceAll("{{TEST_STATUS}}", isTestEnabled ? "enabled" : "disabled").replace("{{TEST_NOTICE}}", testNotice).replace("{{MANIFEST_DEBUGGER_LINK}}", rawAvailability.docsEnabled ? "<p>View the <a href=\"/manifests/components.html\">component manifest debugger</a>.</p>" : "").replace("{{A11Y_BADGE}}", a11yBadge);
|
|
1338
2921
|
res.end(html);
|
|
1339
2922
|
});
|
|
1340
2923
|
return app;
|
|
1341
2924
|
};
|
|
2925
|
+
const experimental_storybookAi = async (existingMetadata, options) => {
|
|
2926
|
+
return buildStorybookAiMetadata(options, existingMetadata);
|
|
2927
|
+
};
|
|
1342
2928
|
const features = async (existingFeatures) => {
|
|
1343
2929
|
return {
|
|
1344
2930
|
...existingFeatures,
|
|
1345
2931
|
componentsManifest: true
|
|
1346
2932
|
};
|
|
1347
2933
|
};
|
|
1348
|
-
/**
|
|
1349
|
-
* Get composed Storybook refs from Storybook config.
|
|
1350
|
-
* See: https://storybook.js.org/docs/sharing/storybook-composition
|
|
1351
|
-
*/
|
|
1352
|
-
async function getRefsFromConfig(options) {
|
|
1353
|
-
try {
|
|
1354
|
-
const refs = await options.presets.apply("refs", {});
|
|
1355
|
-
if (!refs || typeof refs !== "object") return [];
|
|
1356
|
-
return Object.entries(refs).map(([key, value]) => ({
|
|
1357
|
-
id: key,
|
|
1358
|
-
title: value.title || key,
|
|
1359
|
-
url: value.url
|
|
1360
|
-
})).filter((ref) => ref.url);
|
|
1361
|
-
} catch {
|
|
1362
|
-
return [];
|
|
1363
|
-
}
|
|
1364
|
-
}
|
|
1365
2934
|
|
|
1366
2935
|
//#endregion
|
|
1367
|
-
export { experimental_devServer, features, previewAnnotations };
|
|
2936
|
+
export { experimental_devServer, experimental_storybookAi, features, previewAnnotations };
|