@clipy/mcp 0.7.1 → 0.8.1
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.
- package/README.md +62 -10
- package/dist/index.js +799 -57
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -2,10 +2,9 @@
|
|
|
2
2
|
|
|
3
3
|
Give your AI agent access to your [Clipy](https://clipy.online) screen recordings.
|
|
4
4
|
|
|
5
|
-
>
|
|
6
|
-
>
|
|
7
|
-
>
|
|
8
|
-
> [`@clipy/mcp`](https://www.npmjs.com/package/@clipy/mcp).
|
|
5
|
+
> Developed in the Clipy monorepo. A public mirror for browsing the source and filing
|
|
6
|
+
> issues lives at **[github.com/manovagyanik1/clipy-mcp](https://github.com/manovagyanik1/clipy-mcp)**
|
|
7
|
+
> (MIT), kept in sync with each npm release.
|
|
9
8
|
|
|
10
9
|
This is a [Model Context Protocol](https://modelcontextprotocol.io) (MCP) server. It lets
|
|
11
10
|
Claude, Cursor, Windsurf, and other MCP-capable agents **search your recordings and read
|
|
@@ -15,7 +14,7 @@ tool, **record a web app headlessly** and get it back as a Clipy recording (_"bu
|
|
|
15
14
|
feature, then record the outcome"_).
|
|
16
15
|
|
|
17
16
|
The read tools need the `recordings:read` scope, which every key gets by default. The
|
|
18
|
-
write tools — `record`, the session tools (`start_recording`, `add_marker`,
|
|
17
|
+
write tools — `record`, the session tools (`start_recording`, `add_marker`, `add_chapter`,
|
|
19
18
|
`stop_recording`, `abort_recording`), and `replace_transcript` — additionally need the
|
|
20
19
|
key to carry the `ingest` scope ("Record & upload"), which the server enforces. A
|
|
21
20
|
`recordings:read`-only key can read your recordings but cannot create, modify, or
|
|
@@ -98,9 +97,10 @@ or the Windsurf MCP config) directly:
|
|
|
98
97
|
| `download_recording` | Download the MP4 locally so you can clip it or extract frames yourself (e.g. with ffmpeg). |
|
|
99
98
|
| `get_key_moments` | Key moments: timestamps, captions, and click coordinates. |
|
|
100
99
|
| `get_agent_context` | The full agent-context bundle (summary + key moments + transcript) as markdown. |
|
|
101
|
-
| `record` | **Record a web app headlessly** and upload it as a Clipy recording; returns its share + agent-context URLs. Accepts timestamped `notes` that become the (silent) recording's transcript. Needs Playwright in this server's environment and an `ingest`-scoped key (see below). |
|
|
102
|
-
| `start_recording` | **Start a recording session** that keeps recording while you work (drive the page with your own browser tools, run commands, …). Auto-stops + uploads at `maxSeconds` (default 600) so it can never run away. |
|
|
103
|
-
| `add_marker` | Drop a
|
|
100
|
+
| `record` | **Record a web app headlessly** and upload it as a Clipy recording; returns its share + agent-context URLs. Accepts a `type` (recording kind), `viewports` (sweep several screen sizes into one video), `storageState`/`userDataDir`/`initScript` (record behind a login), and timestamped `notes` that become the (silent) recording's transcript. Needs Playwright in this server's environment and an `ingest`-scoped key (see below). |
|
|
101
|
+
| `start_recording` | **Start a recording session** that keeps recording while you work (drive the page with your own browser tools, run commands, …). Accepts `type`, `storageState`/`userDataDir`/`initScript`, and `exposeCdp` (get a CDP endpoint + in-page `window.__clipyMark`/`window.__clipyChapter` bridge to drive the recorded page). Auto-stops + uploads at `maxSeconds` (default 600) so it can never run away. |
|
|
102
|
+
| `add_marker` | Drop a narration marker into the active session (live clock, or backdate with `atSeconds`) — markers become the recording's transcript chapters. Can also **verify** on-screen state (`assertSelector` / `assertText` (requires a selector) / `assertUrl`, `failMode`); an assertion is annotated as a pass (✓), an explicit failure (✗, can abort the session), or **unverified** (⚠, when it couldn't be evaluated — never a silent pass). Navigations + console errors are added automatically as `[auto]` marks. |
|
|
103
|
+
| `add_chapter` | Drop a `=== CHAPTER: <label> ===` boundary into the active session — split a recording into named sections (ideal for before/after demos). |
|
|
104
104
|
| `stop_recording` | Finish the session: close the browser, upload, return the share + agent-context URLs. |
|
|
105
105
|
| `abort_recording` | Discard the active session; nothing is uploaded. |
|
|
106
106
|
| `replace_transcript` | **Replace a recording's transcript** with text you author (needs the `ingest` scope). Fix a bad speech-to-text pass, translate, or enrich a silent agent capture; the summary regenerates automatically. Marked as agent-edited, never passed off as speech-to-text. |
|
|
@@ -108,6 +108,10 @@ or the Windsurf MCP config) directly:
|
|
|
108
108
|
Read tools accept a recording's **public id** (the slug in its share URL) or the full
|
|
109
109
|
`https://clipy.online/video/<id>` URL.
|
|
110
110
|
|
|
111
|
+
> **Capturing the real screen is CLI-only.** These tools record a headless Chromium page.
|
|
112
|
+
> To record the actual Mac screen or a specific window (ScreenCaptureKit — the real
|
|
113
|
+
> logged-in browser), use the Clipy CLI: `clipy record --source mac-screen --window "<app>"`.
|
|
114
|
+
|
|
111
115
|
### Using `record`
|
|
112
116
|
|
|
113
117
|
`record` opens a URL in a headless Chromium (works in CI / cloud sandboxes, no display),
|
|
@@ -121,8 +125,56 @@ records for a few seconds, and streams it into Clipy — then returns the id so
|
|
|
121
125
|
2. An API key with the **"Record & upload" (ingest)** permission — choose it when you mint
|
|
122
126
|
the key at [clipy.online/settings/api-keys](https://clipy.online/settings/api-keys).
|
|
123
127
|
|
|
124
|
-
Parameters: `url` (required, http/https), `durationSeconds` (default 15, max 300
|
|
125
|
-
`
|
|
128
|
+
Parameters: `url` (required, http/https), `durationSeconds` (default 15, max 300, applied
|
|
129
|
+
per viewport pass), `name`, `description`, `type` (recording kind — `bug_report`,
|
|
130
|
+
`feature_request`, `product_demo`, `walkthrough_tutorial`, `feedback_review`,
|
|
131
|
+
`discussion_talk`, `other`, plus aliases), `viewports` (e.g. `mobile,desktop` or
|
|
132
|
+
`390x844,1440x900` — recorded sequentially into one video, frame sized to the largest,
|
|
133
|
+
each pass slow-scrolled and auto-chaptered), `storageState` / `initScript` (paths, never
|
|
134
|
+
logged), `notes`, and `width`/`height` (default 1280×720, ignored when `viewports` is set).
|
|
135
|
+
|
|
136
|
+
**Recording behind a login.** `storageState` seeds exactly what its JSON contains (cookies +
|
|
137
|
+
localStorage) but can't reproduce a whole browser identity (IndexedDB, service workers, some
|
|
138
|
+
cross-origin auth). For a full identity, produce a storageState with an interactive login
|
|
139
|
+
(`npx playwright open --save-storage=state.json <login-url>`) and pass its path, **or** pass
|
|
140
|
+
`userDataDir` pointed at a **dedicated** Chromium profile directory — one no running browser
|
|
141
|
+
is using (a live/locked profile is refused). `storageState` and `userDataDir` are mutually
|
|
142
|
+
exclusive.
|
|
143
|
+
|
|
144
|
+
### Driving the recorded page over CDP (`start_recording` + `exposeCdp: true`)
|
|
145
|
+
|
|
146
|
+
Pass `exposeCdp: true` to `start_recording` and the recording browser opens a Chrome
|
|
147
|
+
DevTools Protocol endpoint; the result returns `cdpHttpUrl` + `cdpUrl`. Connect your own
|
|
148
|
+
Playwright and drive the page while Clipy records it:
|
|
149
|
+
|
|
150
|
+
```js
|
|
151
|
+
const { chromium } = require("playwright");
|
|
152
|
+
const browser = await chromium.connectOverCDP(cdpHttpUrl);
|
|
153
|
+
const page = browser.contexts()[0].pages()[0]; // the page being recorded
|
|
154
|
+
await page.goto("http://localhost:3000/settings");
|
|
155
|
+
await browser.close(); // detaches; the recording keeps going
|
|
156
|
+
```
|
|
157
|
+
|
|
158
|
+
It's **off by default** — while it's open, any local process can attach to that browser.
|
|
159
|
+
`CLIPY_DISABLE_CDP=1` is a hard kill switch that forces it off. Gotchas: the recorded page
|
|
160
|
+
is `contexts()[0].pages()[0]` (a new context you open won't be captured); `page.viewportSize()`
|
|
161
|
+
reads `null` over a CDP attach; and to change the viewport use `newCDPSession` +
|
|
162
|
+
`Emulation.setDeviceMetricsOverride`, not `setViewportSize`.
|
|
163
|
+
|
|
164
|
+
**In-page bridge (zero extra tool calls).** When `exposeCdp` is on, the recorded page also
|
|
165
|
+
exposes `window.__clipyMark(text, opts?)` and `window.__clipyChapter(label)`, so your CDP
|
|
166
|
+
driver can drop asserted marks/chapters from inside the page:
|
|
167
|
+
|
|
168
|
+
```js
|
|
169
|
+
await page.evaluate(() =>
|
|
170
|
+
window.__clipyMark("saved the form", { assertSelector: ".toast", assertText: "Saved" }),
|
|
171
|
+
);
|
|
172
|
+
await page.evaluate(() => window.__clipyChapter("AFTER — fix applied"));
|
|
173
|
+
```
|
|
174
|
+
|
|
175
|
+
`opts` mirrors `add_marker` (`assertSelector` / `assertText` / `assertUrl` / `failMode`);
|
|
176
|
+
`assertText` requires `assertSelector` (the call rejects otherwise), and a failed assert with
|
|
177
|
+
`failMode: "abort"` discards the session — same annotations and tally as the tools.
|
|
126
178
|
|
|
127
179
|
## Config
|
|
128
180
|
|
package/dist/index.js
CHANGED
|
@@ -24,14 +24,16 @@
|
|
|
24
24
|
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
|
25
25
|
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
|
|
26
26
|
import { z } from "zod";
|
|
27
|
-
import { closeSync, createWriteStream, mkdirSync, openSync, readSync, rmSync, statSync } from "node:fs";
|
|
27
|
+
import { closeSync, createWriteStream, mkdirSync, openSync, readdirSync, readFileSync, readSync, rmSync, statSync } from "node:fs";
|
|
28
28
|
import { randomUUID } from "node:crypto";
|
|
29
|
+
import { createServer } from "node:net";
|
|
29
30
|
import { tmpdir } from "node:os";
|
|
30
31
|
import { join, resolve } from "node:path";
|
|
31
32
|
import { Readable } from "node:stream";
|
|
32
33
|
import { pipeline } from "node:stream/promises";
|
|
33
34
|
const API_URL = (process.env.CLIPY_API_URL || "https://clipy.online").replace(/\/+$/, "");
|
|
34
35
|
const API_KEY = process.env.CLIPY_API_KEY;
|
|
36
|
+
const SERVER_VERSION = "0.8.1";
|
|
35
37
|
// The key is checked lazily (per tool call, not at startup) so the server can
|
|
36
38
|
// start and answer introspection (initialize / tools/list) in keyless
|
|
37
39
|
// environments like directory health checks.
|
|
@@ -54,7 +56,7 @@ async function api(path) {
|
|
|
54
56
|
headers: {
|
|
55
57
|
Authorization: `Bearer ${API_KEY}`,
|
|
56
58
|
Accept: "application/json",
|
|
57
|
-
"User-Agent":
|
|
59
|
+
"User-Agent": `clipy-mcp/${SERVER_VERSION}`,
|
|
58
60
|
},
|
|
59
61
|
signal: controller.signal,
|
|
60
62
|
});
|
|
@@ -102,7 +104,7 @@ async function apiPostJson(path, payload, method = "POST") {
|
|
|
102
104
|
Authorization: `Bearer ${API_KEY}`,
|
|
103
105
|
"Content-Type": "application/json",
|
|
104
106
|
Accept: "application/json",
|
|
105
|
-
"User-Agent":
|
|
107
|
+
"User-Agent": `clipy-mcp/${SERVER_VERSION}`,
|
|
106
108
|
},
|
|
107
109
|
body: JSON.stringify(payload),
|
|
108
110
|
signal: controller.signal,
|
|
@@ -159,7 +161,7 @@ async function apiPostChunk(recordingId, uploadToken, partNumber, bytes) {
|
|
|
159
161
|
try {
|
|
160
162
|
res = await fetch(`${API_URL}/api/videos/raw-upload/chunk`, {
|
|
161
163
|
method: "POST",
|
|
162
|
-
headers: { Authorization: `Bearer ${API_KEY}`, "User-Agent":
|
|
164
|
+
headers: { Authorization: `Bearer ${API_KEY}`, "User-Agent": `clipy-mcp/${SERVER_VERSION}` },
|
|
163
165
|
body: form,
|
|
164
166
|
signal: controller.signal,
|
|
165
167
|
});
|
|
@@ -215,6 +217,326 @@ function validateWebmFile(videoPath) {
|
|
|
215
217
|
}
|
|
216
218
|
return size;
|
|
217
219
|
}
|
|
220
|
+
/** Diagnostic line to stderr (the only channel a stdio MCP server can log to
|
|
221
|
+
* without corrupting the protocol on stdout). */
|
|
222
|
+
function serverLog(message) {
|
|
223
|
+
process.stderr.write(`[clipy-mcp] ${message}\n`);
|
|
224
|
+
}
|
|
225
|
+
// --- Recording kind (`type`) -----------------------------------------------
|
|
226
|
+
// Declares what a recording IS, so the AI summary doesn't misread a demo as a
|
|
227
|
+
// bug report. Sent as `recordingKind` on raw-upload/complete. The literals +
|
|
228
|
+
// aliases mirror the CLI (cli/src/index.ts) and the server contract exactly.
|
|
229
|
+
const RECORDING_KINDS = [
|
|
230
|
+
"bug_report",
|
|
231
|
+
"feature_request",
|
|
232
|
+
"product_demo",
|
|
233
|
+
"walkthrough_tutorial",
|
|
234
|
+
"feedback_review",
|
|
235
|
+
"discussion_talk",
|
|
236
|
+
"other",
|
|
237
|
+
];
|
|
238
|
+
const RECORDING_KIND_ALIASES = {
|
|
239
|
+
bug: "bug_report",
|
|
240
|
+
feature: "feature_request",
|
|
241
|
+
demo: "product_demo",
|
|
242
|
+
product: "product_demo",
|
|
243
|
+
walkthrough: "walkthrough_tutorial",
|
|
244
|
+
tutorial: "walkthrough_tutorial",
|
|
245
|
+
guide: "walkthrough_tutorial",
|
|
246
|
+
feedback: "feedback_review",
|
|
247
|
+
review: "feedback_review",
|
|
248
|
+
discussion: "discussion_talk",
|
|
249
|
+
talk: "discussion_talk",
|
|
250
|
+
meeting: "discussion_talk",
|
|
251
|
+
};
|
|
252
|
+
/** Normalize a `type` value (case/space/hyphen-insensitive) to a canonical
|
|
253
|
+
* recordingKind literal, or null if unrecognized. */
|
|
254
|
+
function normalizeRecordingKind(input) {
|
|
255
|
+
const norm = input.trim().toLowerCase().replace(/[\s-]+/g, "_");
|
|
256
|
+
if (RECORDING_KINDS.includes(norm))
|
|
257
|
+
return norm;
|
|
258
|
+
return RECORDING_KIND_ALIASES[norm] ?? null;
|
|
259
|
+
}
|
|
260
|
+
/** The message a tool returns via fail() when `type` is unrecognized. */
|
|
261
|
+
function recordingKindError(input) {
|
|
262
|
+
return (`type "${input}" is not a recording kind. Accepted: ${RECORDING_KINDS.join(", ")} ` +
|
|
263
|
+
`(aliases: bug, feature, demo/product, walkthrough/tutorial/guide, feedback/review, discussion/talk/meeting)`);
|
|
264
|
+
}
|
|
265
|
+
// --- Multi-viewport capture (`viewports`) ----------------------------------
|
|
266
|
+
// Records every size sequentially into ONE video; the frame is sized to the
|
|
267
|
+
// largest viewport and smaller passes letterbox inside it. Mirrors the CLI's
|
|
268
|
+
// parseViewports / VIEWPORT_ALIASES. Throws (never process.exit) so the calling
|
|
269
|
+
// tool can turn it into a fail().
|
|
270
|
+
const VIEWPORT_ALIASES = {
|
|
271
|
+
mobile: { width: 390, height: 844 },
|
|
272
|
+
tablet: { width: 768, height: 1024 },
|
|
273
|
+
desktop: { width: 1440, height: 900 },
|
|
274
|
+
};
|
|
275
|
+
function parseViewports(spec) {
|
|
276
|
+
const out = [];
|
|
277
|
+
for (const part of spec.split(",").map((s) => s.trim().toLowerCase()).filter(Boolean)) {
|
|
278
|
+
const alias = VIEWPORT_ALIASES[part];
|
|
279
|
+
if (alias) {
|
|
280
|
+
out.push({ ...alias, label: `${part} (${alias.width}×${alias.height})` });
|
|
281
|
+
continue;
|
|
282
|
+
}
|
|
283
|
+
const m = part.match(/^(\d{2,4})x(\d{2,4})$/);
|
|
284
|
+
if (!m) {
|
|
285
|
+
throw new Error(`invalid viewport "${part}" — use WIDTHxHEIGHT (e.g. 390x844) or ${Object.keys(VIEWPORT_ALIASES).join("/")}`);
|
|
286
|
+
}
|
|
287
|
+
out.push({ width: parseInt(m[1], 10), height: parseInt(m[2], 10), label: `${m[1]}×${m[2]}` });
|
|
288
|
+
}
|
|
289
|
+
if (out.length === 0)
|
|
290
|
+
throw new Error("no viewports parsed from `viewports`");
|
|
291
|
+
if (out.length > 8)
|
|
292
|
+
throw new Error("`viewports` supports at most 8 sizes per recording");
|
|
293
|
+
return out;
|
|
294
|
+
}
|
|
295
|
+
/**
|
|
296
|
+
* Blank-frame heuristic (mirrors the CLI). We can't decode pixels without a
|
|
297
|
+
* dependency, so JPEG size per megapixel is a complexity proxy: a uniform
|
|
298
|
+
* "still compiling" screen compresses to a tiny JPEG, real UI to a much larger
|
|
299
|
+
* one. 12 KB/MP at quality 30 sits well clear of both, biased to treat
|
|
300
|
+
* splash/compile screens as blank.
|
|
301
|
+
*/
|
|
302
|
+
function isBlankFrame(jpeg, width, height) {
|
|
303
|
+
const px = Math.max(1, width * height);
|
|
304
|
+
const bytesPerMegapixel = (jpeg.length / px) * 1_000_000;
|
|
305
|
+
return bytesPerMegapixel < 12_000;
|
|
306
|
+
}
|
|
307
|
+
/**
|
|
308
|
+
* Poll cheap JPEG screenshots until the frame has real content (not the blank
|
|
309
|
+
* t=0 a still-compiling dev server shows) or a 10s cap, so the capture clock —
|
|
310
|
+
* and every note anchored to it — starts on the first meaningful frame. Returns
|
|
311
|
+
* the ms spent waiting.
|
|
312
|
+
*/
|
|
313
|
+
async function waitForFirstPaint(page, size) {
|
|
314
|
+
const CAP_MS = 10_000;
|
|
315
|
+
const POLL_MS = 250;
|
|
316
|
+
const start = Date.now();
|
|
317
|
+
for (;;) {
|
|
318
|
+
let blank = true;
|
|
319
|
+
try {
|
|
320
|
+
const buf = await page.screenshot({ type: "jpeg", quality: 30 });
|
|
321
|
+
blank = isBlankFrame(buf, size.width, size.height);
|
|
322
|
+
}
|
|
323
|
+
catch {
|
|
324
|
+
blank = true; // screenshot failed (page not ready yet) — keep waiting
|
|
325
|
+
}
|
|
326
|
+
if (!blank)
|
|
327
|
+
break;
|
|
328
|
+
if (Date.now() - start >= CAP_MS) {
|
|
329
|
+
serverLog(`no meaningful paint after ${Math.round(CAP_MS / 1000)}s — starting the clock anyway`);
|
|
330
|
+
break;
|
|
331
|
+
}
|
|
332
|
+
await page.waitForTimeout(POLL_MS);
|
|
333
|
+
}
|
|
334
|
+
return Date.now() - start;
|
|
335
|
+
}
|
|
336
|
+
// --- CDP exposure (session --expose-cdp equivalent) ------------------------
|
|
337
|
+
/** Reserve a free localhost TCP port for Chromium's CDP endpoint. Binding to
|
|
338
|
+
* :0 then closing hands us a concrete port to pass to --remote-debugging-port,
|
|
339
|
+
* which we can then poll. Mirrors the CLI's pickFreePort. */
|
|
340
|
+
function pickFreePort() {
|
|
341
|
+
return new Promise((resolvePort, reject) => {
|
|
342
|
+
const srv = createServer();
|
|
343
|
+
srv.on("error", reject);
|
|
344
|
+
srv.listen(0, "127.0.0.1", () => {
|
|
345
|
+
const addr = srv.address();
|
|
346
|
+
const port = typeof addr === "object" && addr ? addr.port : 0;
|
|
347
|
+
srv.close(() => (port ? resolvePort(port) : reject(new Error("no port"))));
|
|
348
|
+
});
|
|
349
|
+
});
|
|
350
|
+
}
|
|
351
|
+
/** After Chromium is up with --remote-debugging-port, its HTTP endpoint exposes
|
|
352
|
+
* the browser-level ws URL at /json/version. Poll until it answers (or 10s). */
|
|
353
|
+
async function discoverCdpWsUrl(port) {
|
|
354
|
+
const deadline = Date.now() + 10_000;
|
|
355
|
+
for (;;) {
|
|
356
|
+
try {
|
|
357
|
+
const res = await fetch(`http://127.0.0.1:${port}/json/version`);
|
|
358
|
+
if (res.ok) {
|
|
359
|
+
const body = (await res.json());
|
|
360
|
+
if (body.webSocketDebuggerUrl)
|
|
361
|
+
return body.webSocketDebuggerUrl;
|
|
362
|
+
}
|
|
363
|
+
}
|
|
364
|
+
catch {
|
|
365
|
+
// endpoint not up yet
|
|
366
|
+
}
|
|
367
|
+
if (Date.now() >= deadline)
|
|
368
|
+
return null;
|
|
369
|
+
await sleep(200);
|
|
370
|
+
}
|
|
371
|
+
}
|
|
372
|
+
/** The four driver gotchas returned to the agent when a CDP endpoint is exposed,
|
|
373
|
+
* so an agent that only sees this tool's output can drive the page correctly. */
|
|
374
|
+
const CDP_DRIVER_NOTE = "Drive the recorded page with your own Playwright: chromium.connectOverCDP(cdpHttpUrl). " +
|
|
375
|
+
"Gotchas: (1) the page being recorded is browser.contexts()[0].pages()[0] — a NEW context/page you open is NOT captured; " +
|
|
376
|
+
"(2) page.viewportSize() reads null over a CDP attach; " +
|
|
377
|
+
"(3) to change the viewport use page.context().newCDPSession(page) + Emulation.setDeviceMetricsOverride, not setViewportSize; " +
|
|
378
|
+
"(4) close your connection (browser.close()) when done — it only detaches, the recording keeps going. " +
|
|
379
|
+
"In-page bridge (zero extra tool calls): call window.__clipyMark(text, {assertSelector, assertText, assertUrl, failMode}) to drop an asserted mark and window.__clipyChapter(label) for a chapter — from the recorded page, e.g. await page.evaluate(() => window.__clipyMark('saved', {assertSelector:'.toast', assertText:'Saved'})); assertText requires assertSelector (the call rejects otherwise), and a failed assert with failMode:'abort' discards the session.";
|
|
380
|
+
// --- URL-glob matching (add_marker assertUrl) ------------------------------
|
|
381
|
+
// `**` matches anything (including `/`); `*` matches within a path segment.
|
|
382
|
+
function globToRegExp(glob) {
|
|
383
|
+
let re = "";
|
|
384
|
+
for (let i = 0; i < glob.length; i++) {
|
|
385
|
+
const ch = glob[i];
|
|
386
|
+
if (ch === "*") {
|
|
387
|
+
if (glob[i + 1] === "*") {
|
|
388
|
+
re += ".*";
|
|
389
|
+
i++;
|
|
390
|
+
}
|
|
391
|
+
else {
|
|
392
|
+
re += "[^/]*";
|
|
393
|
+
}
|
|
394
|
+
}
|
|
395
|
+
else {
|
|
396
|
+
re += ch.replace(/[.+?^${}()|[\]\\]/g, "\\$&");
|
|
397
|
+
}
|
|
398
|
+
}
|
|
399
|
+
return new RegExp(`^${re}$`);
|
|
400
|
+
}
|
|
401
|
+
function globMatch(value, glob) {
|
|
402
|
+
try {
|
|
403
|
+
return globToRegExp(glob).test(value);
|
|
404
|
+
}
|
|
405
|
+
catch {
|
|
406
|
+
return false;
|
|
407
|
+
}
|
|
408
|
+
}
|
|
409
|
+
// --- Auth-state inputs (storageState / initScript) -------------------------
|
|
410
|
+
// Same semantics as the CLI: storageState is a Playwright storageState JSON
|
|
411
|
+
// passed unchanged to newContext; initScript runs via context.addInitScript
|
|
412
|
+
// before navigation. Both validated with clear errors; contents NEVER logged.
|
|
413
|
+
function validateReadableFile(label, p) {
|
|
414
|
+
const resolved = resolve(p);
|
|
415
|
+
let st;
|
|
416
|
+
try {
|
|
417
|
+
st = statSync(resolved);
|
|
418
|
+
}
|
|
419
|
+
catch {
|
|
420
|
+
throw new Error(`${label} file not found: ${resolved}`);
|
|
421
|
+
}
|
|
422
|
+
if (!st.isFile())
|
|
423
|
+
throw new Error(`${label} path is not a file: ${resolved}`);
|
|
424
|
+
return resolved;
|
|
425
|
+
}
|
|
426
|
+
/** Validate a Playwright storageState JSON path — resolves, confirms it parses
|
|
427
|
+
* and carries the expected shape, and returns the absolute path (never its
|
|
428
|
+
* contents, which may hold cookies/tokens). */
|
|
429
|
+
function validateStorageStateFile(p) {
|
|
430
|
+
const resolved = validateReadableFile("storageState", p);
|
|
431
|
+
let raw;
|
|
432
|
+
try {
|
|
433
|
+
raw = readFileSync(resolved, "utf8");
|
|
434
|
+
}
|
|
435
|
+
catch {
|
|
436
|
+
throw new Error(`storageState file is not readable: ${resolved}`);
|
|
437
|
+
}
|
|
438
|
+
let parsed;
|
|
439
|
+
try {
|
|
440
|
+
parsed = JSON.parse(raw);
|
|
441
|
+
}
|
|
442
|
+
catch {
|
|
443
|
+
throw new Error(`storageState file is not valid JSON (Playwright storageState format expected): ${resolved}`);
|
|
444
|
+
}
|
|
445
|
+
if (typeof parsed !== "object" ||
|
|
446
|
+
parsed === null ||
|
|
447
|
+
(!("cookies" in parsed) && !("origins" in parsed))) {
|
|
448
|
+
throw new Error(`storageState file does not look like a Playwright storageState JSON (expected "cookies"/"origins" keys): ${resolved}`);
|
|
449
|
+
}
|
|
450
|
+
return resolved;
|
|
451
|
+
}
|
|
452
|
+
/** Validate an init-script path (resolves + confirms it is a readable file);
|
|
453
|
+
* returns the absolute path, never its contents. */
|
|
454
|
+
function validateInitScriptFile(p) {
|
|
455
|
+
const resolved = validateReadableFile("initScript", p);
|
|
456
|
+
try {
|
|
457
|
+
// Confirm readability without retaining the contents.
|
|
458
|
+
closeSync(openSync(resolved, "r"));
|
|
459
|
+
}
|
|
460
|
+
catch {
|
|
461
|
+
throw new Error(`initScript file is not readable: ${resolved}`);
|
|
462
|
+
}
|
|
463
|
+
return resolved;
|
|
464
|
+
}
|
|
465
|
+
/** Validate a userDataDir (a whole Chromium profile) — resolves, confirms it's a
|
|
466
|
+
* directory, and REFUSES a live/locked profile (Chrome leaves SingletonLock /
|
|
467
|
+
* SingletonSocket while running). Returns the absolute path. */
|
|
468
|
+
function validateUserDataDir(p) {
|
|
469
|
+
const resolved = resolve(p);
|
|
470
|
+
let st;
|
|
471
|
+
try {
|
|
472
|
+
st = statSync(resolved);
|
|
473
|
+
}
|
|
474
|
+
catch {
|
|
475
|
+
throw new Error(`userDataDir not found: ${resolved}`);
|
|
476
|
+
}
|
|
477
|
+
if (!st.isDirectory())
|
|
478
|
+
throw new Error(`userDataDir is not a directory: ${resolved}`);
|
|
479
|
+
let entries;
|
|
480
|
+
try {
|
|
481
|
+
entries = readdirSync(resolved);
|
|
482
|
+
}
|
|
483
|
+
catch {
|
|
484
|
+
throw new Error(`userDataDir is not readable: ${resolved}`);
|
|
485
|
+
}
|
|
486
|
+
// Match by NAME (these are often symlinks/sockets that statSync can't follow).
|
|
487
|
+
if (entries.includes("SingletonLock") || entries.includes("SingletonSocket")) {
|
|
488
|
+
throw new Error(`userDataDir looks like a LIVE Chrome profile — found a Singleton lock in ${resolved}. ` +
|
|
489
|
+
`Close that browser, or point userDataDir at a DEDICATED profile directory no running browser is using. ` +
|
|
490
|
+
`Driving a locked profile fails and risks corrupting it.`);
|
|
491
|
+
}
|
|
492
|
+
return resolved;
|
|
493
|
+
}
|
|
494
|
+
/** First line of an error message, trimmed — keeps annotations/logs one-line. */
|
|
495
|
+
function firstLine(message) {
|
|
496
|
+
return (message ?? "").split("\n")[0].trim();
|
|
497
|
+
}
|
|
498
|
+
/** Race a promise against a timeout so a hung page.evaluate can't wedge a mark. */
|
|
499
|
+
function withTimeout(p, ms, message) {
|
|
500
|
+
return Promise.race([
|
|
501
|
+
p,
|
|
502
|
+
new Promise((_, reject) => setTimeout(() => reject(new Error(message)), ms)),
|
|
503
|
+
]);
|
|
504
|
+
}
|
|
505
|
+
/** Open the recording context + page. Persistent (userDataDir) mode uses
|
|
506
|
+
* launchPersistentContext (a whole browser profile, no separate Browser
|
|
507
|
+
* handle); otherwise launch + newContext, optionally seeded with storageState.
|
|
508
|
+
* initScript applies either way; storageState and userDataDir are mutually
|
|
509
|
+
* exclusive and validated before this is called. */
|
|
510
|
+
async function openCaptureContext(chromium, opts) {
|
|
511
|
+
const args = [
|
|
512
|
+
"--no-sandbox",
|
|
513
|
+
"--disable-dev-shm-usage",
|
|
514
|
+
...(opts.cdpPort ? [`--remote-debugging-port=${opts.cdpPort}`] : []),
|
|
515
|
+
];
|
|
516
|
+
if (opts.userDataDir) {
|
|
517
|
+
const context = await chromium.launchPersistentContext(opts.userDataDir, {
|
|
518
|
+
headless: true,
|
|
519
|
+
args,
|
|
520
|
+
viewport: opts.viewport,
|
|
521
|
+
recordVideo: { dir: opts.recordDir, size: opts.recordSize },
|
|
522
|
+
});
|
|
523
|
+
if (opts.initScriptPath)
|
|
524
|
+
await context.addInitScript({ path: opts.initScriptPath });
|
|
525
|
+
const existing = context.pages();
|
|
526
|
+
const page = existing.length > 0 ? existing[0] : await context.newPage();
|
|
527
|
+
return { context, page, browser: null };
|
|
528
|
+
}
|
|
529
|
+
const browser = await chromium.launch({ headless: true, args });
|
|
530
|
+
const context = await browser.newContext({
|
|
531
|
+
viewport: opts.viewport,
|
|
532
|
+
recordVideo: { dir: opts.recordDir, size: opts.recordSize },
|
|
533
|
+
...(opts.storageStatePath ? { storageState: opts.storageStatePath } : {}),
|
|
534
|
+
});
|
|
535
|
+
if (opts.initScriptPath)
|
|
536
|
+
await context.addInitScript({ path: opts.initScriptPath });
|
|
537
|
+
const page = await context.newPage();
|
|
538
|
+
return { context, page, browser };
|
|
539
|
+
}
|
|
218
540
|
/**
|
|
219
541
|
* Streams a captured WebM through the raw-upload pipeline
|
|
220
542
|
* (initiate → chunks → finalize → complete). Shared by the one-shot `record`
|
|
@@ -230,7 +552,7 @@ async function uploadCapturedWebm(opts) {
|
|
|
230
552
|
recordingId,
|
|
231
553
|
createVideoRow: true,
|
|
232
554
|
sourcePlatform: "web",
|
|
233
|
-
sourceVersion:
|
|
555
|
+
sourceVersion: `mcp/${SERVER_VERSION}`,
|
|
234
556
|
});
|
|
235
557
|
uploadToken = String(init.uploadToken ?? "");
|
|
236
558
|
publicId = String(init.publicId ?? "");
|
|
@@ -261,7 +583,8 @@ async function uploadCapturedWebm(opts) {
|
|
|
261
583
|
name: opts.name,
|
|
262
584
|
description: opts.description,
|
|
263
585
|
sourcePlatform: "web",
|
|
264
|
-
sourceVersion:
|
|
586
|
+
sourceVersion: `mcp/${SERVER_VERSION}`,
|
|
587
|
+
...(opts.recordingKind ? { recordingKind: opts.recordingKind } : {}),
|
|
265
588
|
...(opts.narration && (opts.narration.text || opts.narration.notes?.length)
|
|
266
589
|
? { narration: opts.narration }
|
|
267
590
|
: {}),
|
|
@@ -286,7 +609,7 @@ function fail(message) {
|
|
|
286
609
|
};
|
|
287
610
|
}
|
|
288
611
|
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
|
|
289
|
-
const server = new McpServer({ name: "clipy", version:
|
|
612
|
+
const server = new McpServer({ name: "clipy", version: SERVER_VERSION });
|
|
290
613
|
const recordingIdSchema = z
|
|
291
614
|
.string()
|
|
292
615
|
.describe("The recording's public id (the slug in its share URL, e.g. 'a1b2c3d4e5f6') or the full https://clipy.online/video/<id> URL.");
|
|
@@ -749,7 +1072,7 @@ server.tool("get_agent_context", "ONE-CALL CONTEXT BUNDLE for a recording: metad
|
|
|
749
1072
|
return fail(e.message);
|
|
750
1073
|
}
|
|
751
1074
|
});
|
|
752
|
-
server.tool("record", "Record a web app HEADLESSLY and upload it as a Clipy recording, then return its share link + agent-context URL. Use this to capture the outcome of work you just did — e.g. after building a feature, record the running app so it can be shared or read back. Opens the given URL in a headless Chromium (works in cloud sandboxes, no display needed), records for `durationSeconds`, and streams the video into Clipy's pipeline. Requires (1) Playwright installed in this MCP server's environment (`npm i -g playwright && npx playwright install chromium`) and (2) the CLIPY_API_KEY to carry the 'ingest' scope. After it returns, call wait_for_artifacts then get_agent_context to read the transcript/summary.", {
|
|
1075
|
+
server.tool("record", "Record a web app HEADLESSLY and upload it as a Clipy recording, then return its share link + agent-context URL. Use this to capture the outcome of work you just did — e.g. after building a feature, record the running app so it can be shared or read back. Opens the given URL in a headless Chromium (works in cloud sandboxes, no display needed), records for `durationSeconds`, and streams the video into Clipy's pipeline. Set `type` so the summary reads the recording correctly, `viewports` to sweep multiple screen sizes into one video, and `storageState`/`initScript`/`userDataDir` to record behind a login. Requires (1) Playwright installed in this MCP server's environment (`npm i -g playwright && npx playwright install chromium`) and (2) the CLIPY_API_KEY to carry the 'ingest' scope. Recording the REAL Mac screen or a specific window (ScreenCaptureKit, real logged-in browser) is CLI-only — `clipy record --source mac-screen --window \"<app>\"` — and not available via MCP. Quick per-cookie / per-localStorage-key injection (the CLI's `--cookie` / `--local-storage`) is a CLI-only convenience; `storageState` covers the same need here. Auth note: `storageState` seeds exactly what it contains (cookies + localStorage) but can't reproduce a whole browser identity (IndexedDB, service workers, some cross-origin auth); for those, produce a storageState via an interactive `npx playwright open --save-storage=state.json <login-url>` first, or use `userDataDir` pointed at a DEDICATED (never live) profile directory. After it returns, call wait_for_artifacts then get_agent_context to read the transcript/summary.", {
|
|
753
1076
|
url: z.string().describe("The http(s) URL to open and record (e.g. http://localhost:3000)."),
|
|
754
1077
|
durationSeconds: z
|
|
755
1078
|
.number()
|
|
@@ -757,9 +1080,17 @@ server.tool("record", "Record a web app HEADLESSLY and upload it as a Clipy reco
|
|
|
757
1080
|
.min(2)
|
|
758
1081
|
.max(300)
|
|
759
1082
|
.optional()
|
|
760
|
-
.describe("How long to record after the page loads (default 15, max 300)."),
|
|
1083
|
+
.describe("How long to record after the page loads, per viewport pass (default 15, max 300)."),
|
|
761
1084
|
name: z.string().optional().describe("Optional title for the recording."),
|
|
762
1085
|
description: z.string().optional().describe("Optional description for the recording."),
|
|
1086
|
+
type: z
|
|
1087
|
+
.string()
|
|
1088
|
+
.optional()
|
|
1089
|
+
.describe("What the recording IS, so the AI summary doesn't misread it. One of: bug_report, feature_request, product_demo, walkthrough_tutorial, feedback_review, discussion_talk, other (aliases like bug/feature/demo/tutorial/review/talk accepted)."),
|
|
1090
|
+
viewports: z
|
|
1091
|
+
.string()
|
|
1092
|
+
.optional()
|
|
1093
|
+
.describe("Record several screen sizes sequentially into ONE video (for cross-size demos). Comma-separated aliases (mobile,tablet,desktop) or WIDTHxHEIGHT (e.g. '390x844,1440x900'). The frame is sized to the largest; each pass slow-scrolls the page and gets an auto chapter note. When set, width/height are ignored."),
|
|
763
1094
|
notes: z
|
|
764
1095
|
.array(z.object({
|
|
765
1096
|
atSeconds: z.number().min(0).describe("Position on the video timeline, in seconds."),
|
|
@@ -768,9 +1099,21 @@ server.tool("record", "Record a web app HEADLESSLY and upload it as a Clipy reco
|
|
|
768
1099
|
.max(200)
|
|
769
1100
|
.optional()
|
|
770
1101
|
.describe("Timestamped narration notes describing what the recording shows. Headless captures are silent, so these notes BECOME the recording's transcript — write them like chapters ('0s: homepage loads', '8s: the new export button appears')."),
|
|
771
|
-
|
|
772
|
-
|
|
773
|
-
|
|
1102
|
+
storageState: z
|
|
1103
|
+
.string()
|
|
1104
|
+
.optional()
|
|
1105
|
+
.describe("Path to a Playwright storageState JSON (cookies + localStorage) to record behind a login. Passed unchanged to the browser context; its contents are never logged. Mutually exclusive with userDataDir."),
|
|
1106
|
+
userDataDir: z
|
|
1107
|
+
.string()
|
|
1108
|
+
.optional()
|
|
1109
|
+
.describe("Path to a DEDICATED Chromium user-data (profile) directory to record with a full browser identity — launched via launchPersistentContext. Use a profile NO running browser is using (a live/locked profile is refused). Mutually exclusive with storageState."),
|
|
1110
|
+
initScript: z
|
|
1111
|
+
.string()
|
|
1112
|
+
.optional()
|
|
1113
|
+
.describe("Path to a JS file run in the page before every navigation (context.addInitScript) — e.g. to seed localStorage or stub an API. Contents are never logged."),
|
|
1114
|
+
width: z.number().int().min(320).max(3840).optional().describe("Viewport + video width (default 1280). Ignored when `viewports` is set."),
|
|
1115
|
+
height: z.number().int().min(240).max(2160).optional().describe("Viewport + video height (default 720). Ignored when `viewports` is set."),
|
|
1116
|
+
}, async ({ url, durationSeconds, name, description, type, viewports, notes, storageState, userDataDir, initScript, width, height }) => {
|
|
774
1117
|
// Validate the URL before spinning up a browser.
|
|
775
1118
|
let target;
|
|
776
1119
|
try {
|
|
@@ -785,8 +1128,47 @@ server.tool("record", "Record a web app HEADLESSLY and upload it as a Clipy reco
|
|
|
785
1128
|
if (!API_KEY) {
|
|
786
1129
|
return fail(`Missing CLIPY_API_KEY. Create an ingest-scoped key at ${API_URL}/settings/api-keys.`);
|
|
787
1130
|
}
|
|
1131
|
+
// Validate the structured inputs before touching a browser so an agent gets
|
|
1132
|
+
// instant, precise feedback on a bad `type` / `viewports` / auth path.
|
|
1133
|
+
let recordingKind;
|
|
1134
|
+
if (type) {
|
|
1135
|
+
const kind = normalizeRecordingKind(type);
|
|
1136
|
+
if (!kind)
|
|
1137
|
+
return fail(recordingKindError(type));
|
|
1138
|
+
recordingKind = kind;
|
|
1139
|
+
}
|
|
1140
|
+
let passes;
|
|
788
1141
|
const w = width ?? 1280;
|
|
789
1142
|
const h = height ?? 720;
|
|
1143
|
+
try {
|
|
1144
|
+
passes = viewports
|
|
1145
|
+
? parseViewports(viewports)
|
|
1146
|
+
: [{ width: w, height: h, label: `${w}×${h}` }];
|
|
1147
|
+
}
|
|
1148
|
+
catch (e) {
|
|
1149
|
+
return fail(e.message);
|
|
1150
|
+
}
|
|
1151
|
+
const frame = {
|
|
1152
|
+
width: Math.max(...passes.map((v) => v.width)),
|
|
1153
|
+
height: Math.max(...passes.map((v) => v.height)),
|
|
1154
|
+
};
|
|
1155
|
+
if (userDataDir && storageState) {
|
|
1156
|
+
return fail("userDataDir and storageState are mutually exclusive — userDataDir launches a whole persistent profile; storageState seeds a fresh context. Pick one.");
|
|
1157
|
+
}
|
|
1158
|
+
let storageStatePath;
|
|
1159
|
+
let userDataDirPath;
|
|
1160
|
+
let initScriptPath;
|
|
1161
|
+
try {
|
|
1162
|
+
if (storageState)
|
|
1163
|
+
storageStatePath = validateStorageStateFile(storageState);
|
|
1164
|
+
if (userDataDir)
|
|
1165
|
+
userDataDirPath = validateUserDataDir(userDataDir);
|
|
1166
|
+
if (initScript)
|
|
1167
|
+
initScriptPath = validateInitScriptFile(initScript);
|
|
1168
|
+
}
|
|
1169
|
+
catch (e) {
|
|
1170
|
+
return fail(e.message);
|
|
1171
|
+
}
|
|
790
1172
|
const forSec = durationSeconds ?? 15;
|
|
791
1173
|
const recordingId = randomUUID();
|
|
792
1174
|
const dir = join(tmpdir(), `clipy-mcp-record-${recordingId}`);
|
|
@@ -800,26 +1182,53 @@ server.tool("record", "Record a web app HEADLESSLY and upload it as a Clipy reco
|
|
|
800
1182
|
mkdirSync(dir, { recursive: true });
|
|
801
1183
|
let publicId = "";
|
|
802
1184
|
let sizeBytes = 0;
|
|
1185
|
+
const autoNotes = [];
|
|
803
1186
|
try {
|
|
804
1187
|
// ── Capture ──
|
|
805
1188
|
let videoPath;
|
|
806
|
-
const
|
|
807
|
-
|
|
808
|
-
|
|
1189
|
+
const opened = await openCaptureContext(chromium, {
|
|
1190
|
+
userDataDir: userDataDirPath,
|
|
1191
|
+
viewport: { width: frame.width, height: frame.height },
|
|
1192
|
+
recordDir: dir,
|
|
1193
|
+
recordSize: frame,
|
|
1194
|
+
storageStatePath,
|
|
1195
|
+
initScriptPath,
|
|
809
1196
|
});
|
|
1197
|
+
const { context, page } = opened;
|
|
810
1198
|
try {
|
|
811
|
-
|
|
812
|
-
|
|
813
|
-
|
|
814
|
-
|
|
815
|
-
|
|
816
|
-
|
|
817
|
-
|
|
818
|
-
|
|
819
|
-
|
|
820
|
-
|
|
1199
|
+
// captureStart is set AFTER the first meaningful paint so notes and pass
|
|
1200
|
+
// marks aren't anchored to the blank t=0 a compiling app shows.
|
|
1201
|
+
let captureStart = 0;
|
|
1202
|
+
for (const [i, vp] of passes.entries()) {
|
|
1203
|
+
if (viewports)
|
|
1204
|
+
await page.setViewportSize({ width: vp.width, height: vp.height }).catch(() => { });
|
|
1205
|
+
try {
|
|
1206
|
+
await page.goto(target.href, { waitUntil: "load", timeout: 30_000 });
|
|
1207
|
+
}
|
|
1208
|
+
catch {
|
|
1209
|
+
// slow SPA may not fire 'load' — record current state anyway
|
|
1210
|
+
}
|
|
1211
|
+
if (i === 0) {
|
|
1212
|
+
await waitForFirstPaint(page, frame);
|
|
1213
|
+
captureStart = Date.now();
|
|
1214
|
+
}
|
|
1215
|
+
if (viewports) {
|
|
1216
|
+
autoNotes.push({
|
|
1217
|
+
startMs: Math.max(0, Date.now() - captureStart),
|
|
1218
|
+
text: `[auto] Viewport pass ${i + 1}/${passes.length} start: ${vp.label}`,
|
|
1219
|
+
});
|
|
1220
|
+
// Slow-scroll so each size shows real layout, not just the fold.
|
|
1221
|
+
const steps = 6;
|
|
1222
|
+
const stepMs = (forSec * 1000) / steps;
|
|
1223
|
+
for (let s = 0; s < steps; s++) {
|
|
1224
|
+
await page.waitForTimeout(stepMs);
|
|
1225
|
+
await page.mouse.wheel(0, Math.round(vp.height * 0.7)).catch(() => { });
|
|
1226
|
+
}
|
|
1227
|
+
}
|
|
1228
|
+
else {
|
|
1229
|
+
await page.waitForTimeout(forSec * 1000);
|
|
1230
|
+
}
|
|
821
1231
|
}
|
|
822
|
-
await page.waitForTimeout(forSec * 1000);
|
|
823
1232
|
const video = page.video();
|
|
824
1233
|
await page.close();
|
|
825
1234
|
await context.close();
|
|
@@ -828,21 +1237,25 @@ server.tool("record", "Record a web app HEADLESSLY and upload it as a Clipy reco
|
|
|
828
1237
|
videoPath = await video.path();
|
|
829
1238
|
}
|
|
830
1239
|
finally {
|
|
831
|
-
|
|
1240
|
+
// Non-persistent: close the browser (also closes the context). Persistent:
|
|
1241
|
+
// no browser handle — make sure the context is closed either way.
|
|
1242
|
+
if (opened.browser)
|
|
1243
|
+
await opened.browser.close().catch(() => { });
|
|
1244
|
+
else
|
|
1245
|
+
await opened.context.close().catch(() => { });
|
|
832
1246
|
}
|
|
833
1247
|
// ── Upload through the same pipeline the web/desktop clients use ──
|
|
1248
|
+
const userNotes = (notes ?? []).map((n) => ({
|
|
1249
|
+
startMs: Math.round(n.atSeconds * 1000),
|
|
1250
|
+
text: n.text.trim(),
|
|
1251
|
+
}));
|
|
1252
|
+
const allNotes = [...autoNotes, ...userNotes].sort((a, b) => a.startMs - b.startMs);
|
|
834
1253
|
const uploaded = await uploadCapturedWebm({
|
|
835
1254
|
videoPath,
|
|
836
1255
|
name,
|
|
837
1256
|
description,
|
|
838
|
-
|
|
839
|
-
|
|
840
|
-
notes: notes.map((n) => ({
|
|
841
|
-
startMs: Math.round(n.atSeconds * 1000),
|
|
842
|
-
text: n.text.trim(),
|
|
843
|
-
})),
|
|
844
|
-
}
|
|
845
|
-
: undefined,
|
|
1257
|
+
recordingKind,
|
|
1258
|
+
narration: allNotes.length ? { notes: allNotes } : undefined,
|
|
846
1259
|
});
|
|
847
1260
|
publicId = uploaded.publicId;
|
|
848
1261
|
sizeBytes = uploaded.sizeBytes;
|
|
@@ -863,7 +1276,9 @@ server.tool("record", "Record a web app HEADLESSLY and upload it as a Clipy reco
|
|
|
863
1276
|
shareUrl: `${API_URL}/video/${publicId}`,
|
|
864
1277
|
agentContextUrl: `${API_URL}/api/agent-context/${publicId}`,
|
|
865
1278
|
sizeBytes,
|
|
866
|
-
recordedSeconds: forSec,
|
|
1279
|
+
recordedSeconds: forSec * passes.length,
|
|
1280
|
+
...(recordingKind ? { recordingKind } : {}),
|
|
1281
|
+
...(viewports ? { viewports: passes.map((p) => p.label) } : {}),
|
|
867
1282
|
next: "Processing runs in the background. Call wait_for_artifacts with this id (require:'all'), then get_agent_context / get_transcript to read it.",
|
|
868
1283
|
});
|
|
869
1284
|
});
|
|
@@ -883,11 +1298,11 @@ const SESSION_HARD_CAP_SEC = 1800;
|
|
|
883
1298
|
let activeSession = null;
|
|
884
1299
|
/** Result of a max-duration auto-stop, held for the next stop_recording call. */
|
|
885
1300
|
let autoStoppedResult = null;
|
|
886
|
-
|
|
887
|
-
|
|
888
|
-
|
|
889
|
-
|
|
890
|
-
};
|
|
1301
|
+
/** Append a mark. Defaults to the live recording clock; pass `atMs` to backdate
|
|
1302
|
+
* it to an explicit point on the timeline (add_marker's `atSeconds`). */
|
|
1303
|
+
function sessionMark(session, text, atMs) {
|
|
1304
|
+
const startMs = atMs != null ? Math.max(0, Math.round(atMs)) : Math.max(0, Date.now() - session.recordStartEpochMs);
|
|
1305
|
+
const note = { startMs, text };
|
|
891
1306
|
if (session.marks.length < 500)
|
|
892
1307
|
session.marks.push(note);
|
|
893
1308
|
return note;
|
|
@@ -908,12 +1323,24 @@ function finishSession(session, mode) {
|
|
|
908
1323
|
if (!video)
|
|
909
1324
|
throw new Error("browser did not produce a video");
|
|
910
1325
|
const videoPath = await video.path();
|
|
911
|
-
await session.browser
|
|
912
|
-
const
|
|
1326
|
+
await session.browser?.close().catch(() => { });
|
|
1327
|
+
const collected = [...session.marks];
|
|
1328
|
+
// If any assertions ran, lead the transcript with a verification summary
|
|
1329
|
+
// at 0ms so a reader sees the pass/fail/unverified tally up front.
|
|
1330
|
+
const assertionsRan = session.assertPassed + session.assertFailed + session.assertUnverified;
|
|
1331
|
+
if (assertionsRan > 0) {
|
|
1332
|
+
const unverifiedClause = session.assertUnverified > 0 ? `, ${session.assertUnverified} unverified` : "";
|
|
1333
|
+
collected.unshift({
|
|
1334
|
+
startMs: 0,
|
|
1335
|
+
text: `[verification] ${assertionsRan} assertion${assertionsRan === 1 ? "" : "s"}: ${session.assertPassed} passed, ${session.assertFailed} failed${unverifiedClause}`,
|
|
1336
|
+
});
|
|
1337
|
+
}
|
|
1338
|
+
const notes = collected.sort((a, b) => a.startMs - b.startMs);
|
|
913
1339
|
const uploaded = await uploadCapturedWebm({
|
|
914
1340
|
videoPath,
|
|
915
1341
|
name: session.name,
|
|
916
1342
|
description: session.description,
|
|
1343
|
+
recordingKind: session.recordingKind,
|
|
917
1344
|
narration: notes.length ? { notes } : undefined,
|
|
918
1345
|
});
|
|
919
1346
|
return {
|
|
@@ -926,7 +1353,11 @@ function finishSession(session, mode) {
|
|
|
926
1353
|
};
|
|
927
1354
|
}
|
|
928
1355
|
finally {
|
|
929
|
-
|
|
1356
|
+
// Persistent mode has no browser handle; make sure the context is closed.
|
|
1357
|
+
if (session.browser)
|
|
1358
|
+
await session.browser.close().catch(() => { });
|
|
1359
|
+
else
|
|
1360
|
+
await session.context.close().catch(() => { });
|
|
930
1361
|
try {
|
|
931
1362
|
rmSync(session.tmpDir, { recursive: true, force: true });
|
|
932
1363
|
}
|
|
@@ -939,10 +1370,14 @@ function finishSession(session, mode) {
|
|
|
939
1370
|
})();
|
|
940
1371
|
return session.finishing;
|
|
941
1372
|
}
|
|
942
|
-
server.tool("start_recording", "Start a RECORDING SESSION: opens the given URL in a headless Chromium that keeps recording in the background while you continue working. Use add_marker to narrate
|
|
1373
|
+
server.tool("start_recording", "Start a RECORDING SESSION: opens the given URL in a headless Chromium that keeps recording in the background while you continue working. Use add_marker to narrate (and optionally ASSERT on-screen state) at each step, add_chapter for before/after boundaries, then stop_recording to upload and get the share link. Set `type` for the recording kind, `storageState`/`initScript` to record behind a login, and `exposeCdp` to get a CDP endpoint you can drive with your own Playwright while it records. The session auto-stops and uploads by itself at maxSeconds (default 600) so a forgotten session can never run away. One session at a time. Requires Playwright + an ingest-scoped CLIPY_API_KEY (like the record tool). Recording the REAL Mac screen or a specific window (ScreenCaptureKit, real logged-in browser) is CLI-only — `clipy session start --source mac-screen --window \"<app>\"` — and not available via MCP. Quick per-cookie / per-localStorage-key injection (the CLI's `--cookie` / `--local-storage`) is CLI-only — use `storageState` here; and backdating a mark by a relative offset (the CLI's `--ago`) is CLI-only — use add_marker's `atSeconds`.", {
|
|
943
1374
|
url: z.string().describe("The http(s) URL to open and record (e.g. http://localhost:3000)."),
|
|
944
1375
|
name: z.string().optional().describe("Optional title for the recording."),
|
|
945
1376
|
description: z.string().optional().describe("Optional description for the recording."),
|
|
1377
|
+
type: z
|
|
1378
|
+
.string()
|
|
1379
|
+
.optional()
|
|
1380
|
+
.describe("What the recording IS, so the AI summary doesn't misread it. One of: bug_report, feature_request, product_demo, walkthrough_tutorial, feedback_review, discussion_talk, other (aliases like bug/feature/demo/tutorial/review/talk accepted)."),
|
|
946
1381
|
maxSeconds: z
|
|
947
1382
|
.number()
|
|
948
1383
|
.int()
|
|
@@ -950,9 +1385,25 @@ server.tool("start_recording", "Start a RECORDING SESSION: opens the given URL i
|
|
|
950
1385
|
.max(SESSION_HARD_CAP_SEC)
|
|
951
1386
|
.optional()
|
|
952
1387
|
.describe(`Auto-stop ceiling in seconds (default ${SESSION_DEFAULT_MAX_SEC}, hard cap ${SESSION_HARD_CAP_SEC}). On expiry the session uploads what it captured.`),
|
|
1388
|
+
exposeCdp: z
|
|
1389
|
+
.boolean()
|
|
1390
|
+
.optional()
|
|
1391
|
+
.describe("Open a Chrome DevTools Protocol endpoint on the recording browser (default false) so you can drive the page (navigate/click/type) with your own Playwright WHILE it records. When on, the result returns cdpHttpUrl + cdpUrl and driver notes, AND the recorded page exposes window.__clipyMark(text, {assertSelector, assertText, assertUrl, failMode}) + window.__clipyChapter(label) so a CDP driver can drop asserted marks/chapters with zero extra tool calls. OFF by default (while open, any local process can attach). The env var CLIPY_DISABLE_CDP=1 is a hard kill switch that forces it off."),
|
|
1392
|
+
storageState: z
|
|
1393
|
+
.string()
|
|
1394
|
+
.optional()
|
|
1395
|
+
.describe("Path to a Playwright storageState JSON (cookies + localStorage) to record behind a login. Passed unchanged to the browser context; its contents are never logged. Mutually exclusive with userDataDir."),
|
|
1396
|
+
userDataDir: z
|
|
1397
|
+
.string()
|
|
1398
|
+
.optional()
|
|
1399
|
+
.describe("Path to a DEDICATED Chromium user-data (profile) directory to record with a full browser identity (launchPersistentContext). Use a profile NO running browser is using (a live/locked profile is refused). Mutually exclusive with storageState."),
|
|
1400
|
+
initScript: z
|
|
1401
|
+
.string()
|
|
1402
|
+
.optional()
|
|
1403
|
+
.describe("Path to a JS file run in the page before every navigation (context.addInitScript). Contents are never logged."),
|
|
953
1404
|
width: z.number().int().min(320).max(3840).optional().describe("Viewport + video width (default 1280)."),
|
|
954
1405
|
height: z.number().int().min(240).max(2160).optional().describe("Viewport + video height (default 720)."),
|
|
955
|
-
}, async ({ url, name, description, maxSeconds, width, height }) => {
|
|
1406
|
+
}, async ({ url, name, description, type, maxSeconds, exposeCdp, storageState, userDataDir, initScript, width, height }) => {
|
|
956
1407
|
let target;
|
|
957
1408
|
try {
|
|
958
1409
|
target = new URL(url);
|
|
@@ -969,6 +1420,30 @@ server.tool("start_recording", "Start a RECORDING SESSION: opens the given URL i
|
|
|
969
1420
|
if (activeSession) {
|
|
970
1421
|
return fail("a recording session is already active — finish it with stop_recording or discard it with abort_recording first.");
|
|
971
1422
|
}
|
|
1423
|
+
let recordingKind;
|
|
1424
|
+
if (type) {
|
|
1425
|
+
const kind = normalizeRecordingKind(type);
|
|
1426
|
+
if (!kind)
|
|
1427
|
+
return fail(recordingKindError(type));
|
|
1428
|
+
recordingKind = kind;
|
|
1429
|
+
}
|
|
1430
|
+
if (userDataDir && storageState) {
|
|
1431
|
+
return fail("userDataDir and storageState are mutually exclusive — userDataDir launches a whole persistent profile; storageState seeds a fresh context. Pick one.");
|
|
1432
|
+
}
|
|
1433
|
+
let storageStatePath;
|
|
1434
|
+
let userDataDirPath;
|
|
1435
|
+
let initScriptPath;
|
|
1436
|
+
try {
|
|
1437
|
+
if (storageState)
|
|
1438
|
+
storageStatePath = validateStorageStateFile(storageState);
|
|
1439
|
+
if (userDataDir)
|
|
1440
|
+
userDataDirPath = validateUserDataDir(userDataDir);
|
|
1441
|
+
if (initScript)
|
|
1442
|
+
initScriptPath = validateInitScriptFile(initScript);
|
|
1443
|
+
}
|
|
1444
|
+
catch (e) {
|
|
1445
|
+
return fail(e.message);
|
|
1446
|
+
}
|
|
972
1447
|
let chromium;
|
|
973
1448
|
try {
|
|
974
1449
|
chromium = await loadChromium();
|
|
@@ -981,16 +1456,35 @@ server.tool("start_recording", "Start a RECORDING SESSION: opens the given URL i
|
|
|
981
1456
|
const maxSec = Math.min(maxSeconds ?? SESSION_DEFAULT_MAX_SEC, SESSION_HARD_CAP_SEC);
|
|
982
1457
|
const tmpDirPath = join(tmpdir(), `clipy-mcp-session-${randomUUID()}`);
|
|
983
1458
|
mkdirSync(tmpDirPath, { recursive: true });
|
|
1459
|
+
// CDP is OPT-IN and the env kill switch wins over the flag: only open a
|
|
1460
|
+
// debugging port when the caller asked AND CLIPY_DISABLE_CDP isn't set.
|
|
1461
|
+
const cdpDisabled = process.env.CLIPY_DISABLE_CDP === "1";
|
|
1462
|
+
const wantCdp = !!exposeCdp && !cdpDisabled;
|
|
984
1463
|
try {
|
|
985
|
-
const
|
|
986
|
-
|
|
987
|
-
|
|
988
|
-
});
|
|
989
|
-
const context = await browser.newContext({
|
|
1464
|
+
const cdpPort = wantCdp ? await pickFreePort().catch(() => 0) : 0;
|
|
1465
|
+
const opened = await openCaptureContext(chromium, {
|
|
1466
|
+
userDataDir: userDataDirPath,
|
|
990
1467
|
viewport: { width: w, height: h },
|
|
991
|
-
|
|
1468
|
+
recordDir: tmpDirPath,
|
|
1469
|
+
recordSize: { width: w, height: h },
|
|
1470
|
+
storageStatePath,
|
|
1471
|
+
initScriptPath,
|
|
1472
|
+
cdpPort: cdpPort || undefined,
|
|
992
1473
|
});
|
|
993
|
-
const page =
|
|
1474
|
+
const { context, page, browser } = opened;
|
|
1475
|
+
// Best-effort CDP discovery — the recording works even if it fails.
|
|
1476
|
+
let cdpUrl;
|
|
1477
|
+
let cdpHttpUrl;
|
|
1478
|
+
if (cdpPort) {
|
|
1479
|
+
cdpUrl = (await discoverCdpWsUrl(cdpPort)) ?? undefined;
|
|
1480
|
+
if (cdpUrl) {
|
|
1481
|
+
cdpHttpUrl = `http://127.0.0.1:${cdpPort}`;
|
|
1482
|
+
serverLog(`CDP endpoint ready at ${cdpHttpUrl}`);
|
|
1483
|
+
}
|
|
1484
|
+
else {
|
|
1485
|
+
serverLog(`CDP endpoint not reachable on port ${cdpPort} — browser drive unavailable`);
|
|
1486
|
+
}
|
|
1487
|
+
}
|
|
994
1488
|
const session = {
|
|
995
1489
|
browser,
|
|
996
1490
|
context,
|
|
@@ -999,12 +1493,52 @@ server.tool("start_recording", "Start a RECORDING SESSION: opens the given URL i
|
|
|
999
1493
|
url: target.href,
|
|
1000
1494
|
name,
|
|
1001
1495
|
description,
|
|
1496
|
+
recordingKind,
|
|
1002
1497
|
maxSec,
|
|
1003
1498
|
recordStartEpochMs: Date.now(),
|
|
1004
1499
|
marks: [],
|
|
1500
|
+
assertPassed: 0,
|
|
1501
|
+
assertFailed: 0,
|
|
1502
|
+
assertUnverified: 0,
|
|
1503
|
+
cdpUrl,
|
|
1504
|
+
cdpHttpUrl,
|
|
1005
1505
|
maxTimer: setTimeout(() => { }, 0),
|
|
1006
1506
|
finishing: null,
|
|
1007
1507
|
};
|
|
1508
|
+
// In-page CDP bridge: when CDP is exposed, install window.__clipyMark /
|
|
1509
|
+
// window.__clipyChapter so a driver attached over connectOverCDP can drop
|
|
1510
|
+
// asserted marks/chapters without any extra MCP tool call. exposeBinding
|
|
1511
|
+
// routes the page call back to THIS process (same annotations/caps as the
|
|
1512
|
+
// add_marker/add_chapter tools). Installed before navigation so it's live
|
|
1513
|
+
// on first load.
|
|
1514
|
+
if (wantCdp) {
|
|
1515
|
+
await context
|
|
1516
|
+
.exposeBinding("__clipyMark", async (_source, ...args) => {
|
|
1517
|
+
if (session.finishing)
|
|
1518
|
+
throw new Error("recording session is finishing — mark ignored");
|
|
1519
|
+
const markText = String(args[0] ?? "").slice(0, 1000);
|
|
1520
|
+
const { note, assertion, aborted } = await applyMark(session, markText, coerceMarkOpts(args[1]));
|
|
1521
|
+
return {
|
|
1522
|
+
atSeconds: Math.round(note.startMs / 100) / 10,
|
|
1523
|
+
...(assertion
|
|
1524
|
+
? assertion.status === "unverified"
|
|
1525
|
+
? { unverified: true, observed: assertion.observed }
|
|
1526
|
+
: { passed: assertion.status === "passed", observed: assertion.observed }
|
|
1527
|
+
: {}),
|
|
1528
|
+
...(aborted ? { aborted: true } : {}),
|
|
1529
|
+
};
|
|
1530
|
+
})
|
|
1531
|
+
.catch((e) => serverLog(`__clipyMark binding failed: ${firstLine(e.message)}`));
|
|
1532
|
+
await context
|
|
1533
|
+
.exposeBinding("__clipyChapter", async (_source, ...args) => {
|
|
1534
|
+
if (session.finishing)
|
|
1535
|
+
throw new Error("recording session is finishing — chapter ignored");
|
|
1536
|
+
const label = String(args[0] ?? "").trim().slice(0, 200);
|
|
1537
|
+
const note = sessionMark(session, `=== CHAPTER: ${label} ===`);
|
|
1538
|
+
return { atSeconds: Math.round(note.startMs / 100) / 10, chapter: label };
|
|
1539
|
+
})
|
|
1540
|
+
.catch((e) => serverLog(`__clipyChapter binding failed: ${firstLine(e.message)}`));
|
|
1541
|
+
}
|
|
1008
1542
|
clearTimeout(session.maxTimer);
|
|
1009
1543
|
session.maxTimer = setTimeout(() => {
|
|
1010
1544
|
// Auto-stop rail: upload the partial rather than record forever.
|
|
@@ -1043,11 +1577,22 @@ server.tool("start_recording", "Start a RECORDING SESSION: opens the given URL i
|
|
|
1043
1577
|
.catch(() => {
|
|
1044
1578
|
// slow SPA — the recording is running regardless
|
|
1045
1579
|
});
|
|
1580
|
+
// Describe the CDP outcome precisely: disabled-by-env, requested-but-
|
|
1581
|
+
// unreachable, or ready with the endpoints + driver gotchas.
|
|
1582
|
+
const cdpResult = cdpHttpUrl
|
|
1583
|
+
? { cdpHttpUrl, cdpUrl, cdpNote: CDP_DRIVER_NOTE }
|
|
1584
|
+
: exposeCdp && cdpDisabled
|
|
1585
|
+
? { cdpNote: "exposeCdp was requested but CLIPY_DISABLE_CDP=1 is set — no debugging port was opened." }
|
|
1586
|
+
: exposeCdp
|
|
1587
|
+
? { cdpNote: "exposeCdp was requested but the CDP endpoint could not be reached — the recording is running normally without a drive endpoint." }
|
|
1588
|
+
: {};
|
|
1046
1589
|
return ok({
|
|
1047
1590
|
state: "recording",
|
|
1048
1591
|
url: target.href,
|
|
1049
1592
|
maxSeconds: maxSec,
|
|
1050
|
-
|
|
1593
|
+
...(recordingKind ? { recordingKind } : {}),
|
|
1594
|
+
...cdpResult,
|
|
1595
|
+
next: "The session is recording. Use add_marker to narrate (and optionally assert) each step, add_chapter for before/after boundaries; call stop_recording when done (or abort_recording to discard). It auto-stops + uploads at the max duration.",
|
|
1051
1596
|
});
|
|
1052
1597
|
}
|
|
1053
1598
|
catch (e) {
|
|
@@ -1060,15 +1605,212 @@ server.tool("start_recording", "Start a RECORDING SESSION: opens the given URL i
|
|
|
1060
1605
|
return fail(e.message);
|
|
1061
1606
|
}
|
|
1062
1607
|
});
|
|
1063
|
-
|
|
1608
|
+
// --- Marker assertions ------------------------------------------------------
|
|
1609
|
+
// The session page is in-process, so an assertion is evaluated at mark time
|
|
1610
|
+
// against the live DOM/URL. The outcome is folded into the mark text so a
|
|
1611
|
+
// failure — or an inability to check — can never be misread as fact, and is
|
|
1612
|
+
// returned to the caller. Shared by add_marker AND the in-page CDP bridge.
|
|
1613
|
+
const ASSERT_EVAL_TIMEOUT_MS = 15_000;
|
|
1614
|
+
async function runMarkerAssertions(page, a) {
|
|
1615
|
+
const expected = [];
|
|
1616
|
+
const observed = [];
|
|
1617
|
+
let failed = false;
|
|
1618
|
+
// URL is cheap + reliable (no page.evaluate), so check it first.
|
|
1619
|
+
if (a.assertUrl) {
|
|
1620
|
+
const url = page.url();
|
|
1621
|
+
expected.push(`url matches ${JSON.stringify(a.assertUrl)}`);
|
|
1622
|
+
observed.push(`url ${JSON.stringify(url)}`);
|
|
1623
|
+
if (!globMatch(url, a.assertUrl))
|
|
1624
|
+
failed = true;
|
|
1625
|
+
}
|
|
1626
|
+
// DOM checks need page.evaluate — which can throw (invalid selector, page
|
|
1627
|
+
// detached mid-navigation) or hang (bound by ASSERT_EVAL_TIMEOUT_MS). Either
|
|
1628
|
+
// way we must NOT report a pass we couldn't confirm — that's `unverified`.
|
|
1629
|
+
if (a.assertSelector) {
|
|
1630
|
+
expected.push(a.assertText
|
|
1631
|
+
? `selector ${JSON.stringify(a.assertSelector)} present with text ${JSON.stringify(a.assertText)}`
|
|
1632
|
+
: `selector ${JSON.stringify(a.assertSelector)} present`);
|
|
1633
|
+
let probe;
|
|
1634
|
+
try {
|
|
1635
|
+
probe = await withTimeout(
|
|
1636
|
+
// `document` is a browser global; the cast keeps it out of the (DOM-less)
|
|
1637
|
+
// server lib. assertText is always paired with a selector (caller-enforced).
|
|
1638
|
+
page.evaluate((sel) => {
|
|
1639
|
+
const doc = globalThis.document;
|
|
1640
|
+
let selectorExists = null;
|
|
1641
|
+
let selectorText = null;
|
|
1642
|
+
if (sel && doc) {
|
|
1643
|
+
const el = doc.querySelector(sel);
|
|
1644
|
+
selectorExists = !!el;
|
|
1645
|
+
if (el)
|
|
1646
|
+
selectorText = (el.textContent || "").replace(/\s+/g, " ").trim();
|
|
1647
|
+
}
|
|
1648
|
+
return { selectorExists, selectorText };
|
|
1649
|
+
}, a.assertSelector ?? null), ASSERT_EVAL_TIMEOUT_MS, `page.evaluate timed out after ${ASSERT_EVAL_TIMEOUT_MS / 1000}s`);
|
|
1650
|
+
}
|
|
1651
|
+
catch (e) {
|
|
1652
|
+
const reason = firstLine(e.message) || "evaluate failed";
|
|
1653
|
+
// If something else already failed definitively, the failure stands;
|
|
1654
|
+
// otherwise this claim is UNVERIFIED — never a silent pass.
|
|
1655
|
+
if (failed) {
|
|
1656
|
+
observed.push(`selector could not be evaluated (${reason})`);
|
|
1657
|
+
return { status: "failed", expected: expected.join("; "), observed: observed.join("; ") };
|
|
1658
|
+
}
|
|
1659
|
+
return { status: "unverified", expected: expected.join("; "), observed: reason };
|
|
1660
|
+
}
|
|
1661
|
+
if (probe.selectorExists) {
|
|
1662
|
+
observed.push("selector present");
|
|
1663
|
+
}
|
|
1664
|
+
else {
|
|
1665
|
+
observed.push("selector NOT found");
|
|
1666
|
+
failed = true;
|
|
1667
|
+
}
|
|
1668
|
+
if (a.assertText) {
|
|
1669
|
+
const ref = probe.selectorText ?? "";
|
|
1670
|
+
observed.push(`text ${JSON.stringify(ref.slice(0, 200))}`);
|
|
1671
|
+
if (!ref.includes(a.assertText))
|
|
1672
|
+
failed = true;
|
|
1673
|
+
}
|
|
1674
|
+
}
|
|
1675
|
+
return { status: failed ? "failed" : "passed", expected: expected.join("; "), observed: observed.join("; ") };
|
|
1676
|
+
}
|
|
1677
|
+
/** Apply a mark to the session: strict assertText/assertSelector contract,
|
|
1678
|
+
* evaluate assertions, annotate the mark so pass/fail/unverified is explicit,
|
|
1679
|
+
* update the tally, and abort the session on a FAILED assert under failMode
|
|
1680
|
+
* 'abort'. Shared by the add_marker tool and the in-page CDP bridge. Throws on
|
|
1681
|
+
* the assertText-without-assertSelector contract violation (so a CDP driver
|
|
1682
|
+
* sees the rejection). */
|
|
1683
|
+
async function applyMark(session, text, opts) {
|
|
1684
|
+
if (opts.assertText && !opts.assertSelector) {
|
|
1685
|
+
throw new Error("assertText requires assertSelector — name the element whose text you're checking. A bare page-body text match is weak evidence, so it's rejected (same rule as the CLI's --assert-text / --assert-selector).");
|
|
1686
|
+
}
|
|
1687
|
+
const hasAssertion = !!(opts.assertSelector || opts.assertText || opts.assertUrl);
|
|
1688
|
+
let markText = text.trim();
|
|
1689
|
+
let assertion = null;
|
|
1690
|
+
if (hasAssertion) {
|
|
1691
|
+
try {
|
|
1692
|
+
assertion = await runMarkerAssertions(session.page, {
|
|
1693
|
+
assertSelector: opts.assertSelector,
|
|
1694
|
+
assertText: opts.assertText,
|
|
1695
|
+
assertUrl: opts.assertUrl,
|
|
1696
|
+
});
|
|
1697
|
+
}
|
|
1698
|
+
catch (e) {
|
|
1699
|
+
// Defensive: runMarkerAssertions swallows evaluate errors, but if anything
|
|
1700
|
+
// else throws, the claim is unverified — never a silent pass.
|
|
1701
|
+
assertion = { status: "unverified", expected: "assertion", observed: firstLine(e.message) || "evaluation failed" };
|
|
1702
|
+
}
|
|
1703
|
+
if (assertion.status === "passed") {
|
|
1704
|
+
session.assertPassed += 1;
|
|
1705
|
+
markText = `${markText} [assert ✓ ${assertion.observed}]`;
|
|
1706
|
+
}
|
|
1707
|
+
else if (assertion.status === "failed") {
|
|
1708
|
+
session.assertFailed += 1;
|
|
1709
|
+
markText = `${markText} [ASSERT ✗ expected ${assertion.expected}; observed ${assertion.observed}]`;
|
|
1710
|
+
}
|
|
1711
|
+
else {
|
|
1712
|
+
session.assertUnverified += 1;
|
|
1713
|
+
markText = `${markText} [ASSERT ⚠ could not evaluate — ${assertion.observed}]`;
|
|
1714
|
+
}
|
|
1715
|
+
}
|
|
1716
|
+
const note = sessionMark(session, markText, opts.atSeconds != null ? opts.atSeconds * 1000 : undefined);
|
|
1717
|
+
// failMode 'abort' discards the session ONLY on a definitive failure — never
|
|
1718
|
+
// on an unverified claim (inability to check must not nuke the recording).
|
|
1719
|
+
let aborted = false;
|
|
1720
|
+
if (assertion && assertion.status === "failed" && opts.failMode === "abort") {
|
|
1721
|
+
await finishSession(session, "abort").catch(() => { });
|
|
1722
|
+
aborted = true;
|
|
1723
|
+
}
|
|
1724
|
+
return { note, assertion, aborted };
|
|
1725
|
+
}
|
|
1726
|
+
/** Coerce a bridge-supplied (untrusted) options object into typed mark opts. */
|
|
1727
|
+
function coerceMarkOpts(raw) {
|
|
1728
|
+
const o = (raw && typeof raw === "object" ? raw : {});
|
|
1729
|
+
const str = (v) => (typeof v === "string" && v.trim() ? v : undefined);
|
|
1730
|
+
const failMode = o.failMode === "abort" ? "abort" : o.failMode === "warn" ? "warn" : undefined;
|
|
1731
|
+
return {
|
|
1732
|
+
assertSelector: str(o.assertSelector),
|
|
1733
|
+
assertText: str(o.assertText),
|
|
1734
|
+
assertUrl: str(o.assertUrl),
|
|
1735
|
+
failMode,
|
|
1736
|
+
};
|
|
1737
|
+
}
|
|
1738
|
+
server.tool("add_marker", "Drop a live-timestamped narration marker into the active recording session ('reproduced the bug', 'the fix renders correctly at mobile width'). Markers become the recording's transcript chapters, so narrate as you work — they are how the recording stays agent-readable despite having no audio. Optionally VERIFY on-screen state at the mark: assertSelector (element must exist), assertText (that element must contain the text — requires assertSelector), assertUrl (glob match on the live URL). A failed assertion is annotated into the mark as an explicit FAILURE (never written as fact), counted into the recording's verification summary, and — with failMode 'abort' — discards the whole session. Marks default to the live recording clock; pass atSeconds to backdate one.", {
|
|
1064
1739
|
text: z.string().min(1).max(1000).describe("What is happening right now."),
|
|
1065
|
-
|
|
1740
|
+
atSeconds: z
|
|
1741
|
+
.number()
|
|
1742
|
+
.min(0)
|
|
1743
|
+
.optional()
|
|
1744
|
+
.describe("Place the mark at this point on the recording timeline (seconds from the start), instead of the live clock — e.g. to annotate something that happened a few seconds ago. Clamped to >= 0. (The CLI's relative --ago shorthand is CLI-only; compute the absolute second and pass it here.)"),
|
|
1745
|
+
assertSelector: z
|
|
1746
|
+
.string()
|
|
1747
|
+
.optional()
|
|
1748
|
+
.describe("CSS selector that must exist on the page at this moment."),
|
|
1749
|
+
assertText: z
|
|
1750
|
+
.string()
|
|
1751
|
+
.optional()
|
|
1752
|
+
.describe("Substring that must appear in assertSelector's element text. REQUIRES assertSelector — a bare page-body text match is weak evidence and is rejected."),
|
|
1753
|
+
assertUrl: z
|
|
1754
|
+
.string()
|
|
1755
|
+
.optional()
|
|
1756
|
+
.describe("Glob the current page URL must match. `**` matches anything (including `/`); `*` matches within a path segment. e.g. 'http://localhost:3000/**/settings'."),
|
|
1757
|
+
failMode: z
|
|
1758
|
+
.enum(["warn", "abort"])
|
|
1759
|
+
.optional()
|
|
1760
|
+
.describe("On a FAILED assertion: 'warn' (default) records the failure and keeps recording; 'abort' discards the whole session (like abort_recording) and returns loudly. A passing assertion never aborts."),
|
|
1761
|
+
}, async ({ text, atSeconds, assertSelector, assertText, assertUrl, failMode }) => {
|
|
1762
|
+
if (!activeSession || activeSession.finishing) {
|
|
1763
|
+
return fail("no active recording session — call start_recording first.");
|
|
1764
|
+
}
|
|
1765
|
+
// Stricter contract (matches the CLI): assertText needs a selector to name
|
|
1766
|
+
// WHICH element's text is checked — a whole-page-body match is weak evidence.
|
|
1767
|
+
if (assertText && !assertSelector) {
|
|
1768
|
+
return fail("assertText requires assertSelector — name the element whose text you're checking. A bare page-body text match is weak evidence, so it's rejected (same rule as the CLI's --assert-text / --assert-selector).");
|
|
1769
|
+
}
|
|
1770
|
+
const session = activeSession;
|
|
1771
|
+
const { note, assertion, aborted } = await applyMark(session, text, {
|
|
1772
|
+
atSeconds,
|
|
1773
|
+
assertSelector,
|
|
1774
|
+
assertText,
|
|
1775
|
+
assertUrl,
|
|
1776
|
+
failMode,
|
|
1777
|
+
});
|
|
1778
|
+
if (aborted && assertion) {
|
|
1779
|
+
return ok({
|
|
1780
|
+
aborted: true,
|
|
1781
|
+
assertionFailed: true,
|
|
1782
|
+
marker: note.text,
|
|
1783
|
+
atSeconds: Math.round(note.startMs / 100) / 10,
|
|
1784
|
+
expected: assertion.expected,
|
|
1785
|
+
observed: assertion.observed,
|
|
1786
|
+
note: "ASSERTION FAILED and failMode was 'abort' — the recording session was DISCARDED. Nothing was uploaded.",
|
|
1787
|
+
});
|
|
1788
|
+
}
|
|
1789
|
+
return ok({
|
|
1790
|
+
atSeconds: Math.round(note.startMs / 100) / 10,
|
|
1791
|
+
text: note.text,
|
|
1792
|
+
...(assertion
|
|
1793
|
+
? assertion.status === "unverified"
|
|
1794
|
+
? { assertion: { verified: false, unverified: true, observed: assertion.observed }, unverified: true }
|
|
1795
|
+
: { assertion: { passed: assertion.status === "passed", observed: assertion.observed } }
|
|
1796
|
+
: {}),
|
|
1797
|
+
totalMarkers: session.marks.length,
|
|
1798
|
+
});
|
|
1799
|
+
});
|
|
1800
|
+
server.tool("add_chapter", "Drop a CHAPTER boundary into the active recording session — a mark reading '=== CHAPTER: <label> ===' at the live clock. Use it to split a recording into named sections. Ideal for before/after recordings (e.g. a PR review: demo the base branch, add_chapter \"AFTER — fix applied\", swap branches, demo again, then stop_recording). Chapters ride the transcript so a reader (or the summary) can see the boundaries.", {
|
|
1801
|
+
label: z
|
|
1802
|
+
.string()
|
|
1803
|
+
.min(1)
|
|
1804
|
+
.max(200)
|
|
1805
|
+
.describe("Short chapter label, e.g. 'BEFORE — bug present' or 'AFTER — fix applied'."),
|
|
1806
|
+
}, async ({ label }) => {
|
|
1066
1807
|
if (!activeSession || activeSession.finishing) {
|
|
1067
1808
|
return fail("no active recording session — call start_recording first.");
|
|
1068
1809
|
}
|
|
1069
|
-
const note = sessionMark(activeSession,
|
|
1810
|
+
const note = sessionMark(activeSession, `=== CHAPTER: ${label.trim()} ===`);
|
|
1070
1811
|
return ok({
|
|
1071
1812
|
atSeconds: Math.round(note.startMs / 100) / 10,
|
|
1813
|
+
chapter: label.trim(),
|
|
1072
1814
|
text: note.text,
|
|
1073
1815
|
totalMarkers: activeSession.marks.length,
|
|
1074
1816
|
});
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@clipy/mcp",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.8.1",
|
|
4
4
|
"mcpName": "online.clipy/mcp",
|
|
5
5
|
"description": "Model Context Protocol (MCP) server for Clipy — give Claude, Cursor, and other AI agents read access to your screen recordings' transcripts, AI summaries, and key moments with frames.",
|
|
6
6
|
"license": "MIT",
|