@storybook/mcp 0.8.0 → 10.6.0-alpha.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,1168 +1,1101 @@
1
- import { t as instructions_default } from "./instructions-CiOmp0JI.js";
1
+ import CJS_COMPAT_NODE_URL_5ab1wqe57oe from 'node:url';
2
+ import CJS_COMPAT_NODE_PATH_5ab1wqe57oe from 'node:path';
3
+ import CJS_COMPAT_NODE_MODULE_5ab1wqe57oe from "node:module";
4
+
5
+ var __filename = CJS_COMPAT_NODE_URL_5ab1wqe57oe.fileURLToPath(import.meta.url);
6
+ var __dirname = CJS_COMPAT_NODE_PATH_5ab1wqe57oe.dirname(__filename);
7
+ var require = CJS_COMPAT_NODE_MODULE_5ab1wqe57oe.createRequire(import.meta.url);
8
+
9
+ // ------------------------------------------------------------
10
+ // end of CJS compatibility banner, injected by Storybook's esbuild configuration
11
+ // ------------------------------------------------------------
12
+
13
+ // src/index.ts
2
14
  import { McpServer } from "tmcp";
3
15
  import { ValibotJsonSchemaAdapter } from "@tmcp/adapter-valibot";
4
16
  import { HttpTransport } from "@tmcp/transport-http";
5
- import * as v from "valibot";
6
17
 
7
- //#region package.json
8
- var name = "@storybook/mcp";
9
- var version = "0.8.0";
10
- var description = "MCP server that serves knowledge about your components based on your Storybook stories and documentation";
18
+ // package.json
19
+ var package_default = {
20
+ name: "@storybook/mcp",
21
+ version: "10.6.0-alpha.5",
22
+ description: "MCP server that serves knowledge about your components based on your Storybook stories and documentation",
23
+ keywords: [
24
+ "mcp",
25
+ "storybook"
26
+ ],
27
+ homepage: "https://github.com/storybookjs/storybook/tree/next/code/lib/mcp",
28
+ bugs: {
29
+ url: "https://github.com/storybookjs/storybook/issues"
30
+ },
31
+ repository: {
32
+ type: "git",
33
+ url: "https://github.com/storybookjs/storybook.git",
34
+ directory: "code/lib/mcp"
35
+ },
36
+ funding: {
37
+ type: "opencollective",
38
+ url: "https://opencollective.com/storybook"
39
+ },
40
+ license: "MIT",
41
+ author: "Storybook Core Team",
42
+ type: "module",
43
+ exports: {
44
+ ".": {
45
+ types: "./dist/index.d.ts",
46
+ code: "./src/index.ts",
47
+ default: "./dist/index.js"
48
+ },
49
+ "./package.json": "./package.json"
50
+ },
51
+ files: [
52
+ "dist/**/*",
53
+ "README.md",
54
+ "*.js",
55
+ "*.d.ts",
56
+ "!src/**/*"
57
+ ],
58
+ dependencies: {
59
+ "@tmcp/adapter-valibot": "^0.1.5",
60
+ "@tmcp/transport-http": "^0.8.5",
61
+ tmcp: "^1.19.4",
62
+ valibot: "^1.4.0"
63
+ },
64
+ devDependencies: {
65
+ "@modelcontextprotocol/sdk": "^1.22.0",
66
+ "@tmcp/transport-stdio": "^0.4.3",
67
+ "react-docgen": "^8.0.2",
68
+ "react-docgen-typescript": "^2.4.0",
69
+ srvx: "^0.8.16",
70
+ tinyexec: "^1.0.2",
71
+ typescript: "^6.0.3"
72
+ },
73
+ publishConfig: {
74
+ access: "public"
75
+ }
76
+ };
11
77
 
12
- //#endregion
13
- //#region src/types.ts
14
- const JSDocTag = v.record(v.string(), v.array(v.string()));
15
- const ManifestError = v.object({
16
- name: v.string(),
17
- message: v.string()
18
- });
19
- const BaseManifest = v.object({
20
- name: v.string(),
21
- description: v.optional(v.string()),
22
- jsDocTags: v.optional(JSDocTag),
23
- error: v.optional(ManifestError)
24
- });
25
- const Story = v.object({
26
- ...BaseManifest.entries,
27
- id: v.optional(v.string()),
28
- snippet: v.optional(v.string()),
29
- summary: v.optional(v.string())
30
- });
31
- /**
32
- * A JSON Reference (`{ $ref }`) pointing at a value in another manifest document.
33
- * Used by the v1 (split/ref) manifest format for docgen, story-docs and MDX payloads.
34
- */
35
- const JsonRef = v.object({ $ref: v.string() });
36
- /** Inline (v0) docs entry: the full MDX `content` is embedded. */
37
- const DocV0 = v.object({
38
- id: v.string(),
39
- name: v.string(),
40
- title: v.optional(v.string()),
41
- path: v.optional(v.string()),
42
- content: v.optional(v.string()),
43
- summary: v.optional(v.string()),
44
- error: v.optional(ManifestError)
45
- });
46
- const BaseInlineComponentProperties = v.object({
47
- ...BaseManifest.entries,
48
- path: v.optional(v.string()),
49
- summary: v.optional(v.string()),
50
- import: v.optional(v.string()),
51
- reactDocgen: v.optional(v.any()),
52
- reactDocgenTypescript: v.optional(v.any()),
53
- reactComponentMeta: v.optional(v.any())
54
- });
55
- const SubcomponentManifest = v.object({ ...BaseInlineComponentProperties.entries });
56
- /** Inline (v0) component: docgen, stories and attached docs are all embedded. */
57
- const ComponentManifestV0 = v.object({
58
- ...BaseInlineComponentProperties.entries,
59
- id: v.string(),
60
- stories: v.optional(v.array(Story)),
61
- subcomponents: v.optional(v.record(v.string(), SubcomponentManifest)),
62
- docs: v.optional(v.record(v.string(), DocV0))
63
- });
64
- const ComponentManifestMapV0 = v.object({
65
- v: v.literal(0),
66
- components: v.record(v.string(), ComponentManifestV0)
67
- });
68
- const DocsManifestMapV0 = v.object({
69
- v: v.literal(0),
70
- docs: v.record(v.string(), DocV0)
71
- });
72
- /**
73
- * Shallow (v1) docs entry. The full MDX payload (title/path/content) lives behind
74
- * `mdx.$ref`; `mdx` is optional because Storybook's in-process dev index omits it
75
- * (those entries are resolved in-process via {@link StorybookContext.resolveEntry}).
76
- */
77
- const DocV1 = v.object({
78
- id: v.string(),
79
- name: v.string(),
80
- summary: v.optional(v.string()),
81
- mdx: v.optional(JsonRef),
82
- error: v.optional(ManifestError)
83
- });
84
- /**
85
- * Shallow (v1) component index row. Identity + summary are inlined for cheap
86
- * listing; docgen and story-docs live behind `$ref`s, attached docs behind nested
87
- * `mdx.$ref`s. `docgen`/`stories` are optional (the in-process dev index omits
88
- * `docgen`, and docs-only components have neither).
89
- */
90
- const ComponentManifestV1 = v.object({
91
- id: v.string(),
92
- name: v.string(),
93
- description: v.optional(v.string()),
94
- summary: v.optional(v.string()),
95
- error: v.optional(ManifestError),
96
- docgen: v.optional(JsonRef),
97
- stories: v.optional(JsonRef),
98
- docs: v.optional(v.record(v.string(), DocV1))
99
- });
100
- const ComponentManifestMapV1 = v.object({
101
- v: v.literal(1),
102
- components: v.record(v.string(), ComponentManifestV1)
103
- });
104
- const DocsManifestMapV1 = v.object({
105
- v: v.literal(1),
106
- docs: v.record(v.string(), DocV1)
107
- });
108
- /** `components.json`, discriminated on `v` (0 = inline, 1 = split/ref). */
109
- const ComponentManifestMap = v.variant("v", [ComponentManifestMapV0, ComponentManifestMapV1]);
110
- /**
111
- * `docs.json` for unattached/standalone documentation entries (served at
112
- * `/manifests/docs.json`), discriminated on `v`.
113
- */
114
- const DocsManifestMap = v.variant("v", [DocsManifestMapV0, DocsManifestMapV1]);
115
- /**
116
- * Shared Valibot field for the storybookId input, used in multi-source mode.
117
- * Reused across tools that support source selection.
118
- */
119
- const StorybookIdField = { storybookId: v.pipe(v.string(), v.description("The Storybook source ID (e.g., \"local\", \"tetra\"). Required when multiple Storybooks are composed. See list-all-documentation for available sources.")) };
78
+ // src/tools/list-all-documentation.ts
79
+ import * as v3 from "valibot";
120
80
 
121
- //#endregion
122
- //#region src/utils/adapt-core-manifest.ts
123
- /**
124
- * Adapts Storybook's `experimentalDocgenServer` open-service payloads (the "core
125
- * format") into `@storybook/mcp`'s internal {@link ComponentManifest}/{@link Doc}
126
- * shapes. This is the single place that bridges the two formats, used by both the
127
- * ref-resolution path (built/static/remote manifests) and the addon's in-process
128
- * `resolveEntry` hook (dev).
129
- *
130
- * Only `argTypes` is dropped: prop types still come from `reactComponentMeta` and
131
- * the `react*` docgen-engine fields, which are passed through unchanged.
132
- */
133
- const ARG_TYPES_KEY = "argTypes";
134
- /** Converts the story-docs `stories` record (or an already-resolved array) into `Story[]`. */
81
+ // src/types.ts
82
+ import * as v from "valibot";
83
+ var JSDocTag = v.record(v.string(), v.array(v.string())), ManifestError = v.object({
84
+ name: v.string(),
85
+ message: v.string()
86
+ }), BaseManifest = v.object({
87
+ name: v.string(),
88
+ description: v.optional(v.string()),
89
+ jsDocTags: v.optional(JSDocTag),
90
+ error: v.optional(ManifestError)
91
+ }), Story = v.object({
92
+ ...BaseManifest.entries,
93
+ id: v.optional(v.string()),
94
+ snippet: v.optional(v.string()),
95
+ summary: v.optional(v.string())
96
+ }), JsonRef = v.object({
97
+ $ref: v.string()
98
+ }), DocV0 = v.object({
99
+ id: v.string(),
100
+ name: v.string(),
101
+ title: v.optional(v.string()),
102
+ path: v.optional(v.string()),
103
+ content: v.optional(v.string()),
104
+ summary: v.optional(v.string()),
105
+ error: v.optional(ManifestError)
106
+ }), BaseInlineComponentProperties = v.object({
107
+ ...BaseManifest.entries,
108
+ path: v.optional(v.string()),
109
+ summary: v.optional(v.string()),
110
+ import: v.optional(v.string()),
111
+ reactDocgen: v.optional(v.any()),
112
+ reactDocgenTypescript: v.optional(v.any()),
113
+ reactComponentMeta: v.optional(v.any())
114
+ }), SubcomponentManifest = v.object({
115
+ ...BaseInlineComponentProperties.entries
116
+ }), ComponentManifestV0 = v.object({
117
+ ...BaseInlineComponentProperties.entries,
118
+ id: v.string(),
119
+ stories: v.optional(v.array(Story)),
120
+ subcomponents: v.optional(v.record(v.string(), SubcomponentManifest)),
121
+ docs: v.optional(v.record(v.string(), DocV0))
122
+ }), ComponentManifestMapV0 = v.object({
123
+ v: v.literal(0),
124
+ components: v.record(v.string(), ComponentManifestV0)
125
+ }), DocsManifestMapV0 = v.object({
126
+ v: v.literal(0),
127
+ docs: v.record(v.string(), DocV0)
128
+ }), DocV1 = v.object({
129
+ id: v.string(),
130
+ name: v.string(),
131
+ summary: v.optional(v.string()),
132
+ mdx: v.optional(JsonRef),
133
+ error: v.optional(ManifestError)
134
+ }), ComponentManifestV1 = v.object({
135
+ id: v.string(),
136
+ name: v.string(),
137
+ description: v.optional(v.string()),
138
+ summary: v.optional(v.string()),
139
+ error: v.optional(ManifestError),
140
+ docgen: v.optional(JsonRef),
141
+ stories: v.optional(JsonRef),
142
+ docs: v.optional(v.record(v.string(), DocV1))
143
+ }), ComponentManifestMapV1 = v.object({
144
+ v: v.literal(1),
145
+ components: v.record(v.string(), ComponentManifestV1)
146
+ }), DocsManifestMapV1 = v.object({
147
+ v: v.literal(1),
148
+ docs: v.record(v.string(), DocV1)
149
+ }), ComponentManifestMap = v.variant("v", [
150
+ ComponentManifestMapV0,
151
+ ComponentManifestMapV1
152
+ ]), DocsManifestMap = v.variant("v", [DocsManifestMapV0, DocsManifestMapV1]), StorybookIdField = {
153
+ storybookId: v.pipe(
154
+ v.string(),
155
+ v.description(
156
+ 'The Storybook source ID (e.g., "local", "tetra"). Required when multiple Storybooks are composed. See list-all-documentation for available sources.'
157
+ )
158
+ )
159
+ };
160
+
161
+ // src/utils/get-manifest.ts
162
+ import * as v2 from "valibot";
163
+
164
+ // src/utils/adapt-core-manifest.ts
165
+ var ARG_TYPES_KEY = "argTypes";
135
166
  function adaptCoreStories(stories) {
136
- if (!stories) return;
137
- if (Array.isArray(stories)) return stories;
138
- return Object.values(stories);
167
+ if (stories)
168
+ return Array.isArray(stories) ? stories : Object.values(stories);
139
169
  }
140
- /** Adapts one MDX service payload into a {@link Doc}. */
141
170
  function adaptCoreDoc(doc) {
142
- return { ...doc };
171
+ return { ...doc };
143
172
  }
144
- /** Adapts a core-format component (docgen + story-docs + attached MDX) into a {@link ComponentManifest}. */
145
173
  function adaptCoreComponent(core) {
146
- const { stories, docs, [ARG_TYPES_KEY]: _argTypes, ...rest } = core;
147
- const component = { ...rest };
148
- const adaptedStories = adaptCoreStories(stories);
149
- if (adaptedStories) component.stories = adaptedStories;
150
- if (docs) component.docs = Object.fromEntries(Object.entries(docs).map(([id, doc]) => [id, adaptCoreDoc(doc)]));
151
- return component;
174
+ let { stories, docs, [ARG_TYPES_KEY]: _argTypes, ...rest } = core, component = { ...rest }, adaptedStories = adaptCoreStories(stories);
175
+ return adaptedStories && (component.stories = adaptedStories), docs && (component.docs = Object.fromEntries(
176
+ Object.entries(docs).map(([id, doc]) => [id, adaptCoreDoc(doc)])
177
+ )), component;
152
178
  }
153
179
 
154
- //#endregion
155
- //#region src/utils/requires-own-mcp.ts
180
+ // src/utils/requires-own-mcp.ts
156
181
  function getSourceMcpEndpoint(source) {
157
- const base = new URL(source.url);
158
- base.pathname = `${base.pathname.replace(/\/$/, "")}/`;
159
- return new URL("mcp", base).toString();
182
+ let base = new URL(source.url);
183
+ return base.pathname = `${base.pathname.replace(/\/$/, "")}/`, new URL("mcp", base).toString();
160
184
  }
161
185
  function formatRequiresOwnMcpNotice(source, endpoint, options = {}) {
162
- const parts = [];
163
- if (options.includeHeader ?? true) {
164
- parts.push(`# ${source.title}`);
165
- parts.push(`id: ${source.id}`);
166
- parts.push("");
167
- }
168
- parts.push("This composed Storybook is private and cannot be read through the local Storybook MCP proxy.");
169
- parts.push("");
170
- parts.push("Use this source's own MCP endpoint instead:");
171
- parts.push(endpoint);
172
- return parts.join("\n");
186
+ let parts = [];
187
+ return (options.includeHeader ?? !0) && (parts.push(`# ${source.title}`), parts.push(`id: ${source.id}`), parts.push("")), parts.push(
188
+ "This composed Storybook is private and cannot be read through the local Storybook MCP proxy."
189
+ ), parts.push(""), parts.push("Use this source's own MCP endpoint instead:"), parts.push(endpoint), parts.join(`
190
+ `);
173
191
  }
174
192
 
175
- //#endregion
176
- //#region src/utils/get-manifest.ts
177
- /**
178
- * The paths to the manifest files relative to the Storybook build
179
- */
180
- const COMPONENT_MANIFEST_PATH = "./manifests/components.json";
181
- const DOCS_MANIFEST_PATH = "./manifests/docs.json";
182
- /** Empty placeholder manifest used for sources that errored or need their own MCP endpoint. */
183
- const EMPTY_COMPONENT_MANIFEST = {
184
- v: 1,
185
- components: {}
186
- };
187
- /**
188
- * Error thrown when getting or parsing a manifest fails
189
- */
190
- var ManifestGetError = class extends Error {
191
- url;
192
- cause;
193
- constructor(message, url, cause) {
194
- super(message);
195
- this.name = "ManifestGetError";
196
- this.url = url ?? "No source URL provided";
197
- this.cause = cause;
198
- }
199
- };
200
- var RequiresOwnMcpError = class extends Error {
201
- source;
202
- endpoint;
203
- constructor(source) {
204
- const endpoint = getSourceMcpEndpoint(source);
205
- super(`Composed Storybook "${source.title}" requires its own MCP endpoint: ${endpoint}`);
206
- this.name = "RequiresOwnMcpError";
207
- this.source = source;
208
- this.endpoint = endpoint;
209
- }
193
+ // src/utils/get-manifest.ts
194
+ var COMPONENT_MANIFEST_PATH = "./manifests/components.json", DOCS_MANIFEST_PATH = "./manifests/docs.json", EMPTY_COMPONENT_MANIFEST = { v: 1, components: {} }, ManifestGetError = class extends Error {
195
+ constructor(message, url, cause) {
196
+ super(message), this.name = "ManifestGetError", this.url = url ?? "No source URL provided", this.cause = cause;
197
+ }
198
+ }, RequiresOwnMcpError = class extends Error {
199
+ constructor(source) {
200
+ let endpoint = getSourceMcpEndpoint(source);
201
+ super(`Composed Storybook "${source.title}" requires its own MCP endpoint: ${endpoint}`), this.name = "RequiresOwnMcpError", this.source = source, this.endpoint = endpoint;
202
+ }
203
+ }, errorToMCPContent = (error) => {
204
+ if (error instanceof RequiresOwnMcpError)
205
+ return {
206
+ content: [
207
+ {
208
+ type: "text",
209
+ text: formatRequiresOwnMcpNotice(error.source, error.endpoint)
210
+ }
211
+ ]
212
+ };
213
+ let errorPrefix = error instanceof ManifestGetError ? "Error getting manifest" : "Unexpected error", errorMessage = error instanceof Error ? error.message : String(error), fullMessage = `${errorPrefix}: ${errorMessage}`;
214
+ if (error instanceof ManifestGetError && error.cause) {
215
+ let causeMessage = error.cause instanceof Error ? error.cause.message : String(error.cause);
216
+ fullMessage += `
217
+ Caused by: ${causeMessage}`;
218
+ }
219
+ return {
220
+ content: [
221
+ {
222
+ type: "text",
223
+ text: fullMessage
224
+ }
225
+ ],
226
+ isError: !0
227
+ };
210
228
  };
211
- /**
212
- * Converts an error to MCP-compatible content format
213
- *
214
- * @param error - The error to convert (can be any type)
215
- * @returns A tool result with error content and isError flag
216
- */
217
- const errorToMCPContent = (error) => {
218
- if (error instanceof RequiresOwnMcpError) return { content: [{
219
- type: "text",
220
- text: formatRequiresOwnMcpNotice(error.source, error.endpoint)
221
- }] };
222
- let fullMessage = `${error instanceof ManifestGetError ? "Error getting manifest" : "Unexpected error"}: ${error instanceof Error ? error.message : String(error)}`;
223
- if (error instanceof ManifestGetError && error.cause) {
224
- const causeMessage = error.cause instanceof Error ? error.cause.message : String(error.cause);
225
- fullMessage += `\nCaused by: ${causeMessage}`;
226
- }
227
- return {
228
- content: [{
229
- type: "text",
230
- text: fullMessage
231
- }],
232
- isError: true
233
- };
234
- };
235
- /**
236
- * Parses a JSON string and validates it against a Valibot schema
237
- */
238
- function parseManifest({ jsonString, schema, name, url }) {
239
- try {
240
- return v.parse(v.pipe(v.string(), v.parseJson(), schema), jsonString);
241
- } catch (error) {
242
- throw new ManifestGetError(`Failed to parse ${name} manifest:
243
- ${error instanceof v.ValiError ? error.issues.map((i) => i.message).join("\n") : String(error)}`, url);
244
- }
229
+ function parseManifest({
230
+ jsonString,
231
+ schema,
232
+ name,
233
+ url
234
+ }) {
235
+ try {
236
+ return v2.parse(v2.pipe(v2.string(), v2.parseJson(), schema), jsonString);
237
+ } catch (error) {
238
+ throw new ManifestGetError(
239
+ `Failed to parse ${name} manifest:
240
+ ${error instanceof v2.ValiError ? error.issues.map((i) => i.message).join(`
241
+ `) : String(error)}`,
242
+ url
243
+ );
244
+ }
245
245
  }
246
- /**
247
- * Gets component and docs manifest from a request or using a custom provider
248
- *
249
- * @param request - The HTTP request to get the manifest for (optional when using custom manifestProvider)
250
- * @param manifestProvider - Optional custom function to get the manifest
251
- * @param source - Optional source for multi-source mode
252
- * @returns A promise that resolves to the parsed ComponentManifestMap
253
- * @throws {ManifestGetError} If getting the manifest fails or the response is invalid
254
- */
255
246
  async function getManifests(request, manifestProvider, source) {
256
- const provider = manifestProvider ?? defaultManifestProvider;
257
- const [componentResult, docsResult] = await Promise.allSettled([provider(request, COMPONENT_MANIFEST_PATH, source), provider(request, DOCS_MANIFEST_PATH, source)]);
258
- const getUrl = (path) => request ? getManifestUrlFromRequest(request, path) : "Unknown manifest source";
259
- if (componentResult.status === "rejected") {
260
- const reason = componentResult.reason;
261
- if (reason instanceof RequiresOwnMcpError) throw reason;
262
- const hint = reason instanceof ManifestGetError && reason.message.includes("404") ? `\nHint: The Storybook at this URL may not have the component manifest enabled. Add \`features: { componentsManifest: true }\` (or \`features: { experimentalComponentsManifest: true }\` for older Storybook versions) to its main.ts config.` : "";
263
- throw new ManifestGetError(`Failed to get component manifest: ${reason instanceof Error ? reason.message : String(reason)}${hint}`, getUrl(COMPONENT_MANIFEST_PATH), reason instanceof Error ? reason : void 0);
264
- }
265
- const componentManifest = parseManifest({
266
- jsonString: componentResult.value,
267
- schema: ComponentManifestMap,
268
- name: "component",
269
- url: getUrl(COMPONENT_MANIFEST_PATH)
270
- });
271
- if (Object.keys(componentManifest.components).length === 0) throw new ManifestGetError(`No components found in the manifest`, getUrl(COMPONENT_MANIFEST_PATH));
272
- if (docsResult.status === "rejected") return { componentManifest };
273
- return {
274
- componentManifest,
275
- docsManifest: parseManifest({
276
- jsonString: docsResult.value,
277
- schema: DocsManifestMap,
278
- name: "docs",
279
- url: getUrl(DOCS_MANIFEST_PATH)
280
- })
281
- };
247
+ let provider = manifestProvider ?? defaultManifestProvider, [componentResult, docsResult] = await Promise.allSettled([
248
+ provider(request, COMPONENT_MANIFEST_PATH, source),
249
+ provider(request, DOCS_MANIFEST_PATH, source)
250
+ ]), getUrl = (path) => request ? getManifestUrlFromRequest(request, path) : "Unknown manifest source";
251
+ if (componentResult.status === "rejected") {
252
+ let reason = componentResult.reason;
253
+ if (reason instanceof RequiresOwnMcpError)
254
+ throw reason;
255
+ let hint = reason instanceof ManifestGetError && reason.message.includes("404") ? "\nHint: The Storybook at this URL may not have the component manifest enabled. Add `features: { componentsManifest: true }` (or `features: { experimentalComponentsManifest: true }` for older Storybook versions) to its main.ts config." : "";
256
+ throw new ManifestGetError(
257
+ `Failed to get component manifest: ${reason instanceof Error ? reason.message : String(reason)}${hint}`,
258
+ getUrl(COMPONENT_MANIFEST_PATH),
259
+ reason instanceof Error ? reason : void 0
260
+ );
261
+ }
262
+ let componentManifest = parseManifest({
263
+ jsonString: componentResult.value,
264
+ schema: ComponentManifestMap,
265
+ name: "component",
266
+ url: getUrl(COMPONENT_MANIFEST_PATH)
267
+ });
268
+ if (Object.keys(componentManifest.components).length === 0)
269
+ throw new ManifestGetError(
270
+ "No components found in the manifest",
271
+ getUrl(COMPONENT_MANIFEST_PATH)
272
+ );
273
+ if (docsResult.status === "rejected")
274
+ return { componentManifest };
275
+ let docsManifest = parseManifest({
276
+ jsonString: docsResult.value,
277
+ schema: DocsManifestMap,
278
+ name: "docs",
279
+ url: getUrl(DOCS_MANIFEST_PATH)
280
+ });
281
+ return { componentManifest, docsManifest };
282
282
  }
283
- /**
284
- * Resolves a `$ref` into the provider path of the referenced file and the
285
- * JSON-pointer segments into it.
286
- *
287
- * The `$ref` file path is relative to the component manifest's location, e.g.
288
- * `"../services/core/docgen/button.json#/components/button"` from
289
- * `./manifests/components.json` resolves to `./services/core/docgen/button.json`
290
- * with pointer `["components", "button"]`. The same base (`manifests/`) applies to
291
- * docgen, story-docs and MDX refs.
292
- */
293
283
  function parseManifestRef(ref) {
294
- const [filePath = "", hash = ""] = ref.split("#");
295
- const manifestDir = COMPONENT_MANIFEST_PATH.replace(/^\.\//, "").replace(/[^/]+$/, "");
296
- const resolved = new URL(filePath, `https://localhost/${manifestDir}`).pathname.replace(/^\//, "");
297
- const pointer = hash.split("/").filter(Boolean).map((segment) => segment.replace(/~1/g, "/").replace(/~0/g, "~"));
298
- return {
299
- path: `./${resolved}`,
300
- pointer
301
- };
284
+ let [filePath = "", hash = ""] = ref.split("#"), manifestDir = COMPONENT_MANIFEST_PATH.replace(/^\.\//, "").replace(/[^/]+$/, ""), resolved = new URL(filePath, `https://localhost/${manifestDir}`).pathname.replace(
285
+ /^\//,
286
+ ""
287
+ ), pointer = hash.split("/").filter(Boolean).map((segment) => segment.replace(/~1/g, "/").replace(/~0/g, "~"));
288
+ return { path: `./${resolved}`, pointer };
302
289
  }
303
- /**
304
- * Fetches the file a `$ref` points at (verbatim — never a fabricated path) and
305
- * walks its JSON pointer, returning the pointed-to value.
306
- */
307
290
  async function fetchRefValue(ref, request, provider, source) {
308
- const { path, pointer } = parseManifestRef(ref);
309
- const jsonString = await provider(request, path, source);
310
- let target;
311
- try {
312
- target = JSON.parse(jsonString);
313
- } catch (error) {
314
- throw new ManifestGetError(`Failed to parse externalized payload referenced by "${ref}"`, path, error instanceof Error ? error : void 0);
315
- }
316
- for (const key of pointer) if (target && typeof target === "object" && key in target) target = target[key];
317
- else throw new ManifestGetError(`Reference "${ref}" could not be resolved: missing "${key}".`, path);
318
- return target;
291
+ let { path, pointer } = parseManifestRef(ref), jsonString = await provider(request, path, source), target;
292
+ try {
293
+ target = JSON.parse(jsonString);
294
+ } catch (error) {
295
+ throw new ManifestGetError(
296
+ `Failed to parse externalized payload referenced by "${ref}"`,
297
+ path,
298
+ error instanceof Error ? error : void 0
299
+ );
300
+ }
301
+ for (let key of pointer)
302
+ if (target && typeof target == "object" && key in target)
303
+ target = target[key];
304
+ else
305
+ throw new ManifestGetError(
306
+ `Reference "${ref}" could not be resolved: missing "${key}".`,
307
+ path
308
+ );
309
+ return target;
319
310
  }
320
- /**
321
- * Resolves a component index entry into a full component manifest by following any
322
- * `$ref`s it carries (docgen, story-docs, attached MDX docs), then adapting the
323
- * core-format payloads into `@storybook/mcp`'s internal shape.
324
- *
325
- * Refs are read verbatim from the entry — never fabricated from an id — so a
326
- * provider is only ever asked for top-level manifest paths or paths a manifest
327
- * already pointed at. Components without any `$ref` (inline/v0 format, or entries
328
- * already resolved in-process) are returned unchanged.
329
- */
330
311
  async function resolveComponentEntry(component, request, manifestProvider, source) {
331
- const docgenRef = "docgen" in component ? component.docgen?.$ref : void 0;
332
- const storiesRef = component.stories && !Array.isArray(component.stories) ? component.stories.$ref : void 0;
333
- const docEntries = component.docs ? Object.entries(component.docs) : [];
334
- const docRefs = docEntries.filter(([, doc]) => "mdx" in doc && !!doc.mdx?.$ref);
335
- if (!docgenRef && !storiesRef && docRefs.length === 0) return component;
336
- const provider = manifestProvider ?? defaultManifestProvider;
337
- let core = {
338
- id: component.id,
339
- name: component.name,
340
- ...component.description !== void 0 ? { description: component.description } : {},
341
- ...component.summary !== void 0 ? { summary: component.summary } : {},
342
- ...component.error !== void 0 ? { error: component.error } : {}
343
- };
344
- if (docgenRef) {
345
- const payload = await fetchRefValue(docgenRef, request, provider, source);
346
- core = {
347
- ...core,
348
- ...payload,
349
- id: component.id,
350
- name: component.name,
351
- ...component.description !== void 0 ? { description: component.description } : {},
352
- ...component.summary !== void 0 ? { summary: component.summary } : {},
353
- ...component.error !== void 0 ? { error: component.error } : {}
354
- };
355
- }
356
- if (Array.isArray(component.stories)) core.stories = component.stories;
357
- if (storiesRef) {
358
- const storyDocs = await fetchRefValue(storiesRef, request, provider, source);
359
- if (storyDocs?.stories) core.stories = storyDocs.stories;
360
- if (storyDocs?.import) core.import = storyDocs.import;
361
- }
362
- if (docEntries.length > 0) {
363
- const docs = {};
364
- for (const [docId, doc] of docEntries) {
365
- const mdxRef = "mdx" in doc ? doc.mdx?.$ref : void 0;
366
- docs[docId] = mdxRef ? await fetchRefValue(mdxRef, request, provider, source) : doc;
367
- }
368
- core.docs = docs;
369
- }
370
- return adaptCoreComponent(core);
312
+ let docgenRef = "docgen" in component ? component.docgen?.$ref : void 0, storiesRef = component.stories && !Array.isArray(component.stories) ? component.stories.$ref : void 0, docEntries = component.docs ? Object.entries(component.docs) : [], docRefs = docEntries.filter(([, doc]) => "mdx" in doc && !!doc.mdx?.$ref);
313
+ if (!docgenRef && !storiesRef && docRefs.length === 0)
314
+ return component;
315
+ let provider = manifestProvider ?? defaultManifestProvider, core = {
316
+ id: component.id,
317
+ name: component.name,
318
+ ...component.description !== void 0 ? { description: component.description } : {},
319
+ ...component.summary !== void 0 ? { summary: component.summary } : {},
320
+ ...component.error !== void 0 ? { error: component.error } : {}
321
+ };
322
+ if (docgenRef) {
323
+ let payload = await fetchRefValue(docgenRef, request, provider, source);
324
+ core = {
325
+ ...core,
326
+ ...payload,
327
+ id: component.id,
328
+ name: component.name,
329
+ ...component.description !== void 0 ? { description: component.description } : {},
330
+ ...component.summary !== void 0 ? { summary: component.summary } : {},
331
+ ...component.error !== void 0 ? { error: component.error } : {}
332
+ };
333
+ }
334
+ if (Array.isArray(component.stories) && (core.stories = component.stories), storiesRef) {
335
+ let storyDocs = await fetchRefValue(
336
+ storiesRef,
337
+ request,
338
+ provider,
339
+ source
340
+ );
341
+ storyDocs?.stories && (core.stories = storyDocs.stories), storyDocs?.import && (core.import = storyDocs.import);
342
+ }
343
+ if (docEntries.length > 0) {
344
+ let docs = {};
345
+ for (let [docId, doc] of docEntries) {
346
+ let mdxRef = "mdx" in doc ? doc.mdx?.$ref : void 0;
347
+ docs[docId] = mdxRef ? await fetchRefValue(mdxRef, request, provider, source) : doc;
348
+ }
349
+ core.docs = docs;
350
+ }
351
+ return adaptCoreComponent(core);
371
352
  }
372
- /**
373
- * Resolves only a component's stories `$ref` (story-docs payload) into a `Story[]`,
374
- * leaving docgen/docs refs untouched. Used by `list-all-documentation` when story
375
- * ids are requested, so listing doesn't pay for docgen/MDX resolution it won't show.
376
- */
377
353
  async function resolveComponentStories(component, request, manifestProvider, source) {
378
- if (!component.stories || Array.isArray(component.stories)) return component;
379
- const provider = manifestProvider ?? defaultManifestProvider;
380
- const storyDocs = await fetchRefValue(component.stories.$ref, request, provider, source);
381
- return {
382
- ...component,
383
- stories: storyDocs?.stories ? adaptCoreStories(storyDocs.stories) : []
384
- };
354
+ if (!component.stories || Array.isArray(component.stories))
355
+ return component;
356
+ let provider = manifestProvider ?? defaultManifestProvider, storyDocs = await fetchRefValue(
357
+ component.stories.$ref,
358
+ request,
359
+ provider,
360
+ source
361
+ );
362
+ return {
363
+ ...component,
364
+ stories: storyDocs?.stories ? adaptCoreStories(storyDocs.stories) : []
365
+ };
385
366
  }
386
- /**
387
- * Resolves a standalone docs entry, following its `mdx.$ref` when present.
388
- * Inline docs (v0) are returned unchanged.
389
- */
390
367
  async function resolveDoc(doc, request, manifestProvider, source) {
391
- const ref = "mdx" in doc ? doc.mdx?.$ref : void 0;
392
- if (!ref) return doc;
393
- const payload = await fetchRefValue(ref, request, manifestProvider ?? defaultManifestProvider, source);
394
- return adaptCoreDoc({
395
- ...payload,
396
- id: payload.id ?? doc.id,
397
- name: payload.name ?? doc.name
398
- });
368
+ let ref = "mdx" in doc ? doc.mdx?.$ref : void 0;
369
+ if (!ref)
370
+ return doc;
371
+ let payload = await fetchRefValue(ref, request, manifestProvider ?? defaultManifestProvider, source);
372
+ return adaptCoreDoc({
373
+ ...payload,
374
+ id: payload.id ?? doc.id,
375
+ name: payload.name ?? doc.name
376
+ });
399
377
  }
400
- /**
401
- * Constructs the manifest URL from the request origin and the top-level manifest path.
402
- */
403
378
  function getManifestUrlFromRequest(request, path) {
404
- const normalizedPath = path.replace(/^\.\//, "");
405
- return new URL(`/${normalizedPath}`, request.url).toString();
379
+ let normalizedPath = path.replace(/^\.\//, "");
380
+ return new URL(`/${normalizedPath}`, request.url).toString();
406
381
  }
407
- /**
408
- * Default manifest provider that fetches from the same origin as the request,
409
- * using Storybook's top-level manifest path.
410
- */
411
382
  async function defaultManifestProvider(request, path) {
412
- if (!request) throw new ManifestGetError("Request is required when using the default manifest provider. You must either pass the original request forward to the server context, or set a custom manifestProvider that doesn't need the request.");
413
- const manifestUrl = getManifestUrlFromRequest(request, path);
414
- const response = await fetch(manifestUrl);
415
- if (!response.ok) throw new ManifestGetError(`Failed to fetch manifest: ${response.status} ${response.statusText}`, manifestUrl);
416
- const contentType = response.headers.get("content-type");
417
- if (!contentType?.includes("application/json")) throw new ManifestGetError(`Invalid content type: expected application/json, got ${contentType}`, manifestUrl);
418
- return response.text();
383
+ if (!request)
384
+ throw new ManifestGetError(
385
+ "Request is required when using the default manifest provider. You must either pass the original request forward to the server context, or set a custom manifestProvider that doesn't need the request."
386
+ );
387
+ let manifestUrl = getManifestUrlFromRequest(request, path), response = await fetch(manifestUrl);
388
+ if (!response.ok)
389
+ throw new ManifestGetError(
390
+ `Failed to fetch manifest: ${response.status} ${response.statusText}`,
391
+ manifestUrl
392
+ );
393
+ let contentType = response.headers.get("content-type");
394
+ if (!contentType?.includes("application/json"))
395
+ throw new ManifestGetError(
396
+ `Invalid content type: expected application/json, got ${contentType}`,
397
+ manifestUrl
398
+ );
399
+ return response.text();
419
400
  }
420
- /**
421
- * Gets manifests from multiple sources.
422
- * Returns an array of source manifests, each containing the source info and its manifests.
423
- * Failures for individual sources are captured as errors rather than failing the entire request.
424
- *
425
- * @param sources - Array of source configurations
426
- * @param request - The HTTP request (used for local source)
427
- * @param manifestProvider - Function to fetch manifests, receives source as third parameter
428
- * @returns Promise resolving to array of source manifests
429
- * @throws {ManifestGetError} If no sources could be fetched successfully
430
- */
431
401
  async function getMultiSourceManifests(sources, request, manifestProvider) {
432
- const results = await Promise.all(sources.map(async (source) => {
433
- try {
434
- const manifests = await getManifests(request, manifestProvider, source);
435
- return {
436
- source,
437
- componentManifest: manifests.componentManifest,
438
- docsManifest: manifests.docsManifest
439
- };
440
- } catch (error) {
441
- if (error instanceof RequiresOwnMcpError) return {
442
- source,
443
- componentManifest: EMPTY_COMPONENT_MANIFEST,
444
- notice: {
445
- kind: "requires-own-mcp",
446
- endpoint: error.endpoint
447
- }
448
- };
449
- return {
450
- source,
451
- componentManifest: EMPTY_COMPONENT_MANIFEST,
452
- error: error instanceof Error ? error.message : String(error)
453
- };
454
- }
455
- }));
456
- const successCount = results.filter((r) => !r.error && !r.notice).length;
457
- const noticeCount = results.filter((r) => r.notice).length;
458
- if (successCount === 0 && noticeCount === 0) throw new ManifestGetError(`Failed to fetch manifests from any source. Errors:\n${results.map((r) => `- ${r.source.title}: ${r.error}`).join("\n")}`);
459
- return results;
402
+ let results = await Promise.all(
403
+ sources.map(async (source) => {
404
+ try {
405
+ let manifests = await getManifests(request, manifestProvider, source);
406
+ return {
407
+ source,
408
+ componentManifest: manifests.componentManifest,
409
+ docsManifest: manifests.docsManifest
410
+ };
411
+ } catch (error) {
412
+ if (error instanceof RequiresOwnMcpError)
413
+ return {
414
+ source,
415
+ componentManifest: EMPTY_COMPONENT_MANIFEST,
416
+ notice: {
417
+ kind: "requires-own-mcp",
418
+ endpoint: error.endpoint
419
+ }
420
+ };
421
+ let errorMessage = error instanceof Error ? error.message : String(error);
422
+ return {
423
+ source,
424
+ componentManifest: EMPTY_COMPONENT_MANIFEST,
425
+ error: errorMessage
426
+ };
427
+ }
428
+ })
429
+ ), successCount = results.filter((r) => !r.error && !r.notice).length, noticeCount = results.filter((r) => r.notice).length;
430
+ if (successCount === 0 && noticeCount === 0)
431
+ throw new ManifestGetError(
432
+ `Failed to fetch manifests from any source. Errors:
433
+ ${results.map((r) => `- ${r.source.title}: ${r.error}`).join(`
434
+ `)}`
435
+ );
436
+ return results;
460
437
  }
461
438
 
462
- //#endregion
463
- //#region src/utils/map-with-concurrency.ts
464
- /**
465
- * Maps `items` with at most `limit` concurrent in-flight `fn` calls.
466
- */
439
+ // src/utils/map-with-concurrency.ts
467
440
  async function mapWithConcurrency(items, limit, fn) {
468
- if (items.length === 0) return [];
469
- const safeLimit = Number.isFinite(limit) ? limit : items.length;
470
- const concurrency = Math.max(1, Math.min(safeLimit, items.length));
471
- const results = Array(items.length);
472
- let nextIndex = 0;
473
- async function worker() {
474
- while (nextIndex < items.length) {
475
- const index = nextIndex++;
476
- results[index] = await fn(items[index], index);
477
- }
478
- }
479
- await Promise.all(Array.from({ length: concurrency }, () => worker()));
480
- return results;
441
+ if (items.length === 0)
442
+ return [];
443
+ let safeLimit = Number.isFinite(limit) ? limit : items.length, concurrency = Math.max(1, Math.min(safeLimit, items.length)), results = Array(items.length), nextIndex = 0;
444
+ async function worker() {
445
+ for (; nextIndex < items.length; ) {
446
+ let index = nextIndex++;
447
+ results[index] = await fn(items[index], index);
448
+ }
449
+ }
450
+ return await Promise.all(Array.from({ length: concurrency }, () => worker())), results;
481
451
  }
482
452
 
483
- //#endregion
484
- //#region src/utils/parse-react-docgen.ts
453
+ // src/utils/parse-react-docgen.ts
485
454
  function serializeTsType(tsType) {
486
- if (!tsType) return void 0;
487
- if ("raw" in tsType && typeof tsType.raw === "string" && tsType.raw.trim().length > 0) return tsType.raw;
488
- if (!tsType.name) return void 0;
489
- if ("elements" in tsType) {
490
- const serializeElements = () => (tsType.elements ?? []).map((el) => serializeTsType(el) ?? "unknown");
491
- switch (tsType.name) {
492
- case "union": return serializeElements().join(" | ");
493
- case "intersection": return serializeElements().join(" & ");
494
- case "Array": return `${serializeTsType((tsType.elements ?? [])[0]) ?? "unknown"}[]`;
495
- case "tuple": return `[${serializeElements().join(", ")}]`;
496
- }
497
- }
498
- if ("value" in tsType && tsType.name === "literal") return tsType.value;
499
- if ("signature" in tsType && tsType.name === "signature") {
500
- if (tsType.type === "function") {
501
- const args = (tsType.signature?.arguments ?? []).map((a) => {
502
- const argType = serializeTsType(a.type) ?? "any";
503
- return `${a.name}: ${argType}`;
504
- });
505
- const ret = serializeTsType(tsType.signature?.return) ?? "void";
506
- return `(${args.join(", ")}) => ${ret}`;
507
- }
508
- if (tsType.type === "object") return `{ ${(tsType.signature?.properties ?? []).map((p) => {
509
- const req = Boolean(p.value?.required);
510
- const propType = serializeTsType(p.value) ?? "any";
511
- return `${p.key}${req ? "" : "?"}: ${propType}`;
512
- }).join("; ")} }`;
513
- return "unknown";
514
- }
515
- if ("elements" in tsType) {
516
- const inner = (tsType.elements ?? []).map((el) => serializeTsType(el) ?? "unknown");
517
- if (inner.length > 0) return `${tsType.name}<${inner.join(", ")}>`;
518
- }
519
- return tsType.name;
455
+ if (tsType) {
456
+ if ("raw" in tsType && typeof tsType.raw == "string" && tsType.raw.trim().length > 0)
457
+ return tsType.raw;
458
+ if (tsType.name) {
459
+ if ("elements" in tsType) {
460
+ let serializeElements = () => (tsType.elements ?? []).map((el) => serializeTsType(el) ?? "unknown");
461
+ switch (tsType.name) {
462
+ case "union":
463
+ return serializeElements().join(" | ");
464
+ case "intersection":
465
+ return serializeElements().join(" & ");
466
+ case "Array":
467
+ return `${serializeTsType((tsType.elements ?? [])[0]) ?? "unknown"}[]`;
468
+ case "tuple":
469
+ return `[${serializeElements().join(", ")}]`;
470
+ }
471
+ }
472
+ if ("value" in tsType && tsType.name === "literal")
473
+ return tsType.value;
474
+ if ("signature" in tsType && tsType.name === "signature") {
475
+ if (tsType.type === "function") {
476
+ let args = (tsType.signature?.arguments ?? []).map((a) => {
477
+ let argType = serializeTsType(a.type) ?? "any";
478
+ return `${a.name}: ${argType}`;
479
+ }), ret = serializeTsType(tsType.signature?.return) ?? "void";
480
+ return `(${args.join(", ")}) => ${ret}`;
481
+ }
482
+ return tsType.type === "object" ? `{ ${(tsType.signature?.properties ?? []).map((p) => {
483
+ let req = !!p.value?.required, propType = serializeTsType(p.value) ?? "any";
484
+ return `${p.key}${req ? "" : "?"}: ${propType}`;
485
+ }).join("; ")} }` : "unknown";
486
+ }
487
+ if ("elements" in tsType) {
488
+ let inner = (tsType.elements ?? []).map((el) => serializeTsType(el) ?? "unknown");
489
+ if (inner.length > 0) return `${tsType.name}<${inner.join(", ")}>`;
490
+ }
491
+ return tsType.name;
492
+ }
493
+ }
520
494
  }
521
- const parseReactDocgen = (reactDocgen) => {
522
- const props = reactDocgen?.props ?? {};
523
- return { props: Object.fromEntries(Object.entries(props).map(([propName, prop]) => [propName, {
524
- description: prop.description,
525
- type: serializeTsType(prop.tsType ?? prop.type),
526
- defaultValue: prop.defaultValue?.value,
527
- required: prop.required
528
- }])) };
529
- };
530
- /**
531
- * Parse react-docgen-typescript output into the same simplified ParsedDocgen format.
532
- * RDT uses flat type strings (prop.type.name / prop.type.raw) instead of react-docgen's
533
- * nested tsType structure, so no serialization is needed.
534
- */
535
- const parseComponentDocLike = (componentDoc) => {
536
- const props = componentDoc.props ?? {};
537
- return { props: Object.fromEntries(Object.entries(props).map(([propName, prop]) => [propName, {
538
- description: prop.description || void 0,
539
- type: prop.type?.raw ?? prop.type?.name,
540
- defaultValue: prop.defaultValue?.value,
541
- required: prop.required
542
- }])) };
543
- };
544
- const parseReactDocgenTypescript = (reactDocgenTypescript) => parseComponentDocLike(reactDocgenTypescript);
545
- const parseReactComponentMeta = (reactComponentMeta) => parseComponentDocLike(reactComponentMeta);
495
+ var parseReactDocgen = (reactDocgen) => {
496
+ let props = reactDocgen?.props ?? {};
497
+ return {
498
+ props: Object.fromEntries(
499
+ Object.entries(props).map(([propName, prop]) => [
500
+ propName,
501
+ {
502
+ description: prop.description,
503
+ type: serializeTsType(prop.tsType ?? prop.type),
504
+ defaultValue: prop.defaultValue?.value,
505
+ required: prop.required
506
+ }
507
+ ])
508
+ )
509
+ };
510
+ }, parseComponentDocLike = (componentDoc) => {
511
+ let props = componentDoc.props ?? {};
512
+ return {
513
+ props: Object.fromEntries(
514
+ Object.entries(props).map(([propName, prop]) => [
515
+ propName,
516
+ {
517
+ description: prop.description || void 0,
518
+ // RDT uses prop.type.name as a flat string (e.g. "() => void", "{ id: string }")
519
+ // For enums, prefer prop.type.raw which has the full union
520
+ type: prop.type?.raw ?? prop.type?.name,
521
+ defaultValue: prop.defaultValue?.value,
522
+ required: prop.required
523
+ }
524
+ ])
525
+ )
526
+ };
527
+ }, parseReactDocgenTypescript = (reactDocgenTypescript) => parseComponentDocLike(reactDocgenTypescript), parseReactComponentMeta = (reactComponentMeta) => parseComponentDocLike(reactComponentMeta);
546
528
 
547
- //#endregion
548
- //#region src/utils/dedent.ts
549
- /**
550
- * Copied from https://github.com/tamino-martinius/node-ts-dedent/blob/18c4736c79806d7fe78bdaaaf5ae307b79f9574a/src/index.ts
551
- *
552
- * Rationale for vendoring instead of using the ts-dedent package:
553
- * 1. The package has a broken ESM distribution - the IDE auto-imports as
554
- * `import dedent from 'ts-dedent'` but that breaks at runtime, requiring
555
- * manual changes to named imports. See:
556
- * - https://github.com/tamino-martinius/node-ts-dedent/issues/42
557
- * - https://github.com/tamino-martinius/node-ts-dedent/pull/41
558
- * 2. Keeps bundle size smaller for such a simple utility (avoid "is-even" syndrome)
559
- */
529
+ // src/utils/dedent.ts
560
530
  function dedent(templ, ...values) {
561
- let strings = Array.from(typeof templ === "string" ? [templ] : templ);
562
- strings[strings.length - 1] = strings.at(-1).replace(/\r?\n([\t ]*)$/, "");
563
- const indentLengths = strings.reduce((arr, str) => {
564
- const matches = str.match(/\n([\t ]+|(?!\s).)/g);
565
- if (matches) return arr.concat(matches.map((match) => match.match(/[\t ]/g)?.length ?? 0));
566
- return arr;
567
- }, []);
568
- if (indentLengths.length) {
569
- const pattern = new RegExp(`\n[\t ]{${Math.min(...indentLengths)}}`, "g");
570
- strings = strings.map((str) => str.replace(pattern, "\n"));
571
- }
572
- strings[0] = strings[0].replace(/^\r?\n/, "");
573
- let string = strings[0];
574
- values.forEach((value, i) => {
575
- const endentations = string.match(/(?:^|\n)( *)$/);
576
- const endentation = endentations ? endentations[1] : "";
577
- let indentedValue = value;
578
- if (typeof value === "string" && value.includes("\n")) indentedValue = String(value).split("\n").map((str, i) => {
579
- return i === 0 ? str : `${endentation}${str}`;
580
- }).join("\n");
581
- string += `${String(indentedValue)}${strings[i + 1]}`;
582
- });
583
- return string;
531
+ let strings = Array.from(typeof templ == "string" ? [templ] : templ);
532
+ strings[strings.length - 1] = strings.at(-1).replace(/\r?\n([\t ]*)$/, "");
533
+ let indentLengths = strings.reduce((arr, str) => {
534
+ let matches = str.match(/\n([\t ]+|(?!\s).)/g);
535
+ return matches ? arr.concat(matches.map((match) => match.match(/[\t ]/g)?.length ?? 0)) : arr;
536
+ }, []);
537
+ if (indentLengths.length) {
538
+ let pattern = new RegExp(`
539
+ [ ]{${Math.min(...indentLengths)}}`, "g");
540
+ strings = strings.map((str) => str.replace(pattern, `
541
+ `));
542
+ }
543
+ strings[0] = strings[0].replace(/^\r?\n/, "");
544
+ let string5 = strings[0];
545
+ return values.forEach((value, i) => {
546
+ let endentations = string5.match(/(?:^|\n)( *)$/), endentation = endentations ? endentations[1] : "", indentedValue = value;
547
+ typeof value == "string" && value.includes(`
548
+ `) && (indentedValue = String(value).split(`
549
+ `).map((str, i2) => i2 === 0 ? str : `${endentation}${str}`).join(`
550
+ `)), string5 += `${String(indentedValue)}${strings[i + 1]}`;
551
+ }), string5;
584
552
  }
585
553
 
586
- //#endregion
587
- //#region src/utils/manifest-formatter/extract-docs-summary.ts
588
- /**
589
- * Maximum length for a summary before truncation.
590
- */
591
- const MAX_SUMMARY_LENGTH = 90;
592
- /**
593
- * Extracts a summary from MDX content.
594
- * The summary is created by:
595
- * 1. Removing import statements
596
- * 2. Removing JSX/MDX expressions
597
- * 3. Extracting only text content from JSX/HTML elements
598
- * 4. Truncating to MAX_SUMMARY_LENGTH characters if needed
599
- *
600
- * @param content - The MDX content string
601
- * @returns A summary string, or undefined if no meaningful text content is found
602
- */
554
+ // src/utils/manifest-formatter/extract-docs-summary.ts
603
555
  function extractDocsSummary(content) {
604
- let result = content;
605
- result = result.replace(/^\s*import\s+(?:[\s\S]*?from\s+)?['"][^'"]+['"];?\s*$/gm, "");
606
- let prevResult = "";
607
- while (prevResult !== result) {
608
- prevResult = result;
609
- result = result.replace(/\{[^{}]*\}/g, "");
610
- }
611
- result = result.replace(/<[^>]+\/>/g, "");
612
- prevResult = "";
613
- while (prevResult !== result) {
614
- prevResult = result;
615
- result = result.replace(/<(\w+)[^>]*>([\s\S]*?)<\/\1>/g, "$2");
616
- }
617
- result = result.replace(/<[^>]+>/g, "");
618
- result = result.replace(/\s+/g, " ").trim();
619
- if (!result) return;
620
- if (result.length > MAX_SUMMARY_LENGTH) return `${result.slice(0, MAX_SUMMARY_LENGTH)}...`;
621
- return result;
556
+ let result = content;
557
+ result = result.replace(/^\s*import\s+(?:[\s\S]*?from\s+)?['"][^'"]+['"];?\s*$/gm, "");
558
+ let prevResult = "";
559
+ for (; prevResult !== result; )
560
+ prevResult = result, result = result.replace(/\{[^{}]*\}/g, "");
561
+ for (result = result.replace(/<[^>]+\/>/g, ""), prevResult = ""; prevResult !== result; )
562
+ prevResult = result, result = result.replace(/<(\w+)[^>]*>([\s\S]*?)<\/\1>/g, "$2");
563
+ if (result = result.replace(/<[^>]+>/g, ""), result = result.replace(/\s+/g, " ").trim(), !!result)
564
+ return result.length > 90 ? `${result.slice(0, 90)}...` : result;
622
565
  }
623
566
 
624
- //#endregion
625
- //#region src/utils/manifest-formatter/markdown.ts
626
- /**
627
- * Maximum number of stories to show in full detail in component manifests.
628
- * Remaining stories will be shown as names only.
629
- */
630
- const MAX_STORIES_TO_SHOW = 3;
567
+ // src/utils/manifest-formatter/markdown.ts
568
+ var MAX_STORIES_TO_SHOW = 3;
631
569
  function formatComponentLine(component) {
632
- const summary = component.summary ?? (component.description ? component.description.length > MAX_SUMMARY_LENGTH ? `${component.description.slice(0, MAX_SUMMARY_LENGTH)}...` : component.description : void 0);
633
- if (summary) return `- ${component.name} (${component.id}): ${summary}`;
634
- return `- ${component.name} (${component.id})`;
570
+ let summary = component.summary ?? (component.description ? component.description.length > 90 ? `${component.description.slice(0, 90)}...` : component.description : void 0);
571
+ return summary ? `- ${component.name} (${component.id}): ${summary}` : `- ${component.name} (${component.id})`;
635
572
  }
636
573
  function formatDocLine(doc) {
637
- const title = "title" in doc ? doc.title : void 0;
638
- const content = "content" in doc ? doc.content : void 0;
639
- const summary = doc.summary ?? extractDocsSummary(content ?? "");
640
- return `- ${title ?? doc.name} (${doc.id})${summary ? `: ${summary}` : ""}`;
574
+ let title = "title" in doc ? doc.title : void 0, content = "content" in doc ? doc.content : void 0, summary = doc.summary ?? extractDocsSummary(content ?? "");
575
+ return `- ${title ?? doc.name} (${doc.id})${summary ? `: ${summary}` : ""}`;
641
576
  }
642
577
  function formatStorySubLine(story) {
643
- return ` - ${story.name}` + (story.id ? ` (${story.id})` : "");
578
+ return ` - ${story.name}` + (story.id ? ` (${story.id})` : "");
644
579
  }
645
- /**
646
- * Extracts a summary from an object with optional summary and description fields.
647
- * Prefers summary if available, otherwise truncates description to maxLength.
648
- */
649
- function extractSummary(item, maxLength = MAX_SUMMARY_LENGTH) {
650
- if (item.summary) return item.summary;
651
- if (item.description) return item.description.length > maxLength ? `${item.description.slice(0, maxLength)}...` : item.description;
580
+ function extractSummary(item, maxLength = 90) {
581
+ if (item.summary)
582
+ return item.summary;
583
+ if (item.description)
584
+ return item.description.length > maxLength ? `${item.description.slice(0, maxLength)}...` : item.description;
652
585
  }
653
- /**
654
- * Extract parsed docgen from a component manifest, preferring reactDocgen over
655
- * reactDocgenTypescript over reactComponentMeta.
656
- */
657
586
  function getParsedDocgen(componentManifest) {
658
- if (componentManifest.reactDocgen) return parseReactDocgen(componentManifest.reactDocgen);
659
- if (componentManifest.reactDocgenTypescript) return parseReactDocgenTypescript(componentManifest.reactDocgenTypescript);
660
- if (componentManifest.reactComponentMeta) return parseReactComponentMeta(componentManifest.reactComponentMeta);
587
+ if (componentManifest.reactDocgen)
588
+ return parseReactDocgen(componentManifest.reactDocgen);
589
+ if (componentManifest.reactDocgenTypescript)
590
+ return parseReactDocgenTypescript(componentManifest.reactDocgenTypescript);
591
+ if (componentManifest.reactComponentMeta)
592
+ return parseReactComponentMeta(componentManifest.reactComponentMeta);
661
593
  }
662
- /**
663
- * Formats a story's content (description + code snippet) into markdown.
664
- * Reusable helper for both formatComponentManifest and formatStoryDocumentation.
665
- */
666
594
  function formatStoryContent(story, importStatement) {
667
- const parts = [];
668
- if (story.description) {
669
- parts.push(story.description);
670
- parts.push("");
671
- }
672
- parts.push("```");
673
- if (importStatement) {
674
- parts.push(importStatement);
675
- parts.push("");
676
- }
677
- parts.push(story.snippet ?? "");
678
- parts.push("```");
679
- return parts;
595
+ let parts = [];
596
+ return story.description && (parts.push(story.description), parts.push("")), parts.push("```"), importStatement && (parts.push(importStatement), parts.push("")), parts.push(story.snippet ?? ""), parts.push("```"), parts;
680
597
  }
681
598
  function formatPropsSection(parsedDocgen, options = {}) {
682
- const propEntries = parsedDocgen ? Object.entries(parsedDocgen.props) : [];
683
- if (propEntries.length === 0) return [];
684
- const title = options.title ?? "## Props";
685
- const typeName = options.typeName ?? "Props";
686
- const parts = [];
687
- parts.push(title);
688
- parts.push("");
689
- parts.push("```");
690
- parts.push(`export type ${typeName} = {`);
691
- for (const [propName, propInfo] of propEntries) {
692
- const type = propInfo.type ?? "any";
693
- const isRequired = propInfo.required ?? true;
694
- const hasDefault = propInfo.defaultValue !== void 0;
695
- if (propInfo.description !== void 0) {
696
- parts.push(" /**");
697
- parts.push(` ${propInfo.description}`);
698
- parts.push(" */");
699
- }
700
- let propLine = ` ${propName}`;
701
- if (!isRequired) propLine += "?";
702
- propLine += `: ${type}`;
703
- if (hasDefault) propLine += ` = ${propInfo.defaultValue}`;
704
- propLine += ";";
705
- parts.push(propLine);
706
- }
707
- parts.push("}");
708
- parts.push("```");
709
- parts.push("");
710
- return parts;
599
+ let propEntries = parsedDocgen ? Object.entries(parsedDocgen.props) : [];
600
+ if (propEntries.length === 0)
601
+ return [];
602
+ let title = options.title ?? "## Props", typeName = options.typeName ?? "Props", parts = [];
603
+ parts.push(title), parts.push(""), parts.push("```"), parts.push(`export type ${typeName} = {`);
604
+ for (let [propName, propInfo] of propEntries) {
605
+ let type = propInfo.type ?? "any", isRequired = propInfo.required ?? !0, hasDefault = propInfo.defaultValue !== void 0;
606
+ propInfo.description !== void 0 && (parts.push(" /**"), parts.push(` ${propInfo.description}`), parts.push(" */"));
607
+ let propLine = ` ${propName}`;
608
+ isRequired || (propLine += "?"), propLine += `: ${type}`, hasDefault && (propLine += ` = ${propInfo.defaultValue}`), propLine += ";", parts.push(propLine);
609
+ }
610
+ return parts.push("}"), parts.push("```"), parts.push(""), parts;
711
611
  }
712
612
  function formatSubcomponentsSection(subcomponents) {
713
- if (!subcomponents || Object.keys(subcomponents).length === 0) return [];
714
- const parts = [];
715
- parts.push("## Subcomponents");
716
- parts.push("");
717
- for (const [key, subcomponent] of Object.entries(subcomponents)) {
718
- parts.push(`### ${subcomponent.name || key}`);
719
- parts.push("");
720
- if (subcomponent.summary) {
721
- parts.push(subcomponent.summary);
722
- parts.push("");
723
- }
724
- if (subcomponent.description) {
725
- parts.push(subcomponent.description);
726
- parts.push("");
727
- }
728
- if (subcomponent.import) {
729
- parts.push("```");
730
- parts.push(subcomponent.import);
731
- parts.push("```");
732
- parts.push("");
733
- }
734
- if (subcomponent.error) {
735
- parts.push(`Error: ${subcomponent.error.name}`);
736
- parts.push("");
737
- parts.push("```");
738
- parts.push(subcomponent.error.message);
739
- parts.push("```");
740
- parts.push("");
741
- continue;
742
- }
743
- const parsedDocgen = getParsedDocgen(subcomponent);
744
- const typeName = `${(subcomponent.name || key).replace(/\W+/g, "")}Props`;
745
- parts.push(...formatPropsSection(parsedDocgen, {
746
- title: "#### Props",
747
- typeName
748
- }));
749
- }
750
- return parts;
613
+ if (!subcomponents || Object.keys(subcomponents).length === 0)
614
+ return [];
615
+ let parts = [];
616
+ parts.push("## Subcomponents"), parts.push("");
617
+ for (let [key, subcomponent] of Object.entries(subcomponents)) {
618
+ if (parts.push(`### ${subcomponent.name || key}`), parts.push(""), subcomponent.summary && (parts.push(subcomponent.summary), parts.push("")), subcomponent.description && (parts.push(subcomponent.description), parts.push("")), subcomponent.import && (parts.push("```"), parts.push(subcomponent.import), parts.push("```"), parts.push("")), subcomponent.error) {
619
+ parts.push(`Error: ${subcomponent.error.name}`), parts.push(""), parts.push("```"), parts.push(subcomponent.error.message), parts.push("```"), parts.push("");
620
+ continue;
621
+ }
622
+ let parsedDocgen = getParsedDocgen(subcomponent), typeName = `${(subcomponent.name || key).replace(/\W+/g, "")}Props`;
623
+ parts.push(...formatPropsSection(parsedDocgen, { title: "#### Props", typeName }));
624
+ }
625
+ return parts;
751
626
  }
752
- /**
753
- * Format a single component manifest into markdown.
754
- */
755
627
  function formatComponentManifest(componentManifest) {
756
- const parts = [];
757
- parts.push(`# ${componentManifest.name}`);
758
- parts.push("");
759
- parts.push(`ID: ${componentManifest.id}`);
760
- parts.push("");
761
- if (componentManifest.description) {
762
- parts.push(componentManifest.description);
763
- parts.push("");
764
- }
765
- parts.push(...formatSubcomponentsSection(componentManifest.subcomponents));
766
- const parsedDocgen = getParsedDocgen(componentManifest);
767
- const stories = Array.isArray(componentManifest.stories) ? componentManifest.stories : [];
768
- if (stories.length > 0) {
769
- parts.push("## Stories");
770
- parts.push("");
771
- const storiesWithSnippets = stories.filter((s) => s.snippet);
772
- const hasProps = parsedDocgen && Object.keys(parsedDocgen.props).length > 0;
773
- const storiesToShow = hasProps ? storiesWithSnippets.slice(0, MAX_STORIES_TO_SHOW) : storiesWithSnippets;
774
- const remainingStories = hasProps ? storiesWithSnippets.slice(MAX_STORIES_TO_SHOW) : [];
775
- for (const story of storiesToShow) {
776
- parts.push(`### ${story.name}`);
777
- parts.push("");
778
- if (story.id) {
779
- parts.push(`Story ID: ${story.id}`);
780
- parts.push("");
781
- }
782
- parts.push(...formatStoryContent(story, componentManifest.import));
783
- parts.push("");
784
- }
785
- if (remainingStories.length > 0) {
786
- if (storiesToShow.length > 0) parts.push("### Other Stories");
787
- parts.push("");
788
- for (const story of remainingStories) {
789
- const summary = extractSummary(story);
790
- const summaryPart = summary ? `: ${summary}` : "";
791
- const storyLabel = story.id ? `${story.name} (${story.id})` : story.name;
792
- parts.push(`- ${storyLabel}${summaryPart}`);
793
- }
794
- parts.push("");
795
- }
796
- }
797
- parts.push(...formatPropsSection(parsedDocgen));
798
- if (componentManifest.docs && Object.keys(componentManifest.docs).length > 0) {
799
- const docsWithContent = Object.values(componentManifest.docs).filter((doc) => (doc.content ?? "").trim().length > 0);
800
- if (docsWithContent.length > 0) {
801
- parts.push("## Docs");
802
- parts.push("");
803
- for (const doc of docsWithContent) {
804
- parts.push(`### ${doc.name}`);
805
- parts.push("");
806
- parts.push(doc.content ?? "");
807
- parts.push("");
808
- }
809
- }
810
- }
811
- return parts.join("\n").trim();
628
+ let parts = [];
629
+ parts.push(`# ${componentManifest.name}`), parts.push(""), parts.push(`ID: ${componentManifest.id}`), parts.push(""), componentManifest.description && (parts.push(componentManifest.description), parts.push("")), parts.push(...formatSubcomponentsSection(componentManifest.subcomponents));
630
+ let parsedDocgen = getParsedDocgen(componentManifest), stories = Array.isArray(componentManifest.stories) ? componentManifest.stories : [];
631
+ if (stories.length > 0) {
632
+ parts.push("## Stories"), parts.push("");
633
+ let storiesWithSnippets = stories.filter((s) => s.snippet), hasProps = parsedDocgen && Object.keys(parsedDocgen.props).length > 0, storiesToShow = hasProps ? storiesWithSnippets.slice(0, MAX_STORIES_TO_SHOW) : storiesWithSnippets, remainingStories = hasProps ? storiesWithSnippets.slice(MAX_STORIES_TO_SHOW) : [];
634
+ for (let story of storiesToShow)
635
+ parts.push(`### ${story.name}`), parts.push(""), story.id && (parts.push(`Story ID: ${story.id}`), parts.push("")), parts.push(...formatStoryContent(story, componentManifest.import)), parts.push("");
636
+ if (remainingStories.length > 0) {
637
+ storiesToShow.length > 0 && parts.push("### Other Stories"), parts.push("");
638
+ for (let story of remainingStories) {
639
+ let summary = extractSummary(story), summaryPart = summary ? `: ${summary}` : "", storyLabel = story.id ? `${story.name} (${story.id})` : story.name;
640
+ parts.push(`- ${storyLabel}${summaryPart}`);
641
+ }
642
+ parts.push("");
643
+ }
644
+ }
645
+ if (parts.push(...formatPropsSection(parsedDocgen)), componentManifest.docs && Object.keys(componentManifest.docs).length > 0) {
646
+ let docsWithContent = Object.values(componentManifest.docs).filter(
647
+ (doc) => (doc.content ?? "").trim().length > 0
648
+ );
649
+ if (docsWithContent.length > 0) {
650
+ parts.push("## Docs"), parts.push("");
651
+ for (let doc of docsWithContent)
652
+ parts.push(`### ${doc.name}`), parts.push(""), parts.push(doc.content ?? ""), parts.push("");
653
+ }
654
+ }
655
+ return parts.join(`
656
+ `).trim();
812
657
  }
813
- /**
814
- * Format a single doc manifest into markdown.
815
- */
816
658
  function formatDocsManifest(doc) {
817
- return dedent`# ${doc.title ?? doc.name}
659
+ return dedent`# ${doc.title ?? doc.name}
818
660
 
819
661
  ${doc.content ?? ""}`;
820
662
  }
821
- /**
822
- * Format a component manifest map into a markdown list.
823
- * @param manifest - The component manifest map to format
824
- * @returns Formatted string representation of the component list
825
- */
826
663
  function formatManifestsToLists(manifests, options = {}) {
827
- const parts = [];
828
- parts.push("# Components");
829
- parts.push("");
830
- for (const component of Object.values(manifests.componentManifest.components)) {
831
- parts.push(formatComponentLine(component));
832
- if (options.withStoryIds && Array.isArray(component.stories)) for (const story of component.stories) parts.push(formatStorySubLine(story));
833
- }
834
- parts.push("");
835
- if (!manifests.docsManifest) return parts.join("\n").trim();
836
- parts.push("# Docs");
837
- parts.push("");
838
- for (const doc of Object.values(manifests.docsManifest.docs)) parts.push(formatDocLine(doc));
839
- return parts.join("\n").trim();
664
+ let parts = [];
665
+ parts.push("# Components"), parts.push("");
666
+ for (let component of Object.values(manifests.componentManifest.components))
667
+ if (parts.push(formatComponentLine(component)), options.withStoryIds && Array.isArray(component.stories))
668
+ for (let story of component.stories)
669
+ parts.push(formatStorySubLine(story));
670
+ if (parts.push(""), !manifests.docsManifest)
671
+ return parts.join(`
672
+ `).trim();
673
+ parts.push("# Docs"), parts.push("");
674
+ for (let doc of Object.values(manifests.docsManifest.docs))
675
+ parts.push(formatDocLine(doc));
676
+ return parts.join(`
677
+ `).trim();
840
678
  }
841
679
  function formatMultiSourceManifestsToLists(manifests, options = {}) {
842
- const parts = [];
843
- for (const { source, componentManifest, docsManifest, error, notice } of manifests) {
844
- parts.push(`# ${source.title}`);
845
- parts.push(`id: ${source.id}`);
846
- parts.push("");
847
- if (error) {
848
- parts.push(`error: ${error}`);
849
- parts.push("");
850
- continue;
851
- }
852
- if (notice) {
853
- parts.push(formatRequiresOwnMcpNotice(source, notice.endpoint, { includeHeader: false }));
854
- parts.push("");
855
- continue;
856
- }
857
- const components = Object.values(componentManifest.components);
858
- if (components.length > 0) {
859
- parts.push("## Components");
860
- parts.push("");
861
- for (const component of components) {
862
- parts.push(formatComponentLine(component));
863
- if (options.withStoryIds && Array.isArray(component.stories)) for (const story of component.stories) parts.push(formatStorySubLine(story));
864
- }
865
- parts.push("");
866
- }
867
- if (docsManifest && Object.keys(docsManifest.docs).length > 0) {
868
- parts.push("## Docs");
869
- parts.push("");
870
- for (const doc of Object.values(docsManifest.docs)) parts.push(formatDocLine(doc));
871
- parts.push("");
872
- }
873
- }
874
- return parts.join("\n").trim();
680
+ let parts = [];
681
+ for (let { source, componentManifest, docsManifest, error, notice } of manifests) {
682
+ if (parts.push(`# ${source.title}`), parts.push(`id: ${source.id}`), parts.push(""), error) {
683
+ parts.push(`error: ${error}`), parts.push("");
684
+ continue;
685
+ }
686
+ if (notice) {
687
+ parts.push(formatRequiresOwnMcpNotice(source, notice.endpoint, { includeHeader: !1 })), parts.push("");
688
+ continue;
689
+ }
690
+ let components = Object.values(componentManifest.components);
691
+ if (components.length > 0) {
692
+ parts.push("## Components"), parts.push("");
693
+ for (let component of components)
694
+ if (parts.push(formatComponentLine(component)), options.withStoryIds && Array.isArray(component.stories))
695
+ for (let story of component.stories)
696
+ parts.push(formatStorySubLine(story));
697
+ parts.push("");
698
+ }
699
+ if (docsManifest && Object.keys(docsManifest.docs).length > 0) {
700
+ parts.push("## Docs"), parts.push("");
701
+ for (let doc of Object.values(docsManifest.docs))
702
+ parts.push(formatDocLine(doc));
703
+ parts.push("");
704
+ }
705
+ }
706
+ return parts.join(`
707
+ `).trim();
875
708
  }
876
- /**
877
- * Format a single story's documentation.
878
- */
879
709
  function formatStoryDocumentation(componentManifest, storyName) {
880
- const story = Array.isArray(componentManifest.stories) ? componentManifest.stories.find((s) => s.name === storyName) : void 0;
881
- if (!story || !story.snippet) return "";
882
- const parts = [];
883
- parts.push(`# ${componentManifest.name} - ${story.name}`);
884
- parts.push("");
885
- parts.push(...formatStoryContent(story, componentManifest.import));
886
- return parts.join("\n").trim();
710
+ let story = Array.isArray(componentManifest.stories) ? componentManifest.stories.find((s) => s.name === storyName) : void 0;
711
+ if (!story || !story.snippet)
712
+ return "";
713
+ let parts = [];
714
+ return parts.push(`# ${componentManifest.name} - ${story.name}`), parts.push(""), parts.push(...formatStoryContent(story, componentManifest.import)), parts.join(`
715
+ `).trim();
887
716
  }
888
717
 
889
- //#endregion
890
- //#region src/tools/list-all-documentation.ts
891
- const LIST_TOOL_NAME = "list-all-documentation";
892
- const ListAllDocumentationInput = v.object({ withStoryIds: v.optional(v.pipe(v.boolean(), v.description("When true, includes story sub-bullets under each component with story name and story ID. Use this to discover IDs for downstream story-focused workflows without filesystem lookup.")), false) });
718
+ // src/tools/list-all-documentation.ts
719
+ var LIST_TOOL_NAME = "list-all-documentation", ListAllDocumentationInput = v3.object({
720
+ withStoryIds: v3.optional(
721
+ v3.pipe(
722
+ v3.boolean(),
723
+ v3.description(
724
+ "When true, includes story sub-bullets under each component with story name and story ID. Use this to discover IDs for downstream story-focused workflows without filesystem lookup."
725
+ )
726
+ ),
727
+ !1
728
+ )
729
+ });
893
730
  function getListAllDocumentationToolMetadata() {
894
- return {
895
- name: LIST_TOOL_NAME,
896
- title: "List All Documentation",
897
- description: "List all available UI components and documentation entries from the Storybook, returning the IDs the other documentation tools take as input. Call this first for any UI task — before writing a new component, check what the design system already provides and build on it instead of hand-rolling a duplicate; before answering any question about props, API, or usage, discover the relevant IDs here rather than reading component source. Then fetch the entries with get-documentation, referencing only IDs returned here — never guess IDs. When multiple Storybook sources are configured, entries from every source are included; scope follow-up calls to one source via their `storybookId` input. Pass `withStoryIds: true` when you need story IDs for other tools.",
898
- schema: ListAllDocumentationInput
899
- };
731
+ return {
732
+ name: LIST_TOOL_NAME,
733
+ title: "List All Documentation",
734
+ description: "List all available UI components and documentation entries from the Storybook, returning the IDs the other documentation tools take as input. Call this first for any UI task \u2014 before writing a new component, check what the design system already provides and build on it instead of hand-rolling a duplicate; before answering any question about props, API, or usage, discover the relevant IDs here rather than reading component source. Then fetch the entries with get-documentation, referencing only IDs returned here \u2014 never guess IDs. When multiple Storybook sources are configured, entries from every source are included; scope follow-up calls to one source via their `storybookId` input. Pass `withStoryIds: true` when you need story IDs for other tools.",
735
+ schema: ListAllDocumentationInput
736
+ };
900
737
  }
901
738
  async function addListAllDocumentationTool(server, enabled) {
902
- server.tool({
903
- ...getListAllDocumentationToolMetadata(),
904
- enabled
905
- }, async (input) => {
906
- try {
907
- const ctx = server.ctx.custom;
908
- const withStoryIds = input.withStoryIds ?? false;
909
- if (ctx?.sources?.some((s) => s.url)) {
910
- const multiSourceManifests = await getMultiSourceManifests(ctx.sources, ctx.request, ctx.manifestProvider);
911
- if (withStoryIds) await Promise.all(multiSourceManifests.map(async (sourceManifest) => {
912
- if (sourceManifest.error || sourceManifest.notice) return;
913
- try {
914
- const components = sourceManifest.componentManifest.components;
915
- const resolved = await mapWithConcurrency(Object.entries(components), 16, async ([id, component]) => {
916
- return [id, await resolveComponentStories(component, ctx.request, ctx.manifestProvider, sourceManifest.source)];
917
- });
918
- for (const [id, component] of resolved) components[id] = component;
919
- } catch {}
920
- }));
921
- const lists = formatMultiSourceManifestsToLists(multiSourceManifests, { withStoryIds });
922
- const firstSuccess = multiSourceManifests.find((m) => !m.error && !m.notice);
923
- if (firstSuccess) await ctx.onListAllDocumentation?.({
924
- context: ctx,
925
- manifests: {
926
- componentManifest: firstSuccess.componentManifest,
927
- docsManifest: firstSuccess.docsManifest
928
- },
929
- resultText: lists,
930
- sources: multiSourceManifests
931
- });
932
- return { content: [{
933
- type: "text",
934
- text: lists
935
- }] };
936
- }
937
- const manifests = await getManifests(ctx?.request, ctx?.manifestProvider);
938
- if (withStoryIds) {
939
- const components = manifests.componentManifest.components;
940
- const resolved = await mapWithConcurrency(Object.entries(components), 16, async ([id, component]) => {
941
- return [id, await resolveComponentStories(component, ctx?.request, ctx?.manifestProvider)];
942
- });
943
- for (const [id, component] of resolved) components[id] = component;
944
- }
945
- const lists = formatManifestsToLists(manifests, { withStoryIds });
946
- await ctx?.onListAllDocumentation?.({
947
- context: ctx,
948
- manifests,
949
- resultText: lists
950
- });
951
- return { content: [{
952
- type: "text",
953
- text: lists
954
- }] };
955
- } catch (error) {
956
- return errorToMCPContent(error);
957
- }
958
- });
739
+ server.tool(
740
+ {
741
+ ...getListAllDocumentationToolMetadata(),
742
+ enabled
743
+ },
744
+ async (input) => {
745
+ try {
746
+ let ctx = server.ctx.custom, withStoryIds = input.withStoryIds ?? !1;
747
+ if (ctx?.sources?.some((s) => s.url)) {
748
+ let multiSourceManifests = await getMultiSourceManifests(
749
+ ctx.sources,
750
+ ctx.request,
751
+ ctx.manifestProvider
752
+ );
753
+ withStoryIds && await Promise.all(
754
+ multiSourceManifests.map(async (sourceManifest) => {
755
+ if (!(sourceManifest.error || sourceManifest.notice))
756
+ try {
757
+ let components = sourceManifest.componentManifest.components, entries = Object.entries(components), resolved = await mapWithConcurrency(
758
+ entries,
759
+ 16,
760
+ async ([id, component]) => {
761
+ let storiesResolved = await resolveComponentStories(
762
+ component,
763
+ ctx.request,
764
+ ctx.manifestProvider,
765
+ sourceManifest.source
766
+ );
767
+ return [id, storiesResolved];
768
+ }
769
+ );
770
+ for (let [id, component] of resolved)
771
+ components[id] = component;
772
+ } catch {
773
+ }
774
+ })
775
+ );
776
+ let lists2 = formatMultiSourceManifestsToLists(multiSourceManifests, {
777
+ withStoryIds
778
+ }), firstSuccess = multiSourceManifests.find((m) => !m.error && !m.notice);
779
+ return firstSuccess && await ctx.onListAllDocumentation?.({
780
+ context: ctx,
781
+ manifests: {
782
+ componentManifest: firstSuccess.componentManifest,
783
+ docsManifest: firstSuccess.docsManifest
784
+ },
785
+ resultText: lists2,
786
+ sources: multiSourceManifests
787
+ }), {
788
+ content: [
789
+ {
790
+ type: "text",
791
+ text: lists2
792
+ }
793
+ ]
794
+ };
795
+ }
796
+ let manifests = await getManifests(ctx?.request, ctx?.manifestProvider);
797
+ if (withStoryIds) {
798
+ let components = manifests.componentManifest.components, entries = Object.entries(components), resolved = await mapWithConcurrency(entries, 16, async ([id, component]) => {
799
+ let storiesResolved = await resolveComponentStories(
800
+ component,
801
+ ctx?.request,
802
+ ctx?.manifestProvider
803
+ );
804
+ return [id, storiesResolved];
805
+ });
806
+ for (let [id, component] of resolved)
807
+ components[id] = component;
808
+ }
809
+ let lists = formatManifestsToLists(manifests, {
810
+ withStoryIds
811
+ });
812
+ return await ctx?.onListAllDocumentation?.({
813
+ context: ctx,
814
+ manifests,
815
+ resultText: lists
816
+ }), {
817
+ content: [
818
+ {
819
+ type: "text",
820
+ text: lists
821
+ }
822
+ ]
823
+ };
824
+ } catch (error) {
825
+ return errorToMCPContent(error);
826
+ }
827
+ }
828
+ );
959
829
  }
960
830
 
961
- //#endregion
962
- //#region src/tools/get-documentation-for-story.ts
963
- const GET_STORY_TOOL_NAME = "get-documentation-for-story";
964
- const GET_STORY_DOCUMENTATION_TOOL_DESCRIPTION = "Get detailed documentation for a specific story variant of a UI component. Use this when you need to see more usage examples of a component, via the stories written for it.";
965
- const BaseInput$1 = {
966
- componentId: v.string(),
967
- storyName: v.string()
831
+ // src/tools/get-documentation-for-story.ts
832
+ import * as v4 from "valibot";
833
+ var GET_STORY_TOOL_NAME = "get-documentation-for-story", GET_STORY_DOCUMENTATION_TOOL_DESCRIPTION = "Get detailed documentation for a specific story variant of a UI component. Use this when you need to see more usage examples of a component, via the stories written for it.", BaseInput = {
834
+ componentId: v4.string(),
835
+ storyName: v4.string()
968
836
  };
969
837
  function getStoryDocumentationToolSchema(options) {
970
- return options?.multiSource ? v.object({
971
- ...BaseInput$1,
972
- ...StorybookIdField
973
- }) : v.object(BaseInput$1);
838
+ return options?.multiSource ? v4.object({ ...BaseInput, ...StorybookIdField }) : v4.object(BaseInput);
974
839
  }
975
840
  function getStoryDocumentationToolMetadata(options) {
976
- return {
977
- name: GET_STORY_TOOL_NAME,
978
- title: "Get Documentation for Story",
979
- description: GET_STORY_DOCUMENTATION_TOOL_DESCRIPTION,
980
- schema: getStoryDocumentationToolSchema(options)
981
- };
841
+ return {
842
+ name: GET_STORY_TOOL_NAME,
843
+ title: "Get Documentation for Story",
844
+ description: GET_STORY_DOCUMENTATION_TOOL_DESCRIPTION,
845
+ schema: getStoryDocumentationToolSchema(options)
846
+ };
982
847
  }
983
848
  async function addGetStoryDocumentationTool(server, enabled, options) {
984
- server.tool({
985
- ...getStoryDocumentationToolMetadata(options),
986
- enabled
987
- }, async (input) => {
988
- try {
989
- const ctx = server.ctx.custom;
990
- const { componentId, storyName, storybookId } = input;
991
- const sources = ctx?.sources;
992
- const isMultiSource = sources && sources.some((s) => s.url);
993
- let source;
994
- if (isMultiSource) {
995
- if (!storybookId) return {
996
- content: [{
997
- type: "text",
998
- text: `storybookId is required. Available sources: ${sources.map((s) => s.id).join(", ")}. Use the ${LIST_TOOL_NAME} tool to see available sources.`
999
- }],
1000
- isError: true
1001
- };
1002
- source = sources.find((s) => s.id === storybookId);
1003
- if (!source) return {
1004
- content: [{
1005
- type: "text",
1006
- text: `Storybook source not found: "${storybookId}". Available sources: ${sources.map((s) => s.id).join(", ")}. Use the ${LIST_TOOL_NAME} tool to see available sources.`
1007
- }],
1008
- isError: true
1009
- };
1010
- }
1011
- let component;
1012
- if (ctx?.resolveEntry && !source?.url) {
1013
- const resolved = await ctx.resolveEntry(componentId, source);
1014
- if (resolved?.kind === "component") component = resolved.component;
1015
- } else {
1016
- const componentEntry = (await getManifests(ctx?.request, ctx?.manifestProvider, source)).componentManifest?.components[componentId];
1017
- if (componentEntry) component = await resolveComponentEntry(componentEntry, ctx?.request, ctx?.manifestProvider, source);
1018
- }
1019
- if (!component) return {
1020
- content: [{
1021
- type: "text",
1022
- text: `Component not found: "${componentId}". Use the list-all-documentation tool to see available components.`
1023
- }],
1024
- isError: true
1025
- };
1026
- if (!(Array.isArray(component.stories) ? component.stories.find((s) => s.name === storyName) : void 0)) return {
1027
- content: [{
1028
- type: "text",
1029
- text: `Story "${storyName}" not found for component "${componentId}". Available stories: ${Array.isArray(component.stories) ? component.stories.map((s) => s.name).join(", ") : "none"}`
1030
- }],
1031
- isError: true
1032
- };
1033
- return { content: [{
1034
- type: "text",
1035
- text: formatStoryDocumentation(component, storyName)
1036
- }] };
1037
- } catch (error) {
1038
- return errorToMCPContent(error);
1039
- }
1040
- });
849
+ server.tool(
850
+ {
851
+ ...getStoryDocumentationToolMetadata(options),
852
+ enabled
853
+ },
854
+ async (input) => {
855
+ try {
856
+ let ctx = server.ctx.custom, { componentId, storyName, storybookId } = input, sources = ctx?.sources, isMultiSource = sources && sources.some((s) => s.url), source;
857
+ if (isMultiSource) {
858
+ if (!storybookId)
859
+ return {
860
+ content: [
861
+ {
862
+ type: "text",
863
+ text: `storybookId is required. Available sources: ${sources.map((s) => s.id).join(", ")}. Use the ${LIST_TOOL_NAME} tool to see available sources.`
864
+ }
865
+ ],
866
+ isError: !0
867
+ };
868
+ if (source = sources.find((s) => s.id === storybookId), !source) {
869
+ let availableSources = sources.map((s) => s.id).join(", ");
870
+ return {
871
+ content: [
872
+ {
873
+ type: "text",
874
+ text: `Storybook source not found: "${storybookId}". Available sources: ${availableSources}. Use the ${LIST_TOOL_NAME} tool to see available sources.`
875
+ }
876
+ ],
877
+ isError: !0
878
+ };
879
+ }
880
+ }
881
+ let component;
882
+ if (ctx?.resolveEntry && !source?.url) {
883
+ let resolved = await ctx.resolveEntry(componentId, source);
884
+ resolved?.kind === "component" && (component = resolved.component);
885
+ } else {
886
+ let componentEntry = (await getManifests(ctx?.request, ctx?.manifestProvider, source)).componentManifest?.components[componentId];
887
+ componentEntry && (component = await resolveComponentEntry(
888
+ componentEntry,
889
+ ctx?.request,
890
+ ctx?.manifestProvider,
891
+ source
892
+ ));
893
+ }
894
+ if (!component)
895
+ return {
896
+ content: [
897
+ {
898
+ type: "text",
899
+ text: `Component not found: "${componentId}". Use the list-all-documentation tool to see available components.`
900
+ }
901
+ ],
902
+ isError: !0
903
+ };
904
+ if (!(Array.isArray(component.stories) ? component.stories.find((s) => s.name === storyName) : void 0)) {
905
+ let availableStories = Array.isArray(component.stories) ? component.stories.map((s) => s.name).join(", ") : "none";
906
+ return {
907
+ content: [
908
+ {
909
+ type: "text",
910
+ text: `Story "${storyName}" not found for component "${componentId}". Available stories: ${availableStories}`
911
+ }
912
+ ],
913
+ isError: !0
914
+ };
915
+ }
916
+ return {
917
+ content: [
918
+ {
919
+ type: "text",
920
+ text: formatStoryDocumentation(component, storyName)
921
+ }
922
+ ]
923
+ };
924
+ } catch (error) {
925
+ return errorToMCPContent(error);
926
+ }
927
+ }
928
+ );
1041
929
  }
1042
930
 
1043
- //#endregion
1044
- //#region src/tools/get-documentation.ts
1045
- const GET_TOOL_NAME = "get-documentation";
1046
- const BaseInput = { id: v.pipe(v.string(), v.description("The component or docs entry ID (e.g., \"button\")")) };
1047
- const GET_DOCUMENTATION_TOOL_DESCRIPTION = `Get documentation for a UI component or docs entry.
931
+ // src/tools/get-documentation.ts
932
+ import * as v5 from "valibot";
933
+ var GET_TOOL_NAME = "get-documentation", BaseInput2 = {
934
+ id: v5.pipe(v5.string(), v5.description('The component or docs entry ID (e.g., "button")'))
935
+ }, GET_DOCUMENTATION_TOOL_DESCRIPTION = `Get documentation for a UI component or docs entry.
1048
936
 
1049
- Returns the first ${MAX_STORIES_TO_SHOW} stories (including story IDs) with code snippets showing how props are used, plus TypeScript prop definitions. Call this before using a component to avoid hallucinating prop names, types, or valid combinations, and to answer any question about a component's props, API, or usage — reading or grepping the component source is not a substitute. Stories reveal real prop usage patterns, interactions, and edge cases that type definitions alone don't show. If the example stories don't show the prop you need, use the ${GET_STORY_TOOL_NAME} tool to fetch the story documentation for the specific story variant you need.
937
+ Returns the first ${MAX_STORIES_TO_SHOW} stories (including story IDs) with code snippets showing how props are used, plus TypeScript prop definitions. Call this before using a component to avoid hallucinating prop names, types, or valid combinations, and to answer any question about a component's props, API, or usage \u2014 reading or grepping the component source is not a substitute. Stories reveal real prop usage patterns, interactions, and edge cases that type definitions alone don't show. If the example stories don't show the prop you need, use the ${GET_STORY_TOOL_NAME} tool to fetch the story documentation for the specific story variant you need.
1050
938
 
1051
939
  Example: id="button" returns Primary, Secondary, Large stories with code like <Button variant="primary" size="large"> showing actual prop combinations.`;
1052
940
  function getDocumentationToolSchema(options) {
1053
- return options?.multiSource ? v.object({
1054
- ...BaseInput,
1055
- ...StorybookIdField
1056
- }) : v.object(BaseInput);
941
+ return options?.multiSource ? v5.object({ ...BaseInput2, ...StorybookIdField }) : v5.object(BaseInput2);
1057
942
  }
1058
943
  function getDocumentationToolMetadata(options) {
1059
- return {
1060
- name: GET_TOOL_NAME,
1061
- title: "Get Documentation",
1062
- description: GET_DOCUMENTATION_TOOL_DESCRIPTION,
1063
- schema: getDocumentationToolSchema(options)
1064
- };
944
+ return {
945
+ name: GET_TOOL_NAME,
946
+ title: "Get Documentation",
947
+ description: GET_DOCUMENTATION_TOOL_DESCRIPTION,
948
+ schema: getDocumentationToolSchema(options)
949
+ };
1065
950
  }
1066
951
  async function addGetDocumentationTool(server, enabled, options) {
1067
- server.tool({
1068
- ...getDocumentationToolMetadata(options),
1069
- enabled
1070
- }, async (input) => {
1071
- try {
1072
- const ctx = server.ctx.custom;
1073
- const { id, storybookId } = input;
1074
- const sources = ctx?.sources;
1075
- const isMultiSource = sources && sources.some((s) => s.url);
1076
- let source;
1077
- if (isMultiSource) {
1078
- if (!storybookId) return {
1079
- content: [{
1080
- type: "text",
1081
- text: `storybookId is required. Available sources: ${sources.map((s) => s.id).join(", ")}. Use the ${LIST_TOOL_NAME} tool to see available sources.`
1082
- }],
1083
- isError: true
1084
- };
1085
- source = sources.find((s) => s.id === storybookId);
1086
- if (!source) return {
1087
- content: [{
1088
- type: "text",
1089
- text: `Storybook source not found: "${storybookId}". Available sources: ${sources.map((s) => s.id).join(", ")}. Use the ${LIST_TOOL_NAME} tool to see available sources.`
1090
- }],
1091
- isError: true
1092
- };
1093
- }
1094
- let component;
1095
- let docsEntry;
1096
- if (ctx?.resolveEntry && !source?.url) {
1097
- const resolved = await ctx.resolveEntry(id, source);
1098
- if (resolved?.kind === "component") component = resolved.component;
1099
- else if (resolved?.kind === "doc") docsEntry = resolved.doc;
1100
- } else {
1101
- const { componentManifest, docsManifest } = await getManifests(ctx?.request, ctx?.manifestProvider, source);
1102
- const componentEntry = componentManifest.components[id];
1103
- const docEntry = docsManifest?.docs[id];
1104
- if (componentEntry) component = await resolveComponentEntry(componentEntry, ctx?.request, ctx?.manifestProvider, source);
1105
- else if (docEntry) docsEntry = await resolveDoc(docEntry, ctx?.request, ctx?.manifestProvider, source);
1106
- }
1107
- if (!component && !docsEntry) {
1108
- const suffix = storybookId ? ` in source "${storybookId}"` : "";
1109
- await ctx?.onGetDocumentation?.({
1110
- context: ctx,
1111
- input
1112
- });
1113
- return {
1114
- content: [{
1115
- type: "text",
1116
- text: `Component or Docs Entry not found: "${id}"${suffix}. Use the ${LIST_TOOL_NAME} tool to see available components and documentation entries.`
1117
- }],
1118
- isError: true
1119
- };
1120
- }
1121
- const documentation = component ?? docsEntry;
1122
- const text = component ? formatComponentManifest(documentation) : formatDocsManifest(documentation);
1123
- await ctx?.onGetDocumentation?.({
1124
- context: ctx,
1125
- input,
1126
- foundDocumentation: documentation,
1127
- resultText: text
1128
- });
1129
- return { content: [{
1130
- type: "text",
1131
- text
1132
- }] };
1133
- } catch (error) {
1134
- return errorToMCPContent(error);
1135
- }
1136
- });
952
+ server.tool(
953
+ {
954
+ ...getDocumentationToolMetadata(options),
955
+ enabled
956
+ },
957
+ async (input) => {
958
+ try {
959
+ let ctx = server.ctx.custom, { id, storybookId } = input, sources = ctx?.sources, isMultiSource = sources && sources.some((s) => s.url), source;
960
+ if (isMultiSource) {
961
+ if (!storybookId)
962
+ return {
963
+ content: [
964
+ {
965
+ type: "text",
966
+ text: `storybookId is required. Available sources: ${sources.map((s) => s.id).join(", ")}. Use the ${LIST_TOOL_NAME} tool to see available sources.`
967
+ }
968
+ ],
969
+ isError: !0
970
+ };
971
+ if (source = sources.find((s) => s.id === storybookId), !source) {
972
+ let availableSources = sources.map((s) => s.id).join(", ");
973
+ return {
974
+ content: [
975
+ {
976
+ type: "text",
977
+ text: `Storybook source not found: "${storybookId}". Available sources: ${availableSources}. Use the ${LIST_TOOL_NAME} tool to see available sources.`
978
+ }
979
+ ],
980
+ isError: !0
981
+ };
982
+ }
983
+ }
984
+ let component, docsEntry;
985
+ if (ctx?.resolveEntry && !source?.url) {
986
+ let resolved = await ctx.resolveEntry(id, source);
987
+ resolved?.kind === "component" ? component = resolved.component : resolved?.kind === "doc" && (docsEntry = resolved.doc);
988
+ } else {
989
+ let { componentManifest, docsManifest } = await getManifests(
990
+ ctx?.request,
991
+ ctx?.manifestProvider,
992
+ source
993
+ ), componentEntry = componentManifest.components[id], docEntry = docsManifest?.docs[id];
994
+ componentEntry ? component = await resolveComponentEntry(
995
+ componentEntry,
996
+ ctx?.request,
997
+ ctx?.manifestProvider,
998
+ source
999
+ ) : docEntry && (docsEntry = await resolveDoc(docEntry, ctx?.request, ctx?.manifestProvider, source));
1000
+ }
1001
+ if (!component && !docsEntry) {
1002
+ let suffix = storybookId ? ` in source "${storybookId}"` : "";
1003
+ return await ctx?.onGetDocumentation?.({
1004
+ context: ctx,
1005
+ input
1006
+ }), {
1007
+ content: [
1008
+ {
1009
+ type: "text",
1010
+ text: `Component or Docs Entry not found: "${id}"${suffix}. Use the ${LIST_TOOL_NAME} tool to see available components and documentation entries.`
1011
+ }
1012
+ ],
1013
+ isError: !0
1014
+ };
1015
+ }
1016
+ let documentation = component ?? docsEntry, text = component ? formatComponentManifest(documentation) : formatDocsManifest(documentation);
1017
+ return await ctx?.onGetDocumentation?.({
1018
+ context: ctx,
1019
+ input,
1020
+ foundDocumentation: documentation,
1021
+ resultText: text
1022
+ }), {
1023
+ content: [
1024
+ {
1025
+ type: "text",
1026
+ text
1027
+ }
1028
+ ]
1029
+ };
1030
+ } catch (error) {
1031
+ return errorToMCPContent(error);
1032
+ }
1033
+ }
1034
+ );
1137
1035
  }
1138
1036
 
1139
- //#endregion
1140
- //#region src/index.ts
1141
- const createStorybookMcpHandler = async (options = {}) => {
1142
- const { onSessionInitialize, ...defaultContext } = options;
1143
- const adapter = new ValibotJsonSchemaAdapter();
1144
- const server = new McpServer({
1145
- name,
1146
- version,
1147
- description
1148
- }, {
1149
- adapter,
1150
- instructions: instructions_default,
1151
- capabilities: { tools: { listChanged: true } }
1152
- }).withContext();
1153
- if (onSessionInitialize) server.on("initialize", onSessionInitialize);
1154
- await addListAllDocumentationTool(server);
1155
- await addGetStoryDocumentationTool(server);
1156
- await addGetDocumentationTool(server);
1157
- const transport = new HttpTransport(server, { path: null });
1158
- return (async (req, context) => {
1159
- return await transport.respond(req, {
1160
- ...defaultContext,
1161
- ...context,
1162
- request: req
1163
- });
1164
- });
1165
- };
1037
+ // src/instructions.md
1038
+ var instructions_default = `## Documentation Workflow
1039
+
1040
+ **CRITICAL: Never hallucinate component properties!** Before using ANY property on a component (even common-sounding ones like \`shadow\`), you MUST verify it is documented via these tools. If it is not documented, it does not exist \u2014 never assume props from naming conventions or other libraries; report it to the user instead.
1041
+
1042
+ 1. Call **list-all-documentation** once at the start of the task to discover available component and docs IDs.
1043
+ 2. Call **get-documentation** with an \`id\` from that list to retrieve full component docs, props, usage examples, and stories.
1044
+ 3. Call **get-documentation-for-story** for extra docs on a story variant not covered by the component docs.
1045
+
1046
+ Only use properties explicitly documented or shown in example stories. Only reference IDs returned by these tools; never guess IDs.
1166
1047
 
1167
- //#endregion
1168
- export { COMPONENT_MANIFEST_PATH, ComponentManifestMap, DOCS_MANIFEST_PATH, DocsManifestMap, GET_STORY_TOOL_NAME, GET_TOOL_NAME, LIST_TOOL_NAME, RequiresOwnMcpError, instructions_default as STORYBOOK_MCP_INSTRUCTIONS, adaptCoreComponent, adaptCoreDoc, adaptCoreStories, addGetDocumentationTool, addGetStoryDocumentationTool, addListAllDocumentationTool, createStorybookMcpHandler, getDocumentationToolMetadata, getListAllDocumentationToolMetadata, getMultiSourceManifests, getStoryDocumentationToolMetadata, resolveComponentEntry, resolveComponentStories, resolveDoc };
1048
+ ## Multi-Source Requests
1049
+
1050
+ - With multiple sources configured, **list-all-documentation** returns entries from every source; pass \`storybookId\` to **get-documentation** to scope one.
1051
+ `;
1052
+
1053
+ // src/index.ts
1054
+ var createStorybookMcpHandler = async (options = {}) => {
1055
+ let { onSessionInitialize, ...defaultContext } = options, adapter = new ValibotJsonSchemaAdapter(), server = new McpServer(
1056
+ {
1057
+ name: package_default.name,
1058
+ version: package_default.version,
1059
+ description: package_default.description
1060
+ },
1061
+ {
1062
+ adapter,
1063
+ instructions: instructions_default,
1064
+ capabilities: {
1065
+ tools: { listChanged: !0 }
1066
+ }
1067
+ }
1068
+ ).withContext();
1069
+ onSessionInitialize && server.on("initialize", onSessionInitialize), await addListAllDocumentationTool(server), await addGetStoryDocumentationTool(server), await addGetDocumentationTool(server);
1070
+ let transport = new HttpTransport(server, { path: null });
1071
+ return (async (req, context) => await transport.respond(req, {
1072
+ ...defaultContext,
1073
+ ...context,
1074
+ request: req
1075
+ }));
1076
+ };
1077
+ export {
1078
+ COMPONENT_MANIFEST_PATH,
1079
+ ComponentManifestMap,
1080
+ DOCS_MANIFEST_PATH,
1081
+ DocsManifestMap,
1082
+ GET_STORY_TOOL_NAME,
1083
+ GET_TOOL_NAME,
1084
+ LIST_TOOL_NAME,
1085
+ RequiresOwnMcpError,
1086
+ instructions_default as STORYBOOK_MCP_INSTRUCTIONS,
1087
+ adaptCoreComponent,
1088
+ adaptCoreDoc,
1089
+ adaptCoreStories,
1090
+ addGetDocumentationTool,
1091
+ addGetStoryDocumentationTool,
1092
+ addListAllDocumentationTool,
1093
+ createStorybookMcpHandler,
1094
+ getDocumentationToolMetadata,
1095
+ getListAllDocumentationToolMetadata,
1096
+ getMultiSourceManifests,
1097
+ getStoryDocumentationToolMetadata,
1098
+ resolveComponentEntry,
1099
+ resolveComponentStories,
1100
+ resolveDoc
1101
+ };