slidemind 0.1.5 → 0.1.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,810 +0,0 @@
1
- // Slidemind MCP server (stdio).
2
- //
3
- // Exposes the deck-authoring + push-to-PowerPoint surface to a local agent
4
- // (Claude Code, Codex, opencode) as native MCP tools so the agent can
5
- // enumerate open PowerPoint windows and push a freshly built deck without
6
- // leaving an on-disk .pptx behind.
7
- //
8
- // Tools:
9
- // slidemind_list_open_presentations
10
- // Lists PowerPoint windows registered with the local bridge, including
11
- // retained entries whose task-pane socket is temporarily disconnected.
12
- //
13
- // slidemind_push_deck
14
- // Renders a deck server-side via the add-in and pushes its slides into one
15
- // open PowerPoint window.
16
- //
17
- // slidemind_list_engines
18
- // Lists the live engine catalog (image + slide) for the active corporate
19
- // design, filterable by type/subtype.
20
- //
21
- // slidemind_search_engine
22
- // Searches the active corporate design's engine (image/icon OR slide,
23
- // content/visual intent) over the bridge.
24
- //
25
- // slidemind_view_slide
26
- // Returns a preview image of a chosen slide search result.
27
- //
28
- // slidemind_insert_slide
29
- // Inserts chosen slide search results live into an open PowerPoint window.
30
- //
31
- // slidemind_add_slide_to_deck
32
- // Folds chosen slide search results into a deck as native one-slide .pptx
33
- // under slides/ (survive re-render, spliced into play order).
34
- //
35
- // slidemind_download_result
36
- // Fetches a chosen image search result's bytes and writes them into a deck's
37
- // assets/ folder for the slide JSX to reference.
38
- //
39
- // Everything routes through the add-in's cloud relay at
40
- // `<backendURL>/api/cli/*` with the Bearer session token established by
41
- // `slidemind pair`. See src/bridge/client.mjs.
42
-
43
- import fs from "node:fs";
44
- import path from "node:path";
45
- import { fileURLToPath, pathToFileURL } from "node:url";
46
-
47
- import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
48
- import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
49
- import { z } from "zod";
50
-
51
- import { describeRecolor } from "./recolor.mjs";
52
-
53
- const __filename = fileURLToPath(import.meta.url);
54
- const __dirname = path.dirname(__filename);
55
- const PACKAGE_ROOT = path.resolve(__dirname, "..", "..");
56
- const SRC_DIR = path.join(PACKAGE_ROOT, "src");
57
-
58
- async function loadBridgeClient() {
59
- return import(pathToFileURL(path.join(SRC_DIR, "bridge", "client.mjs")).href);
60
- }
61
-
62
- async function loadBuildAndPush() {
63
- return import(
64
- pathToFileURL(path.join(SRC_DIR, "bridge", "build-and-push.mjs")).href
65
- );
66
- }
67
-
68
- async function loadBundle() {
69
- return import(pathToFileURL(path.join(SRC_DIR, "bridge", "bundle.mjs")).href);
70
- }
71
-
72
- async function loadReusedSlides() {
73
- return import(pathToFileURL(path.join(SRC_DIR, "lib", "reused-slides.mjs")).href);
74
- }
75
-
76
- function textResult(value) {
77
- const text =
78
- typeof value === "string" ? value : JSON.stringify(value, null, 2);
79
- return { content: [{ type: "text", text }] };
80
- }
81
-
82
- function errorResult(err) {
83
- let text = err && err.message ? err.message : String(err);
84
- const code = err && err.code;
85
- // Known transient states are recoverable without rebuilding anything — tell
86
- // the agent exactly how to resume if the bridge timed out waiting for a true
87
- // task-pane reconnect. Normal backgrounded PowerPoint should not reach this.
88
- if (code === "pane_suspended") {
89
- text +=
90
- "\n\nRecoverable: the CLI already waited ~2 minutes for the task pane to " +
91
- "reconnect. The render itself never needs the pane (it runs server-side) — " +
92
- "only pushing/engine ops do. Ask the user to click the slidemind task pane " +
93
- "once, then retry this same call; do NOT ask them to keep PowerPoint " +
94
- "foregrounded beyond that.";
95
- } else if (code === "engine_auth_expired") {
96
- text +=
97
- "\n\nRecoverable: ask the user to click the slidemind task pane for ~1s so " +
98
- "it refreshes its sign-in, then retry this call.";
99
- }
100
- return { content: [{ type: "text", text }], isError: true };
101
- }
102
-
103
- // Parse a `data:<mime>;base64,<data>` URI into an MCP image content block so a
104
- // vision-capable agent can "see" the result grid, exactly as the in-app design
105
- // agent does.
106
- function imageContentFromDataUri(dataUri) {
107
- const m = /^data:([^;]+);base64,(.+)$/.exec(dataUri || "");
108
- if (!m) return null;
109
- return { type: "image", data: m[2], mimeType: m[1] };
110
- }
111
-
112
- const MIME_EXT = {
113
- "image/svg+xml": "svg",
114
- "image/png": "png",
115
- "image/jpeg": "jpg",
116
- "image/jpg": "jpg",
117
- "image/webp": "webp",
118
- "image/gif": "gif",
119
- };
120
-
121
- // Derive a usable file extension from an engine result's MIME type. The brand
122
- // engine can return any image Content-Type (image/x-icon, image/bmp,
123
- // image/avif, …) and may carry a `;charset=` suffix, so an exact-match table
124
- // alone would fall back to a useless `.bin` that won't render in an <img>.
125
- // Strip params, then fall back to the MIME subtype itself for any `image/*`.
126
- function extFromMime(mimeType) {
127
- const mt = String(mimeType || "")
128
- .split(";")[0]
129
- .trim()
130
- .toLowerCase();
131
- if (MIME_EXT[mt]) return MIME_EXT[mt];
132
- const m = /^image\/(?:x-)?([a-z0-9.+-]+)$/.exec(mt);
133
- if (m) {
134
- const sub = m[1].replace(/\+xml$/, "");
135
- if (sub === "svg") return "svg";
136
- if (sub === "jpeg") return "jpg";
137
- if (sub === "icon") return "ico";
138
- return sub; // png, gif, webp, bmp, avif, tiff, heic, …
139
- }
140
- return "bin";
141
- }
142
-
143
- const server = new McpServer(
144
- { name: "slidemind", version: "0.1.0" },
145
- {
146
- instructions:
147
- "Build on-brand slide decks under <cwd>/decks/<slug>/slides/*.jsx for the " +
148
- "presentation's active corporate design, then render + push them into a running " +
149
- "PowerPoint window via the slidemind add-in. The corporate design (tokens, layouts, " +
150
- "brand rules) and the .pptx render both live in the add-in — an open PowerPoint host " +
151
- "with an active corporate design is required, and all brand rules come from that " +
152
- "design's bundle (design.md), never hardcoded here. " +
153
- "Always call slidemind_list_open_presentations first to learn which presentation_id to target. " +
154
- "The CLI may be paired with several add-in environments (local/dev/prod) at once; the list spans " +
155
- "all of them and each entry is tagged with its env, and routing to the right backend is automatic — " +
156
- "just pass the presentation_id back. " +
157
- "Renders run server-side and never need the task pane awake (a suspended/backgrounded PowerPoint " +
158
- "is fine); only pushing slides and engine search/download touch the pane, and those wait for it " +
159
- "and retry automatically. " +
160
- "For brand imagery, slidemind_search_engine then slidemind_download_result.",
161
- },
162
- );
163
-
164
- server.registerTool(
165
- "slidemind_list_open_presentations",
166
- {
167
- title: "List open PowerPoint windows",
168
- description:
169
- "List PowerPoint windows registered with the slidemind local bridge, including retained entries whose task-pane socket is temporarily disconnected. " +
170
- "Spans every paired add-in environment (local/dev/prod); each entry carries an `env` tag and a stable presId — pass the presId as `presentation_id` to the other tools and routing to that env is automatic. " +
171
- "If the list is empty the user has no PowerPoint open with the add-in loaded.",
172
- inputSchema: {},
173
- },
174
- async () => {
175
- try {
176
- const { listOpenPresentations, toPublicPresentation } =
177
- await loadBridgeClient();
178
- const list = await listOpenPresentations();
179
- return textResult({ presentations: list.map(toPublicPresentation) });
180
- } catch (err) {
181
- return errorResult(err);
182
- }
183
- },
184
- );
185
-
186
- server.registerTool(
187
- "slidemind_push_deck",
188
- {
189
- title: "Push a built deck into PowerPoint",
190
- description:
191
- "Build the deck at deck_path and push the resulting slides into the PowerPoint window identified by " +
192
- "presentation_id (from slidemind_list_open_presentations). By default slides are appended at the end. " +
193
- "Use insert_at to place after a specific 0-based slide index. Use replace=true to delete existing slides " +
194
- "first (destructive). slide_ids restricts the push to a subset of the built deck's slide ids and is for " +
195
- "the append/insert path only — it CANNOT be combined with replace=true (that combination is rejected, " +
196
- "because the bridge would otherwise wipe the whole presentation). " +
197
- "The render itself never needs the task pane awake; if the pane is suspended at push time the CLI waits " +
198
- "up to ~2 min for it (the user just clicks the pane once) and retries safely. If the result carries " +
199
- "paneSuspended=true, the rendered .pptx was saved to fallbackFile instead — nothing was lost.",
200
- inputSchema: {
201
- deck_path: z
202
- .string()
203
- .describe("Path to the deck folder (must contain slides/). Absolute or relative to CWD."),
204
- presentation_id: z
205
- .string()
206
- .describe("presId from slidemind_list_open_presentations. Required even when only one window is open."),
207
- insert_at: z
208
- .number()
209
- .int()
210
- .nonnegative()
211
- .nullable()
212
- .optional()
213
- .describe("0-based slide index to insert after. Omit or null = append at end. Ignored when replace=true."),
214
- replace: z
215
- .boolean()
216
- .optional()
217
- .describe("If true, delete all existing slides before inserting. Destructive."),
218
- slide_ids: z
219
- .array(z.string())
220
- .nullable()
221
- .optional()
222
- .describe("Optional subset of source slide ids to push. Omit or null = all slides in the built deck."),
223
- },
224
- },
225
- async ({ deck_path, presentation_id, insert_at, replace, slide_ids }, extra) => {
226
- try {
227
- const { buildAndPush } = await loadBuildAndPush();
228
- // Relay per-slide render progress as MCP progress notifications when the
229
- // client asked for them (sent a progressToken). Fire-and-forget — a
230
- // dropped notification must never fail the push.
231
- const progressToken = extra?._meta?.progressToken;
232
- const onProgress =
233
- progressToken === undefined || typeof extra?.sendNotification !== "function"
234
- ? null
235
- : (p) => {
236
- const message =
237
- p.state === "queued"
238
- ? "render queued behind another render"
239
- : p.state === "restarted"
240
- ? "render restarted (backend replica was replaced)"
241
- : p.stage === "assembling"
242
- ? "assembling deck"
243
- : typeof p.total === "number"
244
- ? `rendering slide ${Math.min((p.done ?? 0) + 1, p.total)}/${p.total}`
245
- : null;
246
- void extra
247
- .sendNotification({
248
- method: "notifications/progress",
249
- params: {
250
- progressToken,
251
- progress: typeof p.done === "number" ? p.done : 0,
252
- ...(typeof p.total === "number" ? { total: p.total } : {}),
253
- ...(message ? { message } : {}),
254
- },
255
- })
256
- .catch(() => {});
257
- };
258
- const result = await buildAndPush({
259
- deckDir: path.resolve(process.cwd(), deck_path),
260
- presentationId: presentation_id,
261
- insertAt: insert_at ?? null,
262
- replace: replace === true,
263
- slideIds: slide_ids ?? null,
264
- onProgress,
265
- });
266
- return textResult(result);
267
- } catch (err) {
268
- return errorResult(err);
269
- }
270
- },
271
- );
272
-
273
- server.registerTool(
274
- "slidemind_search_engine",
275
- {
276
- title: "Search an engine for imagery or slides",
277
- description:
278
- "Search the active corporate design's engine over the bridge — image/icon engines OR slide engines. " +
279
- "Uses the add-in's server-side bridge, so it returns the SAME results the in-app design agent sees. " +
280
- "Returns a searchId and a numbered set of results. For image engines (and visual slide search) you also get a grid image you can view; " +
281
- "for content slide search each result carries the extracted slide `text` plus metadata (slideNumber, presentationTitle, score). " +
282
- "intent selects the slide search mode: 'content' (text is the signal) or 'visual' (the slide image is the signal); image engines are visual-only. " +
283
- "Next: reuse an image with slidemind_download_result, view a slide with slidemind_view_slide, insert a slide live with slidemind_insert_slide, or fold a slide into a deck with slidemind_add_slide_to_deck. " +
284
- "engine_id is optional for image search — omit it to use the corporate design's first image engine; slide search requires engine_id (see slidemind_list_engines). " +
285
- "presentation_id is OPTIONAL: the engine is not bound to a window, so omit it and the search attaches to any connected window automatically. The window it used is echoed back as `presentation_id` in the result — pass THAT to the follow-up tools (view/insert/add), since the searchId is bound to it.",
286
- inputSchema: {
287
- presentation_id: z
288
- .string()
289
- .nullable()
290
- .optional()
291
- .describe("Optional. Omit to attach to any connected window automatically (the engine isn't window-bound). The window used is returned as `presentation_id`; thread it to slidemind_view_slide / _insert_slide / _add_slide_to_deck."),
292
- query: z
293
- .string()
294
- .describe("Concept query, e.g. 'shield', 'handshake', 'revenue bridge'."),
295
- engine_id: z
296
- .string()
297
- .nullable()
298
- .optional()
299
- .describe("Engine id from slidemind_list_engines. Omit/null = first image engine (image search only)."),
300
- intent: z
301
- .enum(["auto", "content", "visual"])
302
- .nullable()
303
- .optional()
304
- .describe("Slide search mode: 'content' (text), 'visual' (image), or 'auto'. Image engines ignore this."),
305
- top: z
306
- .number()
307
- .int()
308
- .positive()
309
- .nullable()
310
- .optional()
311
- .describe("Max number of results to return."),
312
- },
313
- },
314
- async ({ presentation_id, query, engine_id, intent, top }) => {
315
- try {
316
- const client = await loadBridgeClient();
317
- // All engine tools hard-require an open host (the truth lives in the
318
- // add-in); surface the actionable "open PowerPoint…" message up front.
319
- const registry = await client.requireHost();
320
- // The engine is per-user, not window-bound: attach to any connected window
321
- // when the caller didn't pin one. The chosen presId is echoed back so the
322
- // agent threads it to the follow-up tools (the searchId is bound to it).
323
- const entry = client.pickAnyPresentationEntry(registry, presentation_id ?? null);
324
- const presId = entry.presId;
325
- const backendURL = entry.backendURL ?? null;
326
- let engineId = engine_id ?? null;
327
- const slideIntent = intent === "content" || intent === "visual";
328
- // Forward the engine subtype on the wire whenever it's derivable (belt-
329
- // and-suspenders against an add-in regression where a missing subtype no
330
- // longer defaulted to "image"): an explicit slide intent targets a slide
331
- // engine; the pickImageEngine default branch is an image engine. When the
332
- // subtype is unknown we omit it and let the add-in resolve it.
333
- let subtype = slideIntent ? "slide" : null;
334
- if (!engineId) {
335
- if (slideIntent) {
336
- return errorResult(
337
- new Error(
338
- "slide search requires engine_id. Call slidemind_list_engines (type='search', subtype='slide') to find one.",
339
- ),
340
- );
341
- }
342
- const { materializeBundle, readEnginesFromDir, pickImageEngine } =
343
- await loadBundle();
344
- const mat = await materializeBundle(presId, { backendURL });
345
- const pick = pickImageEngine(readEnginesFromDir(mat.dir));
346
- if (!pick) {
347
- return errorResult(
348
- new Error(
349
- "This corporate design has no brand engines to search. Pass engine_id or ask the add-in owner to wire an image engine.",
350
- ),
351
- );
352
- }
353
- engineId = pick.id;
354
- subtype = "image";
355
- }
356
- // Window-agnostic: tries the picked pane, then fails over to any other
357
- // live window on the same backend if it's suspended/frozen. res.presId is
358
- // the window that actually answered — echo THAT back (the searchId is
359
- // bound to it) so follow-up view/insert/add target the right pane.
360
- const res = await client.engineSearchAnyPane({
361
- registry,
362
- explicitPresId: presentation_id ?? null,
363
- engineId,
364
- query,
365
- subtype,
366
- intent: intent ?? null,
367
- top: top ?? null,
368
- });
369
- const ranPresId = res?.presId ?? presId;
370
- const content = [];
371
- const grid = imageContentFromDataUri(res?.gridDataUri);
372
- if (grid) content.push(grid);
373
- // Prefer the new `results` array (image + slide engines); fall back to the
374
- // legacy `thumbnails` shape older add-ins still return for image engines.
375
- const rawResults = Array.isArray(res?.results)
376
- ? res.results
377
- : (res?.thumbnails ?? []).map((t, i) => ({ selection: i + 1, title: t.title }));
378
- const results = rawResults.map((r, i) => ({
379
- selection: r.selection ?? i + 1,
380
- title: r.title ?? null,
381
- ...(typeof r.score === "number" ? { score: r.score } : {}),
382
- ...(r.kind ? { kind: r.kind } : {}),
383
- ...(typeof r.text === "string" ? { text: r.text } : {}),
384
- ...(typeof r.slideNumber === "number" ? { slideNumber: r.slideNumber } : {}),
385
- ...(r.presentationTitle ? { presentationTitle: r.presentationTitle } : {}),
386
- }));
387
- content.push({
388
- type: "text",
389
- text: JSON.stringify(
390
- {
391
- ok: res?.ok ?? false,
392
- // The window the search ran on (auto-attached when the caller didn't
393
- // pin one; may have failed over from the picked pane). The searchId
394
- // is bound to it — pass this presentation_id to slidemind_view_slide
395
- // / _insert_slide / _add_slide_to_deck.
396
- presentation_id: ranPresId,
397
- engineId,
398
- subtype: res?.subtype ?? null,
399
- intent: res?.intent ?? null,
400
- searchId: res?.searchId ?? null,
401
- resultCount: res?.resultCount ?? results.length,
402
- results,
403
- },
404
- null,
405
- 2,
406
- ),
407
- });
408
- return { content };
409
- } catch (err) {
410
- return errorResult(err);
411
- }
412
- },
413
- );
414
-
415
- server.registerTool(
416
- "slidemind_list_engines",
417
- {
418
- title: "List available engines",
419
- description:
420
- "List the LIVE engine catalog for the active corporate design over the bridge (not just the bundle's curated set). " +
421
- "Spans every paired add-in environment; each engine carries an `env` tag. " +
422
- "Filter by `type` (collection|search) and/or `subtype` (image|slide|template|content). " +
423
- "Use the returned engine id with slidemind_search_engine (slide search requires one).",
424
- inputSchema: {
425
- presentation_id: z
426
- .string()
427
- .nullable()
428
- .optional()
429
- .describe("Optional presId — engines are backend-scoped, so this is informational only."),
430
- type: z
431
- .enum(["collection", "search"])
432
- .nullable()
433
- .optional()
434
- .describe("Filter by engine type."),
435
- subtype: z
436
- .enum(["image", "slide", "template", "content"])
437
- .nullable()
438
- .optional()
439
- .describe("Filter by engine subtype."),
440
- },
441
- },
442
- async ({ type, subtype }) => {
443
- try {
444
- const client = await loadBridgeClient();
445
- const { engines } = await client.listEngines({
446
- type: type ?? null,
447
- subtype: subtype ?? null,
448
- });
449
- return textResult({ engines });
450
- } catch (err) {
451
- return errorResult(err);
452
- }
453
- },
454
- );
455
-
456
- server.registerTool(
457
- "slidemind_view_slide",
458
- {
459
- title: "View a slide search result",
460
- description:
461
- "Fetch a chosen slide search result's preview image so you can see it before reusing it. " +
462
- "Pass the searchId from slidemind_search_engine and the 1-based selection number. " +
463
- "Returns an image content block. Then reuse with slidemind_insert_slide (live) or slidemind_add_slide_to_deck (into a deck).",
464
- inputSchema: {
465
- presentation_id: z
466
- .string()
467
- .describe("The presentation_id returned by slidemind_search_engine (the window the search ran on). The searchId is bound to that window, so this must be exactly that presentation_id."),
468
- search_id: z
469
- .number()
470
- .int()
471
- .describe("searchId returned by slidemind_search_engine."),
472
- selection: z
473
- .number()
474
- .int()
475
- .positive()
476
- .describe("1-based result number to view."),
477
- },
478
- },
479
- async ({ presentation_id, search_id, selection }) => {
480
- try {
481
- const client = await loadBridgeClient();
482
- await client.requireHost();
483
- const res = await client.viewSlide({
484
- presId: presentation_id,
485
- searchId: search_id,
486
- selection,
487
- });
488
- if (!res?.ok || !res.dataUri) {
489
- return errorResult(new Error(res?.error ?? "slide view returned no image"));
490
- }
491
- const image = imageContentFromDataUri(res.dataUri);
492
- if (!image) {
493
- return errorResult(new Error("slide view returned an unparseable data URI"));
494
- }
495
- return { content: [image] };
496
- } catch (err) {
497
- return errorResult(err);
498
- }
499
- },
500
- );
501
-
502
- server.registerTool(
503
- "slidemind_insert_slide",
504
- {
505
- title: "Insert reused slide(s) live into PowerPoint",
506
- description:
507
- "Insert one or more chosen slide search results directly into an open PowerPoint window (the 'reuse → insert live' path). " +
508
- "Pass the searchId from slidemind_search_engine and the 1-based selection number(s). " +
509
- "By default the slides are appended; use `at` to insert after a specific 0-based slide index. " +
510
- "To instead fold reused slides into a deck you are authoring, use slidemind_add_slide_to_deck.",
511
- inputSchema: {
512
- presentation_id: z
513
- .string()
514
- .describe("The presentation_id returned by slidemind_search_engine (the window the search ran on). The searchId is bound to that window, so this must be exactly that presentation_id."),
515
- search_id: z
516
- .number()
517
- .int()
518
- .describe("searchId returned by slidemind_search_engine."),
519
- selections: z
520
- .array(z.number().int().positive())
521
- .min(1)
522
- .describe("1-based result number(s) to insert."),
523
- at: z
524
- .number()
525
- .int()
526
- .nonnegative()
527
- .nullable()
528
- .optional()
529
- .describe("0-based slide index to insert after. Omit or null = append at end."),
530
- },
531
- },
532
- async ({ presentation_id, search_id, selections, at }) => {
533
- try {
534
- const client = await loadBridgeClient();
535
- await client.requireHost();
536
- const res = await client.insertSlideLive({
537
- presId: presentation_id,
538
- searchId: search_id,
539
- selections,
540
- at: at ?? null,
541
- });
542
- if (!res?.ok) {
543
- return errorResult(new Error(res?.error ?? "insert slide failed"));
544
- }
545
- return textResult({
546
- ok: true,
547
- insertedCount: res.insertedCount ?? selections.length,
548
- insertedSlideIds: res.insertedSlideIds ?? [],
549
- });
550
- } catch (err) {
551
- return errorResult(err);
552
- }
553
- },
554
- );
555
-
556
- server.registerTool(
557
- "slidemind_add_slide_to_deck",
558
- {
559
- title: "Fold reused slide(s) into a deck",
560
- description:
561
- "Fold one or more chosen slide search results into a deck as native one-slide .pptx files under <deck>/slides/ (the 'reuse → fold into a deck' path). " +
562
- "These native slides survive re-render: every slidemind_push_deck / build-pptx re-includes them, spliced into play order by their numeric filename prefix alongside the deck's .jsx slides. " +
563
- "Pass the searchId from slidemind_search_engine and the 1-based selection number(s). " +
564
- "By default the slides are appended after the last numeric prefix; `at` sets the numeric prefix the first added slide takes. " +
565
- "To instead insert directly into an open window, use slidemind_insert_slide.",
566
- inputSchema: {
567
- presentation_id: z
568
- .string()
569
- .describe("The presentation_id returned by slidemind_search_engine (the window the search ran on). The searchId is bound to that window, so this must be exactly that presentation_id."),
570
- deck_path: z
571
- .string()
572
- .describe("Path to the deck folder (slides are written under <deck>/slides/). Absolute or relative to CWD."),
573
- search_id: z
574
- .number()
575
- .int()
576
- .describe("searchId returned by slidemind_search_engine."),
577
- selections: z
578
- .array(z.number().int().positive())
579
- .min(1)
580
- .describe("1-based result number(s) to fold into the deck."),
581
- at: z
582
- .number()
583
- .int()
584
- .nonnegative()
585
- .nullable()
586
- .optional()
587
- .describe("Numeric prefix the first added slide takes. Omit or null = append after the last existing prefix."),
588
- },
589
- },
590
- async ({ presentation_id, deck_path, search_id, selections, at }) => {
591
- try {
592
- const client = await loadBridgeClient();
593
- await client.requireHost();
594
- const deckDir = path.resolve(process.cwd(), deck_path);
595
- const slidesDir = path.join(deckDir, "slides");
596
- fs.mkdirSync(slidesDir, { recursive: true });
597
-
598
- // Extract each picked slide's bytes, then let the shared helper compute
599
- // the play-order filenames — the SAME prefix math the CLI's add-slide
600
- // uses (src/lib/reused-slides.mjs), so the two paths never diverge.
601
- const { reusedSlideTargets } = await loadReusedSlides();
602
- const extracted = [];
603
- for (const selection of selections) {
604
- const res = await client.extractSlide({
605
- presId: presentation_id,
606
- searchId: search_id,
607
- selection,
608
- });
609
- if (!res?.ok || !res.base64) {
610
- return errorResult(
611
- new Error(
612
- `add slide failed for selection ${selection}: ${res?.error ?? "no slide bytes returned"}`,
613
- ),
614
- );
615
- }
616
- extracted.push({ selection, slideId: res.slideId ?? null, base64: res.base64 });
617
- }
618
- const existing = fs
619
- .readdirSync(slidesDir)
620
- .filter((f) => f.endsWith(".jsx") || f.endsWith(".pptx"));
621
- const targets = reusedSlideTargets(existing, extracted, at);
622
- const written = extracted.map((slide, i) => {
623
- const { filename } = targets[i];
624
- const target = path.join(slidesDir, filename);
625
- fs.writeFileSync(target, Buffer.from(slide.base64, "base64"));
626
- return {
627
- selection: slide.selection,
628
- filename,
629
- reference: `./slides/${filename}`,
630
- path: target,
631
- };
632
- });
633
- return textResult({ ok: true, deckDir, written });
634
- } catch (err) {
635
- return errorResult(err);
636
- }
637
- },
638
- );
639
-
640
- // Fetch one chosen result over the bridge and write it into the deck's
641
- // assets/. Returns the written reference plus a `recolor` descriptor so the
642
- // agent never has to open the SVG to learn how it recolours. Throws on a failed
643
- // download so a batch can record a per-item error without aborting the rest.
644
- async function downloadOneResult({
645
- client,
646
- presId,
647
- searchId,
648
- assetsDir,
649
- selection,
650
- iconColor,
651
- }) {
652
- const res = await client.engineDownload({
653
- presId,
654
- searchId,
655
- selection,
656
- iconColor: iconColor ?? null,
657
- });
658
- if (!res?.ok) {
659
- throw new Error(res?.error ?? "download failed");
660
- }
661
- const ext = extFromMime(res.mimeType);
662
- const filename = `engine-${searchId}-${selection}.${ext}`;
663
- const target = path.join(assetsDir, filename);
664
- if (res.svgMarkup && ext === "svg") {
665
- // The (possibly recoloured) SVG markup is the canonical asset.
666
- fs.writeFileSync(target, res.svgMarkup, "utf8");
667
- } else if (typeof res.base64 === "string" && res.base64.length > 0) {
668
- fs.writeFileSync(target, Buffer.from(res.base64, "base64"));
669
- } else if (res.svgMarkup) {
670
- // SVG bytes arrived only as markup (mimeType lacked an svg hint).
671
- fs.writeFileSync(target, res.svgMarkup, "utf8");
672
- } else {
673
- throw new Error("engine result carried neither base64 bytes nor svgMarkup");
674
- }
675
- return {
676
- selection,
677
- path: target,
678
- reference: `./assets/${filename}`,
679
- mimeType: res.mimeType,
680
- recolor: describeRecolor(res.svgMarkup ?? null, res.mimeType, iconColor ?? null),
681
- };
682
- }
683
-
684
- server.registerTool(
685
- "slidemind_download_result",
686
- {
687
- title: "Download chosen engine result(s) into a deck",
688
- description:
689
- "Fetch the bytes of one or more results from a prior slidemind_search_engine call and write them into the deck's assets/ folder. " +
690
- "Reference each from slide JSX as <img src=\"./assets/<file>\">. " +
691
- "Each result carries a `recolor` descriptor ({ recolorable, mode, applied, note }) — so you NEVER need to open the SVG to learn how it recolours. " +
692
- "To colour an icon, pass icon_color (a hex you resolve from a corporate-design.css token): the bridge bakes it into the saved SVG, correct in BOTH the HTML preview and the .pptx render. " +
693
- "Download several icons (each in its own colour) in ONE call via `selections: [{ selection, icon_color? }, …]` — they download concurrently. Use `selection` for one, or `selections` for many (don't pass both).",
694
- inputSchema: {
695
- presentation_id: z
696
- .string()
697
- .describe("The presentation_id returned by slidemind_search_engine (the window the search ran on). The searchId is bound to that window, so this must be exactly that presentation_id."),
698
- deck_path: z
699
- .string()
700
- .describe("Path to the deck folder (assets are written under <deck>/assets/)."),
701
- search_id: z
702
- .number()
703
- .int()
704
- .describe("searchId returned by slidemind_search_engine."),
705
- selection: z
706
- .number()
707
- .int()
708
- .positive()
709
- .nullable()
710
- .optional()
711
- .describe("1-based result number to download (single). Omit when using `selections`."),
712
- icon_color: z
713
- .string()
714
- .nullable()
715
- .optional()
716
- .describe("Optional hex colour (e.g. '#0000FF') to bake into a single SVG result."),
717
- selections: z
718
- .array(
719
- z.object({
720
- selection: z
721
- .number()
722
- .int()
723
- .positive()
724
- .describe("1-based result number."),
725
- icon_color: z
726
- .string()
727
- .nullable()
728
- .optional()
729
- .describe("Optional hex colour to bake into this SVG."),
730
- }),
731
- )
732
- .nullable()
733
- .optional()
734
- .describe("Batch: several results to download concurrently, each in its own colour."),
735
- },
736
- },
737
- async ({ presentation_id, deck_path, search_id, selection, icon_color, selections }) => {
738
- try {
739
- const batch = Array.isArray(selections) && selections.length > 0;
740
- const jobs = batch
741
- ? selections.map((s) => ({
742
- selection: s.selection,
743
- iconColor: s.icon_color ?? null,
744
- }))
745
- : typeof selection === "number"
746
- ? [{ selection, iconColor: icon_color ?? null }]
747
- : [];
748
- if (jobs.length === 0) {
749
- return errorResult(
750
- new Error(
751
- "Provide `selection` (one result) or `selections` (a batch). Both are missing.",
752
- ),
753
- );
754
- }
755
-
756
- const client = await loadBridgeClient();
757
- await client.requireHost();
758
- const deckDir = path.resolve(process.cwd(), deck_path);
759
- const assetsDir = path.join(deckDir, "assets");
760
- fs.mkdirSync(assetsDir, { recursive: true });
761
-
762
- // Concurrent — each download is its own bridge round-trip, so issuing them
763
- // in parallel turns N serial waits into one. allSettled so one bad
764
- // selection doesn't sink the rest of the batch.
765
- const settled = await Promise.allSettled(
766
- jobs.map((job) =>
767
- downloadOneResult({
768
- client,
769
- presId: presentation_id,
770
- searchId: search_id,
771
- assetsDir,
772
- selection: job.selection,
773
- iconColor: job.iconColor,
774
- }),
775
- ),
776
- );
777
- const results = settled.map((r, i) =>
778
- r.status === "fulfilled"
779
- ? r.value
780
- : {
781
- selection: jobs[i].selection,
782
- error: r.reason?.message ? r.reason.message : String(r.reason),
783
- },
784
- );
785
-
786
- // Single-selection calls keep the original flat shape (back-compat);
787
- // a batch returns { results: [...] }.
788
- if (!batch) {
789
- const only = results[0];
790
- if (only.error) return errorResult(new Error(only.error));
791
- return textResult(only);
792
- }
793
- return textResult({ results });
794
- } catch (err) {
795
- return errorResult(err);
796
- }
797
- },
798
- );
799
-
800
- async function main() {
801
- const transport = new StdioServerTransport();
802
- await server.connect(transport);
803
- // Logging on stdout would corrupt the JSON-RPC stream — keep it on stderr.
804
- process.stderr.write("slidemind MCP server running on stdio\n");
805
- }
806
-
807
- main().catch((err) => {
808
- process.stderr.write(`slidemind MCP fatal: ${err && err.stack ? err.stack : err}\n`);
809
- process.exit(1);
810
- });