surfcad-mcp 0.2.1 → 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.
@@ -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
+ }
package/src/server.mjs CHANGED
@@ -18,6 +18,8 @@ import {
18
18
  stopAgentBridgeRelay,
19
19
  } from './bridge/relayServer.mjs';
20
20
  import { RelaySession } from './relay.mjs';
21
+ import { augmentScreenshotTool, callPairedBridgeTool } from './screenshotFile.mjs';
22
+ import { callPromptTool, isPromptTool, promptToolDefinitions } from './prompt/promptTools.mjs';
21
23
 
22
24
  const PAIR_TOOL_NAME = 'pair';
23
25
 
@@ -71,7 +73,7 @@ function toolErrorPayload(err) {
71
73
  export async function createSurfcadMcpServer(options = {}) {
72
74
  const catalog = options.catalog || loadCommandsCatalog();
73
75
  const session = options.session || new RelaySession();
74
- const bridgeTools = bridgeToolDefinitions(catalog);
76
+ const bridgeTools = bridgeToolDefinitions(catalog).map((tool) => augmentScreenshotTool(tool));
75
77
 
76
78
  const server = new Server(
77
79
  { name: 'surfcad-mcp', version: loadPackageVersion() },
@@ -94,6 +96,7 @@ export async function createSurfcadMcpServer(options = {}) {
94
96
  },
95
97
  },
96
98
  },
99
+ ...promptToolDefinitions(),
97
100
  ...bridgeTools,
98
101
  ],
99
102
  }));
@@ -104,6 +107,17 @@ export async function createSurfcadMcpServer(options = {}) {
104
107
  ? request.params.arguments
105
108
  : {};
106
109
 
110
+ if (isPromptTool(name)) {
111
+ if (name !== 'set_status') session.noteAgentToolCall();
112
+ try {
113
+ const out = await callPromptTool(session.prompts, name, args);
114
+ if (out.isError) return textResult(out.error, true);
115
+ return { content: out.content, isError: false };
116
+ } catch (err) {
117
+ return textResult(toolErrorPayload(err), true);
118
+ }
119
+ }
120
+
107
121
  if (name === PAIR_TOOL_NAME) {
108
122
  const code = typeof args.code === 'string' && args.code.trim()
109
123
  ? args.code.trim()
@@ -143,8 +157,9 @@ export async function createSurfcadMcpServer(options = {}) {
143
157
  }
144
158
 
145
159
  try {
146
- const result = await session.call(name, args);
147
- return textResult(result);
160
+ session.noteAgentToolCall();
161
+ const out = await callPairedBridgeTool(session, name, args);
162
+ return textResult(out.value, out.isError === true);
148
163
  } catch (err) {
149
164
  const code = err?.code;
150
165
  if (