Skip to content
Source
Sign inSign up
fuko/rive-preview-player
Open History to see the last commit

mcp.mjs

285 lines12.0 KB

1// MCP server (stdio) that hands the player's screenshot + note bundles to a coding agent.
2//
3// rive-video-preview mcp [project-dir]
4//
5// It reads bundles straight from <project>/.rive-preview/feedback, so it works whether or
6// not the player is running; only seek_player needs a running player.
7import { existsSync, readFileSync, readdirSync, statSync } from 'node:fs';
8import { readFile } from 'node:fs/promises';
9import path from 'node:path';
10import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
11import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
12import * as z from 'zod';
13import { FeedbackStore } from './feedback.mjs';
14import { MixStore, mixMarkdown } from './mix.mjs';
15import { Claims, claimBundles, registerListener } from './listeners.mjs';
16import { findRunning, listRunning } from './registry.mjs';
17​
18const isDir = (p) => {
19 try {
20 return statSync(p).isDirectory();
21 } catch {
22 return false;
23 }
24};
25const isProject = (dir) => existsSync(path.join(dir, 'rive.yaml'));
26const isInside = (child, parent) => {
27 const rel = path.relative(parent, child);
28 return rel === '' || (!rel.startsWith('..') && !path.isAbsolute(rel));
29};
30​
31function projectName(dir) {
32 try {
33 const m = readFileSync(path.join(dir, 'rive.yaml'), 'utf8').match(/^name:\s*["']?([^"'\n#]+?)["']?\s*$/m);
34 if (m) return m[1];
35 } catch {}
36 return path.basename(dir);
38​
39/**
40 * Which project to read: the tool argument, then the dir given on the command line,
41 * then a rive.yaml at or above the cwd, then one just below it, then a running player
42 * (preferring one under the cwd).
43 */
44async function resolveTarget(arg, fallback) {
45 const cwd = process.cwd();
46 if (arg) return path.resolve(cwd, arg);
47 if (fallback) return path.resolve(cwd, fallback);
48 for (let d = cwd; ; d = path.dirname(d)) {
49 if (isProject(d)) return d;
50 if (path.dirname(d) === d) break;
51 }
52 const children = readdirSync(cwd, { withFileTypes: true })
53 .filter((e) => e.isDirectory() && !e.name.startsWith('.') && e.name !== 'node_modules')
54 .map((e) => path.join(cwd, e.name))
55 .filter(isProject);
56 if (children.length === 1) return children[0];
57 const running = await listRunning();
58 const near = running.filter((r) => isInside(r.target, cwd));
59 if (near.length === 1) return near[0].target;
60 if (running.length === 1) return running[0].target;
61 const known = [...children, ...running.map((r) => r.target)];
62 throw new Error(
63 `can't tell which Rive project to use from ${cwd}. Pass "project".` + (known.length ? ` Candidates: ${[...new Set(known)].join(', ')}` : ''),
64 );
66​
67function storeFor(target) {
68 const name = isDir(target) ? projectName(target) : path.basename(target, '.riv');
69 return new FeedbackStore(target, { project: name });
71​
72/** MCP content for a list of bundles: a text summary per shot followed by its image. */
73async function bundleContent(bundles, { images }) {
74 const content = [];
75 for (const b of bundles) {
76 const head = [
77 `# Feedback ${b.id} — ${b.project} (${b.shots.length} screenshot${b.shots.length === 1 ? '' : 's'}, sent ${new Date(b.createdAt).toLocaleString()})`,
78 `Folder: ${b.dir}`,
79 `Markdown: ${b.markdown}`,
80 ];
81 if (b.message) head.push('', `Overall note: ${b.message}`);
82 content.push({ type: 'text', text: head.join('\n') });
83 for (const s of b.shots) {
84 const where = [s.artboard, s.animation].filter(Boolean).join(' / ');
85 content.push({
86 type: 'text',
87 text: `## ${s.index}. ${s.timecode}${where ? ` — ${where}` : ''}\nImage: ${s.image}\nNote: ${s.note?.trim() || '(no note)'}`,
88 });
89 if (images) {
90 try {
91 content.push({ type: 'image', data: (await readFile(s.image)).toString('base64'), mimeType: 'image/png' });
92 } catch {
93 content.push({ type: 'text', text: `(image missing: ${s.image})` });
94 }
95 }
96 }
97 }
98 return content;
100​
101/** Mark bundles read; returns a note for the agent if that failed (the content is still delivered). */
102async function markRead(store, bundles) {
103 try {
104 for (const b of bundles) if (!b.consumed) await store.markConsumed(b.id);
105 return null;
106 } catch (err) {
107 return { type: 'text', text: `(Could not mark this feedback read: ${err.message}. It may be delivered again.)` };
108 }
110​
111const text = (t) => ({ content: [{ type: 'text', text: t }] });
112const fail = (err) => ({ isError: true, content: [{ type: 'text', text: String(err?.message || err) }] });
113​
114export async function runMcp(argv) {
115 const fallback = argv.find((a) => !a.startsWith('-'));
116 const server = new McpServer(
117 { name: 'rive-video-preview', version: '0.1.0' },
118 {
119 instructions:
120 'The user reviews a Rive animation in the rive-video-preview player, takes screenshots of frames, writes a note on each, ' +
121 'and presses "Send to agent". Call get_feedback to read what they sent (notes, timecodes, artboard/animation and the images). ' +
122 'Call wait_for_feedback when you have asked the user to review something and want to block until they send it. ' +
123 'Timecodes look like "00:12.350 (frame 741)". seek_player moves the open player to a time. ' +
124 'The user can also mix the sound effects in the player (up to 3 tracks, a gain per sound effect); get_audio_mix returns those levels.',
125 },
126 );
127​
128 const projectArg = z.string().optional().describe('Rive project dir (or .riv file). Defaults to the project at or around the working directory.');
129​
130 server.registerTool(
131 'get_feedback',
132 {
133 title: 'Get preview feedback',
134 description:
135 'Return the screenshot + note bundles the user sent from the Rive preview player that have not been read yet, with each image. ' +
136 'Marks them as read unless mark_read is false.',
137 inputSchema: {
138 project: projectArg,
139 include_read: z.boolean().optional().describe('Also return bundles already read (most recent last). Default false.'),
140 limit: z.number().int().positive().optional().describe('Return at most this many of the most recent bundles. Default 5.'),
141 mark_read: z.boolean().optional().describe('Default true.'),
142 images: z.boolean().optional().describe('Include the PNGs as image content. Default true; false returns only file paths.'),
143 },
144 },
145 async ({ project, include_read = false, limit = 5, mark_read = true, images = true }) => {
146 try {
147 const store = storeFor(await resolveTarget(project, fallback));
148 const all = await store.listBundles({ pendingOnly: !include_read });
149 const claims = new Claims(store);
150 try {
151 // The newest `limit` bundles this call may deliver. With mark_read, unread bundles another
152 // consumer (e.g. `wait-feedback`) is delivering right now are left to it and don't count.
153 const bundles = [];
154 for (let i = all.length - 1; i >= 0 && bundles.length < limit; i--) {
155 const b = all[i];
156 if (!mark_read || b.consumed || claims.take(b)) bundles.unshift(b);
157 }
158 if (!bundles.length) {
159 return text(
160 `No ${include_read ? '' : 'unread '}feedback for ${store.project} (${store.sentDir}). ` +
161 'The user sends it from the player with "Send to agent"; use wait_for_feedback to wait for it.',
162 );
163 }
164 const content = await bundleContent(bundles, { images });
165 const note = mark_read ? await markRead(store, bundles) : null;
166 return { content: note ? [...content, note] : content };
167 } finally {
168 claims.release();
169 }
170 } catch (err) {
171 return fail(err);
172 }
173 },
174 );
175​
176 server.registerTool(
177 'wait_for_feedback',
178 {
179 title: 'Wait for preview feedback',
180 description:
181 'Block until the user presses "Send to agent" in the Rive preview player (or the timeout passes), then return the new ' +
182 'feedback like get_feedback. Returns immediately if unread feedback is already waiting.',
183 inputSchema: {
184 project: projectArg,
185 timeout_seconds: z.number().positive().max(3600).optional().describe('Default 600.'),
186 },
187 },
188 async ({ project, timeout_seconds = 600 }, extra) => {
189 let unregister = () => {};
190 try {
191 const target = await resolveTarget(project, fallback);
192 const store = storeFor(target);
193 // Lets the player tell the user that the agent is listening.
194 unregister = registerListener(target, 'mcp');
195 const token = extra?._meta?.progressToken;
196 const started = Date.now();
197 let lastPing = started;
198 while (true) {
199 const { claimed: pending, claims } = claimBundles(store, await store.listBundles({ pendingOnly: true }));
200 if (pending.length) {
201 try {
202 const content = await bundleContent(pending, { images: true });
203 const note = await markRead(store, pending);
204 return { content: note ? [...content, note] : content };
205 } finally {
206 claims.release();
207 }
208 }
209 const waited = (Date.now() - started) / 1000;
210 if (waited >= timeout_seconds) return text(`No feedback arrived within ${timeout_seconds}s.`);
211 if (extra?.signal?.aborted) return text('Cancelled.');
212 // Progress pings keep clients that reset their timeout on progress from giving up.
213 if (token !== undefined && Date.now() - lastPing > 10000) {
214 lastPing = Date.now();
215 await extra
216 .sendNotification({
217 method: 'notifications/progress',
218 params: { progressToken: token, progress: Math.floor(waited), total: timeout_seconds, message: 'waiting for the user to send feedback' },
219 })
220 .catch(() => {});
221 }
222 await new Promise((r) => setTimeout(r, 500));
223 }
224 } catch (err) {
225 return fail(err);
226 } finally {
227 unregister();
228 }
229 },
230 );
231​
232 server.registerTool(
233 'get_audio_mix',
234 {
235 title: 'Get the audio mix',
236 description:
237 'Return the audio mix the user set in the Rive preview player: up to 3 tracks (volume, mute, solo) and, per sound effect ' +
238 '(an AudioEvent keyframe), its track and gain. The player does not change the project; use this to carry the levels over ' +
239 '(for example into AudioAsset volume).',
240 inputSchema: { project: projectArg },
241 },
242 async ({ project }) => {
243 try {
244 const target = await resolveTarget(project, fallback);
245 const store = new MixStore(target);
246 const mix = await store.read();
247 const md = mixMarkdown(mix);
248 return {
249 content: [
250 { type: 'text', text: md.length ? md.join('\n') : `The audio mix for ${target} is at its defaults (one track at 100%, no sound effect adjusted).` },
251 { type: 'text', text: `Raw (${store.file}):\n${JSON.stringify(mix, null, 2)}` },
252 ],
253 };
254 } catch (err) {
255 return fail(err);
256 }
257 },
258 );
259​
260 server.registerTool(
261 'seek_player',
262 {
263 title: 'Move the preview playhead',
264 description: 'Pause the running Rive preview player and move its playhead, e.g. to show the user the frame you changed.',
265 inputSchema: {
266 project: projectArg,
267 time: z.string().describe('12.5, 12.5s, 1:02.250, 500ms, or a frame like f741'),
268 },
269 },
270 async ({ project, time }) => {
271 try {
272 const target = await resolveTarget(project, fallback);
273 const running = await findRunning(target);
274 if (!running) return fail(`no player is running for ${target}. Start it with: rive-video-preview ${target}`);
275 const res = await fetch(`http://127.0.0.1:${running.port}/api/seek`, { method: 'POST', body: JSON.stringify({ at: time }) });
276 const { clients } = await res.json();
277 return text(clients ? `Moved ${clients} player window(s) to ${time}.` : 'The player is running but no window is open.');
278 } catch (err) {
279 return fail(err);
280 }
281 },
282 );
283​
284 await server.connect(new StdioServerTransport());