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

mcp.mjs

288 lines12.2 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, regionLine } 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}` : ''}`, `Image: ${s.image}`, regionLine(s.region), `Note: ${s.note?.trim() || '(no note)'}`]
88 .filter(Boolean)
89 .join('\n'),
90 });
91 if (images) {
92 try {
93 content.push({ type: 'image', data: (await readFile(s.image)).toString('base64'), mimeType: 'image/png' });
94 } catch {
95 content.push({ type: 'text', text: `(image missing: ${s.image})` });
96 }
97 }
98 }
99 }
100 return content;
102​
103/** Mark bundles read; returns a note for the agent if that failed (the content is still delivered). */
104async function markRead(store, bundles) {
105 try {
106 for (const b of bundles) if (!b.consumed) await store.markConsumed(b.id);
107 return null;
108 } catch (err) {
109 return { type: 'text', text: `(Could not mark this feedback read: ${err.message}. It may be delivered again.)` };
110 }
112​
113const text = (t) => ({ content: [{ type: 'text', text: t }] });
114const fail = (err) => ({ isError: true, content: [{ type: 'text', text: String(err?.message || err) }] });
115​
116export async function runMcp(argv) {
117 const fallback = argv.find((a) => !a.startsWith('-'));
118 const server = new McpServer(
119 { name: 'rive-video-preview', version: '0.1.0' },
120 {
121 instructions:
122 'The user reviews a Rive animation in the rive-video-preview player, takes screenshots of frames, writes a note on each ' +
123 '(a shot may highlight a region, given in artboard units), and presses "Send to agent". Call get_feedback to read what they sent (notes, timecodes, artboard/animation and the images). ' +
124 'Call wait_for_feedback when you have asked the user to review something and want to block until they send it. ' +
125 'Timecodes look like "00:12.350 (frame 741)". seek_player moves the open player to a time. ' +
126 '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.',
127 },
128 );
129​
130 const projectArg = z.string().optional().describe('Rive project dir (or .riv file). Defaults to the project at or around the working directory.');
131​
132 server.registerTool(
133 'get_feedback',
134 {
135 title: 'Get preview feedback',
136 description:
137 'Return the screenshot + note bundles the user sent from the Rive preview player that have not been read yet, with each image. ' +
138 'A shot may carry a highlighted region (x, y, width × height in artboard units from the artboard\'s top-left), outlined on its image. ' +
139 'Marks them as read unless mark_read is false.',
140 inputSchema: {
141 project: projectArg,
142 include_read: z.boolean().optional().describe('Also return bundles already read (most recent last). Default false.'),
143 limit: z.number().int().positive().optional().describe('Return at most this many of the most recent bundles. Default 5.'),
144 mark_read: z.boolean().optional().describe('Default true.'),
145 images: z.boolean().optional().describe('Include the PNGs as image content. Default true; false returns only file paths.'),
146 },
147 },
148 async ({ project, include_read = false, limit = 5, mark_read = true, images = true }) => {
149 try {
150 const store = storeFor(await resolveTarget(project, fallback));
151 const all = await store.listBundles({ pendingOnly: !include_read });
152 const claims = new Claims(store);
153 try {
154 // The newest `limit` bundles this call may deliver. With mark_read, unread bundles another
155 // consumer (e.g. `wait-feedback`) is delivering right now are left to it and don't count.
156 const bundles = [];
157 for (let i = all.length - 1; i >= 0 && bundles.length < limit; i--) {
158 const b = all[i];
159 if (!mark_read || b.consumed || claims.take(b)) bundles.unshift(b);
160 }
161 if (!bundles.length) {
162 return text(
163 `No ${include_read ? '' : 'unread '}feedback for ${store.project} (${store.sentDir}). ` +
164 'The user sends it from the player with "Send to agent"; use wait_for_feedback to wait for it.',
165 );
166 }
167 const content = await bundleContent(bundles, { images });
168 const note = mark_read ? await markRead(store, bundles) : null;
169 return { content: note ? [...content, note] : content };
170 } finally {
171 claims.release();
172 }
173 } catch (err) {
174 return fail(err);
175 }
176 },
177 );
178​
179 server.registerTool(
180 'wait_for_feedback',
181 {
182 title: 'Wait for preview feedback',
183 description:
184 'Block until the user presses "Send to agent" in the Rive preview player (or the timeout passes), then return the new ' +
185 'feedback like get_feedback. Returns immediately if unread feedback is already waiting.',
186 inputSchema: {
187 project: projectArg,
188 timeout_seconds: z.number().positive().max(3600).optional().describe('Default 600.'),
189 },
190 },
191 async ({ project, timeout_seconds = 600 }, extra) => {
192 let unregister = () => {};
193 try {
194 const target = await resolveTarget(project, fallback);
195 const store = storeFor(target);
196 // Lets the player tell the user that the agent is listening.
197 unregister = registerListener(target, 'mcp');
198 const token = extra?._meta?.progressToken;
199 const started = Date.now();
200 let lastPing = started;
201 while (true) {
202 const { claimed: pending, claims } = claimBundles(store, await store.listBundles({ pendingOnly: true }));
203 if (pending.length) {
204 try {
205 const content = await bundleContent(pending, { images: true });
206 const note = await markRead(store, pending);
207 return { content: note ? [...content, note] : content };
208 } finally {
209 claims.release();
210 }
211 }
212 const waited = (Date.now() - started) / 1000;
213 if (waited >= timeout_seconds) return text(`No feedback arrived within ${timeout_seconds}s.`);
214 if (extra?.signal?.aborted) return text('Cancelled.');
215 // Progress pings keep clients that reset their timeout on progress from giving up.
216 if (token !== undefined && Date.now() - lastPing > 10000) {
217 lastPing = Date.now();
218 await extra
219 .sendNotification({
220 method: 'notifications/progress',
221 params: { progressToken: token, progress: Math.floor(waited), total: timeout_seconds, message: 'waiting for the user to send feedback' },
222 })
223 .catch(() => {});
224 }
225 await new Promise((r) => setTimeout(r, 500));
226 }
227 } catch (err) {
228 return fail(err);
229 } finally {
230 unregister();
231 }
232 },
233 );
234​
235 server.registerTool(
236 'get_audio_mix',
237 {
238 title: 'Get the audio mix',
239 description:
240 'Return the audio mix the user set in the Rive preview player: up to 3 tracks (volume, mute, solo) and, per sound effect ' +
241 '(an AudioEvent keyframe), its track and gain. The player does not change the project; use this to carry the levels over ' +
242 '(for example into AudioAsset volume).',
243 inputSchema: { project: projectArg },
244 },
245 async ({ project }) => {
246 try {
247 const target = await resolveTarget(project, fallback);
248 const store = new MixStore(target);
249 const mix = await store.read();
250 const md = mixMarkdown(mix);
251 return {
252 content: [
253 { 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).` },
254 { type: 'text', text: `Raw (${store.file}):\n${JSON.stringify(mix, null, 2)}` },
255 ],
256 };
257 } catch (err) {
258 return fail(err);
259 }
260 },
261 );
262​
263 server.registerTool(
264 'seek_player',
265 {
266 title: 'Move the preview playhead',
267 description: 'Pause the running Rive preview player and move its playhead, e.g. to show the user the frame you changed.',
268 inputSchema: {
269 project: projectArg,
270 time: z.string().describe('12.5, 12.5s, 1:02.250, 500ms, or a frame like f741'),
271 },
272 },
273 async ({ project, time }) => {
274 try {
275 const target = await resolveTarget(project, fallback);
276 const running = await findRunning(target);
277 if (!running) return fail(`no player is running for ${target}. Start it with: rive-video-preview ${target}`);
278 const res = await fetch(`http://127.0.0.1:${running.port}/api/seek`, { method: 'POST', body: JSON.stringify({ at: time }) });
279 const { clients } = await res.json();
280 return text(clients ? `Moved ${clients} player window(s) to ${time}.` : 'The player is running but no window is open.');
281 } catch (err) {
282 return fail(err);
283 }
284 },
285 );
286​
287 await server.connect(new StdioServerTransport());