@tmhs/screencast-mcp 0.47.0 → 0.48.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.
package/dist/cli.js CHANGED
@@ -5,10 +5,13 @@ import { join, resolve } from "node:path";
5
5
  import { Client } from "@modelcontextprotocol/sdk/client/index.js";
6
6
  import { InMemoryTransport } from "@modelcontextprotocol/sdk/inMemory.js";
7
7
  import { createServer } from "./server.js";
8
+ import { MAX_RECORDING_CAP_SEC } from "./utils/targets.js";
9
+ import { DEFAULT_ERROR_PATTERN, DEFAULT_SECRET_PATTERN, MAX_ERROR_LINES, maskSecrets } from "./utils/bugReport.js";
10
+ import { defaultSetupDeps, parseSetupArgs, runSetup, SETUP_USAGE } from "./setup.js";
8
11
  const VERSION = createRequire(import.meta.url)("../package.json").version;
9
12
  export class CliUsageError extends Error {
10
13
  }
11
- const SUBCOMMANDS = new Set(["record", "call", "help", "--help", "-h", "--version", "-v"]);
14
+ const SUBCOMMANDS = new Set(["record", "call", "setup", "help", "--help", "-h", "--version", "-v"]);
12
15
  export function isCliInvocation(argv) {
13
16
  return argv.length > 0 && SUBCOMMANDS.has(argv[0] ?? "");
14
17
  }
@@ -18,7 +21,10 @@ Usage:
18
21
  screencast-mcp run the MCP server over stdio (default)
19
22
  screencast-mcp record [options] -- <command...>
20
23
  record the screen while <command> runs
24
+ screencast-mcp record [options] --command-env <NAME>
25
+ the same, running the command in env var NAME
21
26
  screencast-mcp call <tool> [json|@file] call one tool and print its result
27
+ screencast-mcp setup [options] check this machine and wire up MCP clients
22
28
  screencast-mcp --version | --help
23
29
 
24
30
  record options:
@@ -30,10 +36,15 @@ record options:
30
36
  --no-gif skip the GIF
31
37
  --no-contact-sheet skip the contact sheet
32
38
  --discard-on-success delete the recording when the command exits 0
33
- --max-duration <sec> stop recording after <sec> seconds (default SCREENCAST_MAX_RECORDING_SEC)
39
+ --ocr-errors on failure, OCR the last <sec> seconds for error lines (Windows OCR)
40
+ --max-duration <sec> stop recording after <sec> seconds, an integer 0-${MAX_RECORDING_CAP_SEC}
41
+ (0 = no cap; default SCREENCAST_MAX_RECORDING_SEC, else 3600)
42
+ --command-env <NAME> run the command line in environment variable NAME instead of
43
+ the arguments after --, so quotes and & survive any shell
34
44
 
35
45
  record exits with the command's exit code and writes <out>/evidence.json.
36
- `;
46
+
47
+ ${SETUP_USAGE}`;
37
48
  function takeValue(argv, i, flag) {
38
49
  const value = argv[i + 1];
39
50
  if (value === undefined || value === "--")
@@ -42,17 +53,14 @@ function takeValue(argv, i, flag) {
42
53
  }
43
54
  function number(value, flag, min, max = Infinity, integer = false) {
44
55
  const n = Number(value);
45
- if (!Number.isFinite(n) || n < min || n > max || (integer && !Number.isInteger(n))) {
56
+ if (value.trim() === "" || !Number.isFinite(n) || n < min || n > max || (integer && !Number.isInteger(n))) {
46
57
  const range = max === Infinity ? `>= ${min}` : `${min}-${max}`;
47
58
  throw new CliUsageError(`${flag} must be ${integer ? "an integer" : "a number"} ${range}, got "${value}".`);
48
59
  }
49
60
  return n;
50
61
  }
51
- function parseRecord(argv) {
62
+ function parseRecord(argv, env) {
52
63
  const dash = argv.indexOf("--");
53
- if (dash === -1 || dash === argv.length - 1) {
54
- throw new CliUsageError("record needs a command after --, e.g. screencast-mcp record -- npm test");
55
- }
56
64
  const options = {
57
65
  target: "full",
58
66
  fps: 15,
@@ -62,9 +70,11 @@ function parseRecord(argv) {
62
70
  gif: true,
63
71
  contactSheet: true,
64
72
  discardOnSuccess: false,
65
- command: argv.slice(dash + 1),
73
+ ocrErrors: false,
74
+ command: dash === -1 ? [] : argv.slice(dash + 1),
66
75
  };
67
- const flags = argv.slice(0, dash);
76
+ let commandEnv;
77
+ const flags = dash === -1 ? argv : argv.slice(0, dash);
68
78
  for (let i = 0; i < flags.length; i++) {
69
79
  const raw = flags[i] ?? "";
70
80
  const eq = raw.startsWith("--") ? raw.indexOf("=") : -1;
@@ -99,7 +109,10 @@ function parseRecord(argv) {
99
109
  options.lastSec = number(value(), flag, 0);
100
110
  break;
101
111
  case "--max-duration":
102
- options.maxDurationSec = number(value(), flag, 0);
112
+ options.maxDurationSec = number(value(), flag, 0, MAX_RECORDING_CAP_SEC, true);
113
+ break;
114
+ case "--command-env":
115
+ commandEnv = value();
103
116
  break;
104
117
  case "--no-gif":
105
118
  options.gif = false;
@@ -110,13 +123,29 @@ function parseRecord(argv) {
110
123
  case "--discard-on-success":
111
124
  options.discardOnSuccess = true;
112
125
  break;
126
+ case "--ocr-errors":
127
+ options.ocrErrors = true;
128
+ break;
113
129
  default:
114
130
  throw new CliUsageError(`Unknown record option "${raw}". Run screencast-mcp --help.`);
115
131
  }
116
132
  }
133
+ if (commandEnv !== undefined) {
134
+ if (options.command.length > 0) {
135
+ throw new CliUsageError("Give the command either after -- or with --command-env, not both.");
136
+ }
137
+ const line = env[commandEnv];
138
+ if (line === undefined || line.trim() === "") {
139
+ throw new CliUsageError(`--command-env ${commandEnv}: the environment variable is unset or empty.`);
140
+ }
141
+ options.command = [line];
142
+ }
143
+ else if (options.command.length === 0) {
144
+ throw new CliUsageError("record needs a command after -- (or --command-env NAME), e.g. screencast-mcp record -- npm test");
145
+ }
117
146
  return options;
118
147
  }
119
- export function parseCliArgs(argv) {
148
+ export function parseCliArgs(argv, env = process.env) {
120
149
  const [sub, ...rest] = argv;
121
150
  switch (sub) {
122
151
  case "help":
@@ -129,7 +158,7 @@ export function parseCliArgs(argv) {
129
158
  case "record":
130
159
  if (rest[0] === "--help" || rest[0] === "-h")
131
160
  return { kind: "help" };
132
- return { kind: "record", options: parseRecord(rest) };
161
+ return { kind: "record", options: parseRecord(rest, env) };
133
162
  case "call": {
134
163
  const [tool, args, extra] = rest;
135
164
  if (!tool || tool.startsWith("-"))
@@ -138,20 +167,71 @@ export function parseCliArgs(argv) {
138
167
  throw new CliUsageError("call takes one JSON argument; quote it as a single string.");
139
168
  return { kind: "call", tool, args };
140
169
  }
170
+ case "setup": {
171
+ if (rest[0] === "--help" || rest[0] === "-h")
172
+ return { kind: "help" };
173
+ try {
174
+ return { kind: "setup", options: parseSetupArgs(rest) };
175
+ }
176
+ catch (err) {
177
+ throw new CliUsageError(err instanceof Error ? err.message : String(err));
178
+ }
179
+ }
141
180
  default:
142
181
  throw new CliUsageError(`Unknown command "${sub ?? ""}". Run screencast-mcp --help.`);
143
182
  }
144
183
  }
145
- export function commandLine(command) {
184
+ const CMD_META = /([()\][%!^"`<>&|;, *?])/g;
185
+ const BATCH_SHIM = /(\.(cmd|bat)$)|^(npm|npx|pnpm|yarn|corepack)$/i;
186
+ function msvcQuote(arg) {
187
+ const escaped = arg.replace(/(\\*)"/g, '$1$1\\"').replace(/(\\+)$/, "$1$1");
188
+ return `"${escaped}"`;
189
+ }
190
+ const NEEDS_QUOTES = /[\s"&|<>^()!;'`$*?%,[\]]/;
191
+ export function commandLine(command, platform = process.platform) {
192
+ if (command.length === 1)
193
+ return command[0] ?? "";
194
+ if (platform !== "win32") {
195
+ return command.map((a) => (/^[\w@%+=:,./-]+$/.test(a) ? a : `'${a.replace(/'/g, `'\\''`)}'`)).join(" ");
196
+ }
197
+ const batch = BATCH_SHIM.test(command[0] ?? "");
198
+ return command
199
+ .map((a, i) => {
200
+ if (i === 0 || (!NEEDS_QUOTES.test(a) && a !== ""))
201
+ return a;
202
+ let q = msvcQuote(a).replace(CMD_META, "^$1");
203
+ if (batch)
204
+ q = q.replace(CMD_META, "^$1");
205
+ return q;
206
+ })
207
+ .join(" ");
208
+ }
209
+ export function displayCommand(command) {
146
210
  if (command.length === 1)
147
211
  return command[0] ?? "";
148
- return command.map((a) => (/[\s"&|<>^()!;'`$*?]/.test(a) || a === "" ? `"${a.replace(/"/g, '\\"')}"` : a)).join(" ");
212
+ return command.map((a) => (NEEDS_QUOTES.test(a) || a === "" ? `"${a.replace(/"/g, '\\"')}"` : a)).join(" ");
149
213
  }
150
214
  export function tailWindow(durationSec, lastSec) {
151
215
  if (!lastSec || durationSec === null || durationSec <= lastSec)
152
216
  return {};
153
217
  return { start: Math.round((durationSec - lastSec) * 1000) / 1000, duration: lastSec };
154
218
  }
219
+ export function errorLines(matches) {
220
+ const sorted = [...matches].sort((a, b) => (Number(b.t) || 0) - (Number(a.t) || 0));
221
+ const seen = new Set();
222
+ const lines = [];
223
+ for (const m of sorted) {
224
+ const line = String(m.line ?? m.text ?? "").trim();
225
+ const key = line.toLowerCase().replace(/\s+/g, " ");
226
+ if (!line || seen.has(key))
227
+ continue;
228
+ seen.add(key);
229
+ lines.push(line);
230
+ if (lines.length >= MAX_ERROR_LINES)
231
+ break;
232
+ }
233
+ return maskSecrets(lines, DEFAULT_SECRET_PATTERN);
234
+ }
155
235
  export function parseToolArgs(raw, readFile = (p) => readFileSync(p, "utf8")) {
156
236
  if (raw === undefined || raw.trim() === "")
157
237
  return {};
@@ -168,26 +248,28 @@ export function parseToolArgs(raw, readFile = (p) => readFileSync(p, "utf8")) {
168
248
  }
169
249
  return value;
170
250
  }
171
- async function connect() {
251
+ export async function connect() {
172
252
  const [clientSide, serverSide] = InMemoryTransport.createLinkedPair();
173
253
  await createServer({ toolsets: "all" }).connect(serverSide);
174
254
  const client = new Client({ name: "screencast-mcp-cli", version: VERSION });
175
255
  await client.connect(clientSide);
176
- return client;
177
- }
178
- async function callTool(client, name, args) {
179
- const res = await client.callTool({ name, arguments: args });
180
- const text = res.content
181
- .map((c) => (c.type === "text" ? (c.text ?? "") : `[${c.type} omitted]`))
182
- .join("\n");
183
256
  return {
184
- isError: res.isError === true,
185
- text,
186
- structured: res.structuredContent,
257
+ async call(name, args) {
258
+ const res = await client.callTool({ name, arguments: args });
259
+ const text = res.content
260
+ .map((c) => (c.type === "text" ? (c.text ?? "") : `[${c.type} omitted]`))
261
+ .join("\n");
262
+ return {
263
+ isError: res.isError === true,
264
+ text,
265
+ structured: res.structuredContent,
266
+ };
267
+ },
268
+ close: () => client.close(),
187
269
  };
188
270
  }
189
- async function mustCall(client, name, args) {
190
- const res = await callTool(client, name, args);
271
+ export async function mustCall(client, name, args) {
272
+ const res = await client.call(name, args);
191
273
  if (res.isError)
192
274
  throw new Error(`${name}: ${res.text}`);
193
275
  return res.structured ?? {};
@@ -216,24 +298,48 @@ function runCommand(command) {
216
298
  child.on("exit", (code, signal) => done(code ?? (signal ? 1 : 0)));
217
299
  });
218
300
  }
219
- async function record(opts, io) {
301
+ export function earlyEndWarning(status, endReason, durationSec) {
302
+ if (status === null)
303
+ return null;
304
+ const at = durationSec === null ? "" : ` at ${durationSec} s`;
305
+ const tail = "so the GIF and contact sheet show the end of the recording, not the end of the run.";
306
+ if (endReason === "max_duration") {
307
+ return `the recording hit its max-duration cap${at} before the command finished, ${tail} Raise --max-duration (0 = no cap).`;
308
+ }
309
+ if (status === "failed" || endReason === "crashed") {
310
+ return `the recording failed${at} before the command finished (endReason ${endReason ?? "unknown"}), ${tail}`;
311
+ }
312
+ if (endReason === "window_closed") {
313
+ return `the recorded window closed${at} before the command finished, ${tail}`;
314
+ }
315
+ if (endReason !== null && endReason !== "stopped") {
316
+ return `the recording ended early${at} (endReason ${endReason}), ${tail}`;
317
+ }
318
+ return null;
319
+ }
320
+ const defaultRecordDeps = { connect, run: runCommand, now: () => Date.now() };
321
+ export async function runRecord(opts, io = defaultIo, deps = defaultRecordDeps) {
220
322
  const outDir = resolve(opts.outDir);
221
323
  mkdirSync(outDir, { recursive: true });
222
324
  const evidence = {
223
- command: commandLine(opts.command),
325
+ command: displayCommand(opts.command),
224
326
  exitCode: 0,
225
327
  target: opts.target,
226
328
  recording: null,
227
329
  durationSec: null,
330
+ commandSec: 0,
331
+ status: null,
332
+ endReason: null,
228
333
  gif: null,
229
334
  contactSheet: null,
335
+ errors: null,
230
336
  warnings: [],
231
337
  };
232
338
  const warn = (msg) => {
233
339
  evidence.warnings.push(msg);
234
340
  io.err(`screencast-mcp: ${msg}\n`);
235
341
  };
236
- const client = await connect();
342
+ const client = await deps.connect();
237
343
  try {
238
344
  let sessionId = null;
239
345
  try {
@@ -250,12 +356,20 @@ async function record(opts, io) {
250
356
  catch (err) {
251
357
  warn(`recording did not start, running the command without it: ${err instanceof Error ? err.message : String(err)}`);
252
358
  }
253
- evidence.exitCode = await runCommand(opts.command);
359
+ const began = deps.now();
360
+ evidence.exitCode = await deps.run(opts.command);
361
+ evidence.commandSec = Math.round(deps.now() - began) / 1000;
254
362
  if (sessionId) {
255
363
  try {
256
364
  const stopped = await mustCall(client, "stop_recording", { sessionId });
257
365
  evidence.recording = String(stopped.outputPath);
258
366
  evidence.durationSec = typeof stopped.durationSec === "number" ? stopped.durationSec : null;
367
+ evidence.status = typeof stopped.status === "string" ? stopped.status : null;
368
+ evidence.endReason =
369
+ typeof stopped.endReason === "string" ? stopped.endReason : evidence.status === "stopped" ? "stopped" : null;
370
+ const early = earlyEndWarning(evidence.status, evidence.endReason, evidence.durationSec);
371
+ if (early)
372
+ warn(early);
259
373
  }
260
374
  catch (err) {
261
375
  warn(`stop_recording failed: ${err instanceof Error ? err.message : String(err)}`);
@@ -294,6 +408,9 @@ async function record(opts, io) {
294
408
  }
295
409
  }
296
410
  }
411
+ if (evidence.recording && failed && opts.ocrErrors) {
412
+ evidence.errors = await ocrErrors(client, evidence.recording, evidence.durationSec, opts.lastSec, outDir, warn);
413
+ }
297
414
  if (!failed && opts.discardOnSuccess && evidence.recording) {
298
415
  rmSync(evidence.recording, { force: true });
299
416
  evidence.recording = null;
@@ -308,11 +425,47 @@ async function record(opts, io) {
308
425
  "\n");
309
426
  return evidence.exitCode;
310
427
  }
428
+ async function ocrErrors(client, recording, durationSec, lastSec, outDir, warn) {
429
+ const window = tailWindow(durationSec, lastSec);
430
+ let input = recording;
431
+ let tail = null;
432
+ try {
433
+ if (window.start !== undefined) {
434
+ const cut = await mustCall(client, "trim", {
435
+ input: recording,
436
+ start: window.start,
437
+ duration: window.duration,
438
+ output: join(outDir, ".ocr-tail.mp4"),
439
+ overwrite: true,
440
+ });
441
+ tail = String(cut.outputPath);
442
+ input = tail;
443
+ }
444
+ const found = await mustCall(client, "find_text", {
445
+ input,
446
+ scanEverySec: 1,
447
+ maxFrames: 30,
448
+ query: DEFAULT_ERROR_PATTERN,
449
+ regex: true,
450
+ returnImage: false,
451
+ });
452
+ const matches = Array.isArray(found.matches) ? found.matches : [];
453
+ return errorLines(matches);
454
+ }
455
+ catch (err) {
456
+ warn(`OCR of error lines failed: ${err instanceof Error ? err.message : String(err)}`);
457
+ return null;
458
+ }
459
+ finally {
460
+ if (tail)
461
+ rmSync(tail, { force: true });
462
+ }
463
+ }
311
464
  async function call(tool, rawArgs, io) {
312
465
  const args = parseToolArgs(rawArgs);
313
466
  const client = await connect();
314
467
  try {
315
- const res = await callTool(client, tool, args);
468
+ const res = await client.call(tool, args);
316
469
  if (res.isError) {
317
470
  io.err(`${res.text}\n`);
318
471
  return 1;
@@ -344,7 +497,9 @@ export async function runCli(argv, io = defaultIo) {
344
497
  io.out(`${VERSION}\n`);
345
498
  return 0;
346
499
  case "record":
347
- return record(command.options, io);
500
+ return runRecord(command.options, io);
501
+ case "setup":
502
+ return runSetup(command.options, defaultSetupDeps({ connect, io }));
348
503
  case "call":
349
504
  try {
350
505
  return await call(command.tool, command.args, io);
package/dist/server.js CHANGED
@@ -62,6 +62,8 @@ import { registerResources } from "./resources.js";
62
62
  import { registerPrompts } from "./prompts.js";
63
63
  import { attachLogging } from "./utils/logging.js";
64
64
  import { trackClientRoots } from "./utils/roots.js";
65
+ import { assertArgPaths } from "./utils/argPaths.js";
66
+ import { errorResponse } from "./utils/errors.js";
65
67
  const { version } = createRequire(import.meta.url)("../package.json");
66
68
  export function createServer(options = {}) {
67
69
  const selection = parseToolsets(options.toolsets ?? process.env.SCREENCAST_TOOLSETS);
@@ -142,6 +144,17 @@ function captureRegisteredTools(server) {
142
144
  const tools = new Map();
143
145
  const register = server.registerTool.bind(server);
144
146
  server.registerTool = ((...args) => {
147
+ const last = args.length - 1;
148
+ const handler = args[last];
149
+ args[last] = (input, extra) => {
150
+ try {
151
+ assertArgPaths(input);
152
+ }
153
+ catch (err) {
154
+ return errorResponse(err);
155
+ }
156
+ return handler(input, extra);
157
+ };
145
158
  const tool = register(...args);
146
159
  tools.set(args[0], tool);
147
160
  return tool;