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/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "surfcad-mcp",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"description": "SurfCAD agent bridge MCP server (stdio)
|
|
3
|
+
"version": "0.4.0",
|
|
4
|
+
"description": "SurfCAD agent bridge MCP server (stdio). Pairs to a browser tab through a saved server login (npx surfcad-mcp login --code).",
|
|
5
5
|
"license": "Apache-2.0",
|
|
6
6
|
"author": "artur0x0",
|
|
7
7
|
"homepage": "https://github.com/artur0x0/surfcad/tree/main/packages/surfcad-mcp",
|
package/src/cli.mjs
CHANGED
|
@@ -9,26 +9,49 @@ import { resolveAgentName, resolveServerUrl, selectRelayMode } from './remote/co
|
|
|
9
9
|
import { loginDevice, loginWithCode } from './remote/login.mjs';
|
|
10
10
|
import { logoutDevice } from './remote/logout.mjs';
|
|
11
11
|
import { formatLoginStatus, readSavedLogin } from './remote/tokenStore.mjs';
|
|
12
|
-
import {
|
|
12
|
+
import { callSavedTool, errorValue, listCliTools } from './cliCall.mjs';
|
|
13
|
+
import {
|
|
14
|
+
bootstrapAfterLogin,
|
|
15
|
+
runListenCommand,
|
|
16
|
+
runWakeCommand,
|
|
17
|
+
wakeStatusText,
|
|
18
|
+
WAKE_SETUP_STEPS,
|
|
19
|
+
} from './listen/listenCli.mjs';
|
|
20
|
+
import { runWaitCommand } from './listen/waitCli.mjs';
|
|
21
|
+
import { ownerStatus, releaseOwner } from './listen/owner.mjs';
|
|
22
|
+
import { forgetRoomSeat, formatRoomSeatStatus, joinRoom, parseRoomLink, readRoomSeat } from './room/seat.mjs';
|
|
13
23
|
|
|
14
24
|
const HELP = `surfcad-mcp
|
|
15
25
|
|
|
16
26
|
npx surfcad-mcp
|
|
17
|
-
MCP server on stdio.
|
|
27
|
+
MCP server on stdio. Uses the saved server login.
|
|
18
28
|
npx surfcad-mcp login [--name NAME] [--server URL]
|
|
19
29
|
Device-code login at the SurfCAD agent server. Prints the code and
|
|
20
30
|
the approval URL. The token is saved on this machine and is not printed.
|
|
21
31
|
npx surfcad-mcp login --code CODE [--name NAME] [--server URL]
|
|
22
|
-
Redeem
|
|
23
|
-
The token is saved on this machine and is not printed.
|
|
32
|
+
Redeem the join code shown by SurfCAD → Connect Agent (ABCD-EFGH).
|
|
33
|
+
The hyphen is optional. The token is saved on this machine and is not printed.
|
|
24
34
|
npx surfcad-mcp logout
|
|
25
35
|
Revokes this machine's token on the server, then deletes the saved
|
|
26
36
|
file. If the server cannot be reached, the file is still deleted.
|
|
27
37
|
npx surfcad-mcp status
|
|
28
38
|
The saved login, the wake setup, and whether the listener is running.
|
|
39
|
+
npx surfcad-mcp tools [NAME]
|
|
40
|
+
List tools, or one tool's name, description, and argument schema.
|
|
41
|
+
Does not need a login.
|
|
42
|
+
npx surfcad-mcp call TOOL ['{"json":"args"}']
|
|
43
|
+
Call one tool on the paired session and print the JSON result.
|
|
44
|
+
Uses the saved login. Exits non-zero on error. A large result
|
|
45
|
+
(list_edges can be over 8 MB) is printed in full. The token is not printed.
|
|
29
46
|
|
|
30
|
-
Wake: start a
|
|
31
|
-
SurfCAD and no agent process is reading.
|
|
47
|
+
Wake: start a session of the agent when the user sends a chat message from
|
|
48
|
+
SurfCAD and no agent process is reading. A host provides its wake in this
|
|
49
|
+
server's environment (SURFCAD_WAKE_POST with SURFCAD_WAKE_BEARER, and/or
|
|
50
|
+
SURFCAD_WAKE_EXEC); login and pair then start the listener by themselves,
|
|
51
|
+
restarting one that is still on an older login, and pair fires a test
|
|
52
|
+
wake once per login (the session it starts calls status and ends;
|
|
53
|
+
SurfCAD greets the user itself). SURFCAD_WAKE_BOOTSTRAP=0 turns that off.
|
|
54
|
+
The manual way, when the host provides nothing:
|
|
32
55
|
${WAKE_SETUP_STEPS.map((step, i) => ` ${i + 1}. ${step}`).join('\n')}
|
|
33
56
|
npx surfcad-mcp wake set [--post URL [--bearer KEY]] [--exec COMMAND]
|
|
34
57
|
Save how to wake the agent on this machine. --post: the wake JSON is
|
|
@@ -37,32 +60,60 @@ ${WAKE_SETUP_STEPS.map((step, i) => ` ${i + 1}. ${step}`).join('\n')}
|
|
|
37
60
|
the command is the fallback. The key can also come from
|
|
38
61
|
SURFCAD_WAKE_BEARER. It is saved on this machine and is not printed.
|
|
39
62
|
npx surfcad-mcp wake show | test | clear
|
|
40
|
-
npx surfcad-mcp
|
|
63
|
+
npx surfcad-mcp wake claude-code
|
|
64
|
+
The wake command for Claude Code. Save it with:
|
|
65
|
+
npx surfcad-mcp wake set --exec "npx -y surfcad-mcp@latest wake claude-code"
|
|
66
|
+
A chat message then resumes the session that owns the chat (or a fork
|
|
67
|
+
of it when that session is open but idle) instead of a blank one.
|
|
68
|
+
npx surfcad-mcp wait [--timeout SECONDS]
|
|
69
|
+
Block until the next SurfCAD chat message, print it as JSON, and exit
|
|
70
|
+
(0 message, 2 timed out, 3 the chat moved to another session). Run it
|
|
71
|
+
in the background at the end of each turn (Claude Code: run_in_background):
|
|
72
|
+
the message then wakes the same session, however long the reply takes.
|
|
73
|
+
It does not read the message; read_messages does. Default timeout 6 h.
|
|
74
|
+
npx surfcad-mcp owner [--release]
|
|
75
|
+
The agent session that owns this account's chat on this machine (the
|
|
76
|
+
one that answered last), and whether it is waiting. --release drops it:
|
|
77
|
+
the next chat message starts a new session.
|
|
78
|
+
npx surfcad-mcp room join --room LINK [--name NAME] [--machine LABEL]
|
|
79
|
+
Ask for a seat in a SurfCAD room, for an agent on a machine with no
|
|
80
|
+
browser. LINK is the room link the room's host copies from SurfCAD
|
|
81
|
+
(or the room key, owner/name:branch:assemblyId). Prints a short code
|
|
82
|
+
and waits: the host sees the same code and approves or denies. The
|
|
83
|
+
link gives no access by itself. The seat token is for that one room,
|
|
84
|
+
is saved on this machine and is not printed. Needs no login.
|
|
85
|
+
npx surfcad-mcp room status | forget
|
|
86
|
+
The saved room seat (never the token), or delete it from this machine.
|
|
87
|
+
npx surfcad-mcp listen [--detach] [--stop] [--pause] [--resume]
|
|
41
88
|
Watch the server relay for chat messages and fire the wake for one
|
|
42
89
|
that no agent process reads within a few seconds. Outbound HTTPS
|
|
43
90
|
only: no open port, works behind NAT. Needs a saved login and a saved
|
|
44
|
-
wake. --detach starts it in the background and returns
|
|
91
|
+
wake. --detach starts it in the background and returns; a listener
|
|
92
|
+
still on an older login is replaced. --stop ends it. A rejection
|
|
93
|
+
reads the saved login once and continues when a newer token is there.
|
|
45
94
|
|
|
46
|
-
--remote Use the server relay. Requires a saved login.
|
|
47
|
-
--local Use the local relay even when a login is saved.
|
|
48
95
|
--server URL Dev or staging origin (or set SURFCAD_AGENT_SERVER).
|
|
49
96
|
Cleartext http is only allowed for localhost, 127.0.0.1, and ::1.
|
|
50
97
|
--code CODE Join code from the SurfCAD Connect Agent screen (ABCD-EFGH).
|
|
51
98
|
--name NAME Agent name for the approval page. Otherwise the MCP client
|
|
52
99
|
name is used when the server starts, or SURFCAD_AGENT_NAME.
|
|
100
|
+
--machine LABEL With room join: what the host sees as this machine.
|
|
101
|
+
Otherwise the host name. A label only; no address is sent.
|
|
102
|
+
--remote Accepted. The server relay is the only mode.
|
|
53
103
|
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
SURFCAD_AGENT_BRIDGE_WS_PORT,
|
|
57
|
-
--remote and SURFCAD_MCP_TRANSPORT=remote win over those.
|
|
104
|
+
The local loopback relay was removed in 0.4.0. --local,
|
|
105
|
+
SURFCAD_MCP_TRANSPORT=local, SURFCAD_AGENT_BRIDGE_WS_URL,
|
|
106
|
+
SURFCAD_AGENT_BRIDGE_WS_PORT, and SURFCAD_PAIRING_CODE are errors.
|
|
58
107
|
`;
|
|
59
108
|
|
|
60
109
|
/**
|
|
61
110
|
* @param {string[]} argv
|
|
62
111
|
*/
|
|
63
112
|
export function parseArgs(argv) {
|
|
64
|
-
/** @type {'serve' | 'login' | 'logout' | 'status' | 'listen' | 'wake' | 'help'} */
|
|
113
|
+
/** @type {'serve' | 'login' | 'logout' | 'status' | 'listen' | 'wake' | 'call' | 'tools' | 'wait' | 'owner' | 'room' | 'help'} */
|
|
65
114
|
let command = 'serve';
|
|
115
|
+
/** @type {string[]} */
|
|
116
|
+
const positionals = [];
|
|
66
117
|
let name = '';
|
|
67
118
|
let server = '';
|
|
68
119
|
let code = '';
|
|
@@ -74,6 +125,12 @@ export function parseArgs(argv) {
|
|
|
74
125
|
let bearer = '';
|
|
75
126
|
let detach = false;
|
|
76
127
|
let stop = false;
|
|
128
|
+
let pause = false;
|
|
129
|
+
let resume = false;
|
|
130
|
+
let release = false;
|
|
131
|
+
let timeout = '';
|
|
132
|
+
let room = '';
|
|
133
|
+
let machine = '';
|
|
77
134
|
const valued = (arg, flag, i) => {
|
|
78
135
|
const value = arg === flag ? argv[i + 1] : arg.slice(flag.length + 1);
|
|
79
136
|
if (!value || (arg === flag && value.startsWith('--'))) {
|
|
@@ -83,14 +140,23 @@ export function parseArgs(argv) {
|
|
|
83
140
|
};
|
|
84
141
|
for (let i = 0; i < argv.length; i += 1) {
|
|
85
142
|
const arg = argv[i];
|
|
86
|
-
if (
|
|
143
|
+
if ((command === 'call' || command === 'tools') && !arg.startsWith('-')) {
|
|
144
|
+
positionals.push(arg);
|
|
145
|
+
continue;
|
|
146
|
+
}
|
|
147
|
+
// `room status`: status is the room command's action there, not a second command.
|
|
148
|
+
if (command === 'room' && !action && (arg === 'join' || arg === 'status' || arg === 'forget')) {
|
|
149
|
+
action = arg;
|
|
150
|
+
continue;
|
|
151
|
+
}
|
|
152
|
+
if (arg === 'login' || arg === 'logout' || arg === 'status' || arg === 'listen' || arg === 'wake' || arg === 'call' || arg === 'tools' || arg === 'wait' || arg === 'owner' || arg === 'room') {
|
|
87
153
|
if (command !== 'serve') {
|
|
88
|
-
throw Object.assign(new Error('Pass one command: login, logout, status, wake, or
|
|
154
|
+
throw Object.assign(new Error('Pass one command: login, logout, status, wake, listen, wait, owner, room, call, or tools.'), { code: 'bad_args' });
|
|
89
155
|
}
|
|
90
156
|
command = arg;
|
|
91
157
|
continue;
|
|
92
158
|
}
|
|
93
|
-
if (command === 'wake' && !action && (arg === 'set' || arg === 'show' || arg === 'test' || arg === 'clear')) {
|
|
159
|
+
if (command === 'wake' && !action && (arg === 'set' || arg === 'show' || arg === 'test' || arg === 'clear' || arg === 'claude-code')) {
|
|
94
160
|
action = arg;
|
|
95
161
|
continue;
|
|
96
162
|
}
|
|
@@ -102,6 +168,33 @@ export function parseArgs(argv) {
|
|
|
102
168
|
stop = true;
|
|
103
169
|
continue;
|
|
104
170
|
}
|
|
171
|
+
if (arg === '--pause') {
|
|
172
|
+
pause = true;
|
|
173
|
+
continue;
|
|
174
|
+
}
|
|
175
|
+
if (arg === '--resume') {
|
|
176
|
+
resume = true;
|
|
177
|
+
continue;
|
|
178
|
+
}
|
|
179
|
+
if (arg === '--release') {
|
|
180
|
+
release = true;
|
|
181
|
+
continue;
|
|
182
|
+
}
|
|
183
|
+
if (arg === '--timeout' || arg.startsWith('--timeout=')) {
|
|
184
|
+
timeout = valued(arg, '--timeout', i);
|
|
185
|
+
if (arg === '--timeout') i += 1;
|
|
186
|
+
continue;
|
|
187
|
+
}
|
|
188
|
+
if (arg === '--room' || arg.startsWith('--room=')) {
|
|
189
|
+
room = valued(arg, '--room', i);
|
|
190
|
+
if (arg === '--room') i += 1;
|
|
191
|
+
continue;
|
|
192
|
+
}
|
|
193
|
+
if (arg === '--machine' || arg.startsWith('--machine=')) {
|
|
194
|
+
machine = valued(arg, '--machine', i);
|
|
195
|
+
if (arg === '--machine') i += 1;
|
|
196
|
+
continue;
|
|
197
|
+
}
|
|
105
198
|
if (arg === '--post' || arg.startsWith('--post=')) {
|
|
106
199
|
post = valued(arg, '--post', i);
|
|
107
200
|
if (arg === '--post') i += 1;
|
|
@@ -160,13 +253,29 @@ export function parseArgs(argv) {
|
|
|
160
253
|
if (command !== 'wake' && (post || exec || bearer)) {
|
|
161
254
|
throw Object.assign(new Error('--post, --exec and --bearer go with: wake set.'), { code: 'bad_args' });
|
|
162
255
|
}
|
|
163
|
-
if (command !== 'listen' && (detach || stop)) {
|
|
164
|
-
throw Object.assign(new Error('--detach and --
|
|
256
|
+
if (command !== 'listen' && (detach || stop || pause || resume)) {
|
|
257
|
+
throw Object.assign(new Error('--detach, --stop, --pause and --resume go with: listen.'), { code: 'bad_args' });
|
|
258
|
+
}
|
|
259
|
+
if ([detach, stop, pause, resume].filter(Boolean).length > 1) {
|
|
260
|
+
throw Object.assign(new Error('Pass one of --detach, --stop, --pause, --resume.'), { code: 'bad_args' });
|
|
261
|
+
}
|
|
262
|
+
if (command !== 'owner' && release) {
|
|
263
|
+
throw Object.assign(new Error('--release goes with: owner.'), { code: 'bad_args' });
|
|
264
|
+
}
|
|
265
|
+
if (command !== 'wait' && timeout) {
|
|
266
|
+
throw Object.assign(new Error('--timeout goes with: wait.'), { code: 'bad_args' });
|
|
165
267
|
}
|
|
166
|
-
if (
|
|
167
|
-
throw Object.assign(new Error('
|
|
268
|
+
if (command !== 'room' && (room || machine)) {
|
|
269
|
+
throw Object.assign(new Error('--room and --machine go with: room join.'), { code: 'bad_args' });
|
|
168
270
|
}
|
|
169
|
-
|
|
271
|
+
if (command === 'room') {
|
|
272
|
+
if (!action) throw Object.assign(new Error('Pass one of: room join, room status, room forget.'), { code: 'bad_args' });
|
|
273
|
+
if (action === 'join' && !room) throw Object.assign(new Error('room join needs --room LINK.'), { code: 'bad_args' });
|
|
274
|
+
if (action !== 'join' && (room || machine || name)) {
|
|
275
|
+
throw Object.assign(new Error('--room, --machine and --name go with: room join.'), { code: 'bad_args' });
|
|
276
|
+
}
|
|
277
|
+
}
|
|
278
|
+
return { command, name, server, code, remote, local, action, post, exec, bearer, detach, stop, pause, resume, release, timeout, room, machine, positionals };
|
|
170
279
|
}
|
|
171
280
|
|
|
172
281
|
/**
|
|
@@ -218,7 +327,7 @@ export async function runCli(argv, options = {}) {
|
|
|
218
327
|
}
|
|
219
328
|
if (parsed.command !== 'serve') {
|
|
220
329
|
if (parsed.remote || parsed.local) {
|
|
221
|
-
io.stderr(`login, logout, status, wake, and
|
|
330
|
+
io.stderr(`login, logout, status, wake, listen, wait, owner, room, call, and tools do not take --remote or --local.\n${HELP}`);
|
|
222
331
|
return { action: 'exit', code: 1 };
|
|
223
332
|
}
|
|
224
333
|
}
|
|
@@ -236,6 +345,7 @@ export async function runCli(argv, options = {}) {
|
|
|
236
345
|
fetch: options.fetch,
|
|
237
346
|
});
|
|
238
347
|
io.stdout('Logged in. The token is saved on this machine and is not printed.\n');
|
|
348
|
+
io.stdout(await bootstrapAfterLogin({ env, spawn: options.spawn }));
|
|
239
349
|
return { action: 'exit', code: 0 };
|
|
240
350
|
}
|
|
241
351
|
await loginDevice({
|
|
@@ -249,6 +359,36 @@ export async function runCli(argv, options = {}) {
|
|
|
249
359
|
},
|
|
250
360
|
});
|
|
251
361
|
io.stdout('Logged in. The token is saved on this machine and is not printed.\n');
|
|
362
|
+
io.stdout(await bootstrapAfterLogin({ env, spawn: options.spawn }));
|
|
363
|
+
return { action: 'exit', code: 0 };
|
|
364
|
+
}
|
|
365
|
+
if (parsed.command === 'room') {
|
|
366
|
+
if (parsed.action === 'status') {
|
|
367
|
+
io.stdout(formatRoomSeatStatus(await readRoomSeat(env)));
|
|
368
|
+
return { action: 'exit', code: 0 };
|
|
369
|
+
}
|
|
370
|
+
if (parsed.action === 'forget') {
|
|
371
|
+
await forgetRoomSeat(env);
|
|
372
|
+
io.stdout('The room seat is deleted from this machine. The host can remove the agent from the room in SurfCAD.\n');
|
|
373
|
+
return { action: 'exit', code: 0 };
|
|
374
|
+
}
|
|
375
|
+
// The link names the server too. --server (or SURFCAD_AGENT_SERVER) wins, for dev and staging.
|
|
376
|
+
const link = parseRoomLink(parsed.room);
|
|
377
|
+
const serverUrl = parsed.server || env.SURFCAD_AGENT_SERVER?.trim() || !link.server
|
|
378
|
+
? resolveServerUrl({ flag: parsed.server, env })
|
|
379
|
+
: link.server;
|
|
380
|
+
const seat = await joinRoom({
|
|
381
|
+
serverUrl,
|
|
382
|
+
room: link.room,
|
|
383
|
+
label: resolveAgentName({ name: parsed.name, env }),
|
|
384
|
+
machine: parsed.machine || options.machine || hostname(),
|
|
385
|
+
env,
|
|
386
|
+
fetch: options.fetch,
|
|
387
|
+
onCode: ({ code }) => {
|
|
388
|
+
io.stdout(`Code: ${code}\nAsk the room's host to approve this agent in SurfCAD. The code on their screen must match.\nWaiting for approval…\n`);
|
|
389
|
+
},
|
|
390
|
+
});
|
|
391
|
+
io.stdout(`Approved. ${seat.label || 'This agent'} has a seat in the room. The seat token is saved on this machine and is not printed.\n`);
|
|
252
392
|
return { action: 'exit', code: 0 };
|
|
253
393
|
}
|
|
254
394
|
if (parsed.command === 'logout') {
|
|
@@ -271,6 +411,76 @@ export async function runCli(argv, options = {}) {
|
|
|
271
411
|
const code = await runWakeCommand(parsed, { env, io, fetch: options.fetch, spawn: options.spawn });
|
|
272
412
|
return { action: 'exit', code };
|
|
273
413
|
}
|
|
414
|
+
if (parsed.command === 'tools') {
|
|
415
|
+
const tools = listCliTools();
|
|
416
|
+
const wanted = parsed.positionals[0] || '';
|
|
417
|
+
if (parsed.positionals.length > 1) {
|
|
418
|
+
io.stderr(`tools takes at most one tool name.\n${HELP}`);
|
|
419
|
+
return { action: 'exit', code: 1 };
|
|
420
|
+
}
|
|
421
|
+
if (wanted) {
|
|
422
|
+
const tool = tools.find((row) => row.name === wanted);
|
|
423
|
+
if (!tool) {
|
|
424
|
+
io.stderr(`Unknown tool: ${wanted}\n`);
|
|
425
|
+
return { action: 'exit', code: 1 };
|
|
426
|
+
}
|
|
427
|
+
io.stdout(`${JSON.stringify(tool)}\n`);
|
|
428
|
+
return { action: 'exit', code: 0 };
|
|
429
|
+
}
|
|
430
|
+
io.stdout(`${JSON.stringify(tools.map((row) => ({ name: row.name, description: row.description })))}\n`);
|
|
431
|
+
return { action: 'exit', code: 0 };
|
|
432
|
+
}
|
|
433
|
+
if (parsed.command === 'call') {
|
|
434
|
+
const tool = parsed.positionals[0] || '';
|
|
435
|
+
if (!tool) {
|
|
436
|
+
io.stderr(`call needs a tool name.\n${HELP}`);
|
|
437
|
+
return { action: 'exit', code: 1 };
|
|
438
|
+
}
|
|
439
|
+
if (parsed.positionals.length > 2) {
|
|
440
|
+
io.stderr(`call takes a tool name and one JSON argument object.\n${HELP}`);
|
|
441
|
+
return { action: 'exit', code: 1 };
|
|
442
|
+
}
|
|
443
|
+
let args = {};
|
|
444
|
+
if (parsed.positionals.length === 2) {
|
|
445
|
+
try {
|
|
446
|
+
args = JSON.parse(parsed.positionals[1]);
|
|
447
|
+
} catch {
|
|
448
|
+
io.stderr('call arguments must be a JSON object.\n');
|
|
449
|
+
return { action: 'exit', code: 1 };
|
|
450
|
+
}
|
|
451
|
+
if (!args || typeof args !== 'object' || Array.isArray(args)) {
|
|
452
|
+
io.stderr('call arguments must be a JSON object.\n');
|
|
453
|
+
return { action: 'exit', code: 1 };
|
|
454
|
+
}
|
|
455
|
+
}
|
|
456
|
+
try {
|
|
457
|
+
const result = await callSavedTool({
|
|
458
|
+
tool,
|
|
459
|
+
args,
|
|
460
|
+
env,
|
|
461
|
+
fetch: options.fetch,
|
|
462
|
+
server: parsed.server,
|
|
463
|
+
});
|
|
464
|
+
io.stdout(`${JSON.stringify(result.value)}\n`);
|
|
465
|
+
return { action: 'exit', code: result.ok ? 0 : 1 };
|
|
466
|
+
} catch (err) {
|
|
467
|
+
io.stdout(`${JSON.stringify(errorValue(err))}\n`);
|
|
468
|
+
return { action: 'exit', code: 1 };
|
|
469
|
+
}
|
|
470
|
+
}
|
|
471
|
+
if (parsed.command === 'wait') {
|
|
472
|
+
const code = await runWaitCommand(parsed, { env, io, fetch: options.fetch, signal: options.signal });
|
|
473
|
+
return { action: 'exit', code };
|
|
474
|
+
}
|
|
475
|
+
if (parsed.command === 'owner') {
|
|
476
|
+
if (parsed.release) {
|
|
477
|
+
const out = await releaseOwner(env);
|
|
478
|
+
io.stdout(out.released ? `Released the chat (session ${out.session}). The next message starts a new session.\n` : 'No session owns the chat.\n');
|
|
479
|
+
return { action: 'exit', code: 0 };
|
|
480
|
+
}
|
|
481
|
+
io.stdout(`${JSON.stringify(await ownerStatus(env))}\n`);
|
|
482
|
+
return { action: 'exit', code: 0 };
|
|
483
|
+
}
|
|
274
484
|
if (parsed.command === 'listen') {
|
|
275
485
|
const code = await runListenCommand(parsed, {
|
|
276
486
|
env,
|
package/src/cliCall.mjs
ADDED
|
@@ -0,0 +1,221 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `surfcad-mcp call` and `surfcad-mcp tools`.
|
|
3
|
+
*
|
|
4
|
+
* One tool call against the paired session, using the saved login. The
|
|
5
|
+
* process prints the JSON result and exits. It does not speak MCP on stdio.
|
|
6
|
+
* A result can be large (`list_edges` on a detailed part is over 8 MB);
|
|
7
|
+
* nothing here slices it.
|
|
8
|
+
*
|
|
9
|
+
* The token is never written to stdout or stderr.
|
|
10
|
+
*/
|
|
11
|
+
import { bridgeToolDefinitions, loadCommandsCatalog } from './catalog.mjs';
|
|
12
|
+
import { callListHelpersTool, listHelpersToolDefinition } from './helpers.mjs';
|
|
13
|
+
import { stampAwake } from './listen/awake.mjs';
|
|
14
|
+
import { mergeRegisteredIntoListCommands } from './listCommandsMerge.mjs';
|
|
15
|
+
import { withErrorHint } from './prompt/errorHints.mjs';
|
|
16
|
+
import { callGuideTool, guideToolDefinition } from './prompt/guide.mjs';
|
|
17
|
+
import {
|
|
18
|
+
callPromptTool,
|
|
19
|
+
isPromptTool,
|
|
20
|
+
promptToolDefinitions,
|
|
21
|
+
} from './prompt/promptTools.mjs';
|
|
22
|
+
import { resolveServerUrl } from './remote/config.mjs';
|
|
23
|
+
import { RemoteSession } from './remote/session.mjs';
|
|
24
|
+
import { forgetLoginIfToken, readSavedLogin } from './remote/tokenStore.mjs';
|
|
25
|
+
import { callPairedBridgeTool } from './screenshotFile.mjs';
|
|
26
|
+
|
|
27
|
+
const MCP_RETURN_DEFAULT = 'status';
|
|
28
|
+
|
|
29
|
+
const PROMPT_TOOLS_WITHOUT_ACTIVITY = new Set(['set_status', 'post_progress', 'close_session', 'read_messages']);
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* @param {string} name
|
|
33
|
+
*/
|
|
34
|
+
function mutatingTool(name) {
|
|
35
|
+
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);
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* Same default the MCP server sends when the caller leaves `return` out.
|
|
40
|
+
* @param {{ args?: { properties?: Record<string, unknown> } } | undefined} row
|
|
41
|
+
* @param {Record<string, unknown>} args
|
|
42
|
+
*/
|
|
43
|
+
function withDefaultReturn(row, args) {
|
|
44
|
+
if (!row?.args?.properties || !Object.prototype.hasOwnProperty.call(row.args.properties, 'return')) return args;
|
|
45
|
+
if (Object.prototype.hasOwnProperty.call(args, 'return')) return args;
|
|
46
|
+
return { ...args, return: MCP_RETURN_DEFAULT };
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* @returns {Array<{ name: string, description: string, inputSchema: object }>}
|
|
51
|
+
*/
|
|
52
|
+
export function listCliTools() {
|
|
53
|
+
const catalog = loadCommandsCatalog();
|
|
54
|
+
const bridge = bridgeToolDefinitions(catalog).map((tool) => {
|
|
55
|
+
if (tool.name !== 'screenshot') return tool;
|
|
56
|
+
const shot = tool;
|
|
57
|
+
return {
|
|
58
|
+
...shot,
|
|
59
|
+
description: `${shot.description || ''} save_to or file writes the image on this machine and returns { path, size }.`,
|
|
60
|
+
};
|
|
61
|
+
});
|
|
62
|
+
return [
|
|
63
|
+
{
|
|
64
|
+
name: 'pair',
|
|
65
|
+
description: 'Connect with the saved login. SurfCAD greets the user itself; do not send a greeting.',
|
|
66
|
+
inputSchema: { type: 'object', additionalProperties: false, properties: {} },
|
|
67
|
+
},
|
|
68
|
+
guideToolDefinition(),
|
|
69
|
+
listHelpersToolDefinition(),
|
|
70
|
+
...promptToolDefinitions(),
|
|
71
|
+
...bridge,
|
|
72
|
+
];
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/**
|
|
76
|
+
* @param {{ content?: Array<{ type?: string, text?: string, data?: string, mimeType?: string }> }} out
|
|
77
|
+
*/
|
|
78
|
+
function promptToolValue(out) {
|
|
79
|
+
const texts = [];
|
|
80
|
+
const images = [];
|
|
81
|
+
for (const block of out?.content || []) {
|
|
82
|
+
if (block?.type === 'image' && typeof block.data === 'string') {
|
|
83
|
+
images.push({ mimeType: block.mimeType || 'image/png', data: block.data });
|
|
84
|
+
continue;
|
|
85
|
+
}
|
|
86
|
+
if (block?.type !== 'text' || typeof block.text !== 'string') continue;
|
|
87
|
+
try {
|
|
88
|
+
texts.push(JSON.parse(block.text));
|
|
89
|
+
} catch {
|
|
90
|
+
texts.push(block.text);
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
const summary = texts.find((row) => row && typeof row === 'object' && !Array.isArray(row) && Array.isArray(row.acked));
|
|
94
|
+
if (summary) {
|
|
95
|
+
const messages = texts.filter((row) => row && row !== summary && typeof row === 'object' && row.id);
|
|
96
|
+
return {
|
|
97
|
+
messages,
|
|
98
|
+
acked: summary.acked,
|
|
99
|
+
recent: summary.recent || [],
|
|
100
|
+
...(images.length ? { images } : {}),
|
|
101
|
+
};
|
|
102
|
+
}
|
|
103
|
+
if (texts.length === 1 && images.length === 0) return texts[0];
|
|
104
|
+
return { content: texts, ...(images.length ? { images } : {}) };
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/**
|
|
108
|
+
* @param {unknown} err
|
|
109
|
+
*/
|
|
110
|
+
function errorValue(err) {
|
|
111
|
+
const code = err && typeof err === 'object' && typeof err.code === 'string' ? err.code : 'call_failed';
|
|
112
|
+
const message = err instanceof Error ? err.message : 'Call failed';
|
|
113
|
+
return withErrorHint({ ok: false, code, message });
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/**
|
|
117
|
+
* @param {unknown} value
|
|
118
|
+
*/
|
|
119
|
+
function failedValue(value) {
|
|
120
|
+
if (!value || typeof value !== 'object' || Array.isArray(value)) return false;
|
|
121
|
+
if (value.ok === false) return true;
|
|
122
|
+
return false;
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/**
|
|
126
|
+
* @param {{
|
|
127
|
+
* tool: string,
|
|
128
|
+
* args: Record<string, unknown>,
|
|
129
|
+
* env?: NodeJS.ProcessEnv,
|
|
130
|
+
* fetch?: typeof fetch,
|
|
131
|
+
* server?: string,
|
|
132
|
+
* }} options
|
|
133
|
+
* @returns {Promise<{ ok: boolean, value: unknown }>}
|
|
134
|
+
*/
|
|
135
|
+
export async function callSavedTool(options) {
|
|
136
|
+
const tool = options.tool;
|
|
137
|
+
const args = options.args && typeof options.args === 'object' ? options.args : {};
|
|
138
|
+
const env = options.env || process.env;
|
|
139
|
+
if (tool === 'guide') {
|
|
140
|
+
const out = callGuideTool(args);
|
|
141
|
+
const text = (out.content || []).map((block) => block.text).join('\n\n');
|
|
142
|
+
if (out.isError) {
|
|
143
|
+
let value = { ok: false, code: 'unknown_topic', message: text };
|
|
144
|
+
try { value = JSON.parse(out.content[0].text); } catch { /* the text is the message */ }
|
|
145
|
+
return { ok: false, value };
|
|
146
|
+
}
|
|
147
|
+
return { ok: true, value: { text } };
|
|
148
|
+
}
|
|
149
|
+
if (tool === 'list_helpers') {
|
|
150
|
+
const out = callListHelpersTool(args);
|
|
151
|
+
const value = JSON.parse(out.content[0].text);
|
|
152
|
+
return { ok: out.isError !== true, value };
|
|
153
|
+
}
|
|
154
|
+
const saved = await readSavedLogin(env);
|
|
155
|
+
if (!saved?.token) {
|
|
156
|
+
throw Object.assign(new Error('No saved login. Run npx surfcad-mcp login.'), { code: 'not_logged_in' });
|
|
157
|
+
}
|
|
158
|
+
const serverUrl = resolveServerUrl({ flag: options.server || '', env, saved });
|
|
159
|
+
const session = new RemoteSession({
|
|
160
|
+
serverUrl,
|
|
161
|
+
token: saved.token,
|
|
162
|
+
name: saved.name,
|
|
163
|
+
env,
|
|
164
|
+
fetch: options.fetch,
|
|
165
|
+
onLog: () => {},
|
|
166
|
+
});
|
|
167
|
+
try {
|
|
168
|
+
await session.connect();
|
|
169
|
+
await stampAwake(env);
|
|
170
|
+
if (tool === 'pair') {
|
|
171
|
+
return { ok: true, value: { paired: true, remote: true } };
|
|
172
|
+
}
|
|
173
|
+
if (isPromptTool(tool)) {
|
|
174
|
+
if (!PROMPT_TOOLS_WITHOUT_ACTIVITY.has(tool)) session.noteAgentToolCall();
|
|
175
|
+
try {
|
|
176
|
+
const out = await callPromptTool(session.prompts, tool, args);
|
|
177
|
+
const value = promptToolValue(out);
|
|
178
|
+
return { ok: !failedValue(value), value };
|
|
179
|
+
} catch (err) {
|
|
180
|
+
if (err?.code === 'token_revoked' || err?.code === 'expired') {
|
|
181
|
+
await forgetLoginIfToken(saved.token, env);
|
|
182
|
+
}
|
|
183
|
+
throw err;
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
const catalog = loadCommandsCatalog();
|
|
187
|
+
const row = catalog.commands.find((command) => command.name === tool);
|
|
188
|
+
const bridgeNames = new Set(catalog.commands.map((command) => command.name));
|
|
189
|
+
session.noteAgentToolCall({ mutates: row?.mutates === true || (row?.mutates == null && mutatingTool(tool)) });
|
|
190
|
+
session.holdAgentWork(true);
|
|
191
|
+
let out;
|
|
192
|
+
try {
|
|
193
|
+
out = await callPairedBridgeTool(session, tool, withDefaultReturn(row, args));
|
|
194
|
+
} finally {
|
|
195
|
+
session.holdAgentWork(false);
|
|
196
|
+
}
|
|
197
|
+
let value = out.value;
|
|
198
|
+
if (tool === 'status' && out.isError !== true && value && typeof value === 'object' && !Array.isArray(value)) {
|
|
199
|
+
value = { ...value, ...session.prompts.deliveryStatus() };
|
|
200
|
+
}
|
|
201
|
+
if (tool === 'list_commands' && out.isError !== true) {
|
|
202
|
+
value = mergeRegisteredIntoListCommands(value, {
|
|
203
|
+
registered: listCliTools(),
|
|
204
|
+
bridgeNames,
|
|
205
|
+
args,
|
|
206
|
+
});
|
|
207
|
+
}
|
|
208
|
+
return { ok: out.isError !== true && !failedValue(value), value };
|
|
209
|
+
} catch (err) {
|
|
210
|
+
if (err?.code === 'token_revoked' || err?.code === 'expired') {
|
|
211
|
+
await forgetLoginIfToken(saved.token, env);
|
|
212
|
+
}
|
|
213
|
+
throw err;
|
|
214
|
+
} finally {
|
|
215
|
+
// Not disconnect(): the process exits next, and a frame still on its way
|
|
216
|
+
// out (read_messages reporting the prompt taken) must reach the server.
|
|
217
|
+
try { await session.close(); } catch { /* already closed */ }
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
export { errorValue };
|
package/src/errors.mjs
CHANGED
|
@@ -20,7 +20,7 @@ export function formatBridgeError(err) {
|
|
|
20
20
|
export function notPairedError() {
|
|
21
21
|
return {
|
|
22
22
|
code: 'not_paired',
|
|
23
|
-
message: 'Not paired to a SurfCAD tab.
|
|
23
|
+
message: 'Not paired to a SurfCAD tab. Run npx surfcad-mcp login --code with the join code from Connect Agent, then call pair {}.',
|
|
24
24
|
hint: pairingEnvHint(),
|
|
25
25
|
};
|
|
26
26
|
}
|
|
@@ -38,13 +38,13 @@ export function pairingLostError(reason) {
|
|
|
38
38
|
|
|
39
39
|
export function pairPendingError() {
|
|
40
40
|
return Object.assign(
|
|
41
|
-
new Error('
|
|
42
|
-
{ code: 'pair_pending', hint: 'The
|
|
41
|
+
new Error('The saved login is still connecting. Keep the SurfCAD tab open, then retry pair {}.'),
|
|
42
|
+
{ code: 'pair_pending', hint: 'The saved login is still connecting. Keep the SurfCAD tab open, then retry pair {}.', retryable: true },
|
|
43
43
|
);
|
|
44
44
|
}
|
|
45
45
|
|
|
46
46
|
export function pairingEnvHint() {
|
|
47
|
-
return '
|
|
47
|
+
return 'Run npx surfcad-mcp login --code with the join code from Connect Agent (ABCD-EFGH; the hyphen is optional), then call pair {}.';
|
|
48
48
|
}
|
|
49
49
|
|
|
50
50
|
export function tabAsleepError() {
|
|
@@ -138,7 +138,7 @@ export function asRemoteError(error) {
|
|
|
138
138
|
) return error;
|
|
139
139
|
}
|
|
140
140
|
const record = error && typeof error === 'object'
|
|
141
|
-
? /** @type {{ code?: unknown, message?: unknown }} */ (error)
|
|
141
|
+
? /** @type {{ code?: unknown, message?: unknown, details?: unknown, hint?: unknown, retryable?: unknown }} */ (error)
|
|
142
142
|
: {};
|
|
143
143
|
const code = typeof record.code === 'string' ? record.code : (typeof error === 'string' ? error : '');
|
|
144
144
|
const message = typeof record.message === 'string'
|
|
@@ -162,5 +162,8 @@ export function asRemoteError(error) {
|
|
|
162
162
|
if (error instanceof Error) return error;
|
|
163
163
|
return Object.assign(new Error(message || 'Bridge call failed'), {
|
|
164
164
|
code: code || 'bridge_error',
|
|
165
|
+
...(record.details !== undefined ? { details: record.details } : {}),
|
|
166
|
+
...(typeof record.hint === 'string' ? { hint: record.hint } : {}),
|
|
167
|
+
...(record.retryable !== undefined ? { retryable: record.retryable } : {}),
|
|
165
168
|
});
|
|
166
169
|
}
|