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

mcp.mjs

222 lines9.3 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 { findRunning, listRunning } from './registry.mjs';
15​
16const isDir = (p) => {
17 try {
18 return statSync(p).isDirectory();
19 } catch {
20 return false;
21 }
22};
23const isProject = (dir) => existsSync(path.join(dir, 'rive.yaml'));
24const isInside = (child, parent) => {
25 const rel = path.relative(parent, child);
26 return rel === '' || (!rel.startsWith('..') && !path.isAbsolute(rel));
27};
28​
29function projectName(dir) {
30 try {
31 const m = readFileSync(path.join(dir, 'rive.yaml'), 'utf8').match(/^name:\s*["']?([^"'\n#]+?)["']?\s*$/m);
32 if (m) return m[1];
33 } catch {}
34 return path.basename(dir);
36​
37/**
38 * Which project to read: the tool argument, then the dir given on the command line,
39 * then a rive.yaml at or above the cwd, then one just below it, then a running player
40 * (preferring one under the cwd).
41 */
42async function resolveTarget(arg, fallback) {
43 const cwd = process.cwd();
44 if (arg) return path.resolve(cwd, arg);
45 if (fallback) return path.resolve(cwd, fallback);
46 for (let d = cwd; ; d = path.dirname(d)) {
47 if (isProject(d)) return d;
48 if (path.dirname(d) === d) break;
49 }
50 const children = readdirSync(cwd, { withFileTypes: true })
51 .filter((e) => e.isDirectory() && !e.name.startsWith('.') && e.name !== 'node_modules')
52 .map((e) => path.join(cwd, e.name))
53 .filter(isProject);
54 if (children.length === 1) return children[0];
55 const running = await listRunning();
56 const near = running.filter((r) => isInside(r.target, cwd));
57 if (near.length === 1) return near[0].target;
58 if (running.length === 1) return running[0].target;
59 const known = [...children, ...running.map((r) => r.target)];
60 throw new Error(
61 `can't tell which Rive project to use from ${cwd}. Pass "project".` + (known.length ? ` Candidates: ${[...new Set(known)].join(', ')}` : ''),
62 );
64​
65function storeFor(target) {
66 const name = isDir(target) ? projectName(target) : path.basename(target, '.riv');
67 return new FeedbackStore(target, { project: name });
69​
70/** MCP content for a list of bundles: a text summary per shot followed by its image. */
71async function bundleContent(bundles, { images }) {
72 const content = [];
73 for (const b of bundles) {
74 const head = [
75 `# Feedback ${b.id} — ${b.project} (${b.shots.length} screenshot${b.shots.length === 1 ? '' : 's'}, sent ${new Date(b.createdAt).toLocaleString()})`,
76 `Folder: ${b.dir}`,
77 `Markdown: ${b.markdown}`,
78 ];
79 if (b.message) head.push('', `Overall note: ${b.message}`);
80 content.push({ type: 'text', text: head.join('\n') });
81 for (const s of b.shots) {
82 const where = [s.artboard, s.animation].filter(Boolean).join(' / ');
83 content.push({
84 type: 'text',
85 text: `## ${s.index}. ${s.timecode}${where ? ` — ${where}` : ''}\nImage: ${s.image}\nNote: ${s.note?.trim() || '(no note)'}`,
86 });
87 if (images) {
88 try {
89 content.push({ type: 'image', data: (await readFile(s.image)).toString('base64'), mimeType: 'image/png' });
90 } catch {
91 content.push({ type: 'text', text: `(image missing: ${s.image})` });
92 }
93 }
94 }
95 }
96 return content;
98​
99const text = (t) => ({ content: [{ type: 'text', text: t }] });
100const fail = (err) => ({ isError: true, content: [{ type: 'text', text: String(err?.message || err) }] });
101​
102export async function runMcp(argv) {
103 const fallback = argv.find((a) => !a.startsWith('-'));
104 const server = new McpServer(
105 { name: 'rive-video-preview', version: '0.1.0' },
106 {
107 instructions:
108 'The user reviews a Rive animation in the rive-video-preview player, takes screenshots of frames, writes a note on each, ' +
109 'and presses "Send to agent". Call get_feedback to read what they sent (notes, timecodes, artboard/animation and the images). ' +
110 'Call wait_for_feedback when you have asked the user to review something and want to block until they send it. ' +
111 'Timecodes look like "00:12.350 (frame 741)". seek_player moves the open player to a time.',
112 },
113 );
114​
115 const projectArg = z.string().optional().describe('Rive project dir (or .riv file). Defaults to the project at or around the working directory.');
116​
117 server.registerTool(
118 'get_feedback',
119 {
120 title: 'Get preview feedback',
121 description:
122 'Return the screenshot + note bundles the user sent from the Rive preview player that have not been read yet, with each image. ' +
123 'Marks them as read unless mark_read is false.',
124 inputSchema: {
125 project: projectArg,
126 include_read: z.boolean().optional().describe('Also return bundles already read (most recent last). Default false.'),
127 limit: z.number().int().positive().optional().describe('Return at most this many of the most recent bundles. Default 5.'),
128 mark_read: z.boolean().optional().describe('Default true.'),
129 images: z.boolean().optional().describe('Include the PNGs as image content. Default true; false returns only file paths.'),
130 },
131 },
132 async ({ project, include_read = false, limit = 5, mark_read = true, images = true }) => {
133 try {
134 const store = storeFor(await resolveTarget(project, fallback));
135 const bundles = (await store.listBundles({ pendingOnly: !include_read })).slice(-limit);
136 if (!bundles.length) {
137 return text(
138 `No ${include_read ? '' : 'unread '}feedback for ${store.project} (${store.sentDir}). ` +
139 'The user sends it from the player with "Send to agent"; use wait_for_feedback to wait for it.',
140 );
141 }
142 const content = await bundleContent(bundles, { images });
143 if (mark_read) for (const b of bundles) if (!b.consumed) await store.markConsumed(b.id);
144 return { content };
145 } catch (err) {
146 return fail(err);
147 }
148 },
149 );
150​
151 server.registerTool(
152 'wait_for_feedback',
153 {
154 title: 'Wait for preview feedback',
155 description:
156 'Block until the user presses "Send to agent" in the Rive preview player (or the timeout passes), then return the new ' +
157 'feedback like get_feedback. Returns immediately if unread feedback is already waiting.',
158 inputSchema: {
159 project: projectArg,
160 timeout_seconds: z.number().positive().max(3600).optional().describe('Default 600.'),
161 },
162 },
163 async ({ project, timeout_seconds = 600 }, extra) => {
164 try {
165 const store = storeFor(await resolveTarget(project, fallback));
166 const token = extra?._meta?.progressToken;
167 const started = Date.now();
168 let lastPing = started;
169 while (true) {
170 const pending = await store.listBundles({ pendingOnly: true });
171 if (pending.length) {
172 const content = await bundleContent(pending, { images: true });
173 for (const b of pending) await store.markConsumed(b.id);
174 return { content };
175 }
176 const waited = (Date.now() - started) / 1000;
177 if (waited >= timeout_seconds) return text(`No feedback arrived within ${timeout_seconds}s.`);
178 if (extra?.signal?.aborted) return text('Cancelled.');
179 // Progress pings keep clients that reset their timeout on progress from giving up.
180 if (token !== undefined && Date.now() - lastPing > 10000) {
181 lastPing = Date.now();
182 await extra
183 .sendNotification({
184 method: 'notifications/progress',
185 params: { progressToken: token, progress: Math.floor(waited), total: timeout_seconds, message: 'waiting for the user to send feedback' },
186 })
187 .catch(() => {});
188 }
189 await new Promise((r) => setTimeout(r, 500));
190 }
191 } catch (err) {
192 return fail(err);
193 }
194 },
195 );
196​
197 server.registerTool(
198 'seek_player',
199 {
200 title: 'Move the preview playhead',
201 description: 'Pause the running Rive preview player and move its playhead, e.g. to show the user the frame you changed.',
202 inputSchema: {
203 project: projectArg,
204 time: z.string().describe('12.5, 12.5s, 1:02.250, 500ms, or a frame like f741'),
205 },
206 },
207 async ({ project, time }) => {
208 try {
209 const target = await resolveTarget(project, fallback);
210 const running = await findRunning(target);
211 if (!running) return fail(`no player is running for ${target}. Start it with: rive-video-preview ${target}`);
212 const res = await fetch(`http://127.0.0.1:${running.port}/api/seek`, { method: 'POST', body: JSON.stringify({ at: time }) });
213 const { clients } = await res.json();
214 return text(clients ? `Moved ${clients} player window(s) to ${time}.` : 'The player is running but no window is open.');
215 } catch (err) {
216 return fail(err);
217 }
218 },
219 );
220​
221 await server.connect(new StdioServerTransport());