surfcad-mcp 0.2.1 → 0.2.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +60 -20
- package/data/commands.json +578 -116
- package/package.json +1 -1
- package/src/bridge/relayHub.mjs +53 -1
- package/src/bridge/relayServer.mjs +25 -2
- package/src/catalog.mjs +10 -0
- package/src/prompt/promptSession.mjs +495 -0
- package/src/prompt/promptTools.mjs +173 -0
- package/src/prompt/webhookPost.mjs +123 -0
- package/src/prompt/webhookUrl.mjs +206 -0
- package/src/relay.mjs +52 -0
- package/src/relayMessages.mjs +8 -0
- package/src/screenshotFile.mjs +232 -0
- package/src/server.mjs +71 -6
|
@@ -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,9 +18,32 @@ 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 {
|
|
23
|
+
callPromptTool,
|
|
24
|
+
isPromptTool,
|
|
25
|
+
PROMPT_ONBOARDING_NOTE,
|
|
26
|
+
PROMPT_SERVER_INSTRUCTIONS,
|
|
27
|
+
PROMPT_WEBHOOK_ACTIVE,
|
|
28
|
+
promptToolDefinitions,
|
|
29
|
+
} from './prompt/promptTools.mjs';
|
|
21
30
|
|
|
22
31
|
const PAIR_TOOL_NAME = 'pair';
|
|
23
32
|
|
|
33
|
+
const STATUS_PROMPT_NOTE = ' This process also adds webhookRegistered (true when a prompt webhook is registered; the URL and any bearer are not included) and queued (how many prompt messages are waiting for read_messages).';
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* MCP-only fields on the bridge status tool. The host command and commands.json stay unchanged.
|
|
37
|
+
* @param {{ name: string, description?: string }} tool
|
|
38
|
+
*/
|
|
39
|
+
function augmentStatusTool(tool) {
|
|
40
|
+
if (!tool || tool.name !== 'status') return tool;
|
|
41
|
+
return {
|
|
42
|
+
...tool,
|
|
43
|
+
description: `${tool.description || ''}${STATUS_PROMPT_NOTE}`,
|
|
44
|
+
};
|
|
45
|
+
}
|
|
46
|
+
|
|
24
47
|
/** A bridge call that has to pair first waits this long for Allow, then fails. */
|
|
25
48
|
const AUTO_PAIR_WAIT_MS = 1000;
|
|
26
49
|
/** The pair tool returns pair_pending before typical MCP client timeouts (60 s). */
|
|
@@ -52,6 +75,29 @@ function textResult(value, isError = false) {
|
|
|
52
75
|
};
|
|
53
76
|
}
|
|
54
77
|
|
|
78
|
+
/**
|
|
79
|
+
* Pair success is ordinary text content so every MCP client, including Claude Code,
|
|
80
|
+
* shows the note. No structuredContent and no _meta.
|
|
81
|
+
* @param {Record<string, unknown>} result
|
|
82
|
+
* @param {{ webhookRegistered: () => boolean }} prompts
|
|
83
|
+
*/
|
|
84
|
+
function pairToolResult(result, prompts) {
|
|
85
|
+
const webhookRegistered = prompts.webhookRegistered() === true;
|
|
86
|
+
const note = webhookRegistered ? PROMPT_WEBHOOK_ACTIVE : PROMPT_ONBOARDING_NOTE;
|
|
87
|
+
const payload = {
|
|
88
|
+
...(result && typeof result === 'object' ? result : {}),
|
|
89
|
+
webhookRegistered,
|
|
90
|
+
note,
|
|
91
|
+
};
|
|
92
|
+
return {
|
|
93
|
+
content: [
|
|
94
|
+
{ type: 'text', text: JSON.stringify(payload, null, 2) },
|
|
95
|
+
{ type: 'text', text: note },
|
|
96
|
+
],
|
|
97
|
+
isError: false,
|
|
98
|
+
};
|
|
99
|
+
}
|
|
100
|
+
|
|
55
101
|
function toolErrorPayload(err) {
|
|
56
102
|
if (err && typeof err === 'object' && err.code) {
|
|
57
103
|
return formatBridgeError({
|
|
@@ -71,18 +117,21 @@ function toolErrorPayload(err) {
|
|
|
71
117
|
export async function createSurfcadMcpServer(options = {}) {
|
|
72
118
|
const catalog = options.catalog || loadCommandsCatalog();
|
|
73
119
|
const session = options.session || new RelaySession();
|
|
74
|
-
const bridgeTools = bridgeToolDefinitions(catalog);
|
|
120
|
+
const bridgeTools = bridgeToolDefinitions(catalog).map((tool) => augmentStatusTool(augmentScreenshotTool(tool)));
|
|
75
121
|
|
|
76
122
|
const server = new Server(
|
|
77
123
|
{ name: 'surfcad-mcp', version: loadPackageVersion() },
|
|
78
|
-
{
|
|
124
|
+
{
|
|
125
|
+
capabilities: { tools: {} },
|
|
126
|
+
instructions: PROMPT_SERVER_INSTRUCTIONS,
|
|
127
|
+
},
|
|
79
128
|
);
|
|
80
129
|
|
|
81
130
|
server.setRequestHandler(ListToolsRequestSchema, async () => ({
|
|
82
131
|
tools: [
|
|
83
132
|
{
|
|
84
133
|
name: PAIR_TOOL_NAME,
|
|
85
|
-
description: `Pair this MCP server to an open SurfCAD tab via the local WebSocket relay. ${pairingEnvHint()}`,
|
|
134
|
+
description: `Pair this MCP server to an open SurfCAD tab via the local WebSocket relay. ${pairingEnvHint()} ${PROMPT_SERVER_INSTRUCTIONS}`,
|
|
86
135
|
inputSchema: {
|
|
87
136
|
type: 'object',
|
|
88
137
|
additionalProperties: false,
|
|
@@ -94,6 +143,7 @@ export async function createSurfcadMcpServer(options = {}) {
|
|
|
94
143
|
},
|
|
95
144
|
},
|
|
96
145
|
},
|
|
146
|
+
...promptToolDefinitions(),
|
|
97
147
|
...bridgeTools,
|
|
98
148
|
],
|
|
99
149
|
}));
|
|
@@ -104,6 +154,17 @@ export async function createSurfcadMcpServer(options = {}) {
|
|
|
104
154
|
? request.params.arguments
|
|
105
155
|
: {};
|
|
106
156
|
|
|
157
|
+
if (isPromptTool(name)) {
|
|
158
|
+
if (name !== 'set_status') session.noteAgentToolCall();
|
|
159
|
+
try {
|
|
160
|
+
const out = await callPromptTool(session.prompts, name, args);
|
|
161
|
+
if (out.isError) return textResult(out.error, true);
|
|
162
|
+
return { content: out.content, isError: false };
|
|
163
|
+
} catch (err) {
|
|
164
|
+
return textResult(toolErrorPayload(err), true);
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
|
|
107
168
|
if (name === PAIR_TOOL_NAME) {
|
|
108
169
|
const code = typeof args.code === 'string' && args.code.trim()
|
|
109
170
|
? args.code.trim()
|
|
@@ -116,7 +177,7 @@ export async function createSurfcadMcpServer(options = {}) {
|
|
|
116
177
|
}
|
|
117
178
|
try {
|
|
118
179
|
const result = await waitForPairing(session.pair(code), PAIR_TOOL_WAIT_MS);
|
|
119
|
-
return
|
|
180
|
+
return pairToolResult(result, session.prompts);
|
|
120
181
|
} catch (err) {
|
|
121
182
|
return textResult(toolErrorPayload(err), true);
|
|
122
183
|
}
|
|
@@ -143,8 +204,12 @@ export async function createSurfcadMcpServer(options = {}) {
|
|
|
143
204
|
}
|
|
144
205
|
|
|
145
206
|
try {
|
|
146
|
-
|
|
147
|
-
|
|
207
|
+
session.noteAgentToolCall();
|
|
208
|
+
const out = await callPairedBridgeTool(session, name, args);
|
|
209
|
+
if (name === 'status' && out.isError !== true && out.value && typeof out.value === 'object' && !Array.isArray(out.value)) {
|
|
210
|
+
return textResult({ ...out.value, ...session.prompts.deliveryStatus() });
|
|
211
|
+
}
|
|
212
|
+
return textResult(out.value, out.isError === true);
|
|
148
213
|
} catch (err) {
|
|
149
214
|
const code = err?.code;
|
|
150
215
|
if (
|