|
| 1 | +import { createStorybookMcpHandler } from '@storybook/mcp'; |
| 2 | +import fs from 'node:fs/promises'; |
| 3 | +import { basename, resolve } from 'node:path'; |
| 4 | + |
| 5 | +export function createMcpHandler(manifestsPath: string) { |
| 6 | + return createStorybookMcpHandler({ |
| 7 | + manifestProvider: async (_request: Request | undefined, path: string) => { |
| 8 | + const fileName = basename(path); |
| 9 | + |
| 10 | + if (manifestsPath.startsWith('http://') || manifestsPath.startsWith('https://')) { |
| 11 | + const response = await fetch(`${manifestsPath}/${fileName}`); |
| 12 | + if (!response.ok) { |
| 13 | + throw new Error( |
| 14 | + `Failed to fetch manifest from ${manifestsPath}/${fileName}: ${response.status} ${response.statusText}`, |
| 15 | + ); |
| 16 | + } |
| 17 | + return await response.text(); |
| 18 | + } |
| 19 | + |
| 20 | + return await fs.readFile(resolve(manifestsPath, fileName), 'utf-8'); |
| 21 | + }, |
| 22 | + }); |
| 23 | +} |
| 24 | + |
| 25 | +// when running node ./server.ts |
| 26 | +if (import.meta.main) { |
| 27 | + const [{ serve }, { parseArgs }] = await Promise.all([import('srvx'), import('node:util')]); |
| 28 | + |
| 29 | + const args = parseArgs({ |
| 30 | + options: { |
| 31 | + port: { |
| 32 | + type: 'string', |
| 33 | + default: '13316', |
| 34 | + }, |
| 35 | + manifestsPath: { |
| 36 | + type: 'string', |
| 37 | + default: './manifests', |
| 38 | + }, |
| 39 | + }, |
| 40 | + }); |
| 41 | + |
| 42 | + const storybookMcpHandler = await createMcpHandler(args.values.manifestsPath); |
| 43 | + |
| 44 | + serve({ |
| 45 | + port: Number(args.values.port), |
| 46 | + async fetch(request: Request) { |
| 47 | + if (new URL(request.url).pathname !== '/mcp') { |
| 48 | + return new Response('Not found', { status: 404 }); |
| 49 | + } |
| 50 | + |
| 51 | + return await storybookMcpHandler(request); |
| 52 | + }, |
| 53 | + }); |
| 54 | + |
| 55 | + console.log(`@storybook/mcp example server listening on http://localhost:${port}/mcp`); |
| 56 | +} |
0 commit comments