返回 slidev
server.ts
根目录 / packages / slidev / node / mcp / server.ts
1 import type { Awaitable } from '@antfu/utils'
2 import type { LoadedSlidevData } from '@slidev/parser/fs'
3 import type { SlideInfo, SlidevConfig } from '@slidev/types'
4 import { McpServer } from '@modelcontextprotocol/server'
5 import { z } from 'zod'
6 import { applySlidePatch, insertSlide, moveSlide, removeSlide, resolveSlide } from './operations'
7
8 export type SlidevMcpData = LoadedSlidevData & { config?: SlidevConfig }
9
10 export interface SlidevMcpNav {
11 /** Current position of the live presentation */
12 getState: () => { page: number, clicks: number }
13 /** Navigate all connected clients of the live presentation */
14 go: (page: number, clicks: number) => void
15 }
16
17 export interface SlidevMcpContext {
18 /** Slidev version */
19 version: string
20 /** Absolute path of the entry markdown file */
21 entry: string
22 /** Get the up-to-date slides data */
23 getData: () => Awaitable<SlidevMcpData>
24 /** URL of the running dev server, if any */
25 getServerUrl?: () => string | undefined
26 /** Live presentation navigation (only available with a running dev server) */
27 nav?: SlidevMcpNav
28 }
29
30 function result(data: any) {
31 return {
32 content: [
33 {
34 type: 'text' as const,
35 text: typeof data === 'string'
36 ? data
37 : JSON.stringify(data, null, 2),
38 },
39 ],
40 }
41 }
42
43 function slideSummary(slide: SlideInfo) {
44 return {
45 no: slide.index + 1,
46 title: slide.title ?? null,
47 ...slide.frontmatter.layout
48 ? { layout: slide.frontmatter.layout }
49 : {},
50 file: slide.source.filepath,
51 hasNote: !!slide.source.note,
52 ...slide.importChain?.length
53 ? { importedBySrcDirective: true }
54 : {},
55 }
56 }
57
58 const noSchema = z.number().int().min(1).describe('Slide number (1-based, as displayed in the presentation)')
59 const frontmatterSchema = z
60 .record(z.string(), z.any())
61 .optional()
62 .describe('Slide frontmatter (YAML headmatter of the slide) as an object, e.g. { "layout": "two-cols" }')
63
64 /**
65 * Create the Slidev MCP server exposing tools for agents to inspect, edit,
66 * and (with a running dev server) navigate a slides deck.
67 *
68 * The same tool set is served over the dev server HTTP endpoint (`/__mcp`)
69 * and the `slidev mcp` stdio command.
70 */
71 export function createSlidevMcpServer(ctx: SlidevMcpContext): McpServer {
72 const server = new McpServer(
73 {
74 name: 'slidev',
75 version: ctx.version,
76 },
77 {
78 instructions: [
79 'Tools for working with a Slidev (https://sli.dev) slides deck.',
80 'A deck is a Markdown file where slides are separated by `---`; each slide can have YAML frontmatter, Markdown/Vue content, and a speaker note (trailing HTML comment).',
81 'Slides are addressed by their rendered 1-based number, matching the slide numbers shown in the presentation.',
82 'After editing tools run, a running dev server hot-reloads the presentation automatically.',
83 ].join('\n'),
84 },
85 )
86
87 server.registerTool(
88 'slidev-get-info',
89 {
90 title: 'Get deck info',
91 description: 'Get an overview of the Slidev deck: entry file, title, slide count, markdown files, and (when a dev server is running) the server URL and current position of the live presentation.',
92 annotations: { readOnlyHint: true },
93 },
94 async () => {
95 const data = await ctx.getData()
96 const nav = ctx.nav?.getState()
97 return result({
98 slidevVersion: ctx.version,
99 entry: ctx.entry,
100 title: data.headmatter.title ?? data.slides[0]?.title ?? null,
101 theme: data.config?.theme ?? data.headmatter.theme ?? null,
102 totalSlides: data.slides.length,
103 markdownFiles: Object.keys(data.markdownFiles),
104 ...ctx.getServerUrl?.()
105 ? {
106 server: {
107 url: ctx.getServerUrl(),
108 // page 0 means no client has connected yet
109 currentPage: nav?.page || null,
110 currentClicks: nav?.page ? nav.clicks : null,
111 },
112 }
113 : {},
114 })
115 },
116 )
117
118 server.registerTool(
119 'slidev-list-slides',
120 {
121 title: 'List slides',
122 description: 'List all slides of the deck with their number, title, layout, and source file. Slides hidden with `hide`/`disabled` frontmatter are not included.',
123 annotations: { readOnlyHint: true },
124 },
125 async () => {
126 const data = await ctx.getData()
127 return result(data.slides.map(slideSummary))
128 },
129 )
130
131 server.registerTool(
132 'slidev-get-slide',
133 {
134 title: 'Get slide',
135 description: 'Get the full source of one slide: frontmatter, Markdown content, and speaker note.',
136 inputSchema: z.object({ no: noSchema }),
137 annotations: { readOnlyHint: true },
138 },
139 async ({ no }) => {
140 const data = await ctx.getData()
141 const slide = resolveSlide(data, no)
142 return result({
143 ...slideSummary(slide),
144 frontmatter: slide.source.frontmatter,
145 content: slide.source.content.trim(),
146 note: slide.source.note ?? null,
147 ...slide.importChain?.length
148 ? {
149 importedBy: slide.importChain.map(s => `${s.filepath}#${s.index + 1}`),
150 }
151 : {},
152 })
153 },
154 )
155
156 server.registerTool(
157 'slidev-update-slide',
158 {
159 title: 'Update slide',
160 description: 'Update the content, speaker note, and/or frontmatter of a slide. Only the provided fields are changed. Pass an empty string to clear the content or note. In `frontmatter`, only the given keys are patched; pass `null` as a value to delete that key.',
161 inputSchema: z.object({
162 no: noSchema,
163 content: z.string().optional().describe('New Markdown content of the slide (without frontmatter and note)'),
164 note: z.string().optional().describe('New speaker note (Markdown, stored as a trailing HTML comment)'),
165 frontmatter: frontmatterSchema,
166 }),
167 },
168 async ({ no, content, note, frontmatter }) => {
169 if (content == null && note == null && frontmatter == null)
170 throw new Error('Nothing to update: provide at least one of `content`, `note`, or `frontmatter`.')
171 const data = await ctx.getData()
172 const { slide } = await applySlidePatch(data, no, { content, note, frontmatter })
173 return result(`Updated slide ${no} in ${slide.source.filepath}.`)
174 },
175 )
176
177 server.registerTool(
178 'slidev-insert-slide',
179 {
180 title: 'Insert slide',
181 description: 'Insert a new slide after an existing slide (into the same markdown file). To add a slide at the very end, pass the last slide number.',
182 inputSchema: z.object({
183 after: z.number().int().min(1).describe('Slide number (1-based) after which the new slide is inserted'),
184 content: z.string().describe('Markdown content of the new slide'),
185 frontmatter: frontmatterSchema,
186 note: z.string().optional().describe('Speaker note of the new slide'),
187 }),
188 },
189 async ({ after, content, frontmatter, note }) => {
190 const data = await ctx.getData()
191 const { filepath } = await insertSlide(data, { after, content, frontmatter, note })
192 return result(`Inserted a new slide after slide ${after} in ${filepath}. Slide numbers after it have shifted; list the slides again if needed.`)
193 },
194 )
195
196 server.registerTool(
197 'slidev-remove-slide',
198 {
199 title: 'Remove slide',
200 description: 'Remove a slide from the deck (deletes it from its source markdown file).',
201 inputSchema: z.object({ no: noSchema }),
202 annotations: { destructiveHint: true },
203 },
204 async ({ no }) => {
205 const data = await ctx.getData()
206 const { removed, filepath } = await removeSlide(data, no)
207 return result(`Removed slide ${no}${removed.title
208 ? ` ("${removed.title}")`
209 : ''} from ${filepath}. Slide numbers after it have shifted; list the slides again if needed.`)
210 },
211 )
212
213 server.registerTool(
214 'slidev-move-slide',
215 {
216 title: 'Move slide',
217 description: 'Move a slide before or after another slide to reorder the deck. Both slides must be in the same markdown file. To swap two adjacent slides, move one after the other.',
218 inputSchema: z.object({
219 from: z.number().int().min(1).describe('Slide number (1-based) of the slide to move'),
220 before: z.number().int().min(1).optional().describe('Move the slide right before this slide number'),
221 after: z.number().int().min(1).optional().describe('Move the slide right after this slide number'),
222 }),
223 },
224 async ({ from, before, after }) => {
225 const data = await ctx.getData()
226 const { filepath } = await moveSlide(data, { from, before, after })
227 return result(`Moved slide ${from} ${before != null
228 ? `before slide ${before}`
229 : `after slide ${after}`} in ${filepath}. Slide numbers have shifted; list the slides again if needed.`)
230 },
231 )
232
233 if (ctx.nav) {
234 const nav = ctx.nav
235 server.registerTool(
236 'slidev-goto-slide',
237 {
238 title: 'Go to slide',
239 description: 'Navigate the live presentation (all connected browsers) to a given slide, e.g. to visually verify a slide after editing it.',
240 inputSchema: z.object({
241 no: noSchema,
242 clicks: z.number().int().min(0).optional().describe('Click animation step to reveal (defaults to 0)'),
243 }),
244 annotations: { idempotentHint: true },
245 },
246 async ({ no, clicks }) => {
247 const data = await ctx.getData()
248 resolveSlide(data, no) // range check
249 nav.go(no, clicks ?? 0)
250 return result(`Navigated the presentation to slide ${no}${clicks
251 ? ` (click ${clicks})`
252 : ''}.`)
253 },
254 )
255 }
256
257 return server
258 }
259
259 lines TYPESCRIPT