surfcad-mcp 0.2.0 → 0.2.2

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/src/relay.mjs CHANGED
@@ -1,47 +1,55 @@
1
1
  import { WebSocket } from 'ws';
2
2
  import { connectPeer } from './nodeClient.mjs';
3
3
  import { PAIR_MSG } from './relayMessages.mjs';
4
+ import { redactToken } from './bridge/relayHub.mjs';
5
+ import { RECONNECT_HINT, pairPendingError, pairingLostError } from './errors.mjs';
6
+ import { createPromptSession } from './prompt/promptSession.mjs';
4
7
 
5
8
  const DEFAULT_WS_URL = 'ws://127.0.0.1:17341';
6
9
 
10
+ /** Backoff between automatic re-pair attempts after the tab drops. */
11
+ export const DEFAULT_RECONNECT_DELAYS_MS = Object.freeze([250, 500, 1000, 2000, 3000, 5000]);
12
+
13
+ /**
14
+ * @typedef {'unpaired' | 'pairing' | 'paired' | 'lost'} RelaySessionState
15
+ */
16
+
7
17
  export function defaultRelayUrl() {
8
18
  const fromEnv = process.env.SURFCAD_AGENT_BRIDGE_WS_URL;
9
19
  if (typeof fromEnv === 'string' && fromEnv.trim()) return fromEnv.trim();
10
20
  return DEFAULT_WS_URL;
11
21
  }
12
22
 
23
+ function defaultSessionLog(line) {
24
+ console.error(`${new Date().toISOString()} [surfcad-mcp] ${line}`);
25
+ }
26
+
27
+ function notPaired() {
28
+ return Object.assign(new Error('Not paired'), { code: 'not_paired' });
29
+ }
30
+
13
31
  /**
14
- * @param {WebSocket} ws
15
- * @param {string} command
16
- * @param {Record<string, unknown>} args
17
- * @param {string | number} id
32
+ * @param {unknown} err
18
33
  */
19
- export function invokeBridge(ws, command, args = {}, id = '1') {
20
- return new Promise((resolve, reject) => {
21
- const onMessage = (raw) => {
22
- let msg;
23
- try {
24
- msg = JSON.parse(String(raw));
25
- } catch {
26
- return;
27
- }
28
- if (msg?.id !== id) return;
29
- ws.off('message', onMessage);
30
- if (msg.ok === true) {
31
- resolve(msg.result);
32
- return;
33
- }
34
- const error = msg.error && typeof msg.error === 'object'
35
- ? msg.error
36
- : { code: 'bridge_error', message: 'Command refused' };
37
- reject(Object.assign(new Error(error.message || error.code || 'Bridge call failed'), {
38
- code: error.code,
39
- details: error.details,
40
- }));
41
- };
42
- ws.on('message', onMessage);
43
- ws.send(JSON.stringify({ id, command, args }));
44
- });
34
+ function pairError(err) {
35
+ const code = err && typeof err === 'object' && typeof err.code === 'string' ? err.code : 'pair_failed';
36
+ const message = err instanceof Error ? err.message : String(err);
37
+ if (code === 'pair_rejected') {
38
+ return Object.assign(new Error('Pairing rejected in SurfCAD (user clicked Deny)'), { code });
39
+ }
40
+ if (code === 'unknown_token') {
41
+ return Object.assign(new Error('No SurfCAD tab is showing this pairing code'), {
42
+ code,
43
+ hint: RECONNECT_HINT,
44
+ });
45
+ }
46
+ if (code === 'relay_unreachable') {
47
+ return Object.assign(new Error('The local agent bridge relay is not running'), {
48
+ code,
49
+ hint: 'Restart the MCP server (npx surfcad-mcp), then keep the SurfCAD tab open in Chrome.',
50
+ });
51
+ }
52
+ return Object.assign(new Error(message), { code: code === 'relay_error' ? 'pair_failed' : code });
45
53
  }
46
54
 
47
55
  export class RelaySession {
@@ -49,9 +57,59 @@ export class RelaySession {
49
57
  #ws = null;
50
58
  #url;
51
59
  #code = '';
60
+ /** @type {string | null} */
61
+ #resumeKey = null;
62
+ /** @type {RelaySessionState} */
63
+ #state = 'unpaired';
64
+ /** @type {Map<string, { resolve: (v: unknown) => void, reject: (e: Error) => void }>} */
65
+ #pending = new Map();
66
+ /** @type {{ code: string, promise: Promise<{ paired: true, token: string, relay: string }> } | null} */
67
+ #pairing = null;
68
+ #generation = 0;
69
+ /** @type {string | null} */
70
+ #lostReason = null;
71
+ #lostAt = 0;
72
+ #attempt = 0;
73
+ /** @type {ReturnType<typeof setTimeout> | null} */
74
+ #timer = null;
75
+ /** @type {readonly number[]} */
76
+ #delays;
77
+ /** @type {(() => Promise<unknown>) | null} */
78
+ #ensureRelay;
79
+ /** @type {(line: string) => void} */
80
+ #log;
81
+ /** @type {ReturnType<typeof createPromptSession>} */
82
+ #prompts;
52
83
 
84
+ /**
85
+ * @param {{
86
+ * url?: string,
87
+ * reconnectDelaysMs?: readonly number[],
88
+ * ensureRelay?: () => Promise<unknown>,
89
+ * onLog?: (line: string) => void,
90
+ * promptSession?: ReturnType<typeof createPromptSession>,
91
+ * postWebhook?: (url: string, body: object, meta: { pinAddress?: string, insecureTls: boolean }) => Promise<{ ok: boolean, error?: string }>,
92
+ * testWebhookOverride?: () => boolean,
93
+ * resolveHost?: (hostname: string) => Promise<string[]>,
94
+ * now?: () => number,
95
+ * setTimer?: (fn: () => void, ms: number) => unknown,
96
+ * clearTimer?: (timer: unknown) => void,
97
+ * }} [options]
98
+ */
53
99
  constructor(options = {}) {
54
100
  this.#url = options.url || defaultRelayUrl();
101
+ this.#delays = options.reconnectDelaysMs?.length ? options.reconnectDelaysMs : DEFAULT_RECONNECT_DELAYS_MS;
102
+ this.#ensureRelay = options.ensureRelay || null;
103
+ this.#log = options.onLog || defaultSessionLog;
104
+ this.#prompts = options.promptSession || createPromptSession({
105
+ send: (payload) => this.#sendToTab(payload),
106
+ postWebhook: options.postWebhook,
107
+ testWebhookOverride: options.testWebhookOverride,
108
+ resolveHost: options.resolveHost,
109
+ now: options.now,
110
+ setTimer: options.setTimer,
111
+ clearTimer: options.clearTimer,
112
+ });
55
113
  }
56
114
 
57
115
  get url() {
@@ -62,57 +120,259 @@ export class RelaySession {
62
120
  return this.#code;
63
121
  }
64
122
 
123
+ /** @returns {RelaySessionState} */
124
+ get state() {
125
+ return this.#state;
126
+ }
127
+
128
+ status() {
129
+ return {
130
+ state: this.#state,
131
+ lostReason: this.#state === 'lost' ? this.#lostReason : null,
132
+ lostForMs: this.#state === 'lost' ? Date.now() - this.#lostAt : 0,
133
+ };
134
+ }
135
+
65
136
  isPaired() {
66
- return this.#ws != null && this.#ws.readyState === WebSocket.OPEN;
137
+ return this.#state === 'paired' && this.#ws != null && this.#ws.readyState === WebSocket.OPEN;
138
+ }
139
+
140
+ /** In-memory prompt queue and webhook for this pairing. */
141
+ get prompts() {
142
+ return this.#prompts;
143
+ }
144
+
145
+ /**
146
+ * First tool call after a prompt arrives marks the agent working.
147
+ * Best-effort: a dead socket does not fail the tool call.
148
+ */
149
+ noteAgentToolCall() {
150
+ try {
151
+ this.#prompts.noteToolCall();
152
+ } catch {
153
+ /* status is advisory */
154
+ }
155
+ }
156
+
157
+ /**
158
+ * @param {object} payload
159
+ */
160
+ #sendToTab(payload) {
161
+ if (!this.isPaired()) throw notPaired();
162
+ const ws = /** @type {WebSocket} */ (this.#ws);
163
+ ws.send(JSON.stringify(payload));
67
164
  }
68
165
 
69
166
  /**
70
167
  * @param {string} token
71
168
  */
72
- async pair(token) {
169
+ pair(token) {
73
170
  const code = String(token || '').trim().toUpperCase();
74
171
  if (!code) {
75
- throw Object.assign(new Error('Pairing code is required'), { code: 'bad_pairing_code' });
172
+ return Promise.reject(Object.assign(new Error('Pairing code is required'), { code: 'bad_pairing_code' }));
76
173
  }
77
- if (this.#ws) {
78
- try { this.#ws.close(); } catch { /* noop */ }
79
- this.#ws = null;
174
+ if (this.#pairing && this.#pairing.code === code) return this.#pairing.promise;
175
+ if (this.isPaired() && this.#code === code) {
176
+ return Promise.resolve({ paired: true, token: code, relay: this.#url });
80
177
  }
178
+ const resume = code === this.#code ? this.#resumeKey : null;
179
+ const recovering = this.#state === 'lost' && code === this.#code;
180
+ this.#clearTimer();
181
+ this.#detach(new Error('Re-pairing'), 'not_paired');
81
182
  this.#code = code;
183
+ if (!recovering) {
184
+ this.#resumeKey = null;
185
+ this.#state = 'pairing';
186
+ }
187
+ return this.#startPairing(code, resume);
188
+ }
189
+
190
+ /**
191
+ * @param {string} code
192
+ * @param {string | null} resume
193
+ */
194
+ #startPairing(code, resume) {
195
+ const generation = ++this.#generation;
196
+ const promise = connectPeer(this.#url, code, { resume }).then(
197
+ ({ ws, resumeKey }) => {
198
+ if (generation !== this.#generation) {
199
+ try { ws.close(); } catch { /* noop */ }
200
+ throw notPaired();
201
+ }
202
+ this.#pairing = null;
203
+ this.#attach(ws, resumeKey);
204
+ return { paired: true, token: code, relay: this.#url };
205
+ },
206
+ (err) => {
207
+ if (generation === this.#generation) {
208
+ this.#pairing = null;
209
+ if (this.#state === 'lost') this.#scheduleReconnect();
210
+ else this.#state = 'unpaired';
211
+ }
212
+ throw pairError(err);
213
+ },
214
+ );
215
+ this.#pairing = { code, promise };
216
+ return promise;
217
+ }
218
+
219
+ /**
220
+ * @param {WebSocket} ws
221
+ * @param {string | null} resumeKey
222
+ */
223
+ #attach(ws, resumeKey) {
224
+ const restored = this.#state === 'lost';
225
+ this.#ws = ws;
226
+ this.#resumeKey = resumeKey;
227
+ this.#state = 'paired';
228
+ this.#attempt = 0;
229
+ if (restored) {
230
+ this.#log(`pairing restored token=${redactToken(this.#code)} after ${Date.now() - this.#lostAt}ms`);
231
+ }
232
+ this.#lostReason = null;
233
+ ws.on('message', (raw) => {
234
+ let msg;
235
+ try {
236
+ msg = JSON.parse(String(raw));
237
+ } catch {
238
+ return;
239
+ }
240
+ if (!msg || typeof msg !== 'object') return;
241
+ if (msg.type === PAIR_MSG.UNPAIRED) {
242
+ this.#lose(ws, typeof msg.detail === 'string' ? `${msg.reason}: ${msg.detail}` : String(msg.reason || 'unpaired'));
243
+ return;
244
+ }
245
+ if (msg.type === PAIR_MSG.AGENT_PROMPT) {
246
+ void this.#prompts.acceptPrompt(msg);
247
+ return;
248
+ }
249
+ const id = typeof msg.id === 'string' ? msg.id : null;
250
+ const waiter = id ? this.#pending.get(id) : undefined;
251
+ if (waiter) {
252
+ this.#pending.delete(id);
253
+ if (msg.ok === true) {
254
+ waiter.resolve(msg.result);
255
+ return;
256
+ }
257
+ const error = msg.error && typeof msg.error === 'object'
258
+ ? msg.error
259
+ : { code: 'bridge_error', message: 'Command refused' };
260
+ waiter.reject(Object.assign(new Error(error.message || error.code || 'Bridge call failed'), {
261
+ code: error.code,
262
+ details: error.details,
263
+ }));
264
+ return;
265
+ }
266
+ if (msg.type === PAIR_MSG.ERROR && msg.id == null) {
267
+ this.#lose(ws, `relay_error ${msg.code || 'unknown'}`);
268
+ }
269
+ });
270
+ ws.on('close', () => { this.#lose(ws, 'relay_closed'); });
271
+ ws.on('error', () => { /* `close` follows */ });
272
+ }
273
+
274
+ /**
275
+ * @param {WebSocket} ws
276
+ * @param {string} reason
277
+ */
278
+ #lose(ws, reason) {
279
+ if (this.#ws !== ws) return;
280
+ this.#prompts.clear();
281
+ this.#ws = null;
282
+ try { ws.close(); } catch { /* noop */ }
283
+ this.#state = 'lost';
284
+ this.#lostAt = Date.now();
285
+ this.#lostReason = reason;
286
+ this.#log(`pairing lost token=${redactToken(this.#code)} reason=${reason}; reconnecting`);
287
+ const err = pairingLostError(reason);
288
+ for (const waiter of this.#pending.values()) waiter.reject(err);
289
+ this.#pending.clear();
290
+ this.#scheduleReconnect();
291
+ }
292
+
293
+ #scheduleReconnect() {
294
+ if (this.#timer || this.#state !== 'lost' || this.#pairing) return;
295
+ const delay = this.#delays[Math.min(this.#attempt, this.#delays.length - 1)];
296
+ this.#attempt += 1;
297
+ this.#timer = setTimeout(() => {
298
+ this.#timer = null;
299
+ void this.#reconnectOnce();
300
+ }, delay);
301
+ if (typeof this.#timer.unref === 'function') this.#timer.unref();
302
+ }
303
+
304
+ async #reconnectOnce() {
305
+ if (this.#state !== 'lost' || this.#pairing) return;
82
306
  try {
83
- this.#ws = await connectPeer(this.#url, code);
307
+ await this.#startPairing(this.#code, this.#resumeKey);
84
308
  } catch (err) {
85
- const message = err instanceof Error ? err.message : String(err);
86
- if (/rejected/i.test(message) || message.includes('pair_rejected')) {
87
- throw Object.assign(new Error('Pairing rejected in SurfCAD (user clicked Deny)'), {
88
- code: 'pair_rejected',
89
- });
309
+ if (this.#state !== 'lost') return;
310
+ if (err?.code === 'pair_rejected') {
311
+ this.#log(`pairing denied in SurfCAD token=${redactToken(this.#code)}; stopped reconnecting`);
312
+ this.#state = 'unpaired';
313
+ this.#resumeKey = null;
314
+ this.#clearTimer();
315
+ return;
90
316
  }
91
- if (/unknown_token/i.test(message)) {
92
- throw Object.assign(new Error('No SurfCAD tab is showing this pairing code'), {
93
- code: 'unknown_token',
94
- });
317
+ if (err?.code === 'relay_unreachable' && this.#ensureRelay) {
318
+ await this.#ensureRelay().catch(() => {});
95
319
  }
96
- throw Object.assign(new Error(message), { code: err?.code || 'pair_failed' });
97
320
  }
98
- this.#ws.on('close', () => {
99
- this.#ws = null;
100
- });
101
- return { paired: true, token: code, relay: this.#url };
102
321
  }
103
322
 
104
- async call(command, args = {}) {
105
- if (!this.isPaired()) {
106
- throw Object.assign(new Error('Not paired'), { code: 'not_paired' });
323
+ #clearTimer() {
324
+ if (this.#timer) {
325
+ clearTimeout(this.#timer);
326
+ this.#timer = null;
107
327
  }
108
- return invokeBridge(this.#ws, command, args, `mcp-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`);
109
328
  }
110
329
 
111
- disconnect() {
112
- if (this.#ws) {
113
- try { this.#ws.close(); } catch { /* noop */ }
114
- this.#ws = null;
330
+ /**
331
+ * @param {Error} reason
332
+ * @param {string} code
333
+ */
334
+ #detach(reason, code) {
335
+ const endPrompts = this.#state === 'paired' || this.#state === 'lost';
336
+ this.#generation += 1;
337
+ this.#pairing = null;
338
+ if (endPrompts) this.#prompts.clear();
339
+ const ws = this.#ws;
340
+ this.#ws = null;
341
+ if (ws) {
342
+ try { ws.close(); } catch { /* noop */ }
115
343
  }
344
+ const err = Object.assign(reason, { code });
345
+ for (const waiter of this.#pending.values()) waiter.reject(err);
346
+ this.#pending.clear();
347
+ }
348
+
349
+ /**
350
+ * Never waits on a dead link: while unpaired or lost this rejects at once.
351
+ *
352
+ * @param {string} command
353
+ * @param {Record<string, unknown>} [args]
354
+ */
355
+ call(command, args = {}) {
356
+ if (this.#state === 'lost') return Promise.reject(pairingLostError(this.#lostReason || undefined));
357
+ if (this.#state === 'pairing') return Promise.reject(pairPendingError());
358
+ if (!this.isPaired()) return Promise.reject(notPaired());
359
+ const ws = /** @type {WebSocket} */ (this.#ws);
360
+ const id = `mcp-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
361
+ return new Promise((resolve, reject) => {
362
+ this.#pending.set(id, { resolve, reject });
363
+ try {
364
+ ws.send(JSON.stringify({ id, command, args }));
365
+ } catch {
366
+ this.#lose(ws, 'send_failed');
367
+ }
368
+ });
369
+ }
370
+
371
+ disconnect() {
372
+ this.#clearTimer();
373
+ this.#detach(new Error('Disconnected'), 'not_paired');
374
+ this.#state = 'unpaired';
375
+ this.#resumeKey = null;
116
376
  }
117
377
  }
118
378
 
@@ -13,4 +13,12 @@ export const PAIR_MSG = Object.freeze({
13
13
  UNPAIRED: 'unpaired',
14
14
  CALL: 'call',
15
15
  RESPONSE: 'response',
16
+ /** Page → paired agent. Contract v:1. */
17
+ AGENT_PROMPT: 'agent.prompt',
18
+ /** Agent → page. `{ id, delivery, error? }`. */
19
+ AGENT_PROMPT_ACK: 'agent.prompt.ack',
20
+ /** Agent → page. Contract v:1. Several replies may share one prompt id. */
21
+ AGENT_REPLY: 'agent.reply',
22
+ /** Agent → page. Contract v:1. */
23
+ AGENT_STATUS: 'agent.status',
16
24
  });
@@ -0,0 +1,232 @@
1
+ import { randomBytes } from 'node:crypto';
2
+ import { mkdir, open, stat, writeFile } from 'node:fs/promises';
3
+ import { tmpdir } from 'node:os';
4
+ import { basename, dirname, extname, isAbsolute, join, resolve } from 'node:path';
5
+
6
+ const BROWSER_KEYS = ['format', 'quality', 'max_width', 'scale'];
7
+
8
+ /**
9
+ * Browser-safe screenshot args. File paths stay on the MCP host.
10
+ * @param {Record<string, unknown>} args
11
+ */
12
+ export function browserScreenshotArgs(args) {
13
+ const out = {};
14
+ const src = args && typeof args === 'object' ? args : {};
15
+ for (const key of BROWSER_KEYS) {
16
+ if (Object.prototype.hasOwnProperty.call(src, key)) out[key] = src[key];
17
+ }
18
+ return out;
19
+ }
20
+
21
+ function interpretSaveValue(value, key) {
22
+ if (value === true) return { path: null };
23
+ if (typeof value === 'string') {
24
+ if (value.includes('\0')) {
25
+ return { error: { code: 'bad_args', message: `screenshot ${key} has an invalid path` } };
26
+ }
27
+ const trimmed = value.trim();
28
+ if (!trimmed) return { path: null };
29
+ return { path: isAbsolute(trimmed) ? resolve(trimmed) : resolve(trimmed) };
30
+ }
31
+ return { error: { code: 'bad_args', message: `screenshot ${key} must be a file path or true` } };
32
+ }
33
+
34
+ /**
35
+ * Split a screenshot tool call into browser args and an optional host save.
36
+ * `save` is null when the caller did not ask to write a file (historical
37
+ * default: the data URL is returned as-is).
38
+ * @param {Record<string, unknown>} args
39
+ */
40
+ export function prepareScreenshotCall(args) {
41
+ const src = args && typeof args === 'object' ? args : {};
42
+ const browserArgs = browserScreenshotArgs(src);
43
+ const hasTo = Object.prototype.hasOwnProperty.call(src, 'save_to');
44
+ const hasFile = Object.prototype.hasOwnProperty.call(src, 'file');
45
+ if (!hasTo && !hasFile) return { browserArgs, save: null };
46
+ const left = hasTo ? interpretSaveValue(src.save_to, 'save_to') : null;
47
+ const right = hasFile ? interpretSaveValue(src.file, 'file') : null;
48
+ if (left?.error) return { browserArgs, error: left.error };
49
+ if (right?.error) return { browserArgs, error: right.error };
50
+ const pathA = left ? left.path : null;
51
+ const pathB = right ? right.path : null;
52
+ if (pathA && pathB && pathA !== pathB) {
53
+ return {
54
+ browserArgs,
55
+ error: { code: 'bad_args', message: 'screenshot save_to and file must be the same path' },
56
+ };
57
+ }
58
+ return {
59
+ browserArgs,
60
+ save: {
61
+ path: pathA || pathB || null,
62
+ overwrite: src.overwrite === true,
63
+ },
64
+ };
65
+ }
66
+
67
+ function extensionFor(format) {
68
+ return format === 'jpeg' ? '.jpg' : '.png';
69
+ }
70
+
71
+ function uniqueName(format) {
72
+ return `surfcad-${Date.now().toString(36)}-${randomBytes(4).toString('hex')}${extensionFor(format)}`;
73
+ }
74
+
75
+ async function exists(path) {
76
+ try {
77
+ return await stat(path);
78
+ } catch (err) {
79
+ if (err?.code === 'ENOENT') return null;
80
+ throw err;
81
+ }
82
+ }
83
+
84
+ async function uniqueSibling(desired) {
85
+ const dir = dirname(desired);
86
+ const ext = extname(desired);
87
+ const base = basename(desired, ext);
88
+ for (let n = 2; n < 1000; n += 1) {
89
+ const candidate = join(dir, `${base}-${n}${ext}`);
90
+ if (!(await exists(candidate))) return candidate;
91
+ }
92
+ return join(dir, `${base}-${randomBytes(4).toString('hex')}${ext}`);
93
+ }
94
+
95
+ /**
96
+ * @param {{ path: string|null, overwrite: boolean }} save
97
+ * @param {'png'|'jpeg'} format
98
+ */
99
+ export async function resolveScreenshotDestination(save, format) {
100
+ if (!save?.path) return join(tmpdir(), uniqueName(format));
101
+ const wanted = save.path;
102
+ const current = await exists(wanted);
103
+ if (current?.isDirectory()) return join(wanted, uniqueName(format));
104
+ const parent = dirname(wanted);
105
+ const parentStat = await exists(parent);
106
+ if (!parentStat?.isDirectory()) {
107
+ const err = new Error(`screenshot save directory does not exist: ${parent}`);
108
+ err.code = 'screenshot_save_failed';
109
+ throw err;
110
+ }
111
+ if (current && !save.overwrite) return uniqueSibling(wanted);
112
+ if (!extname(wanted)) return `${wanted}${extensionFor(format)}`;
113
+ return wanted;
114
+ }
115
+
116
+ function decodeDataUrl(dataUrl) {
117
+ const match = /^data:image\/(png|jpeg);base64,([A-Za-z0-9+/=\s]+)$/i.exec(String(dataUrl || ''));
118
+ if (!match) {
119
+ const err = new Error('screenshot did not return a png or jpeg data URL');
120
+ err.code = 'screenshot_save_failed';
121
+ throw err;
122
+ }
123
+ const format = match[1].toLowerCase() === 'jpeg' ? 'jpeg' : 'png';
124
+ const bytes = Buffer.from(match[2].replace(/\s/g, ''), 'base64');
125
+ return { format, bytes };
126
+ }
127
+
128
+ async function writeBytes(path, bytes, overwrite) {
129
+ if (overwrite) {
130
+ await writeFile(path, bytes);
131
+ return path;
132
+ }
133
+ let handle;
134
+ try {
135
+ handle = await open(path, 'wx');
136
+ await handle.writeFile(bytes);
137
+ return path;
138
+ } catch (err) {
139
+ if (err?.code !== 'EEXIST') throw err;
140
+ const next = await uniqueSibling(path);
141
+ return writeBytes(next, bytes, false);
142
+ } finally {
143
+ await handle?.close();
144
+ }
145
+ }
146
+
147
+ /**
148
+ * Write the browser image and return path + size. Never includes the data URL.
149
+ * @param {{ dataUrl?: string, width?: number, height?: number }} result
150
+ * @param {{ path: string|null, overwrite: boolean }} save
151
+ */
152
+ export async function writeScreenshotResult(result, save) {
153
+ const decoded = decodeDataUrl(result?.dataUrl);
154
+ const path = await resolveScreenshotDestination(save, decoded.format);
155
+ await mkdir(dirname(path), { recursive: false }).catch((err) => {
156
+ if (err?.code !== 'EEXIST') throw err;
157
+ });
158
+ const written = await writeBytes(path, decoded.bytes, save.overwrite === true && path === save.path);
159
+ const saved = {
160
+ path: written,
161
+ size: decoded.bytes.length,
162
+ format: decoded.format,
163
+ };
164
+ if (Number.isInteger(result?.width)) saved.width = result.width;
165
+ if (Number.isInteger(result?.height)) saved.height = result.height;
166
+ return saved;
167
+ }
168
+
169
+ /**
170
+ * Screenshot tool call after the session is paired. Other tools pass through.
171
+ * @param {{ call: (name: string, args: object) => Promise<unknown> }} session
172
+ * @param {string} name
173
+ * @param {Record<string, unknown>} args
174
+ */
175
+ export async function callPairedBridgeTool(session, name, args) {
176
+ let forward = args && typeof args === 'object' ? args : {};
177
+ let save = null;
178
+ if (name === 'screenshot') {
179
+ const prepared = prepareScreenshotCall(forward);
180
+ if (prepared.error) return { value: prepared.error, isError: true };
181
+ forward = prepared.browserArgs;
182
+ save = prepared.save;
183
+ }
184
+ const result = await session.call(name, forward);
185
+ if (!save) return { value: result, isError: false };
186
+ try {
187
+ const saved = await writeScreenshotResult(result, save);
188
+ return { value: saved, isError: false };
189
+ } catch (err) {
190
+ return {
191
+ value: {
192
+ code: err?.code || 'screenshot_save_failed',
193
+ message: String(err?.message || err),
194
+ },
195
+ isError: true,
196
+ };
197
+ }
198
+ }
199
+
200
+ /**
201
+ * Add MCP-only file options to the screenshot tool. The browser catalog
202
+ * does not list them, and they are stripped before the tab is called.
203
+ * @param {{ name: string, description?: string, inputSchema?: object }} tool
204
+ */
205
+ export function augmentScreenshotTool(tool) {
206
+ if (!tool || tool.name !== 'screenshot') return tool;
207
+ const inputSchema = JSON.parse(JSON.stringify(tool.inputSchema || {
208
+ type: 'object',
209
+ additionalProperties: false,
210
+ properties: {},
211
+ }));
212
+ inputSchema.properties = {
213
+ ...(inputSchema.properties || {}),
214
+ save_to: {
215
+ description: 'Write the image on the MCP host and return { path, size } instead of base64. A string is a file path. true or "" uses a unique file in the OS temp directory. Never sent to the browser.',
216
+ anyOf: [{ type: 'string' }, { type: 'boolean' }],
217
+ },
218
+ file: {
219
+ description: 'Alias of save_to.',
220
+ anyOf: [{ type: 'string' }, { type: 'boolean' }],
221
+ },
222
+ overwrite: {
223
+ type: 'boolean',
224
+ description: 'Replace an existing file at save_to. Without this, an existing path gets a unique name.',
225
+ },
226
+ };
227
+ return {
228
+ ...tool,
229
+ description: `${tool.description || 'Capture the viewport.'} On the MCP host, save_to or file writes the image to disk and returns { path, size } instead of base64. A missing path (true or "") uses a unique file in the OS temp directory. An existing file is not replaced unless overwrite is true. The path is never sent to the browser.`,
230
+ inputSchema,
231
+ };
232
+ }