surfcad-mcp 0.3.8 → 0.4.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/README.md +102 -49
- package/bin/surfcad-mcp.js +4 -3
- package/data/commands.json +6481 -5817
- package/data/helpers.json +243 -268
- package/package.json +2 -2
- package/src/cli.mjs +234 -24
- package/src/cliCall.mjs +221 -0
- package/src/errors.mjs +8 -5
- package/src/helpers.mjs +7 -5
- package/src/importFile.mjs +186 -0
- package/src/listen/bootstrap.mjs +285 -0
- package/src/listen/claudeCodeWake.mjs +74 -0
- package/src/listen/daemon.mjs +40 -0
- package/src/listen/listenCli.mjs +157 -27
- package/src/listen/listener.mjs +138 -8
- package/src/listen/owner.mjs +293 -0
- package/src/listen/waitCli.mjs +133 -0
- package/src/listen/wake.mjs +42 -8
- package/src/listen/wakeConfig.mjs +17 -2
- package/src/listen/wakeSetupText.mjs +53 -14
- package/src/pairWait.mjs +3 -3
- package/src/pairingCode.mjs +10 -0
- package/src/prompt/buildGuidance.mjs +9 -7
- package/src/prompt/chatFlow.mjs +15 -0
- package/src/prompt/errorHints.mjs +24 -10
- package/src/prompt/guide.mjs +31 -18
- package/src/prompt/promptSession.mjs +74 -10
- package/src/prompt/promptTools.mjs +10 -15
- package/src/prompt/replyConfirm.mjs +69 -0
- package/src/relayMessages.mjs +43 -1
- package/src/remote/config.mjs +17 -13
- package/src/remote/session.mjs +103 -5
- package/src/remote/tokenStore.mjs +20 -0
- package/src/room/seat.mjs +334 -0
- package/src/screenshotFile.mjs +9 -0
- package/src/server.mjs +241 -119
- package/src/stepUploadLimit.mjs +8 -0
- package/src/bridge/bridgePage.mjs +0 -132
- package/src/bridge/bridgePopup.mjs +0 -288
- package/src/bridge/relayHub.mjs +0 -556
- package/src/bridge/relayServer.mjs +0 -291
- package/src/nodeClient.mjs +0 -63
- package/src/relay.mjs +0 -419
package/src/server.mjs
CHANGED
|
@@ -15,22 +15,17 @@ import {
|
|
|
15
15
|
pairingEnvHint,
|
|
16
16
|
} from './errors.mjs';
|
|
17
17
|
import { loadPackageVersion } from './packageVersion.mjs';
|
|
18
|
-
import {
|
|
19
|
-
ensureAgentBridgeRelay,
|
|
20
|
-
resetAgentBridgeRelayCache,
|
|
21
|
-
stopAgentBridgeRelay,
|
|
22
|
-
} from './bridge/relayServer.mjs';
|
|
23
|
-
import { RelaySession } from './relay.mjs';
|
|
24
18
|
import { resolveAgentName, resolveServerUrl } from './remote/config.mjs';
|
|
25
19
|
import { handleRemoteStdinEnd, installRemoteProcessExitLogs } from './remote/processExit.mjs';
|
|
26
20
|
import { RemoteSession } from './remote/session.mjs';
|
|
27
|
-
import {
|
|
21
|
+
import { claimOwner, hostSession, ownerAttached, ownerStatus, readOwner, wakeTarget } from './listen/owner.mjs';
|
|
22
|
+
import { forgetLoginIfToken, readSavedLogin } from './remote/tokenStore.mjs';
|
|
28
23
|
import { waitForPairing } from './pairWait.mjs';
|
|
24
|
+
import { augmentBenchShowTool, augmentImportTool } from './importFile.mjs';
|
|
29
25
|
import { augmentScreenshotTool, callPairedBridgeTool } from './screenshotFile.mjs';
|
|
30
26
|
import {
|
|
31
27
|
callPromptTool,
|
|
32
28
|
isPromptTool,
|
|
33
|
-
PROMPT_ONBOARDING_NOTE,
|
|
34
29
|
PROMPT_SERVER_INSTRUCTIONS,
|
|
35
30
|
PROMPT_WEBHOOK_ACTIVE,
|
|
36
31
|
promptToolDefinitions,
|
|
@@ -48,7 +43,8 @@ import { callListHelpersTool, LIST_HELPERS_TOOL_NAME, listHelpersToolDefinition
|
|
|
48
43
|
import { mergeRegisteredIntoListCommands } from './listCommandsMerge.mjs';
|
|
49
44
|
import { agentAwake, stampAwake } from './listen/awake.mjs';
|
|
50
45
|
import { readListenerPid } from './listen/daemon.mjs';
|
|
51
|
-
import {
|
|
46
|
+
import { bootstrapWake } from './listen/bootstrap.mjs';
|
|
47
|
+
import { wakeReadinessNote } from './listen/listenCli.mjs';
|
|
52
48
|
import { createWaker, wakePayload } from './listen/wake.mjs';
|
|
53
49
|
import { readWake } from './listen/wakeConfig.mjs';
|
|
54
50
|
import { tabAdvertisesTool } from './unlistedTools.mjs';
|
|
@@ -56,7 +52,7 @@ import { tabAdvertisesTool } from './unlistedTools.mjs';
|
|
|
56
52
|
const PAIR_TOOL_NAME = 'pair';
|
|
57
53
|
|
|
58
54
|
/** One line in the pair result; the guidance itself is guide { topic: "start" } and guide { topic: "chat" }. */
|
|
59
|
-
const PAIR_GUIDE_POINTER = 'Before the first model call read guide { topic: "start" } (how to build in SurfCAD: block out first, features first, hardware as patterned parts). guide { topic: "chat" } is the required in-viewer chat workflow:
|
|
55
|
+
const PAIR_GUIDE_POINTER = 'Before the first model call read guide { topic: "start" } (how to build in SurfCAD: block out first, features first, hardware as patterned parts). guide { topic: "chat" } is the required in-viewer chat workflow: idle wake (section A), ack first, and the 10 second read_messages long-poll while connected. guide {} lists every topic.';
|
|
60
56
|
|
|
61
57
|
/**
|
|
62
58
|
* Prompt tools that do not count as agent activity when called. set_status,
|
|
@@ -65,7 +61,81 @@ const PAIR_GUIDE_POINTER = 'Before the first model call read guide { topic: "sta
|
|
|
65
61
|
*/
|
|
66
62
|
const PROMPT_TOOLS_WITHOUT_ACTIVITY = new Set(['set_status', 'post_progress', 'close_session', 'read_messages']);
|
|
67
63
|
|
|
68
|
-
|
|
64
|
+
/**
|
|
65
|
+
* Chat messages waiting for this agent, for every tool result, so an agent in
|
|
66
|
+
* the middle of a build sees a message on its very next call instead of only
|
|
67
|
+
* at its next read_messages. null when nothing waits (the result is unchanged).
|
|
68
|
+
* @param {{ queuedIds?: () => string[] } | null | undefined} prompts
|
|
69
|
+
* @returns {{ count: number, ids: string[], next: string } | null}
|
|
70
|
+
*/
|
|
71
|
+
export function pendingPromptsNotice(prompts) {
|
|
72
|
+
const ids = typeof prompts?.queuedIds === 'function' ? prompts.queuedIds() : [];
|
|
73
|
+
if (!Array.isArray(ids) || ids.length === 0) return null;
|
|
74
|
+
return {
|
|
75
|
+
count: ids.length,
|
|
76
|
+
ids: ids.slice(0, 10),
|
|
77
|
+
next: 'read_messages {} now, then set_status { state: "responding", id } for each',
|
|
78
|
+
};
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/**
|
|
82
|
+
* The agent's display name for the chat cap, from the MCP client name.
|
|
83
|
+
* @param {unknown} clientName
|
|
84
|
+
*/
|
|
85
|
+
export function agentDisplayName(clientName) {
|
|
86
|
+
const raw = typeof clientName === 'string' ? clientName.trim() : '';
|
|
87
|
+
if (!raw) return '';
|
|
88
|
+
const known = { 'claude-code': 'Claude Code', 'claude-ai': 'Claude', cursor: 'Cursor', 'grok-bot': 'Grok Bot' };
|
|
89
|
+
if (known[raw.toLowerCase()]) return known[raw.toLowerCase()];
|
|
90
|
+
return raw.replace(/[-_]+/g, ' ').replace(/\b\w/g, (c) => c.toUpperCase()).slice(0, 40);
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/**
|
|
94
|
+
* Merge extra fields into a tool result: into an object result, else as one
|
|
95
|
+
* more text block.
|
|
96
|
+
* @param {{ content: Array<{ type: string, text?: string }>, isError?: boolean }} result
|
|
97
|
+
* @param {Record<string, unknown>} fields
|
|
98
|
+
*/
|
|
99
|
+
export function withNotice(result, fields) {
|
|
100
|
+
if (!result || !Array.isArray(result.content)) return result;
|
|
101
|
+
const first = result.content[0];
|
|
102
|
+
if (result.content.length === 1 && first?.type === 'text') {
|
|
103
|
+
try {
|
|
104
|
+
const value = JSON.parse(first.text);
|
|
105
|
+
if (value && typeof value === 'object' && !Array.isArray(value)) {
|
|
106
|
+
return { ...result, content: [{ type: 'text', text: JSON.stringify({ ...value, ...fields }) }] };
|
|
107
|
+
}
|
|
108
|
+
} catch {
|
|
109
|
+
/* plain text: add a block below */
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
return { ...result, content: [...result.content, { type: 'text', text: JSON.stringify(fields) }] };
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/**
|
|
116
|
+
* Add `pendingPrompts` to a tool result when chat messages are waiting. An
|
|
117
|
+
* object result gets the field; any other result gets one more text block.
|
|
118
|
+
* @param {{ content: Array<{ type: string, text?: string }>, isError?: boolean }} result
|
|
119
|
+
* @param {{ queuedIds?: () => string[] } | null | undefined} prompts
|
|
120
|
+
*/
|
|
121
|
+
export function withPendingPrompts(result, prompts) {
|
|
122
|
+
const pending = pendingPromptsNotice(prompts);
|
|
123
|
+
if (!pending || !result || !Array.isArray(result.content)) return result;
|
|
124
|
+
const first = result.content[0];
|
|
125
|
+
if (result.content.length === 1 && first?.type === 'text') {
|
|
126
|
+
try {
|
|
127
|
+
const value = JSON.parse(first.text);
|
|
128
|
+
if (value && typeof value === 'object' && !Array.isArray(value)) {
|
|
129
|
+
return { ...result, content: [{ type: 'text', text: JSON.stringify({ ...value, pendingPrompts: pending }) }] };
|
|
130
|
+
}
|
|
131
|
+
} catch {
|
|
132
|
+
/* plain text: add a block below */
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
return { ...result, content: [...result.content, { type: 'text', text: JSON.stringify({ pendingPrompts: pending }) }] };
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
const STATUS_WAKE_NOTE = ' It also adds mcpVersion (this surfcad-mcp package), host ({ name, version }: what your MCP client calls itself, null when it did not say) and wake ({ coldWake, forms, source, listenerRunning, note }): whether a chat message can start a session of you while you are idle. coldWake is "ready", "listener_stopped" or "unavailable"; with "unavailable" messages reach you only while you are in a turn and polling (guide { topic: "chat" } section A).';
|
|
69
139
|
|
|
70
140
|
const STATUS_PROMPT_NOTE = ' This process also adds webhookRegistered (true when a prompt webhook is registered; the URL and any bearer are not included), queued (prompt messages waiting for read_messages; cancelled prompts are not counted), counts ({ queued, delivered, replied, cancelled }), and last ({ id, state } of the latest prompt, or null).';
|
|
71
141
|
|
|
@@ -90,16 +160,11 @@ function registeredToolDefinitions(bridgeTools) {
|
|
|
90
160
|
return [
|
|
91
161
|
{
|
|
92
162
|
name: PAIR_TOOL_NAME,
|
|
93
|
-
description: `
|
|
163
|
+
description: `Connect this MCP server to the SurfCAD tab that redeemed the saved login. Call pair {} with no code. Pairing itself is npx surfcad-mcp login --code with the join code from Connect Agent (ABCD-EFGH; the hyphen is optional). pair {} starts the wake listener and fires the test wake once per login. SurfCAD greets the user itself; do not send a greeting. ${pairingEnvHint()} ${PROMPT_SERVER_INSTRUCTIONS} After pairing call guide { topic: "start" } (How to build in SurfCAD: block out first, features first, hardware as patterned parts) before the first model call.`,
|
|
94
164
|
inputSchema: {
|
|
95
165
|
type: 'object',
|
|
96
166
|
additionalProperties: false,
|
|
97
|
-
properties: {
|
|
98
|
-
code: {
|
|
99
|
-
type: 'string',
|
|
100
|
-
description: '8-character pairing code from the SurfCAD Local agent panel',
|
|
101
|
-
},
|
|
102
|
-
},
|
|
167
|
+
properties: {},
|
|
103
168
|
},
|
|
104
169
|
},
|
|
105
170
|
guideToolDefinition(),
|
|
@@ -121,8 +186,6 @@ function augmentListCommandsTool(tool, extraNames) {
|
|
|
121
186
|
};
|
|
122
187
|
}
|
|
123
188
|
|
|
124
|
-
/** A bridge call that has to pair first waits this long for Allow, then fails. */
|
|
125
|
-
const AUTO_PAIR_WAIT_MS = 1000;
|
|
126
189
|
/** The pair tool returns pair_pending before typical MCP client timeouts (60 s). */
|
|
127
190
|
const PAIR_TOOL_WAIT_MS = 30_000;
|
|
128
191
|
|
|
@@ -176,12 +239,15 @@ export function withDefaultReturn(row, args) {
|
|
|
176
239
|
* @param {string} name
|
|
177
240
|
*/
|
|
178
241
|
function mutatingTool(name) {
|
|
179
|
-
return /^(set_script|run|insert_|invoke_helper|confirm_feature|delete_feature|rollback_to|undo|redo|create_|delete_|rename_|part_set_transform|insert_part|open_|paint_confirm|paint$|joint_commit|sheet_commit|sheet_set_params|sheet_edit|sketch_commit|slot_commit|hole_commit|git_|export_|edit_feature|pick_done|select_)/.test(name);
|
|
242
|
+
return /^(set_script|run|insert_|invoke_helper|confirm_feature|delete_feature|rollback_to|undo|redo|create_|delete_|rename_|part_set_transform|set_part_placement|insert_part|open_|paint_confirm|paint$|joint_commit|sheet_commit|sheet_set_params|sheet_edit|sketch_commit|slot_commit|hole_commit|boss_commit|git_|export_|edit_feature|pick_done|select_)/.test(name);
|
|
180
243
|
}
|
|
181
244
|
|
|
182
245
|
function pairToolResult(result, prompts, wake) {
|
|
183
246
|
const webhookRegistered = prompts.webhookRegistered() === true;
|
|
184
|
-
|
|
247
|
+
// The note is what is true about reaching this agent while it is idle. It
|
|
248
|
+
// used to be "ask the user for a webhook URL and key"; an agent relayed
|
|
249
|
+
// that to the user on every pair. The user is never asked now.
|
|
250
|
+
const note = [wake?.note, webhookRegistered ? PROMPT_WEBHOOK_ACTIVE : ''].filter(Boolean).join(' ');
|
|
185
251
|
const payload = {
|
|
186
252
|
...(result && typeof result === 'object' ? result : {}),
|
|
187
253
|
webhookRegistered,
|
|
@@ -191,9 +257,7 @@ function pairToolResult(result, prompts, wake) {
|
|
|
191
257
|
return {
|
|
192
258
|
content: [
|
|
193
259
|
{ type: 'text', text: JSON.stringify(payload, null, 2) },
|
|
194
|
-
{ type: 'text', text: note },
|
|
195
|
-
// The install step an agent must not skip: without it the user cannot reach an idle agent.
|
|
196
|
-
...(wake?.note ? [{ type: 'text', text: wake.note }] : []),
|
|
260
|
+
...(note ? [{ type: 'text', text: note }] : []),
|
|
197
261
|
// The build guidance lives in the guide tool; one pointer here, for every client.
|
|
198
262
|
{ type: 'text', text: PAIR_GUIDE_POINTER },
|
|
199
263
|
],
|
|
@@ -205,15 +269,51 @@ function pairToolResult(result, prompts, wake) {
|
|
|
205
269
|
* The wake setup on this machine, for the pair and status results.
|
|
206
270
|
* @param {{ status?: () => { remote?: boolean } }} session
|
|
207
271
|
*/
|
|
208
|
-
async function wakeStatus(session) {
|
|
209
|
-
const state = await wakeSetupState(process.env);
|
|
272
|
+
async function wakeStatus(session, opts = {}) {
|
|
210
273
|
let remote = false;
|
|
211
274
|
try {
|
|
212
275
|
remote = session?.status?.()?.remote === true;
|
|
213
276
|
} catch {
|
|
214
277
|
remote = false;
|
|
215
278
|
}
|
|
216
|
-
|
|
279
|
+
const env = process.env;
|
|
280
|
+
// A test run must never start a listener or wake an agent on the machine
|
|
281
|
+
// it runs on: off under node --test and NODE_ENV=test, and every harness
|
|
282
|
+
// that spawns this server sets SURFCAD_WAKE_BOOTSTRAP=0. That switch
|
|
283
|
+
// turns the bootstrap off for anyone; =1 turns it on inside a test.
|
|
284
|
+
const enabled = env.SURFCAD_WAKE_BOOTSTRAP === '1'
|
|
285
|
+
|| (env.SURFCAD_WAKE_BOOTSTRAP !== '0' && !env.NODE_TEST_CONTEXT && env.NODE_ENV !== 'test');
|
|
286
|
+
const state = await bootstrapWake({
|
|
287
|
+
env,
|
|
288
|
+
remote,
|
|
289
|
+
check: enabled && opts.check === true,
|
|
290
|
+
tellUser: opts.tellUser !== false,
|
|
291
|
+
autoListen: enabled,
|
|
292
|
+
});
|
|
293
|
+
return {
|
|
294
|
+
coldWake: state.coldWake,
|
|
295
|
+
forms: state.forms,
|
|
296
|
+
source: state.source,
|
|
297
|
+
listenerRunning: state.listenerRunning,
|
|
298
|
+
note: wakeReadinessNote(state, { remote }),
|
|
299
|
+
};
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
/**
|
|
303
|
+
* The MCP client's own name and version, for `status`: what the host calls
|
|
304
|
+
* itself, so wording can be keyed to it once a playtest has shown it.
|
|
305
|
+
* @param {{ getClientVersion?: () => { name?: string, version?: string } | undefined }} server
|
|
306
|
+
*/
|
|
307
|
+
function hostInfo(server) {
|
|
308
|
+
try {
|
|
309
|
+
const info = server?.getClientVersion?.();
|
|
310
|
+
if (!info || typeof info !== 'object') return null;
|
|
311
|
+
const name = typeof info.name === 'string' ? info.name.slice(0, 120) : '';
|
|
312
|
+
const version = typeof info.version === 'string' ? info.version.slice(0, 40) : '';
|
|
313
|
+
return name || version ? { name, version } : null;
|
|
314
|
+
} catch {
|
|
315
|
+
return null;
|
|
316
|
+
}
|
|
217
317
|
}
|
|
218
318
|
|
|
219
319
|
/**
|
|
@@ -250,6 +350,8 @@ export function createInProcessWake(options) {
|
|
|
250
350
|
const wake = async (prompts) => {
|
|
251
351
|
try {
|
|
252
352
|
if (options.remote && await readListenerPid(env)) return { ok: false, skipped: 'listener' };
|
|
353
|
+
// The chat's owner is waiting (surfcad-mcp wait): its waiter delivers.
|
|
354
|
+
if (await ownerAttached(env)) return { ok: false, skipped: 'owner_waiting' };
|
|
253
355
|
let pending = Array.isArray(prompts) ? prompts : [];
|
|
254
356
|
// Up to ten minutes of an agent that keeps working without reading.
|
|
255
357
|
for (let tries = 0; tries < 40 && await isAwake(); tries += 1) {
|
|
@@ -265,7 +367,10 @@ export function createInProcessWake(options) {
|
|
|
265
367
|
waker = createWaker(config, { env, ...(options.deps || {}) });
|
|
266
368
|
wakerKey = key;
|
|
267
369
|
}
|
|
268
|
-
|
|
370
|
+
// The chat's owner answers: its conversation resumed, or a fork of it
|
|
371
|
+
// when it is open but idle. No owner: a fresh session.
|
|
372
|
+
const target = await wakeTarget(env).catch(() => ({ action: 'fresh' }));
|
|
373
|
+
const outcome = await waker.wake(wakePayload(prompts, { session: target.action === 'busy' ? { ...target, action: 'fork' } : target }));
|
|
269
374
|
log(outcome.ok ? `woke the agent by ${outcome.form} for an unread chat message` : `wake failed (${outcome.error})`);
|
|
270
375
|
return outcome;
|
|
271
376
|
} catch {
|
|
@@ -279,7 +384,38 @@ export function createInProcessWake(options) {
|
|
|
279
384
|
return wake;
|
|
280
385
|
}
|
|
281
386
|
|
|
387
|
+
/**
|
|
388
|
+
* The login this process runs on (server relay only), until the server says
|
|
389
|
+
* it is dead.
|
|
390
|
+
* @type {{ token: string, env: NodeJS.ProcessEnv, clear?: () => void } | null}
|
|
391
|
+
*/
|
|
392
|
+
let liveLogin = null;
|
|
393
|
+
|
|
394
|
+
/**
|
|
395
|
+
* The user disconnected this agent in SurfCAD, or the pairing expired. The
|
|
396
|
+
* token is dead on the server. Drop the saved copy and the webhook so
|
|
397
|
+
* nothing here reuses it: the next step is an explicit `surfcad-mcp login`.
|
|
398
|
+
* @param {unknown} code
|
|
399
|
+
*/
|
|
400
|
+
export function forgetDeadLogin(code) {
|
|
401
|
+
if (!liveLogin || (code !== 'token_revoked' && code !== 'expired')) return Promise.resolve(false);
|
|
402
|
+
const { token, env, clear } = liveLogin;
|
|
403
|
+
liveLogin = null;
|
|
404
|
+
try {
|
|
405
|
+
clear?.();
|
|
406
|
+
} catch {
|
|
407
|
+
/* the webhook is process memory; nothing else to undo */
|
|
408
|
+
}
|
|
409
|
+
return forgetLoginIfToken(token, env);
|
|
410
|
+
}
|
|
411
|
+
|
|
412
|
+
/** Test hook: the login `forgetDeadLogin` acts on. */
|
|
413
|
+
export function _setLiveLogin(login) {
|
|
414
|
+
liveLogin = login;
|
|
415
|
+
}
|
|
416
|
+
|
|
282
417
|
function toolErrorPayload(err) {
|
|
418
|
+
if (err && typeof err === 'object') void forgetDeadLogin(err.code);
|
|
283
419
|
if (err && typeof err === 'object' && err.code) {
|
|
284
420
|
return formatBridgeError({
|
|
285
421
|
code: err.code,
|
|
@@ -293,13 +429,19 @@ function toolErrorPayload(err) {
|
|
|
293
429
|
}
|
|
294
430
|
|
|
295
431
|
/**
|
|
296
|
-
* @param {{ catalog?: ReturnType<typeof loadCommandsCatalog>, session
|
|
432
|
+
* @param {{ catalog?: ReturnType<typeof loadCommandsCatalog>, session: import('./remote/session.mjs').RemoteSession }} options
|
|
297
433
|
*/
|
|
298
434
|
export async function createSurfcadMcpServer(options = {}) {
|
|
299
435
|
const catalog = options.catalog || loadCommandsCatalog();
|
|
300
|
-
|
|
436
|
+
if (!options.session) {
|
|
437
|
+
throw Object.assign(
|
|
438
|
+
new Error('createSurfcadMcpServer requires a session. Run npx surfcad-mcp login --code CODE.'),
|
|
439
|
+
{ code: 'not_logged_in' },
|
|
440
|
+
);
|
|
441
|
+
}
|
|
442
|
+
const session = options.session;
|
|
301
443
|
const bridgeNames = new Set(catalog.commands.map((command) => command.name));
|
|
302
|
-
const bridgeTools = bridgeToolDefinitions(catalog).map((tool) => augmentStatusTool(augmentScreenshotTool(tool)));
|
|
444
|
+
const bridgeTools = bridgeToolDefinitions(catalog).map((tool) => augmentStatusTool(augmentBenchShowTool(augmentImportTool(augmentScreenshotTool(tool)))));
|
|
303
445
|
/** Names outside the shipped catalog the paired tab was asked about (tabAdvertisesTool). */
|
|
304
446
|
const unlistedToolCache = new Map();
|
|
305
447
|
const mcpOnlyNames = registeredToolDefinitions(bridgeTools)
|
|
@@ -337,7 +479,38 @@ export async function createSurfcadMcpServer(options = {}) {
|
|
|
337
479
|
tools: registeredTools,
|
|
338
480
|
}));
|
|
339
481
|
|
|
482
|
+
/** This process's session answered a chat prompt and owned the chat. */
|
|
483
|
+
let ownedChat = false;
|
|
484
|
+
|
|
340
485
|
server.setRequestHandler(CallToolRequestSchema, async (request) => {
|
|
486
|
+
const result = await handleToolCall(request);
|
|
487
|
+
const moved = ownedChat ? await chatMovedNotice() : null;
|
|
488
|
+
// read_messages is how the waiting messages are taken: no notice on it.
|
|
489
|
+
if (request.params.name === 'read_messages') return moved ? withNotice(result, { chatMoved: moved }) : result;
|
|
490
|
+
const out = withPendingPrompts(result, session.prompts);
|
|
491
|
+
return moved ? withNotice(out, { chatMoved: moved }) : out;
|
|
492
|
+
});
|
|
493
|
+
|
|
494
|
+
/**
|
|
495
|
+
* The chat this session owned now belongs to another session (a fork of
|
|
496
|
+
* this one answered while it was idle, or the user started over). Said
|
|
497
|
+
* once, then this process stops tracking it.
|
|
498
|
+
*/
|
|
499
|
+
async function chatMovedNotice() {
|
|
500
|
+
const me = hostSession(process.env);
|
|
501
|
+
if (!me) return null;
|
|
502
|
+
const owner = await readOwner(process.env).catch(() => null);
|
|
503
|
+
if (owner && owner.session === me.session) return null;
|
|
504
|
+
ownedChat = false;
|
|
505
|
+
return {
|
|
506
|
+
to: owner?.session || null,
|
|
507
|
+
message: owner
|
|
508
|
+
? 'The SurfCAD chat moved to another agent session (it answered while you were idle). Stop waiting for chat messages here; do not reply to old prompts.'
|
|
509
|
+
: 'The SurfCAD chat was released (the user deleted the chat history). Stop waiting for chat messages here.',
|
|
510
|
+
};
|
|
511
|
+
}
|
|
512
|
+
|
|
513
|
+
async function handleToolCall(request) {
|
|
341
514
|
// A tool call means the agent is in a turn: the wake leaves it alone.
|
|
342
515
|
void stampAwake(process.env);
|
|
343
516
|
const name = request.params.name;
|
|
@@ -361,6 +534,12 @@ export async function createSurfcadMcpServer(options = {}) {
|
|
|
361
534
|
try {
|
|
362
535
|
const out = await callPromptTool(session.prompts, name, args);
|
|
363
536
|
if (out.isError) return errorResult(out.error, name);
|
|
537
|
+
// Answering a chat prompt makes this session the chat's owner: the
|
|
538
|
+
// user's next message, however late, goes to it (owner.mjs).
|
|
539
|
+
if (name === 'reply_to_user' || (name === 'set_status' && (args.state === 'responding' || args.state === 'typing'))) {
|
|
540
|
+
const claimed = await claimOwner(process.env).catch(() => null);
|
|
541
|
+
if (claimed?.owner) ownedChat = true;
|
|
542
|
+
}
|
|
364
543
|
return { content: out.content, isError: false };
|
|
365
544
|
} catch (err) {
|
|
366
545
|
return errorResult(toolErrorPayload(err), name);
|
|
@@ -368,18 +547,11 @@ export async function createSurfcadMcpServer(options = {}) {
|
|
|
368
547
|
}
|
|
369
548
|
|
|
370
549
|
if (name === PAIR_TOOL_NAME) {
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
: (process.env.SURFCAD_PAIRING_CODE || '').trim();
|
|
374
|
-
if (!code) {
|
|
375
|
-
return errorResult({
|
|
376
|
-
code: 'bad_pairing_code',
|
|
377
|
-
message: `Missing pairing code. Pass { "code": "........" } or set SURFCAD_PAIRING_CODE. ${pairingEnvHint()}`,
|
|
378
|
-
}, name);
|
|
379
|
-
}
|
|
550
|
+
// The saved login is the pairing. pair {} connects and runs the
|
|
551
|
+
// bootstrap. A code is not accepted here: login --code redeems it.
|
|
380
552
|
try {
|
|
381
|
-
const result = await waitForPairing(session.pair(
|
|
382
|
-
return pairToolResult(result, session.prompts, await wakeStatus(session));
|
|
553
|
+
const result = await waitForPairing(session.pair(''), PAIR_TOOL_WAIT_MS);
|
|
554
|
+
return pairToolResult(result, session.prompts, await wakeStatus(session, { check: true }));
|
|
383
555
|
} catch (err) {
|
|
384
556
|
return errorResult(toolErrorPayload(err), name);
|
|
385
557
|
}
|
|
@@ -395,17 +567,8 @@ export async function createSurfcadMcpServer(options = {}) {
|
|
|
395
567
|
|
|
396
568
|
// A lost session is already re-pairing in the background; session.call
|
|
397
569
|
// fails fast with pairing_lost until it is back.
|
|
398
|
-
if (!session.isPaired() && session.state !== 'lost') {
|
|
399
|
-
|
|
400
|
-
if (envCode) {
|
|
401
|
-
try {
|
|
402
|
-
await waitForPairing(session.pair(envCode), AUTO_PAIR_WAIT_MS);
|
|
403
|
-
} catch (err) {
|
|
404
|
-
return errorResult(toolErrorPayload(err), name);
|
|
405
|
-
}
|
|
406
|
-
} else if (session.state !== 'pairing') {
|
|
407
|
-
return errorResult(notPairedError(), name);
|
|
408
|
-
}
|
|
570
|
+
if (!session.isPaired() && session.state !== 'lost' && session.state !== 'pairing') {
|
|
571
|
+
return errorResult(notPairedError(), name);
|
|
409
572
|
}
|
|
410
573
|
if (!known && !(await tabAdvertisesTool(session, name, unlistedToolCache))) {
|
|
411
574
|
return errorResult({ code: 'unknown_tool', message: `Unknown tool: ${name}` });
|
|
@@ -425,7 +588,7 @@ export async function createSurfcadMcpServer(options = {}) {
|
|
|
425
588
|
session.holdAgentWork(false);
|
|
426
589
|
}
|
|
427
590
|
if (name === 'status' && out.isError !== true && out.value && typeof out.value === 'object' && !Array.isArray(out.value)) {
|
|
428
|
-
return textResult({ ...out.value, ...session.prompts.deliveryStatus(), wake: await wakeStatus(session) });
|
|
591
|
+
return textResult({ ...out.value, ...session.prompts.deliveryStatus(), wake: await wakeStatus(session), chat: await ownerStatus(process.env).catch(() => ({ owner: null })), host: hostInfo(server), mcpVersion: version });
|
|
429
592
|
}
|
|
430
593
|
if (name === 'list_commands' && out.isError !== true) {
|
|
431
594
|
out = {
|
|
@@ -452,76 +615,24 @@ export async function createSurfcadMcpServer(options = {}) {
|
|
|
452
615
|
}
|
|
453
616
|
return errorResult(toolErrorPayload(err), name);
|
|
454
617
|
}
|
|
455
|
-
}
|
|
618
|
+
}
|
|
456
619
|
|
|
457
620
|
return { server, session, catalog, bridgeTools };
|
|
458
621
|
}
|
|
459
622
|
|
|
460
623
|
/**
|
|
461
|
-
*
|
|
624
|
+
* Stdio server. Always the server relay. A saved login is required.
|
|
625
|
+
* `mode: 'local'` is refused: the loopback relay was removed in 0.4.0.
|
|
626
|
+
* @param {{ mode?: 'local' | 'remote', server?: string, name?: string, env?: NodeJS.ProcessEnv }} [options]
|
|
462
627
|
*/
|
|
463
628
|
export async function runSurfcadMcpServer(options = {}) {
|
|
464
|
-
if (options.mode === '
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
const relayOptions = {
|
|
470
|
-
onReady: (url) => {
|
|
471
|
-
if (process.env.SURFCAD_AGENT_BRIDGE_WS_VERBOSE === '1') {
|
|
472
|
-
console.error(`[surfcad-mcp] Agent bridge relay on ${url}`);
|
|
473
|
-
}
|
|
474
|
-
},
|
|
475
|
-
};
|
|
476
|
-
if (startRelay) {
|
|
477
|
-
const relay = await ensureAgentBridgeRelay(relayOptions);
|
|
478
|
-
if (relay.ownsServer) ownedRelay = relay;
|
|
629
|
+
if (options.mode === 'local') {
|
|
630
|
+
throw Object.assign(
|
|
631
|
+
new Error('The local relay was removed in surfcad-mcp 0.4.0. Run npx surfcad-mcp login --code CODE.'),
|
|
632
|
+
{ code: 'local_relay_removed' },
|
|
633
|
+
);
|
|
479
634
|
}
|
|
480
|
-
|
|
481
|
-
// Another surfcad-mcp process may own the relay; when it exits, take over
|
|
482
|
-
// the port so the tab and this session can reconnect.
|
|
483
|
-
const takeOverRelay = async () => {
|
|
484
|
-
if (!startRelay || ownedRelay) return;
|
|
485
|
-
resetAgentBridgeRelayCache();
|
|
486
|
-
const relay = await ensureAgentBridgeRelay(relayOptions);
|
|
487
|
-
if (relay.ownsServer) {
|
|
488
|
-
ownedRelay = relay;
|
|
489
|
-
console.error(`${new Date().toISOString()} [surfcad-mcp] relay owner went away; now serving ${relay.url}`);
|
|
490
|
-
}
|
|
491
|
-
};
|
|
492
|
-
|
|
493
|
-
// Intended MCP stdio lifecycle: when the client closes stdin the process
|
|
494
|
-
// (and the relay it owns) must exit. Playtests that spawn this bin have to
|
|
495
|
-
// keep stdin open; stdio: 'ignore' ends the stream immediately.
|
|
496
|
-
const onStdinClosed = () => {
|
|
497
|
-
if (ownedRelay) {
|
|
498
|
-
const closing = ownedRelay;
|
|
499
|
-
ownedRelay = null;
|
|
500
|
-
void stopAgentBridgeRelay(closing).finally(() => {
|
|
501
|
-
setTimeout(() => process.exit(0), 0).unref();
|
|
502
|
-
});
|
|
503
|
-
return;
|
|
504
|
-
}
|
|
505
|
-
setTimeout(() => process.exit(0), 0).unref();
|
|
506
|
-
};
|
|
507
|
-
process.stdin.once('end', onStdinClosed);
|
|
508
|
-
|
|
509
|
-
const localWake = createInProcessWake({ remote: false });
|
|
510
|
-
const { server, session } = await createSurfcadMcpServer({
|
|
511
|
-
session: new RelaySession({ ensureRelay: takeOverRelay, onUnread: localWake }),
|
|
512
|
-
});
|
|
513
|
-
localWake.attach(session.prompts);
|
|
514
|
-
const transport = new StdioServerTransport();
|
|
515
|
-
await server.connect(transport);
|
|
516
|
-
|
|
517
|
-
const envCode = (process.env.SURFCAD_PAIRING_CODE || '').trim();
|
|
518
|
-
if (options.autoPairFromEnv !== false && envCode) {
|
|
519
|
-
session.pair(envCode).catch(() => {
|
|
520
|
-
/* user may approve later; tools will retry */
|
|
521
|
-
});
|
|
522
|
-
}
|
|
523
|
-
|
|
524
|
-
return { server, session, transport };
|
|
635
|
+
return runRemoteMcpServer(options);
|
|
525
636
|
}
|
|
526
637
|
|
|
527
638
|
/**
|
|
@@ -546,15 +657,26 @@ async function runRemoteMcpServer(options) {
|
|
|
546
657
|
onUnread: remoteWake,
|
|
547
658
|
});
|
|
548
659
|
remoteWake.attach(remote.prompts);
|
|
660
|
+
liveLogin = { token: saved.token, env, clear: () => remote.prompts.unregisterWebhook() };
|
|
549
661
|
const { server, session } = await createSurfcadMcpServer({ session: remote });
|
|
662
|
+
// A logged-in agent may never call `pair`. Once connected, start the
|
|
663
|
+
// listener and fire the test wake (once per login). With no wake there is
|
|
664
|
+
// nobody to tell here, so the one-time user notice waits for the next pair.
|
|
665
|
+
let bootstrapped = false;
|
|
666
|
+
const bootstrapOnce = () => {
|
|
667
|
+
if (bootstrapped) return;
|
|
668
|
+
bootstrapped = true;
|
|
669
|
+
void wakeStatus(remote, { check: true, tellUser: false }).catch(() => {});
|
|
670
|
+
};
|
|
550
671
|
server.oninitialized = () => {
|
|
551
672
|
remote.applyClientInfo(server.getClientVersion());
|
|
552
|
-
|
|
673
|
+
remote.prompts?.setAgentName?.(agentDisplayName(server.getClientVersion()?.name));
|
|
674
|
+
void remote.connect().then(bootstrapOnce, (err) => {
|
|
553
675
|
console.error(`${new Date().toISOString()} [surfcad-mcp] ${err?.message || 'remote connect failed'}`);
|
|
554
676
|
});
|
|
555
677
|
};
|
|
556
678
|
if (!remote.needsClientName()) {
|
|
557
|
-
void remote.connect().
|
|
679
|
+
void remote.connect().then(bootstrapOnce, (err) => {
|
|
558
680
|
console.error(`${new Date().toISOString()} [surfcad-mcp] ${err?.message || 'remote connect failed'}`);
|
|
559
681
|
});
|
|
560
682
|
}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* STEP import cap. Keep in lockstep with src/utils/stepUploadLimit.js.
|
|
3
|
+
* The published package cannot import the app copy.
|
|
4
|
+
*/
|
|
5
|
+
export const STEP_UPLOAD_MAX_BYTES = 200 * 1024 * 1024;
|
|
6
|
+
|
|
7
|
+
export const STEP_UPLOAD_TOO_LARGE =
|
|
8
|
+
'This STEP file is over 200 MB. Export a smaller model and try again.';
|