@clipy/mcp 0.7.0 → 0.8.0

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.
Files changed (4) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +63 -16
  3. package/dist/index.js +586 -45
  4. package/package.json +1 -1
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Codersera (clipy.online)
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,13 +1,11 @@
1
- > **⚠️ This directory is no longer the canonical source.**
2
- > The official Clipy MCP server now lives at
3
- > **https://github.com/manovagyanik1/clipy-mcp** (public, MIT) — develop and
4
- > publish `@clipy/mcp` from there. This copy remains temporarily for
5
- > reference and will be removed in a future cleanup.
6
-
7
1
  # @clipy/mcp
8
2
 
9
3
  Give your AI agent access to your [Clipy](https://clipy.online) screen recordings.
10
4
 
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.
8
+
11
9
  This is a [Model Context Protocol](https://modelcontextprotocol.io) (MCP) server. It lets
12
10
  Claude, Cursor, Windsurf, and other MCP-capable agents **search your recordings and read
13
11
  their transcripts and AI summaries** — so you can do things like _"turn this bug-report
@@ -15,14 +13,32 @@ recording into a Linear ticket"_ without leaving your agent — and, with the `r
15
13
  tool, **record a web app headlessly** and get it back as a Clipy recording (_"build the
16
14
  feature, then record the outcome"_).
17
15
 
18
- Every tool except `record` is **read-only**. `record` is the only one that creates a
19
- recording, and only when your key carries the `ingest` scope.
16
+ The read tools need the `recordings:read` scope, which every key gets by default. The
17
+ write tools — `record`, the session tools (`start_recording`, `add_marker`, `add_chapter`,
18
+ `stop_recording`, `abort_recording`), and `replace_transcript` — additionally need the
19
+ key to carry the `ingest` scope ("Record & upload"), which the server enforces. A
20
+ `recordings:read`-only key can read your recordings but cannot create, modify, or
21
+ delete anything.
20
22
 
21
23
  ## Setup
22
24
 
23
- 1. Create a free API key at **https://clipy.online/settings/api-keys** (it looks like
24
- `clipy_sk_live_…`). Copy it — it's shown only once.
25
- 2. Add the server to your MCP client.
25
+ This is a headless server process, so it authenticates with a Clipy API key in the
26
+ `CLIPY_API_KEY` env var (it looks like `clipy_sk_live_…`). The easiest way to get one is
27
+ the Clipy CLI's browser login:
28
+
29
+ ```bash
30
+ npx @clipy/cli@latest login
31
+ ```
32
+
33
+ It opens your browser; click **Approve** once. The key is saved to
34
+ `~/.config/clipy/config.json` — copy its `apiKey` value into `CLIPY_API_KEY` when you add
35
+ the server below.
36
+
37
+ **Prefer to mint one by hand?** Create a key at
38
+ **https://clipy.online/settings/api-keys** instead (it's shown only once — copy it
39
+ immediately).
40
+
41
+ Then add the server to your MCP client.
26
42
 
27
43
  ### Claude Code
28
44
 
@@ -81,15 +97,21 @@ or the Windsurf MCP config) directly:
81
97
  | `download_recording` | Download the MP4 locally so you can clip it or extract frames yourself (e.g. with ffmpeg). |
82
98
  | `get_key_moments` | Key moments: timestamps, captions, and click coordinates. |
83
99
  | `get_agent_context` | The full agent-context bundle (summary + key moments + transcript) as markdown. |
84
- | `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). |
85
- | `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. |
86
- | `add_marker` | Drop a live-timestamped narration marker into the active session — markers become the recording's transcript chapters. Navigations + console errors are added automatically as `[auto]` marks. |
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`/`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`/`initScript`, and `exposeCdp` (get a CDP endpoint 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`); a failed assertion is annotated as an explicit failure and can abort the session. 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). |
87
104
  | `stop_recording` | Finish the session: close the browser, upload, return the share + agent-context URLs. |
88
105
  | `abort_recording` | Discard the active session; nothing is uploaded. |
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. |
89
107
 
90
108
  Read tools accept a recording's **public id** (the slug in its share URL) or the full
91
109
  `https://clipy.online/video/<id>` URL.
92
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
+
93
115
  ### Using `record`
94
116
 
95
117
  `record` opens a URL in a headless Chromium (works in CI / cloud sandboxes, no display),
@@ -103,8 +125,33 @@ records for a few seconds, and streams it into Clipy — then returns the id so
103
125
  2. An API key with the **"Record & upload" (ingest)** permission — choose it when you mint
104
126
  the key at [clipy.online/settings/api-keys](https://clipy.online/settings/api-keys).
105
127
 
106
- Parameters: `url` (required, http/https), `durationSeconds` (default 15, max 300), `name`,
107
- `width`/`height` (default 1280×720).
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
+ ### Driving the recorded page over CDP (`start_recording` + `exposeCdp: true`)
137
+
138
+ Pass `exposeCdp: true` to `start_recording` and the recording browser opens a Chrome
139
+ DevTools Protocol endpoint; the result returns `cdpHttpUrl` + `cdpUrl`. Connect your own
140
+ Playwright and drive the page while Clipy records it:
141
+
142
+ ```js
143
+ const { chromium } = require("playwright");
144
+ const browser = await chromium.connectOverCDP(cdpHttpUrl);
145
+ const page = browser.contexts()[0].pages()[0]; // the page being recorded
146
+ await page.goto("http://localhost:3000/settings");
147
+ await browser.close(); // detaches; the recording keeps going
148
+ ```
149
+
150
+ It's **off by default** — while it's open, any local process can attach to that browser.
151
+ `CLIPY_DISABLE_CDP=1` is a hard kill switch that forces it off. Gotchas: the recorded page
152
+ is `contexts()[0].pages()[0]` (a new context you open won't be captured); `page.viewportSize()`
153
+ reads `null` over a CDP attach; and to change the viewport use `newCDPSession` +
154
+ `Emulation.setDeviceMetricsOverride`, not `setViewportSize`.
108
155
 
109
156
  ## Config
110
157
 
package/dist/index.js CHANGED
@@ -10,9 +10,12 @@
10
10
  * headline write use case is "build a feature, then record the outcome."
11
11
  *
12
12
  * Auth: a personal API key (`CLIPY_API_KEY`, looks like `clipy_sk_live_…`),
13
- * minted at https://clipy.online/settings/api-keys. Read tools need any key;
14
- * the `record` tool additionally needs the key to carry the `ingest` scope
15
- * ("Record & upload"). Everything except `record` is read-only.
13
+ * minted at https://clipy.online/settings/api-keys. Read tools need the default
14
+ * `recordings:read` scope; the write tools — `record`, the session tools
15
+ * (start_recording, add_marker, stop_recording, abort_recording), and
16
+ * `replace_transcript` — additionally need the key to carry the `ingest` scope
17
+ * ("Record & upload"), enforced server-side. A `recordings:read`-only key cannot
18
+ * create, modify, or delete anything.
16
19
  *
17
20
  * Config (env):
18
21
  * CLIPY_API_KEY (required) your personal key
@@ -21,14 +24,16 @@
21
24
  import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
22
25
  import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
23
26
  import { z } from "zod";
24
- import { closeSync, createWriteStream, mkdirSync, openSync, readSync, rmSync, statSync } from "node:fs";
27
+ import { closeSync, createWriteStream, mkdirSync, openSync, readFileSync, readSync, rmSync, statSync } from "node:fs";
25
28
  import { randomUUID } from "node:crypto";
29
+ import { createServer } from "node:net";
26
30
  import { tmpdir } from "node:os";
27
31
  import { join, resolve } from "node:path";
28
32
  import { Readable } from "node:stream";
29
33
  import { pipeline } from "node:stream/promises";
30
34
  const API_URL = (process.env.CLIPY_API_URL || "https://clipy.online").replace(/\/+$/, "");
31
35
  const API_KEY = process.env.CLIPY_API_KEY;
36
+ const SERVER_VERSION = "0.8.0";
32
37
  // The key is checked lazily (per tool call, not at startup) so the server can
33
38
  // start and answer introspection (initialize / tools/list) in keyless
34
39
  // environments like directory health checks.
@@ -51,7 +56,7 @@ async function api(path) {
51
56
  headers: {
52
57
  Authorization: `Bearer ${API_KEY}`,
53
58
  Accept: "application/json",
54
- "User-Agent": "clipy-mcp/0.7.0",
59
+ "User-Agent": `clipy-mcp/${SERVER_VERSION}`,
55
60
  },
56
61
  signal: controller.signal,
57
62
  });
@@ -99,7 +104,7 @@ async function apiPostJson(path, payload, method = "POST") {
99
104
  Authorization: `Bearer ${API_KEY}`,
100
105
  "Content-Type": "application/json",
101
106
  Accept: "application/json",
102
- "User-Agent": "clipy-mcp/0.7.0",
107
+ "User-Agent": `clipy-mcp/${SERVER_VERSION}`,
103
108
  },
104
109
  body: JSON.stringify(payload),
105
110
  signal: controller.signal,
@@ -156,7 +161,7 @@ async function apiPostChunk(recordingId, uploadToken, partNumber, bytes) {
156
161
  try {
157
162
  res = await fetch(`${API_URL}/api/videos/raw-upload/chunk`, {
158
163
  method: "POST",
159
- headers: { Authorization: `Bearer ${API_KEY}`, "User-Agent": "clipy-mcp/0.7.0" },
164
+ headers: { Authorization: `Bearer ${API_KEY}`, "User-Agent": `clipy-mcp/${SERVER_VERSION}` },
160
165
  body: form,
161
166
  signal: controller.signal,
162
167
  });
@@ -212,6 +217,250 @@ function validateWebmFile(videoPath) {
212
217
  }
213
218
  return size;
214
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
+ // --- URL-glob matching (add_marker assertUrl) ------------------------------
380
+ // `**` matches anything (including `/`); `*` matches within a path segment.
381
+ function globToRegExp(glob) {
382
+ let re = "";
383
+ for (let i = 0; i < glob.length; i++) {
384
+ const ch = glob[i];
385
+ if (ch === "*") {
386
+ if (glob[i + 1] === "*") {
387
+ re += ".*";
388
+ i++;
389
+ }
390
+ else {
391
+ re += "[^/]*";
392
+ }
393
+ }
394
+ else {
395
+ re += ch.replace(/[.+?^${}()|[\]\\]/g, "\\$&");
396
+ }
397
+ }
398
+ return new RegExp(`^${re}$`);
399
+ }
400
+ function globMatch(value, glob) {
401
+ try {
402
+ return globToRegExp(glob).test(value);
403
+ }
404
+ catch {
405
+ return false;
406
+ }
407
+ }
408
+ // --- Auth-state inputs (storageState / initScript) -------------------------
409
+ // Same semantics as the CLI: storageState is a Playwright storageState JSON
410
+ // passed unchanged to newContext; initScript runs via context.addInitScript
411
+ // before navigation. Both validated with clear errors; contents NEVER logged.
412
+ function validateReadableFile(label, p) {
413
+ const resolved = resolve(p);
414
+ let st;
415
+ try {
416
+ st = statSync(resolved);
417
+ }
418
+ catch {
419
+ throw new Error(`${label} file not found: ${resolved}`);
420
+ }
421
+ if (!st.isFile())
422
+ throw new Error(`${label} path is not a file: ${resolved}`);
423
+ return resolved;
424
+ }
425
+ /** Validate a Playwright storageState JSON path — resolves, confirms it parses
426
+ * and carries the expected shape, and returns the absolute path (never its
427
+ * contents, which may hold cookies/tokens). */
428
+ function validateStorageStateFile(p) {
429
+ const resolved = validateReadableFile("storageState", p);
430
+ let raw;
431
+ try {
432
+ raw = readFileSync(resolved, "utf8");
433
+ }
434
+ catch {
435
+ throw new Error(`storageState file is not readable: ${resolved}`);
436
+ }
437
+ let parsed;
438
+ try {
439
+ parsed = JSON.parse(raw);
440
+ }
441
+ catch {
442
+ throw new Error(`storageState file is not valid JSON (Playwright storageState format expected): ${resolved}`);
443
+ }
444
+ if (typeof parsed !== "object" ||
445
+ parsed === null ||
446
+ (!("cookies" in parsed) && !("origins" in parsed))) {
447
+ throw new Error(`storageState file does not look like a Playwright storageState JSON (expected "cookies"/"origins" keys): ${resolved}`);
448
+ }
449
+ return resolved;
450
+ }
451
+ /** Validate an init-script path (resolves + confirms it is a readable file);
452
+ * returns the absolute path, never its contents. */
453
+ function validateInitScriptFile(p) {
454
+ const resolved = validateReadableFile("initScript", p);
455
+ try {
456
+ // Confirm readability without retaining the contents.
457
+ closeSync(openSync(resolved, "r"));
458
+ }
459
+ catch {
460
+ throw new Error(`initScript file is not readable: ${resolved}`);
461
+ }
462
+ return resolved;
463
+ }
215
464
  /**
216
465
  * Streams a captured WebM through the raw-upload pipeline
217
466
  * (initiate → chunks → finalize → complete). Shared by the one-shot `record`
@@ -227,7 +476,7 @@ async function uploadCapturedWebm(opts) {
227
476
  recordingId,
228
477
  createVideoRow: true,
229
478
  sourcePlatform: "web",
230
- sourceVersion: "mcp/0.7.0",
479
+ sourceVersion: `mcp/${SERVER_VERSION}`,
231
480
  });
232
481
  uploadToken = String(init.uploadToken ?? "");
233
482
  publicId = String(init.publicId ?? "");
@@ -258,7 +507,8 @@ async function uploadCapturedWebm(opts) {
258
507
  name: opts.name,
259
508
  description: opts.description,
260
509
  sourcePlatform: "web",
261
- sourceVersion: "mcp/0.7.0",
510
+ sourceVersion: `mcp/${SERVER_VERSION}`,
511
+ ...(opts.recordingKind ? { recordingKind: opts.recordingKind } : {}),
262
512
  ...(opts.narration && (opts.narration.text || opts.narration.notes?.length)
263
513
  ? { narration: opts.narration }
264
514
  : {}),
@@ -283,7 +533,7 @@ function fail(message) {
283
533
  };
284
534
  }
285
535
  const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
286
- const server = new McpServer({ name: "clipy", version: "0.7.0" });
536
+ const server = new McpServer({ name: "clipy", version: SERVER_VERSION });
287
537
  const recordingIdSchema = z
288
538
  .string()
289
539
  .describe("The recording's public id (the slug in its share URL, e.g. 'a1b2c3d4e5f6') or the full https://clipy.online/video/<id> URL.");
@@ -746,7 +996,7 @@ server.tool("get_agent_context", "ONE-CALL CONTEXT BUNDLE for a recording: metad
746
996
  return fail(e.message);
747
997
  }
748
998
  });
749
- 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.", {
999
+ 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` 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. After it returns, call wait_for_artifacts then get_agent_context to read the transcript/summary.", {
750
1000
  url: z.string().describe("The http(s) URL to open and record (e.g. http://localhost:3000)."),
751
1001
  durationSeconds: z
752
1002
  .number()
@@ -754,9 +1004,17 @@ server.tool("record", "Record a web app HEADLESSLY and upload it as a Clipy reco
754
1004
  .min(2)
755
1005
  .max(300)
756
1006
  .optional()
757
- .describe("How long to record after the page loads (default 15, max 300)."),
1007
+ .describe("How long to record after the page loads, per viewport pass (default 15, max 300)."),
758
1008
  name: z.string().optional().describe("Optional title for the recording."),
759
1009
  description: z.string().optional().describe("Optional description for the recording."),
1010
+ type: z
1011
+ .string()
1012
+ .optional()
1013
+ .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)."),
1014
+ viewports: z
1015
+ .string()
1016
+ .optional()
1017
+ .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."),
760
1018
  notes: z
761
1019
  .array(z.object({
762
1020
  atSeconds: z.number().min(0).describe("Position on the video timeline, in seconds."),
@@ -765,9 +1023,17 @@ server.tool("record", "Record a web app HEADLESSLY and upload it as a Clipy reco
765
1023
  .max(200)
766
1024
  .optional()
767
1025
  .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')."),
768
- width: z.number().int().min(320).max(3840).optional().describe("Viewport + video width (default 1280)."),
769
- height: z.number().int().min(240).max(2160).optional().describe("Viewport + video height (default 720)."),
770
- }, async ({ url, durationSeconds, name, description, notes, width, height }) => {
1026
+ storageState: z
1027
+ .string()
1028
+ .optional()
1029
+ .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."),
1030
+ initScript: z
1031
+ .string()
1032
+ .optional()
1033
+ .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."),
1034
+ width: z.number().int().min(320).max(3840).optional().describe("Viewport + video width (default 1280). Ignored when `viewports` is set."),
1035
+ height: z.number().int().min(240).max(2160).optional().describe("Viewport + video height (default 720). Ignored when `viewports` is set."),
1036
+ }, async ({ url, durationSeconds, name, description, type, viewports, notes, storageState, initScript, width, height }) => {
771
1037
  // Validate the URL before spinning up a browser.
772
1038
  let target;
773
1039
  try {
@@ -782,8 +1048,41 @@ server.tool("record", "Record a web app HEADLESSLY and upload it as a Clipy reco
782
1048
  if (!API_KEY) {
783
1049
  return fail(`Missing CLIPY_API_KEY. Create an ingest-scoped key at ${API_URL}/settings/api-keys.`);
784
1050
  }
1051
+ // Validate the structured inputs before touching a browser so an agent gets
1052
+ // instant, precise feedback on a bad `type` / `viewports` / auth path.
1053
+ let recordingKind;
1054
+ if (type) {
1055
+ const kind = normalizeRecordingKind(type);
1056
+ if (!kind)
1057
+ return fail(recordingKindError(type));
1058
+ recordingKind = kind;
1059
+ }
1060
+ let passes;
785
1061
  const w = width ?? 1280;
786
1062
  const h = height ?? 720;
1063
+ try {
1064
+ passes = viewports
1065
+ ? parseViewports(viewports)
1066
+ : [{ width: w, height: h, label: `${w}×${h}` }];
1067
+ }
1068
+ catch (e) {
1069
+ return fail(e.message);
1070
+ }
1071
+ const frame = {
1072
+ width: Math.max(...passes.map((v) => v.width)),
1073
+ height: Math.max(...passes.map((v) => v.height)),
1074
+ };
1075
+ let storageStatePath;
1076
+ let initScriptPath;
1077
+ try {
1078
+ if (storageState)
1079
+ storageStatePath = validateStorageStateFile(storageState);
1080
+ if (initScript)
1081
+ initScriptPath = validateInitScriptFile(initScript);
1082
+ }
1083
+ catch (e) {
1084
+ return fail(e.message);
1085
+ }
787
1086
  const forSec = durationSeconds ?? 15;
788
1087
  const recordingId = randomUUID();
789
1088
  const dir = join(tmpdir(), `clipy-mcp-record-${recordingId}`);
@@ -797,6 +1096,7 @@ server.tool("record", "Record a web app HEADLESSLY and upload it as a Clipy reco
797
1096
  mkdirSync(dir, { recursive: true });
798
1097
  let publicId = "";
799
1098
  let sizeBytes = 0;
1099
+ const autoNotes = [];
800
1100
  try {
801
1101
  // ── Capture ──
802
1102
  let videoPath;
@@ -806,17 +1106,46 @@ server.tool("record", "Record a web app HEADLESSLY and upload it as a Clipy reco
806
1106
  });
807
1107
  try {
808
1108
  const context = await browser.newContext({
809
- viewport: { width: w, height: h },
810
- recordVideo: { dir, size: { width: w, height: h } },
1109
+ viewport: { width: frame.width, height: frame.height },
1110
+ recordVideo: { dir, size: frame },
1111
+ ...(storageStatePath ? { storageState: storageStatePath } : {}),
811
1112
  });
1113
+ if (initScriptPath)
1114
+ await context.addInitScript({ path: initScriptPath });
812
1115
  const page = await context.newPage();
813
- try {
814
- await page.goto(target.href, { waitUntil: "load", timeout: 30_000 });
815
- }
816
- catch {
817
- // slow SPA may not fire 'load' — record current state anyway
1116
+ // captureStart is set AFTER the first meaningful paint so notes and pass
1117
+ // marks aren't anchored to the blank t=0 a compiling app shows.
1118
+ let captureStart = 0;
1119
+ for (const [i, vp] of passes.entries()) {
1120
+ if (viewports)
1121
+ await page.setViewportSize({ width: vp.width, height: vp.height }).catch(() => { });
1122
+ try {
1123
+ await page.goto(target.href, { waitUntil: "load", timeout: 30_000 });
1124
+ }
1125
+ catch {
1126
+ // slow SPA may not fire 'load' — record current state anyway
1127
+ }
1128
+ if (i === 0) {
1129
+ await waitForFirstPaint(page, frame);
1130
+ captureStart = Date.now();
1131
+ }
1132
+ if (viewports) {
1133
+ autoNotes.push({
1134
+ startMs: Math.max(0, Date.now() - captureStart),
1135
+ text: `[auto] Viewport pass ${i + 1}/${passes.length} start: ${vp.label}`,
1136
+ });
1137
+ // Slow-scroll so each size shows real layout, not just the fold.
1138
+ const steps = 6;
1139
+ const stepMs = (forSec * 1000) / steps;
1140
+ for (let s = 0; s < steps; s++) {
1141
+ await page.waitForTimeout(stepMs);
1142
+ await page.mouse.wheel(0, Math.round(vp.height * 0.7)).catch(() => { });
1143
+ }
1144
+ }
1145
+ else {
1146
+ await page.waitForTimeout(forSec * 1000);
1147
+ }
818
1148
  }
819
- await page.waitForTimeout(forSec * 1000);
820
1149
  const video = page.video();
821
1150
  await page.close();
822
1151
  await context.close();
@@ -828,18 +1157,17 @@ server.tool("record", "Record a web app HEADLESSLY and upload it as a Clipy reco
828
1157
  await browser.close().catch(() => { });
829
1158
  }
830
1159
  // ── Upload through the same pipeline the web/desktop clients use ──
1160
+ const userNotes = (notes ?? []).map((n) => ({
1161
+ startMs: Math.round(n.atSeconds * 1000),
1162
+ text: n.text.trim(),
1163
+ }));
1164
+ const allNotes = [...autoNotes, ...userNotes].sort((a, b) => a.startMs - b.startMs);
831
1165
  const uploaded = await uploadCapturedWebm({
832
1166
  videoPath,
833
1167
  name,
834
1168
  description,
835
- narration: notes?.length
836
- ? {
837
- notes: notes.map((n) => ({
838
- startMs: Math.round(n.atSeconds * 1000),
839
- text: n.text.trim(),
840
- })),
841
- }
842
- : undefined,
1169
+ recordingKind,
1170
+ narration: allNotes.length ? { notes: allNotes } : undefined,
843
1171
  });
844
1172
  publicId = uploaded.publicId;
845
1173
  sizeBytes = uploaded.sizeBytes;
@@ -860,7 +1188,9 @@ server.tool("record", "Record a web app HEADLESSLY and upload it as a Clipy reco
860
1188
  shareUrl: `${API_URL}/video/${publicId}`,
861
1189
  agentContextUrl: `${API_URL}/api/agent-context/${publicId}`,
862
1190
  sizeBytes,
863
- recordedSeconds: forSec,
1191
+ recordedSeconds: forSec * passes.length,
1192
+ ...(recordingKind ? { recordingKind } : {}),
1193
+ ...(viewports ? { viewports: passes.map((p) => p.label) } : {}),
864
1194
  next: "Processing runs in the background. Call wait_for_artifacts with this id (require:'all'), then get_agent_context / get_transcript to read it.",
865
1195
  });
866
1196
  });
@@ -880,11 +1210,11 @@ const SESSION_HARD_CAP_SEC = 1800;
880
1210
  let activeSession = null;
881
1211
  /** Result of a max-duration auto-stop, held for the next stop_recording call. */
882
1212
  let autoStoppedResult = null;
883
- function sessionMark(session, text) {
884
- const note = {
885
- startMs: Math.max(0, Date.now() - session.recordStartEpochMs),
886
- text,
887
- };
1213
+ /** Append a mark. Defaults to the live recording clock; pass `atMs` to backdate
1214
+ * it to an explicit point on the timeline (add_marker's `atSeconds`). */
1215
+ function sessionMark(session, text, atMs) {
1216
+ const startMs = atMs != null ? Math.max(0, Math.round(atMs)) : Math.max(0, Date.now() - session.recordStartEpochMs);
1217
+ const note = { startMs, text };
888
1218
  if (session.marks.length < 500)
889
1219
  session.marks.push(note);
890
1220
  return note;
@@ -906,11 +1236,22 @@ function finishSession(session, mode) {
906
1236
  throw new Error("browser did not produce a video");
907
1237
  const videoPath = await video.path();
908
1238
  await session.browser.close().catch(() => { });
909
- const notes = [...session.marks].sort((a, b) => a.startMs - b.startMs);
1239
+ const collected = [...session.marks];
1240
+ // If any assertions ran, lead the transcript with a verification summary
1241
+ // at 0ms so a reader sees the pass/fail tally up front.
1242
+ const assertionsRan = session.assertPassed + session.assertFailed;
1243
+ if (assertionsRan > 0) {
1244
+ collected.unshift({
1245
+ startMs: 0,
1246
+ text: `[verification] ${assertionsRan} assertions: ${session.assertPassed} passed, ${session.assertFailed} failed`,
1247
+ });
1248
+ }
1249
+ const notes = collected.sort((a, b) => a.startMs - b.startMs);
910
1250
  const uploaded = await uploadCapturedWebm({
911
1251
  videoPath,
912
1252
  name: session.name,
913
1253
  description: session.description,
1254
+ recordingKind: session.recordingKind,
914
1255
  narration: notes.length ? { notes } : undefined,
915
1256
  });
916
1257
  return {
@@ -936,10 +1277,14 @@ function finishSession(session, mode) {
936
1277
  })();
937
1278
  return session.finishing;
938
1279
  }
939
- 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 what you're doing at each step (markers become the recording's transcript), then stop_recording to upload and get the share link. 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).", {
1280
+ 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`.", {
940
1281
  url: z.string().describe("The http(s) URL to open and record (e.g. http://localhost:3000)."),
941
1282
  name: z.string().optional().describe("Optional title for the recording."),
942
1283
  description: z.string().optional().describe("Optional description for the recording."),
1284
+ type: z
1285
+ .string()
1286
+ .optional()
1287
+ .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)."),
943
1288
  maxSeconds: z
944
1289
  .number()
945
1290
  .int()
@@ -947,9 +1292,21 @@ server.tool("start_recording", "Start a RECORDING SESSION: opens the given URL i
947
1292
  .max(SESSION_HARD_CAP_SEC)
948
1293
  .optional()
949
1294
  .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.`),
1295
+ exposeCdp: z
1296
+ .boolean()
1297
+ .optional()
1298
+ .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. 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."),
1299
+ storageState: z
1300
+ .string()
1301
+ .optional()
1302
+ .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."),
1303
+ initScript: z
1304
+ .string()
1305
+ .optional()
1306
+ .describe("Path to a JS file run in the page before every navigation (context.addInitScript). Contents are never logged."),
950
1307
  width: z.number().int().min(320).max(3840).optional().describe("Viewport + video width (default 1280)."),
951
1308
  height: z.number().int().min(240).max(2160).optional().describe("Viewport + video height (default 720)."),
952
- }, async ({ url, name, description, maxSeconds, width, height }) => {
1309
+ }, async ({ url, name, description, type, maxSeconds, exposeCdp, storageState, initScript, width, height }) => {
953
1310
  let target;
954
1311
  try {
955
1312
  target = new URL(url);
@@ -966,6 +1323,24 @@ server.tool("start_recording", "Start a RECORDING SESSION: opens the given URL i
966
1323
  if (activeSession) {
967
1324
  return fail("a recording session is already active — finish it with stop_recording or discard it with abort_recording first.");
968
1325
  }
1326
+ let recordingKind;
1327
+ if (type) {
1328
+ const kind = normalizeRecordingKind(type);
1329
+ if (!kind)
1330
+ return fail(recordingKindError(type));
1331
+ recordingKind = kind;
1332
+ }
1333
+ let storageStatePath;
1334
+ let initScriptPath;
1335
+ try {
1336
+ if (storageState)
1337
+ storageStatePath = validateStorageStateFile(storageState);
1338
+ if (initScript)
1339
+ initScriptPath = validateInitScriptFile(initScript);
1340
+ }
1341
+ catch (e) {
1342
+ return fail(e.message);
1343
+ }
969
1344
  let chromium;
970
1345
  try {
971
1346
  chromium = await loadChromium();
@@ -978,16 +1353,41 @@ server.tool("start_recording", "Start a RECORDING SESSION: opens the given URL i
978
1353
  const maxSec = Math.min(maxSeconds ?? SESSION_DEFAULT_MAX_SEC, SESSION_HARD_CAP_SEC);
979
1354
  const tmpDirPath = join(tmpdir(), `clipy-mcp-session-${randomUUID()}`);
980
1355
  mkdirSync(tmpDirPath, { recursive: true });
1356
+ // CDP is OPT-IN and the env kill switch wins over the flag: only open a
1357
+ // debugging port when the caller asked AND CLIPY_DISABLE_CDP isn't set.
1358
+ const cdpDisabled = process.env.CLIPY_DISABLE_CDP === "1";
1359
+ const wantCdp = !!exposeCdp && !cdpDisabled;
981
1360
  try {
1361
+ const cdpPort = wantCdp ? await pickFreePort().catch(() => 0) : 0;
982
1362
  const browser = await chromium.launch({
983
1363
  headless: true,
984
- args: ["--no-sandbox", "--disable-dev-shm-usage"],
1364
+ args: [
1365
+ "--no-sandbox",
1366
+ "--disable-dev-shm-usage",
1367
+ ...(cdpPort ? [`--remote-debugging-port=${cdpPort}`] : []),
1368
+ ],
985
1369
  });
986
1370
  const context = await browser.newContext({
987
1371
  viewport: { width: w, height: h },
988
1372
  recordVideo: { dir: tmpDirPath, size: { width: w, height: h } },
1373
+ ...(storageStatePath ? { storageState: storageStatePath } : {}),
989
1374
  });
1375
+ if (initScriptPath)
1376
+ await context.addInitScript({ path: initScriptPath });
990
1377
  const page = await context.newPage();
1378
+ // Best-effort CDP discovery — the recording works even if it fails.
1379
+ let cdpUrl;
1380
+ let cdpHttpUrl;
1381
+ if (cdpPort) {
1382
+ cdpUrl = (await discoverCdpWsUrl(cdpPort)) ?? undefined;
1383
+ if (cdpUrl) {
1384
+ cdpHttpUrl = `http://127.0.0.1:${cdpPort}`;
1385
+ serverLog(`CDP endpoint ready at ${cdpHttpUrl}`);
1386
+ }
1387
+ else {
1388
+ serverLog(`CDP endpoint not reachable on port ${cdpPort} — browser drive unavailable`);
1389
+ }
1390
+ }
991
1391
  const session = {
992
1392
  browser,
993
1393
  context,
@@ -996,9 +1396,14 @@ server.tool("start_recording", "Start a RECORDING SESSION: opens the given URL i
996
1396
  url: target.href,
997
1397
  name,
998
1398
  description,
1399
+ recordingKind,
999
1400
  maxSec,
1000
1401
  recordStartEpochMs: Date.now(),
1001
1402
  marks: [],
1403
+ assertPassed: 0,
1404
+ assertFailed: 0,
1405
+ cdpUrl,
1406
+ cdpHttpUrl,
1002
1407
  maxTimer: setTimeout(() => { }, 0),
1003
1408
  finishing: null,
1004
1409
  };
@@ -1040,11 +1445,22 @@ server.tool("start_recording", "Start a RECORDING SESSION: opens the given URL i
1040
1445
  .catch(() => {
1041
1446
  // slow SPA — the recording is running regardless
1042
1447
  });
1448
+ // Describe the CDP outcome precisely: disabled-by-env, requested-but-
1449
+ // unreachable, or ready with the endpoints + driver gotchas.
1450
+ const cdpResult = cdpHttpUrl
1451
+ ? { cdpHttpUrl, cdpUrl, cdpNote: CDP_DRIVER_NOTE }
1452
+ : exposeCdp && cdpDisabled
1453
+ ? { cdpNote: "exposeCdp was requested but CLIPY_DISABLE_CDP=1 is set — no debugging port was opened." }
1454
+ : exposeCdp
1455
+ ? { cdpNote: "exposeCdp was requested but the CDP endpoint could not be reached — the recording is running normally without a drive endpoint." }
1456
+ : {};
1043
1457
  return ok({
1044
1458
  state: "recording",
1045
1459
  url: target.href,
1046
1460
  maxSeconds: maxSec,
1047
- next: "The session is recording. Use add_marker to narrate each step as you work; call stop_recording when done (or abort_recording to discard). It auto-stops + uploads at the max duration.",
1461
+ ...(recordingKind ? { recordingKind } : {}),
1462
+ ...cdpResult,
1463
+ 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.",
1048
1464
  });
1049
1465
  }
1050
1466
  catch (e) {
@@ -1057,15 +1473,140 @@ server.tool("start_recording", "Start a RECORDING SESSION: opens the given URL i
1057
1473
  return fail(e.message);
1058
1474
  }
1059
1475
  });
1060
- 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.", {
1476
+ async function runMarkerAssertions(page, a) {
1477
+ // One page.evaluate reads whatever the selected assertions need. `document`
1478
+ // is a browser global; the cast keeps it out of the (DOM-less) server lib.
1479
+ // assertText is always paired with assertSelector (enforced by the caller),
1480
+ // so text is read from the selector's element — never a weak page-body match.
1481
+ const probe = await page.evaluate((sel) => {
1482
+ const doc = globalThis.document;
1483
+ let selectorExists = null;
1484
+ let selectorText = null;
1485
+ if (sel && doc) {
1486
+ const el = doc.querySelector(sel);
1487
+ selectorExists = !!el;
1488
+ if (el)
1489
+ selectorText = (el.textContent || "").replace(/\s+/g, " ").trim();
1490
+ }
1491
+ return { selectorExists, selectorText };
1492
+ }, a.assertSelector ?? null);
1493
+ const url = page.url();
1494
+ const expected = [];
1495
+ const observed = [];
1496
+ let passed = true;
1497
+ if (a.assertSelector) {
1498
+ expected.push(`selector ${JSON.stringify(a.assertSelector)} present`);
1499
+ if (probe.selectorExists) {
1500
+ observed.push("selector present");
1501
+ }
1502
+ else {
1503
+ observed.push("selector NOT found");
1504
+ passed = false;
1505
+ }
1506
+ }
1507
+ if (a.assertText) {
1508
+ // Text is read from assertSelector's element (the caller guarantees one).
1509
+ const ref = probe.selectorText ?? "";
1510
+ expected.push(`text contains ${JSON.stringify(a.assertText)}`);
1511
+ observed.push(`text ${JSON.stringify(ref.slice(0, 200))}`);
1512
+ if (!ref.includes(a.assertText))
1513
+ passed = false;
1514
+ }
1515
+ if (a.assertUrl) {
1516
+ expected.push(`url matches ${JSON.stringify(a.assertUrl)}`);
1517
+ observed.push(`url ${JSON.stringify(url)}`);
1518
+ if (!globMatch(url, a.assertUrl))
1519
+ passed = false;
1520
+ }
1521
+ return { passed, expected: expected.join("; "), observed: observed.join("; ") };
1522
+ }
1523
+ 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.", {
1061
1524
  text: z.string().min(1).max(1000).describe("What is happening right now."),
1062
- }, async ({ text }) => {
1525
+ atSeconds: z
1526
+ .number()
1527
+ .min(0)
1528
+ .optional()
1529
+ .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.)"),
1530
+ assertSelector: z
1531
+ .string()
1532
+ .optional()
1533
+ .describe("CSS selector that must exist on the page at this moment."),
1534
+ assertText: z
1535
+ .string()
1536
+ .optional()
1537
+ .describe("Substring that must appear in assertSelector's element text. REQUIRES assertSelector — a bare page-body text match is weak evidence and is rejected."),
1538
+ assertUrl: z
1539
+ .string()
1540
+ .optional()
1541
+ .describe("Glob the current page URL must match. `**` matches anything (including `/`); `*` matches within a path segment. e.g. 'http://localhost:3000/**/settings'."),
1542
+ failMode: z
1543
+ .enum(["warn", "abort"])
1544
+ .optional()
1545
+ .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."),
1546
+ }, async ({ text, atSeconds, assertSelector, assertText, assertUrl, failMode }) => {
1547
+ if (!activeSession || activeSession.finishing) {
1548
+ return fail("no active recording session — call start_recording first.");
1549
+ }
1550
+ // Stricter contract (matches the CLI): assertText needs a selector to name
1551
+ // WHICH element's text is checked — a whole-page-body match is weak evidence.
1552
+ if (assertText && !assertSelector) {
1553
+ 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).");
1554
+ }
1555
+ const session = activeSession;
1556
+ const hasAssertion = !!(assertSelector || assertText || assertUrl);
1557
+ let markText = text.trim();
1558
+ let assertion = null;
1559
+ if (hasAssertion) {
1560
+ try {
1561
+ assertion = await runMarkerAssertions(session.page, { assertSelector, assertText, assertUrl });
1562
+ }
1563
+ catch (e) {
1564
+ return fail(`assertion evaluation failed: ${e.message}`);
1565
+ }
1566
+ if (assertion.passed) {
1567
+ session.assertPassed += 1;
1568
+ markText = `${markText} [assert ✓ ${assertion.observed}]`;
1569
+ }
1570
+ else {
1571
+ session.assertFailed += 1;
1572
+ markText = `${markText} [ASSERT ✗ expected ${assertion.expected}; observed ${assertion.observed}]`;
1573
+ }
1574
+ }
1575
+ const note = sessionMark(session, markText, atSeconds != null ? atSeconds * 1000 : undefined);
1576
+ // failMode 'abort' on a failed assertion: discard the whole session.
1577
+ if (assertion && !assertion.passed && failMode === "abort") {
1578
+ await finishSession(session, "abort").catch(() => { });
1579
+ return ok({
1580
+ aborted: true,
1581
+ assertionFailed: true,
1582
+ marker: note.text,
1583
+ atSeconds: Math.round(note.startMs / 100) / 10,
1584
+ expected: assertion.expected,
1585
+ observed: assertion.observed,
1586
+ note: "ASSERTION FAILED and failMode was 'abort' — the recording session was DISCARDED. Nothing was uploaded.",
1587
+ });
1588
+ }
1589
+ return ok({
1590
+ atSeconds: Math.round(note.startMs / 100) / 10,
1591
+ text: note.text,
1592
+ ...(assertion ? { assertion: { passed: assertion.passed, observed: assertion.observed } } : {}),
1593
+ totalMarkers: session.marks.length,
1594
+ });
1595
+ });
1596
+ 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.", {
1597
+ label: z
1598
+ .string()
1599
+ .min(1)
1600
+ .max(200)
1601
+ .describe("Short chapter label, e.g. 'BEFORE — bug present' or 'AFTER — fix applied'."),
1602
+ }, async ({ label }) => {
1063
1603
  if (!activeSession || activeSession.finishing) {
1064
1604
  return fail("no active recording session — call start_recording first.");
1065
1605
  }
1066
- const note = sessionMark(activeSession, text.trim());
1606
+ const note = sessionMark(activeSession, `=== CHAPTER: ${label.trim()} ===`);
1067
1607
  return ok({
1068
1608
  atSeconds: Math.round(note.startMs / 100) / 10,
1609
+ chapter: label.trim(),
1069
1610
  text: note.text,
1070
1611
  totalMarkers: activeSession.marks.length,
1071
1612
  });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@clipy/mcp",
3
- "version": "0.7.0",
3
+ "version": "0.8.0",
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",