surfcad-mcp 0.3.2 → 0.3.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,502 @@
1
+ /**
2
+ * Outbound session to the server relay. WebSocket first; if that upgrade
3
+ * fails, commands go over HTTPS POST plus SSE, then long-poll.
4
+ * The bearer token is never logged and is never placed in the URL.
5
+ */
6
+
7
+ import { WebSocket } from 'ws';
8
+ import {
9
+ AGENT_HANDSHAKE_UPDATE_MESSAGE,
10
+ AGENT_PROTOCOL_VERSION,
11
+ commandRequest,
12
+ } from '../commandProtocol.mjs';
13
+ import {
14
+ asRemoteError,
15
+ clientUpdateError,
16
+ pairingLostError,
17
+ tokenRevokedError,
18
+ } from '../errors.mjs';
19
+ import { PAIR_MSG } from '../relayMessages.mjs';
20
+ import { createPromptSession } from '../prompt/promptSession.mjs';
21
+ import { agentUrls, resolveAgentName } from './config.mjs';
22
+ import { callOverHttp, COMMAND_WAIT_MS, commandWaitTimeout, resultFromCommandResponse } from './httpFallback.mjs';
23
+
24
+ /** Server relay closes a revoked or expired token with this code. */
25
+ const TOKEN_CLOSE_CODE = 4001;
26
+ const HELLO_TIMEOUT_MS = 8000;
27
+
28
+ /**
29
+ * @param {string} wsUrl
30
+ * @param {string} token
31
+ */
32
+ function openAuthorizedSocket(wsUrl, token) {
33
+ return new Promise((resolve, reject) => {
34
+ const ws = new WebSocket(wsUrl, {
35
+ headers: { Authorization: `Bearer ${token}` },
36
+ handshakeTimeout: HELLO_TIMEOUT_MS,
37
+ });
38
+ let settled = false;
39
+ const fail = (err) => {
40
+ if (settled) return;
41
+ settled = true;
42
+ try { ws.terminate(); } catch { /* noop */ }
43
+ reject(err);
44
+ };
45
+ ws.once('unexpected-response', (_req, res) => {
46
+ const status = res.statusCode || 0;
47
+ res.resume();
48
+ if (status === 401) {
49
+ fail(tokenRevokedError());
50
+ return;
51
+ }
52
+ fail(Object.assign(new Error(`WebSocket upgrade failed (${status})`), {
53
+ code: 'ws_blocked',
54
+ statusCode: status,
55
+ }));
56
+ });
57
+ ws.once('error', (error) => {
58
+ const errno = error && typeof error === 'object' ? error.code : '';
59
+ const code = errno === 'ECONNREFUSED' || errno === 'ENOTFOUND' ? 'unreachable' : 'ws_blocked';
60
+ const err = error instanceof Error ? error : new Error(String(error));
61
+ fail(Object.assign(err, { code: /** @type {Error & { code?: string }} */ (err).code || code }));
62
+ });
63
+ ws.once('open', () => {
64
+ if (settled) return;
65
+ settled = true;
66
+ resolve(ws);
67
+ });
68
+ });
69
+ }
70
+
71
+ /**
72
+ * Hello frame. `name` is omitted when empty so the server keeps its default.
73
+ * @param {{ v?: number, name?: string }} fields
74
+ */
75
+ export function agentHelloFrame(fields = {}) {
76
+ /** @type {{ type: 'hello', v: number, name?: string }} */
77
+ const frame = {
78
+ type: 'hello',
79
+ v: typeof fields.v === 'number' ? fields.v : AGENT_PROTOCOL_VERSION,
80
+ };
81
+ if (typeof fields.name === 'string' && fields.name.trim()) frame.name = fields.name.trim();
82
+ return frame;
83
+ }
84
+
85
+ function defaultLog(line) {
86
+ console.error(`${new Date().toISOString()} [surfcad-mcp] ${line}`);
87
+ }
88
+
89
+ export class RemoteSession {
90
+ /** @type {WebSocket | null} */
91
+ #ws = null;
92
+ #urls;
93
+ #token;
94
+ #name;
95
+ #fillFromClient;
96
+ #protocolVersion;
97
+ /** @type {'ws' | 'http' | null} */
98
+ #transport = null;
99
+ /** @type {'unpaired' | 'pairing' | 'paired'} */
100
+ #state = 'unpaired';
101
+ /** @type {Promise<void> | null} */
102
+ #connecting = null;
103
+ /** @type {{ resolve: () => void, reject: (err: Error) => void } | null} */
104
+ #hello = null;
105
+ /** @type {Map<string, { resolve: (v: unknown) => void, reject: (e: Error) => void }>} */
106
+ #pending = new Map();
107
+ #log;
108
+ #fetch;
109
+ #commandTimeoutMs;
110
+ #prompts;
111
+
112
+ /**
113
+ * @param {{
114
+ * serverUrl: string,
115
+ * token: string,
116
+ * name?: string,
117
+ * fillNameFromClient?: boolean,
118
+ * protocolVersion?: number,
119
+ * onLog?: (line: string) => void,
120
+ * fetch?: typeof fetch,
121
+ * env?: NodeJS.ProcessEnv,
122
+ * promptSession?: ReturnType<typeof createPromptSession>,
123
+ * commandTimeoutMs?: number,
124
+ * }} options
125
+ */
126
+ constructor(options) {
127
+ this.#urls = agentUrls(options.serverUrl);
128
+ this.#token = options.token;
129
+ this.#name = typeof options.name === 'string' ? options.name.trim() : '';
130
+ this.#fillFromClient = options.fillNameFromClient === true && !this.#name;
131
+ this.#protocolVersion = typeof options.protocolVersion === 'number'
132
+ ? options.protocolVersion
133
+ : AGENT_PROTOCOL_VERSION;
134
+ this.#log = options.onLog || defaultLog;
135
+ this.#fetch = options.fetch || fetch;
136
+ this.#commandTimeoutMs = Number.isFinite(options.commandTimeoutMs) && options.commandTimeoutMs > 0
137
+ ? options.commandTimeoutMs
138
+ : COMMAND_WAIT_MS;
139
+ this.#prompts = options.promptSession || createPromptSession({
140
+ send: (payload) => this.#sendToTab(payload),
141
+ });
142
+ }
143
+
144
+ get url() {
145
+ return this.#urls.wsUrl;
146
+ }
147
+
148
+ get state() {
149
+ return this.#state;
150
+ }
151
+
152
+ get agentName() {
153
+ return this.#name;
154
+ }
155
+
156
+ /** True when hello should wait for the MCP client name. */
157
+ needsClientName() {
158
+ return this.#fillFromClient && !this.#name;
159
+ }
160
+
161
+ /**
162
+ * @param {{ name?: string } | null | undefined} clientInfo
163
+ */
164
+ applyClientInfo(clientInfo) {
165
+ if (!this.#fillFromClient || this.#name) return;
166
+ const name = resolveAgentName({ clientInfo });
167
+ if (name) this.#name = name;
168
+ }
169
+
170
+ /**
171
+ * @param {string} name
172
+ */
173
+ setName(name) {
174
+ const text = typeof name === 'string' ? name.trim() : '';
175
+ if (text) this.#name = text;
176
+ }
177
+
178
+ status() {
179
+ return {
180
+ state: this.#state,
181
+ transport: this.#transport,
182
+ remote: true,
183
+ server: this.#urls.origin,
184
+ };
185
+ }
186
+
187
+ isPaired() {
188
+ if (this.#state !== 'paired') return false;
189
+ if (this.#transport === 'http') return true;
190
+ return this.#ws != null && this.#ws.readyState === WebSocket.OPEN;
191
+ }
192
+
193
+ get prompts() {
194
+ return this.#prompts;
195
+ }
196
+
197
+ /**
198
+ * @param {{ mutates?: boolean }} [info]
199
+ */
200
+ noteAgentToolCall(info = {}) {
201
+ try {
202
+ this.#prompts.noteToolCall(info);
203
+ } catch {
204
+ /* status is advisory */
205
+ }
206
+ }
207
+
208
+ /**
209
+ * @param {boolean} held
210
+ */
211
+ holdAgentWork(held) {
212
+ try {
213
+ this.#prompts.holdWork(held === true);
214
+ } catch {
215
+ /* status is advisory */
216
+ }
217
+ }
218
+
219
+ /**
220
+ * Already logged in. The 8-character code is the local relay's; remote
221
+ * mode ignores it and reports the saved login.
222
+ * @param {string} [_] local pairing code; a remote login ignores it
223
+ */
224
+ pair(_) {
225
+ return this.connect().then(() => ({
226
+ paired: true,
227
+ remote: true,
228
+ relay: this.#urls.approvalUrl,
229
+ }));
230
+ }
231
+
232
+ connect() {
233
+ if (this.#state === 'paired' && this.isPaired()) return Promise.resolve();
234
+ if (!this.#connecting) this.#connecting = this.#connect();
235
+ return this.#connecting;
236
+ }
237
+
238
+ async #connect() {
239
+ this.#state = 'pairing';
240
+ try {
241
+ try {
242
+ await this.#openWebSocket();
243
+ this.#transport = 'ws';
244
+ this.#state = 'paired';
245
+ this.#log('remote agent connected via websocket');
246
+ return;
247
+ } catch (err) {
248
+ this.#dropSocket();
249
+ const code = err && typeof err === 'object' ? err.code : '';
250
+ if (code === 'token_revoked' || code === 'client_update_required') {
251
+ // Stay 'pairing' so a later tool call reaches `call()` and surfaces this error.
252
+ this.#state = 'pairing';
253
+ throw err;
254
+ }
255
+ try {
256
+ await this.#probeHttp();
257
+ } catch (probeErr) {
258
+ this.#state = 'pairing';
259
+ throw probeErr;
260
+ }
261
+ this.#transport = 'http';
262
+ this.#state = 'paired';
263
+ this.#log('remote agent connected via https fallback');
264
+ }
265
+ } finally {
266
+ // Success used to leave the settled promise here, so a later connect()
267
+ // that was no longer paired reused it and never opened a new socket.
268
+ this.#connecting = null;
269
+ }
270
+ }
271
+
272
+ async #openWebSocket() {
273
+ const ws = await openAuthorizedSocket(this.#urls.wsUrl, this.#token);
274
+ this.#ws = ws;
275
+ ws.on('message', (raw) => this.#onMessage(raw));
276
+ ws.on('close', (code, reason) => this.#onClose(code, reason));
277
+ ws.on('error', () => { /* close follows */ });
278
+ const hello = agentHelloFrame({ v: this.#protocolVersion, name: this.#name });
279
+ const acked = new Promise((resolve, reject) => {
280
+ this.#hello = { resolve, reject };
281
+ const timer = setTimeout(() => {
282
+ if (this.#hello) {
283
+ this.#hello = null;
284
+ reject(Object.assign(new Error('Agent handshake timed out'), { code: 'ws_blocked' }));
285
+ }
286
+ }, HELLO_TIMEOUT_MS);
287
+ const settle = this.#hello;
288
+ this.#hello = {
289
+ resolve: () => {
290
+ clearTimeout(timer);
291
+ settle.resolve();
292
+ },
293
+ reject: (err) => {
294
+ clearTimeout(timer);
295
+ settle.reject(err);
296
+ },
297
+ };
298
+ });
299
+ ws.send(JSON.stringify(hello));
300
+ await acked;
301
+ }
302
+
303
+ async #probeHttp() {
304
+ try {
305
+ const res = await this.#fetch(this.#urls.approvalUrl, {
306
+ method: 'GET',
307
+ signal: AbortSignal.timeout(HELLO_TIMEOUT_MS),
308
+ });
309
+ try { await res.body?.cancel?.(); } catch { /* noop */ }
310
+ if (!res.status) {
311
+ throw Object.assign(new Error('Could not reach the SurfCAD agent server.'), { code: 'unreachable' });
312
+ }
313
+ } catch (err) {
314
+ if (err && typeof err === 'object' && err.code === 'unreachable') throw err;
315
+ throw Object.assign(new Error('Could not reach the SurfCAD agent server.'), { code: 'unreachable' });
316
+ }
317
+ }
318
+
319
+ #dropSocket() {
320
+ const ws = this.#ws;
321
+ this.#ws = null;
322
+ this.#hello = null;
323
+ if (!ws) return;
324
+ ws.removeAllListeners();
325
+ try { ws.terminate(); } catch { /* noop */ }
326
+ }
327
+
328
+ /**
329
+ * @param {import('ws').RawData} raw
330
+ */
331
+ #onMessage(raw) {
332
+ /** @type {any} */
333
+ let msg;
334
+ try {
335
+ msg = JSON.parse(String(raw));
336
+ } catch {
337
+ return;
338
+ }
339
+ if (!msg || typeof msg !== 'object') return;
340
+ if (this.#hello) {
341
+ const hello = this.#hello;
342
+ this.#hello = null;
343
+ if (msg.type === 'hello') {
344
+ hello.resolve();
345
+ return;
346
+ }
347
+ const text = typeof msg.error === 'string' ? msg.error : '';
348
+ hello.reject(asRemoteError({
349
+ code: text.includes(AGENT_HANDSHAKE_UPDATE_MESSAGE) ? 'client_update_required' : 'ws_blocked',
350
+ message: text || 'Agent handshake failed',
351
+ }));
352
+ return;
353
+ }
354
+ if (msg.type === PAIR_MSG.AGENT_PROMPT) {
355
+ void this.#prompts.acceptPrompt(msg);
356
+ return;
357
+ }
358
+ if (msg.type === PAIR_MSG.AGENT_PROMPT_CANCEL) {
359
+ const cancelId = typeof msg.id === 'string' ? msg.id : '';
360
+ void this.#prompts.cancel(cancelId).then((result) => {
361
+ try {
362
+ this.#sendToTab({
363
+ type: PAIR_MSG.AGENT_PROMPT_CANCEL_RESULT,
364
+ v: 1,
365
+ id: result.id,
366
+ state: result.state,
367
+ });
368
+ } catch {
369
+ /* socket closed before the result could be sent */
370
+ }
371
+ }, () => {});
372
+ return;
373
+ }
374
+ const id = msg.id == null ? '' : String(msg.id);
375
+ const waiter = id ? this.#pending.get(id) : undefined;
376
+ if (!waiter) return;
377
+ this.#pending.delete(id);
378
+ const outcome = resultFromCommandResponse(msg);
379
+ if (outcome.ok) waiter.resolve(outcome.result);
380
+ else waiter.reject(outcome.error);
381
+ }
382
+
383
+ /**
384
+ * @param {number} code
385
+ * @param {Buffer | string} reason
386
+ */
387
+ #onClose(code, reason) {
388
+ const why = Buffer.isBuffer(reason) ? reason.toString('utf8') : String(reason || '');
389
+ const hello = this.#hello;
390
+ this.#hello = null;
391
+ this.#ws = null;
392
+ if (code === TOKEN_CLOSE_CODE) {
393
+ this.#transport = null;
394
+ this.#state = 'pairing';
395
+ this.#connecting = null;
396
+ const err = tokenRevokedError();
397
+ if (hello) hello.reject(err);
398
+ this.#failPending(err);
399
+ return;
400
+ }
401
+ if (code === 1008 || why.includes(AGENT_HANDSHAKE_UPDATE_MESSAGE)) {
402
+ this.#transport = null;
403
+ this.#state = 'pairing';
404
+ this.#connecting = null;
405
+ const err = clientUpdateError(why || AGENT_HANDSHAKE_UPDATE_MESSAGE);
406
+ if (hello) hello.reject(err);
407
+ this.#failPending(err);
408
+ return;
409
+ }
410
+ if (hello) {
411
+ hello.reject(Object.assign(new Error(`WebSocket closed (${code})`), { code: 'ws_blocked' }));
412
+ return;
413
+ }
414
+ if (this.#state === 'paired' && this.#transport === 'ws') {
415
+ this.#transport = 'http';
416
+ this.#log('websocket closed; later commands use https');
417
+ this.#failPending(pairingLostError('socket closed'));
418
+ }
419
+ }
420
+
421
+ /**
422
+ * @param {Error} err
423
+ */
424
+ #failPending(err) {
425
+ for (const waiter of this.#pending.values()) waiter.reject(err);
426
+ this.#pending.clear();
427
+ }
428
+
429
+ /**
430
+ * @param {object} payload
431
+ */
432
+ #sendToTab(payload) {
433
+ if (this.#transport !== 'ws' || !this.#ws || this.#ws.readyState !== WebSocket.OPEN) {
434
+ throw Object.assign(
435
+ new Error('In-viewer prompts need the agent WebSocket. This session is using the HTTPS fallback.'),
436
+ {
437
+ code: 'prompts_need_websocket',
438
+ hint: 'This session is on the HTTPS fallback because WebSocket was blocked. In-viewer prompts need the WebSocket; retry where the agent server allows wss.',
439
+ },
440
+ );
441
+ }
442
+ this.#ws.send(JSON.stringify(payload));
443
+ }
444
+
445
+ /**
446
+ * @param {string} command
447
+ * @param {Record<string, unknown>} [args]
448
+ */
449
+ call(command, args = {}) {
450
+ return this.connect().then(() => this.#call(command, args));
451
+ }
452
+
453
+ /**
454
+ * @param {string} command
455
+ * @param {Record<string, unknown>} args
456
+ */
457
+ #call(command, args) {
458
+ const id = `mcp-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
459
+ const frame = commandRequest({ id, command, args });
460
+ if (this.#transport === 'ws' && this.#ws && this.#ws.readyState === WebSocket.OPEN) {
461
+ return new Promise((resolve, reject) => {
462
+ const timer = setTimeout(() => {
463
+ if (!this.#pending.has(id)) return;
464
+ this.#pending.delete(id);
465
+ reject(commandWaitTimeout());
466
+ }, this.#commandTimeoutMs);
467
+ if (typeof timer.unref === 'function') timer.unref();
468
+ const finish = (fn, value) => {
469
+ clearTimeout(timer);
470
+ fn(value);
471
+ };
472
+ this.#pending.set(id, {
473
+ resolve: (value) => finish(resolve, value),
474
+ reject: (err) => finish(reject, err),
475
+ });
476
+ try {
477
+ this.#ws.send(JSON.stringify(frame));
478
+ } catch {
479
+ this.#pending.delete(id);
480
+ finish(reject, pairingLostError('send failed'));
481
+ }
482
+ });
483
+ }
484
+ return callOverHttp({
485
+ commandsUrl: this.#urls.commandsUrl,
486
+ token: this.#token,
487
+ frame,
488
+ fetch: this.#fetch,
489
+ }).catch((err) => {
490
+ throw asRemoteError(err);
491
+ });
492
+ }
493
+
494
+ disconnect() {
495
+ this.#connecting = null;
496
+ this.#dropSocket();
497
+ this.#transport = null;
498
+ this.#state = 'unpaired';
499
+ this.#prompts.clear();
500
+ this.#failPending(Object.assign(new Error('Disconnected'), { code: 'not_paired' }));
501
+ }
502
+ }
@@ -0,0 +1,109 @@
1
+ /**
2
+ * Saved remote login. The file mode is 0600 and the directory is 0700.
3
+ * Callers must not log the returned token.
4
+ */
5
+
6
+ import { chmod, mkdir, readFile, rename, rm, writeFile } from 'node:fs/promises';
7
+ import { join } from 'node:path';
8
+ import { configDir, tokenPath } from './config.mjs';
9
+
10
+ /**
11
+ * @typedef {{
12
+ * token: string,
13
+ * server: string,
14
+ * name: string,
15
+ * machine: string,
16
+ * savedAt: string,
17
+ * }} SavedLogin
18
+ */
19
+
20
+ /**
21
+ * @param {NodeJS.ProcessEnv} [env]
22
+ * @returns {Promise<SavedLogin | null>}
23
+ */
24
+ export async function readSavedLogin(env = process.env) {
25
+ const path = tokenPath(env);
26
+ /** @type {string} */
27
+ let text;
28
+ try {
29
+ text = await readFile(path, 'utf8');
30
+ } catch (err) {
31
+ if (err && typeof err === 'object' && err.code === 'ENOENT') return null;
32
+ throw Object.assign(new Error('Saved login could not be read.'), { code: 'bad_login_file' });
33
+ }
34
+ /** @type {unknown} */
35
+ let parsed;
36
+ try {
37
+ parsed = JSON.parse(text);
38
+ } catch {
39
+ throw Object.assign(new Error('Saved login could not be read.'), { code: 'bad_login_file' });
40
+ }
41
+ if (!parsed || typeof parsed !== 'object') return null;
42
+ const record = /** @type {Record<string, unknown>} */ (parsed);
43
+ if (typeof record.token !== 'string' || !record.token) return null;
44
+ return {
45
+ token: record.token,
46
+ server: typeof record.server === 'string' ? record.server : '',
47
+ name: typeof record.name === 'string' ? record.name : '',
48
+ machine: typeof record.machine === 'string' ? record.machine : '',
49
+ savedAt: typeof record.savedAt === 'string' ? record.savedAt : '',
50
+ };
51
+ }
52
+
53
+ /**
54
+ * @param {{ token: string, server: string, name?: string, machine?: string, savedAt?: string }} record
55
+ * @param {NodeJS.ProcessEnv} [env]
56
+ * @returns {Promise<string>} path written
57
+ */
58
+ export async function saveLogin(record, env = process.env) {
59
+ if (typeof record.token !== 'string' || !record.token) {
60
+ throw Object.assign(new Error('Login did not return a token.'), { code: 'bad_login' });
61
+ }
62
+ const dir = configDir(env);
63
+ await mkdir(dir, { recursive: true, mode: 0o700 });
64
+ await chmod(dir, 0o700);
65
+ const path = tokenPath(env);
66
+ const tmp = join(dir, `.token-${process.pid}-${Date.now()}.tmp`);
67
+ const body = `${JSON.stringify({
68
+ token: record.token,
69
+ server: record.server,
70
+ name: record.name || '',
71
+ machine: record.machine || '',
72
+ savedAt: record.savedAt || new Date().toISOString(),
73
+ })}\n`;
74
+ try {
75
+ await writeFile(tmp, body, { mode: 0o600, flag: 'wx' });
76
+ await chmod(tmp, 0o600);
77
+ await rename(tmp, path);
78
+ await chmod(path, 0o600);
79
+ } catch (err) {
80
+ await rm(tmp, { force: true });
81
+ if (err && typeof err === 'object' && err.code === 'bad_login') throw err;
82
+ throw Object.assign(new Error('Could not save the login.'), { code: 'save_failed' });
83
+ }
84
+ return path;
85
+ }
86
+
87
+ /**
88
+ * @param {NodeJS.ProcessEnv} [env]
89
+ */
90
+ export async function deleteSavedLogin(env = process.env) {
91
+ await rm(tokenPath(env), { force: true });
92
+ }
93
+
94
+ /**
95
+ * Status text. Never includes the token.
96
+ * @param {SavedLogin | null} saved
97
+ * @param {string} serverUrl effective server (flag or env may override the saved one)
98
+ */
99
+ export function formatLoginStatus(saved, serverUrl) {
100
+ if (!saved) return 'not logged in\n';
101
+ const lines = [
102
+ 'logged in',
103
+ `server: ${serverUrl}`,
104
+ `name: ${saved.name || '(none)'}`,
105
+ `machine: ${saved.machine || '(none)'}`,
106
+ `saved: ${saved.savedAt || '(unknown)'}`,
107
+ ];
108
+ return `${lines.join('\n')}\n`;
109
+ }