surfcad-mcp 0.3.9 → 0.4.1
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 +71 -50
- package/bin/surfcad-mcp.js +16 -8
- package/data/commands.json +6481 -5817
- package/data/helpers.json +243 -268
- package/package.json +10 -2
- package/src/cli.mjs +296 -23
- 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 +87 -34
- package/src/listen/claudeCodeWake.mjs +74 -0
- package/src/listen/daemon.mjs +35 -0
- package/src/listen/listenCli.mjs +121 -30
- 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 +39 -19
- package/src/listen/wakeSetupText.mjs +23 -5
- 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 +27 -14
- package/src/prompt/promptSession.mjs +74 -10
- package/src/prompt/promptTools.mjs +10 -6
- 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/room/roomRuntime.mjs +186 -0
- package/src/room/roomServer.mjs +112 -0
- package/src/room/roomToolSchemas.mjs +228 -0
- package/src/room/seat.mjs +334 -0
- package/src/screenshotFile.mjs +9 -0
- package/src/server.mjs +155 -111
- 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.1",
|
|
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",
|
|
@@ -41,5 +41,13 @@
|
|
|
41
41
|
"dependencies": {
|
|
42
42
|
"@modelcontextprotocol/sdk": "^1.32.1",
|
|
43
43
|
"ws": "^8.22.0"
|
|
44
|
+
},
|
|
45
|
+
"peerDependencies": {
|
|
46
|
+
"surfcad": ">=0.1.0"
|
|
47
|
+
},
|
|
48
|
+
"peerDependenciesMeta": {
|
|
49
|
+
"surfcad": {
|
|
50
|
+
"optional": true
|
|
51
|
+
}
|
|
44
52
|
}
|
|
45
53
|
}
|
package/src/cli.mjs
CHANGED
|
@@ -9,6 +9,7 @@ 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 { callSavedTool, errorValue, listCliTools } from './cliCall.mjs';
|
|
12
13
|
import {
|
|
13
14
|
bootstrapAfterLogin,
|
|
14
15
|
runListenCommand,
|
|
@@ -16,28 +17,42 @@ import {
|
|
|
16
17
|
wakeStatusText,
|
|
17
18
|
WAKE_SETUP_STEPS,
|
|
18
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';
|
|
23
|
+
import { connectRoomSession } from './room/roomRuntime.mjs';
|
|
24
|
+
import { listRoomMcpTools } from './room/roomServer.mjs';
|
|
19
25
|
|
|
20
26
|
const HELP = `surfcad-mcp
|
|
21
27
|
|
|
22
28
|
npx surfcad-mcp
|
|
23
|
-
MCP server on stdio.
|
|
29
|
+
MCP server on stdio. Uses the saved server login.
|
|
24
30
|
npx surfcad-mcp login [--name NAME] [--server URL]
|
|
25
31
|
Device-code login at the SurfCAD agent server. Prints the code and
|
|
26
32
|
the approval URL. The token is saved on this machine and is not printed.
|
|
27
33
|
npx surfcad-mcp login --code CODE [--name NAME] [--server URL]
|
|
28
|
-
Redeem
|
|
29
|
-
The token is saved on this machine and is not printed.
|
|
34
|
+
Redeem the join code shown by SurfCAD → Connect Agent (ABCD-EFGH).
|
|
35
|
+
The hyphen is optional. The token is saved on this machine and is not printed.
|
|
30
36
|
npx surfcad-mcp logout
|
|
31
37
|
Revokes this machine's token on the server, then deletes the saved
|
|
32
38
|
file. If the server cannot be reached, the file is still deleted.
|
|
33
39
|
npx surfcad-mcp status
|
|
34
40
|
The saved login, the wake setup, and whether the listener is running.
|
|
41
|
+
npx surfcad-mcp tools [NAME]
|
|
42
|
+
List tools, or one tool's name, description, and argument schema.
|
|
43
|
+
Does not need a login.
|
|
44
|
+
npx surfcad-mcp call TOOL ['{"json":"args"}']
|
|
45
|
+
Call one tool on the paired session and print the JSON result.
|
|
46
|
+
Uses the saved login. Exits non-zero on error. A large result
|
|
47
|
+
(list_edges can be over 8 MB) is printed in full. The token is not printed.
|
|
35
48
|
|
|
36
49
|
Wake: start a session of the agent when the user sends a chat message from
|
|
37
50
|
SurfCAD and no agent process is reading. A host provides its wake in this
|
|
38
51
|
server's environment (SURFCAD_WAKE_POST with SURFCAD_WAKE_BEARER, and/or
|
|
39
|
-
SURFCAD_WAKE_EXEC); login and pair then start the listener by themselves
|
|
40
|
-
|
|
52
|
+
SURFCAD_WAKE_EXEC); login and pair then start the listener by themselves,
|
|
53
|
+
restarting one that is still on an older login, and pair fires a test
|
|
54
|
+
wake once per login (the session it starts calls status and ends;
|
|
55
|
+
SurfCAD greets the user itself). SURFCAD_WAKE_BOOTSTRAP=0 turns that off.
|
|
41
56
|
The manual way, when the host provides nothing:
|
|
42
57
|
${WAKE_SETUP_STEPS.map((step, i) => ` ${i + 1}. ${step}`).join('\n')}
|
|
43
58
|
npx surfcad-mcp wake set [--post URL [--bearer KEY]] [--exec COMMAND]
|
|
@@ -47,32 +62,68 @@ ${WAKE_SETUP_STEPS.map((step, i) => ` ${i + 1}. ${step}`).join('\n')}
|
|
|
47
62
|
the command is the fallback. The key can also come from
|
|
48
63
|
SURFCAD_WAKE_BEARER. It is saved on this machine and is not printed.
|
|
49
64
|
npx surfcad-mcp wake show | test | clear
|
|
50
|
-
npx surfcad-mcp
|
|
65
|
+
npx surfcad-mcp wake claude-code
|
|
66
|
+
The wake command for Claude Code. Save it with:
|
|
67
|
+
npx surfcad-mcp wake set --exec "npx -y surfcad-mcp@latest wake claude-code"
|
|
68
|
+
A chat message then resumes the session that owns the chat (or a fork
|
|
69
|
+
of it when that session is open but idle) instead of a blank one.
|
|
70
|
+
npx surfcad-mcp wait [--timeout SECONDS]
|
|
71
|
+
Block until the next SurfCAD chat message, print it as JSON, and exit
|
|
72
|
+
(0 message, 2 timed out, 3 the chat moved to another session). Run it
|
|
73
|
+
in the background at the end of each turn (Claude Code: run_in_background):
|
|
74
|
+
the message then wakes the same session, however long the reply takes.
|
|
75
|
+
It does not read the message; read_messages does. Default timeout 6 h.
|
|
76
|
+
npx surfcad-mcp owner [--release]
|
|
77
|
+
The agent session that owns this account's chat on this machine (the
|
|
78
|
+
one that answered last), and whether it is waiting. --release drops it:
|
|
79
|
+
the next chat message starts a new session.
|
|
80
|
+
npx surfcad-mcp room join --room LINK [--name NAME] [--machine LABEL]
|
|
81
|
+
Ask for a seat in a SurfCAD room, for an agent on a machine with no
|
|
82
|
+
browser. LINK is the room link the room's host copies from SurfCAD
|
|
83
|
+
(or the room key, owner/name:branch:assemblyId). Prints a short code
|
|
84
|
+
and waits: the host sees the same code and approves or denies. The
|
|
85
|
+
link gives no access by itself. The seat token is for that one room,
|
|
86
|
+
is saved on this machine and is not printed. Needs no login.
|
|
87
|
+
npx surfcad-mcp room status | forget
|
|
88
|
+
The saved room seat (never the token), or delete it from this machine.
|
|
89
|
+
npx surfcad-mcp room tools [NAME]
|
|
90
|
+
List headless room tools, or one tool's description and schema.
|
|
91
|
+
Works offline without a saved room seat.
|
|
92
|
+
npx surfcad-mcp room mcp [--server URL]
|
|
93
|
+
Headless room MCP server on stdio. Uses the saved room seat and the
|
|
94
|
+
standalone "surfcad" runtime package (Node >= 22.15). No browser needed.
|
|
95
|
+
npx surfcad-mcp room call TOOL ['{"json":"args"}'] [--server URL]
|
|
96
|
+
Run one headless room tool against the saved room seat and print JSON.
|
|
97
|
+
npx surfcad-mcp listen [--detach] [--stop] [--pause] [--resume]
|
|
51
98
|
Watch the server relay for chat messages and fire the wake for one
|
|
52
99
|
that no agent process reads within a few seconds. Outbound HTTPS
|
|
53
100
|
only: no open port, works behind NAT. Needs a saved login and a saved
|
|
54
|
-
wake. --detach starts it in the background and returns
|
|
101
|
+
wake. --detach starts it in the background and returns; a listener
|
|
102
|
+
still on an older login is replaced. --stop ends it. A rejection
|
|
103
|
+
reads the saved login once and continues when a newer token is there.
|
|
55
104
|
|
|
56
|
-
--remote Use the server relay. Requires a saved login.
|
|
57
|
-
--local Use the local relay even when a login is saved.
|
|
58
105
|
--server URL Dev or staging origin (or set SURFCAD_AGENT_SERVER).
|
|
59
106
|
Cleartext http is only allowed for localhost, 127.0.0.1, and ::1.
|
|
60
107
|
--code CODE Join code from the SurfCAD Connect Agent screen (ABCD-EFGH).
|
|
61
108
|
--name NAME Agent name for the approval page. Otherwise the MCP client
|
|
62
109
|
name is used when the server starts, or SURFCAD_AGENT_NAME.
|
|
110
|
+
--machine LABEL With room join: what the host sees as this machine.
|
|
111
|
+
Otherwise the host name. A label only; no address is sent.
|
|
112
|
+
--remote Accepted. The server relay is the only mode.
|
|
63
113
|
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
SURFCAD_AGENT_BRIDGE_WS_PORT,
|
|
67
|
-
--remote and SURFCAD_MCP_TRANSPORT=remote win over those.
|
|
114
|
+
The local loopback relay was removed in 0.4.0. --local,
|
|
115
|
+
SURFCAD_MCP_TRANSPORT=local, SURFCAD_AGENT_BRIDGE_WS_URL,
|
|
116
|
+
SURFCAD_AGENT_BRIDGE_WS_PORT, and SURFCAD_PAIRING_CODE are errors.
|
|
68
117
|
`;
|
|
69
118
|
|
|
70
119
|
/**
|
|
71
120
|
* @param {string[]} argv
|
|
72
121
|
*/
|
|
73
122
|
export function parseArgs(argv) {
|
|
74
|
-
/** @type {'serve' | 'login' | 'logout' | 'status' | 'listen' | 'wake' | 'help'} */
|
|
123
|
+
/** @type {'serve' | 'login' | 'logout' | 'status' | 'listen' | 'wake' | 'call' | 'tools' | 'wait' | 'owner' | 'room' | 'help'} */
|
|
75
124
|
let command = 'serve';
|
|
125
|
+
/** @type {string[]} */
|
|
126
|
+
const positionals = [];
|
|
76
127
|
let name = '';
|
|
77
128
|
let server = '';
|
|
78
129
|
let code = '';
|
|
@@ -84,6 +135,12 @@ export function parseArgs(argv) {
|
|
|
84
135
|
let bearer = '';
|
|
85
136
|
let detach = false;
|
|
86
137
|
let stop = false;
|
|
138
|
+
let pause = false;
|
|
139
|
+
let resume = false;
|
|
140
|
+
let release = false;
|
|
141
|
+
let timeout = '';
|
|
142
|
+
let room = '';
|
|
143
|
+
let machine = '';
|
|
87
144
|
const valued = (arg, flag, i) => {
|
|
88
145
|
const value = arg === flag ? argv[i + 1] : arg.slice(flag.length + 1);
|
|
89
146
|
if (!value || (arg === flag && value.startsWith('--'))) {
|
|
@@ -93,14 +150,23 @@ export function parseArgs(argv) {
|
|
|
93
150
|
};
|
|
94
151
|
for (let i = 0; i < argv.length; i += 1) {
|
|
95
152
|
const arg = argv[i];
|
|
96
|
-
if (
|
|
153
|
+
if ((command === 'call' || command === 'tools' || (command === 'room' && (action === 'call' || action === 'tools'))) && !arg.startsWith('-')) {
|
|
154
|
+
positionals.push(arg);
|
|
155
|
+
continue;
|
|
156
|
+
}
|
|
157
|
+
// `room status` / `room call` / `room tools`: action belongs to `room`, not a second command.
|
|
158
|
+
if (command === 'room' && !action && (arg === 'join' || arg === 'status' || arg === 'forget' || arg === 'mcp' || arg === 'call' || arg === 'tools')) {
|
|
159
|
+
action = arg;
|
|
160
|
+
continue;
|
|
161
|
+
}
|
|
162
|
+
if (arg === 'login' || arg === 'logout' || arg === 'status' || arg === 'listen' || arg === 'wake' || arg === 'call' || arg === 'tools' || arg === 'wait' || arg === 'owner' || arg === 'room') {
|
|
97
163
|
if (command !== 'serve') {
|
|
98
|
-
throw Object.assign(new Error('Pass one command: login, logout, status, wake, or
|
|
164
|
+
throw Object.assign(new Error('Pass one command: login, logout, status, wake, listen, wait, owner, room, call, or tools.'), { code: 'bad_args' });
|
|
99
165
|
}
|
|
100
166
|
command = arg;
|
|
101
167
|
continue;
|
|
102
168
|
}
|
|
103
|
-
if (command === 'wake' && !action && (arg === 'set' || arg === 'show' || arg === 'test' || arg === 'clear')) {
|
|
169
|
+
if (command === 'wake' && !action && (arg === 'set' || arg === 'show' || arg === 'test' || arg === 'clear' || arg === 'claude-code')) {
|
|
104
170
|
action = arg;
|
|
105
171
|
continue;
|
|
106
172
|
}
|
|
@@ -112,6 +178,33 @@ export function parseArgs(argv) {
|
|
|
112
178
|
stop = true;
|
|
113
179
|
continue;
|
|
114
180
|
}
|
|
181
|
+
if (arg === '--pause') {
|
|
182
|
+
pause = true;
|
|
183
|
+
continue;
|
|
184
|
+
}
|
|
185
|
+
if (arg === '--resume') {
|
|
186
|
+
resume = true;
|
|
187
|
+
continue;
|
|
188
|
+
}
|
|
189
|
+
if (arg === '--release') {
|
|
190
|
+
release = true;
|
|
191
|
+
continue;
|
|
192
|
+
}
|
|
193
|
+
if (arg === '--timeout' || arg.startsWith('--timeout=')) {
|
|
194
|
+
timeout = valued(arg, '--timeout', i);
|
|
195
|
+
if (arg === '--timeout') i += 1;
|
|
196
|
+
continue;
|
|
197
|
+
}
|
|
198
|
+
if (arg === '--room' || arg.startsWith('--room=')) {
|
|
199
|
+
room = valued(arg, '--room', i);
|
|
200
|
+
if (arg === '--room') i += 1;
|
|
201
|
+
continue;
|
|
202
|
+
}
|
|
203
|
+
if (arg === '--machine' || arg.startsWith('--machine=')) {
|
|
204
|
+
machine = valued(arg, '--machine', i);
|
|
205
|
+
if (arg === '--machine') i += 1;
|
|
206
|
+
continue;
|
|
207
|
+
}
|
|
115
208
|
if (arg === '--post' || arg.startsWith('--post=')) {
|
|
116
209
|
post = valued(arg, '--post', i);
|
|
117
210
|
if (arg === '--post') i += 1;
|
|
@@ -170,13 +263,29 @@ export function parseArgs(argv) {
|
|
|
170
263
|
if (command !== 'wake' && (post || exec || bearer)) {
|
|
171
264
|
throw Object.assign(new Error('--post, --exec and --bearer go with: wake set.'), { code: 'bad_args' });
|
|
172
265
|
}
|
|
173
|
-
if (command !== 'listen' && (detach || stop)) {
|
|
174
|
-
throw Object.assign(new Error('--detach and --
|
|
266
|
+
if (command !== 'listen' && (detach || stop || pause || resume)) {
|
|
267
|
+
throw Object.assign(new Error('--detach, --stop, --pause and --resume go with: listen.'), { code: 'bad_args' });
|
|
268
|
+
}
|
|
269
|
+
if ([detach, stop, pause, resume].filter(Boolean).length > 1) {
|
|
270
|
+
throw Object.assign(new Error('Pass one of --detach, --stop, --pause, --resume.'), { code: 'bad_args' });
|
|
271
|
+
}
|
|
272
|
+
if (command !== 'owner' && release) {
|
|
273
|
+
throw Object.assign(new Error('--release goes with: owner.'), { code: 'bad_args' });
|
|
175
274
|
}
|
|
176
|
-
if (
|
|
177
|
-
throw Object.assign(new Error('
|
|
275
|
+
if (command !== 'wait' && timeout) {
|
|
276
|
+
throw Object.assign(new Error('--timeout goes with: wait.'), { code: 'bad_args' });
|
|
277
|
+
}
|
|
278
|
+
if (command !== 'room' && (room || machine)) {
|
|
279
|
+
throw Object.assign(new Error('--room and --machine go with: room join.'), { code: 'bad_args' });
|
|
280
|
+
}
|
|
281
|
+
if (command === 'room') {
|
|
282
|
+
if (!action) throw Object.assign(new Error('Pass one of: room join, room status, room forget, room mcp, room call, room tools.'), { code: 'bad_args' });
|
|
283
|
+
if (action === 'join' && !room) throw Object.assign(new Error('room join needs --room LINK.'), { code: 'bad_args' });
|
|
284
|
+
if (action !== 'join' && (room || machine || name)) {
|
|
285
|
+
throw Object.assign(new Error('--room, --machine and --name go with: room join.'), { code: 'bad_args' });
|
|
286
|
+
}
|
|
178
287
|
}
|
|
179
|
-
return { command, name, server, code, remote, local, action, post, exec, bearer, detach, stop };
|
|
288
|
+
return { command, name, server, code, remote, local, action, post, exec, bearer, detach, stop, pause, resume, release, timeout, room, machine, positionals };
|
|
180
289
|
}
|
|
181
290
|
|
|
182
291
|
/**
|
|
@@ -228,7 +337,7 @@ export async function runCli(argv, options = {}) {
|
|
|
228
337
|
}
|
|
229
338
|
if (parsed.command !== 'serve') {
|
|
230
339
|
if (parsed.remote || parsed.local) {
|
|
231
|
-
io.stderr(`login, logout, status, wake, and
|
|
340
|
+
io.stderr(`login, logout, status, wake, listen, wait, owner, room, call, and tools do not take --remote or --local.\n${HELP}`);
|
|
232
341
|
return { action: 'exit', code: 1 };
|
|
233
342
|
}
|
|
234
343
|
}
|
|
@@ -263,6 +372,100 @@ export async function runCli(argv, options = {}) {
|
|
|
263
372
|
io.stdout(await bootstrapAfterLogin({ env, spawn: options.spawn }));
|
|
264
373
|
return { action: 'exit', code: 0 };
|
|
265
374
|
}
|
|
375
|
+
if (parsed.command === 'room') {
|
|
376
|
+
if (parsed.action === 'status') {
|
|
377
|
+
io.stdout(formatRoomSeatStatus(await readRoomSeat(env)));
|
|
378
|
+
return { action: 'exit', code: 0 };
|
|
379
|
+
}
|
|
380
|
+
if (parsed.action === 'forget') {
|
|
381
|
+
await forgetRoomSeat(env);
|
|
382
|
+
io.stdout('The room seat is deleted from this machine. The host can remove the agent from the room in SurfCAD.\n');
|
|
383
|
+
return { action: 'exit', code: 0 };
|
|
384
|
+
}
|
|
385
|
+
if (parsed.action === 'tools') {
|
|
386
|
+
const tools = listRoomMcpTools();
|
|
387
|
+
const wanted = parsed.positionals[0] || '';
|
|
388
|
+
if (parsed.positionals.length > 1) {
|
|
389
|
+
io.stderr(`room tools takes at most one tool name.\n${HELP}`);
|
|
390
|
+
return { action: 'exit', code: 1 };
|
|
391
|
+
}
|
|
392
|
+
if (wanted) {
|
|
393
|
+
const tool = tools.find((row) => row.name === wanted);
|
|
394
|
+
if (!tool) {
|
|
395
|
+
io.stderr(`Unknown room tool: ${wanted}\n`);
|
|
396
|
+
return { action: 'exit', code: 1 };
|
|
397
|
+
}
|
|
398
|
+
io.stdout(`${JSON.stringify(tool)}\n`);
|
|
399
|
+
return { action: 'exit', code: 0 };
|
|
400
|
+
}
|
|
401
|
+
io.stdout(`${JSON.stringify(tools.map((row) => ({ name: row.name, description: row.description })))}\n`);
|
|
402
|
+
return { action: 'exit', code: 0 };
|
|
403
|
+
}
|
|
404
|
+
if (parsed.action === 'mcp') {
|
|
405
|
+
return { action: 'serve_room', server: parsed.server };
|
|
406
|
+
}
|
|
407
|
+
if (parsed.action === 'call') {
|
|
408
|
+
const tool = parsed.positionals[0] || '';
|
|
409
|
+
if (!tool) {
|
|
410
|
+
io.stderr(`room call needs a tool name.\n${HELP}`);
|
|
411
|
+
return { action: 'exit', code: 1 };
|
|
412
|
+
}
|
|
413
|
+
if (parsed.positionals.length > 2) {
|
|
414
|
+
io.stderr(`room call takes a tool name and one JSON argument object.\n${HELP}`);
|
|
415
|
+
return { action: 'exit', code: 1 };
|
|
416
|
+
}
|
|
417
|
+
let args = {};
|
|
418
|
+
if (parsed.positionals.length === 2) {
|
|
419
|
+
try {
|
|
420
|
+
args = JSON.parse(parsed.positionals[1]);
|
|
421
|
+
} catch {
|
|
422
|
+
io.stderr('room call arguments must be a JSON object.\n');
|
|
423
|
+
return { action: 'exit', code: 1 };
|
|
424
|
+
}
|
|
425
|
+
if (!args || typeof args !== 'object' || Array.isArray(args)) {
|
|
426
|
+
io.stderr('room call arguments must be a JSON object.\n');
|
|
427
|
+
return { action: 'exit', code: 1 };
|
|
428
|
+
}
|
|
429
|
+
}
|
|
430
|
+
const session = await connectRoomSession({
|
|
431
|
+
env,
|
|
432
|
+
server: parsed.server,
|
|
433
|
+
importRoom: options.importRoom,
|
|
434
|
+
WebSocketImpl: options.WebSocketImpl,
|
|
435
|
+
prewarm: false,
|
|
436
|
+
});
|
|
437
|
+
try {
|
|
438
|
+
const ready = await session.waitReady();
|
|
439
|
+
if (!ready.ok) {
|
|
440
|
+
io.stdout(`${JSON.stringify(ready)}\n`);
|
|
441
|
+
return { action: 'exit', code: 1 };
|
|
442
|
+
}
|
|
443
|
+
const result = await session.callTool(tool, args);
|
|
444
|
+
io.stdout(`${JSON.stringify(result)}\n`);
|
|
445
|
+
return { action: 'exit', code: result?.ok === false ? 1 : 0 };
|
|
446
|
+
} finally {
|
|
447
|
+
await session.close();
|
|
448
|
+
}
|
|
449
|
+
}
|
|
450
|
+
// The link names the server too. --server (or SURFCAD_AGENT_SERVER) wins, for dev and staging.
|
|
451
|
+
const link = parseRoomLink(parsed.room);
|
|
452
|
+
const serverUrl = parsed.server || env.SURFCAD_AGENT_SERVER?.trim() || !link.server
|
|
453
|
+
? resolveServerUrl({ flag: parsed.server, env })
|
|
454
|
+
: link.server;
|
|
455
|
+
const seat = await joinRoom({
|
|
456
|
+
serverUrl,
|
|
457
|
+
room: link.room,
|
|
458
|
+
label: resolveAgentName({ name: parsed.name, env }),
|
|
459
|
+
machine: parsed.machine || options.machine || hostname(),
|
|
460
|
+
env,
|
|
461
|
+
fetch: options.fetch,
|
|
462
|
+
onCode: ({ code }) => {
|
|
463
|
+
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`);
|
|
464
|
+
},
|
|
465
|
+
});
|
|
466
|
+
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`);
|
|
467
|
+
return { action: 'exit', code: 0 };
|
|
468
|
+
}
|
|
266
469
|
if (parsed.command === 'logout') {
|
|
267
470
|
const result = await logoutDevice({ env, fetch: options.fetch });
|
|
268
471
|
if (result.hadLogin && !result.confirmed) {
|
|
@@ -283,6 +486,76 @@ export async function runCli(argv, options = {}) {
|
|
|
283
486
|
const code = await runWakeCommand(parsed, { env, io, fetch: options.fetch, spawn: options.spawn });
|
|
284
487
|
return { action: 'exit', code };
|
|
285
488
|
}
|
|
489
|
+
if (parsed.command === 'tools') {
|
|
490
|
+
const tools = listCliTools();
|
|
491
|
+
const wanted = parsed.positionals[0] || '';
|
|
492
|
+
if (parsed.positionals.length > 1) {
|
|
493
|
+
io.stderr(`tools takes at most one tool name.\n${HELP}`);
|
|
494
|
+
return { action: 'exit', code: 1 };
|
|
495
|
+
}
|
|
496
|
+
if (wanted) {
|
|
497
|
+
const tool = tools.find((row) => row.name === wanted);
|
|
498
|
+
if (!tool) {
|
|
499
|
+
io.stderr(`Unknown tool: ${wanted}\n`);
|
|
500
|
+
return { action: 'exit', code: 1 };
|
|
501
|
+
}
|
|
502
|
+
io.stdout(`${JSON.stringify(tool)}\n`);
|
|
503
|
+
return { action: 'exit', code: 0 };
|
|
504
|
+
}
|
|
505
|
+
io.stdout(`${JSON.stringify(tools.map((row) => ({ name: row.name, description: row.description })))}\n`);
|
|
506
|
+
return { action: 'exit', code: 0 };
|
|
507
|
+
}
|
|
508
|
+
if (parsed.command === 'call') {
|
|
509
|
+
const tool = parsed.positionals[0] || '';
|
|
510
|
+
if (!tool) {
|
|
511
|
+
io.stderr(`call needs a tool name.\n${HELP}`);
|
|
512
|
+
return { action: 'exit', code: 1 };
|
|
513
|
+
}
|
|
514
|
+
if (parsed.positionals.length > 2) {
|
|
515
|
+
io.stderr(`call takes a tool name and one JSON argument object.\n${HELP}`);
|
|
516
|
+
return { action: 'exit', code: 1 };
|
|
517
|
+
}
|
|
518
|
+
let args = {};
|
|
519
|
+
if (parsed.positionals.length === 2) {
|
|
520
|
+
try {
|
|
521
|
+
args = JSON.parse(parsed.positionals[1]);
|
|
522
|
+
} catch {
|
|
523
|
+
io.stderr('call arguments must be a JSON object.\n');
|
|
524
|
+
return { action: 'exit', code: 1 };
|
|
525
|
+
}
|
|
526
|
+
if (!args || typeof args !== 'object' || Array.isArray(args)) {
|
|
527
|
+
io.stderr('call arguments must be a JSON object.\n');
|
|
528
|
+
return { action: 'exit', code: 1 };
|
|
529
|
+
}
|
|
530
|
+
}
|
|
531
|
+
try {
|
|
532
|
+
const result = await callSavedTool({
|
|
533
|
+
tool,
|
|
534
|
+
args,
|
|
535
|
+
env,
|
|
536
|
+
fetch: options.fetch,
|
|
537
|
+
server: parsed.server,
|
|
538
|
+
});
|
|
539
|
+
io.stdout(`${JSON.stringify(result.value)}\n`);
|
|
540
|
+
return { action: 'exit', code: result.ok ? 0 : 1 };
|
|
541
|
+
} catch (err) {
|
|
542
|
+
io.stdout(`${JSON.stringify(errorValue(err))}\n`);
|
|
543
|
+
return { action: 'exit', code: 1 };
|
|
544
|
+
}
|
|
545
|
+
}
|
|
546
|
+
if (parsed.command === 'wait') {
|
|
547
|
+
const code = await runWaitCommand(parsed, { env, io, fetch: options.fetch, signal: options.signal });
|
|
548
|
+
return { action: 'exit', code };
|
|
549
|
+
}
|
|
550
|
+
if (parsed.command === 'owner') {
|
|
551
|
+
if (parsed.release) {
|
|
552
|
+
const out = await releaseOwner(env);
|
|
553
|
+
io.stdout(out.released ? `Released the chat (session ${out.session}). The next message starts a new session.\n` : 'No session owns the chat.\n');
|
|
554
|
+
return { action: 'exit', code: 0 };
|
|
555
|
+
}
|
|
556
|
+
io.stdout(`${JSON.stringify(await ownerStatus(env))}\n`);
|
|
557
|
+
return { action: 'exit', code: 0 };
|
|
558
|
+
}
|
|
286
559
|
if (parsed.command === 'listen') {
|
|
287
560
|
const code = await runListenCommand(parsed, {
|
|
288
561
|
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 };
|