surfcad-mcp 0.2.0 → 0.2.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/src/relay.mjs CHANGED
@@ -1,47 +1,54 @@
1
1
  import { WebSocket } from 'ws';
2
2
  import { connectPeer } from './nodeClient.mjs';
3
3
  import { PAIR_MSG } from './relayMessages.mjs';
4
+ import { redactToken } from './bridge/relayHub.mjs';
5
+ import { RECONNECT_HINT, pairPendingError, pairingLostError } from './errors.mjs';
4
6
 
5
7
  const DEFAULT_WS_URL = 'ws://127.0.0.1:17341';
6
8
 
9
+ /** Backoff between automatic re-pair attempts after the tab drops. */
10
+ export const DEFAULT_RECONNECT_DELAYS_MS = Object.freeze([250, 500, 1000, 2000, 3000, 5000]);
11
+
12
+ /**
13
+ * @typedef {'unpaired' | 'pairing' | 'paired' | 'lost'} RelaySessionState
14
+ */
15
+
7
16
  export function defaultRelayUrl() {
8
17
  const fromEnv = process.env.SURFCAD_AGENT_BRIDGE_WS_URL;
9
18
  if (typeof fromEnv === 'string' && fromEnv.trim()) return fromEnv.trim();
10
19
  return DEFAULT_WS_URL;
11
20
  }
12
21
 
22
+ function defaultSessionLog(line) {
23
+ console.error(`${new Date().toISOString()} [surfcad-mcp] ${line}`);
24
+ }
25
+
26
+ function notPaired() {
27
+ return Object.assign(new Error('Not paired'), { code: 'not_paired' });
28
+ }
29
+
13
30
  /**
14
- * @param {WebSocket} ws
15
- * @param {string} command
16
- * @param {Record<string, unknown>} args
17
- * @param {string | number} id
31
+ * @param {unknown} err
18
32
  */
19
- export function invokeBridge(ws, command, args = {}, id = '1') {
20
- return new Promise((resolve, reject) => {
21
- const onMessage = (raw) => {
22
- let msg;
23
- try {
24
- msg = JSON.parse(String(raw));
25
- } catch {
26
- return;
27
- }
28
- if (msg?.id !== id) return;
29
- ws.off('message', onMessage);
30
- if (msg.ok === true) {
31
- resolve(msg.result);
32
- return;
33
- }
34
- const error = msg.error && typeof msg.error === 'object'
35
- ? msg.error
36
- : { code: 'bridge_error', message: 'Command refused' };
37
- reject(Object.assign(new Error(error.message || error.code || 'Bridge call failed'), {
38
- code: error.code,
39
- details: error.details,
40
- }));
41
- };
42
- ws.on('message', onMessage);
43
- ws.send(JSON.stringify({ id, command, args }));
44
- });
33
+ function pairError(err) {
34
+ const code = err && typeof err === 'object' && typeof err.code === 'string' ? err.code : 'pair_failed';
35
+ const message = err instanceof Error ? err.message : String(err);
36
+ if (code === 'pair_rejected') {
37
+ return Object.assign(new Error('Pairing rejected in SurfCAD (user clicked Deny)'), { code });
38
+ }
39
+ if (code === 'unknown_token') {
40
+ return Object.assign(new Error('No SurfCAD tab is showing this pairing code'), {
41
+ code,
42
+ hint: RECONNECT_HINT,
43
+ });
44
+ }
45
+ if (code === 'relay_unreachable') {
46
+ return Object.assign(new Error('The local agent bridge relay is not running'), {
47
+ code,
48
+ hint: 'Restart the MCP server (npx surfcad-mcp), then keep the SurfCAD tab open in Chrome.',
49
+ });
50
+ }
51
+ return Object.assign(new Error(message), { code: code === 'relay_error' ? 'pair_failed' : code });
45
52
  }
46
53
 
47
54
  export class RelaySession {
@@ -49,9 +56,41 @@ export class RelaySession {
49
56
  #ws = null;
50
57
  #url;
51
58
  #code = '';
59
+ /** @type {string | null} */
60
+ #resumeKey = null;
61
+ /** @type {RelaySessionState} */
62
+ #state = 'unpaired';
63
+ /** @type {Map<string, { resolve: (v: unknown) => void, reject: (e: Error) => void }>} */
64
+ #pending = new Map();
65
+ /** @type {{ code: string, promise: Promise<{ paired: true, token: string, relay: string }> } | null} */
66
+ #pairing = null;
67
+ #generation = 0;
68
+ /** @type {string | null} */
69
+ #lostReason = null;
70
+ #lostAt = 0;
71
+ #attempt = 0;
72
+ /** @type {ReturnType<typeof setTimeout> | null} */
73
+ #timer = null;
74
+ /** @type {readonly number[]} */
75
+ #delays;
76
+ /** @type {(() => Promise<unknown>) | null} */
77
+ #ensureRelay;
78
+ /** @type {(line: string) => void} */
79
+ #log;
52
80
 
81
+ /**
82
+ * @param {{
83
+ * url?: string,
84
+ * reconnectDelaysMs?: readonly number[],
85
+ * ensureRelay?: () => Promise<unknown>,
86
+ * onLog?: (line: string) => void,
87
+ * }} [options]
88
+ */
53
89
  constructor(options = {}) {
54
90
  this.#url = options.url || defaultRelayUrl();
91
+ this.#delays = options.reconnectDelaysMs?.length ? options.reconnectDelaysMs : DEFAULT_RECONNECT_DELAYS_MS;
92
+ this.#ensureRelay = options.ensureRelay || null;
93
+ this.#log = options.onLog || defaultSessionLog;
55
94
  }
56
95
 
57
96
  get url() {
@@ -62,57 +101,226 @@ export class RelaySession {
62
101
  return this.#code;
63
102
  }
64
103
 
104
+ /** @returns {RelaySessionState} */
105
+ get state() {
106
+ return this.#state;
107
+ }
108
+
109
+ status() {
110
+ return {
111
+ state: this.#state,
112
+ lostReason: this.#state === 'lost' ? this.#lostReason : null,
113
+ lostForMs: this.#state === 'lost' ? Date.now() - this.#lostAt : 0,
114
+ };
115
+ }
116
+
65
117
  isPaired() {
66
- return this.#ws != null && this.#ws.readyState === WebSocket.OPEN;
118
+ return this.#state === 'paired' && this.#ws != null && this.#ws.readyState === WebSocket.OPEN;
67
119
  }
68
120
 
69
121
  /**
70
122
  * @param {string} token
71
123
  */
72
- async pair(token) {
124
+ pair(token) {
73
125
  const code = String(token || '').trim().toUpperCase();
74
126
  if (!code) {
75
- throw Object.assign(new Error('Pairing code is required'), { code: 'bad_pairing_code' });
127
+ return Promise.reject(Object.assign(new Error('Pairing code is required'), { code: 'bad_pairing_code' }));
76
128
  }
77
- if (this.#ws) {
78
- try { this.#ws.close(); } catch { /* noop */ }
79
- this.#ws = null;
129
+ if (this.#pairing && this.#pairing.code === code) return this.#pairing.promise;
130
+ if (this.isPaired() && this.#code === code) {
131
+ return Promise.resolve({ paired: true, token: code, relay: this.#url });
80
132
  }
133
+ const resume = code === this.#code ? this.#resumeKey : null;
134
+ const recovering = this.#state === 'lost' && code === this.#code;
135
+ this.#clearTimer();
136
+ this.#detach(new Error('Re-pairing'), 'not_paired');
81
137
  this.#code = code;
138
+ if (!recovering) {
139
+ this.#resumeKey = null;
140
+ this.#state = 'pairing';
141
+ }
142
+ return this.#startPairing(code, resume);
143
+ }
144
+
145
+ /**
146
+ * @param {string} code
147
+ * @param {string | null} resume
148
+ */
149
+ #startPairing(code, resume) {
150
+ const generation = ++this.#generation;
151
+ const promise = connectPeer(this.#url, code, { resume }).then(
152
+ ({ ws, resumeKey }) => {
153
+ if (generation !== this.#generation) {
154
+ try { ws.close(); } catch { /* noop */ }
155
+ throw notPaired();
156
+ }
157
+ this.#pairing = null;
158
+ this.#attach(ws, resumeKey);
159
+ return { paired: true, token: code, relay: this.#url };
160
+ },
161
+ (err) => {
162
+ if (generation === this.#generation) {
163
+ this.#pairing = null;
164
+ if (this.#state === 'lost') this.#scheduleReconnect();
165
+ else this.#state = 'unpaired';
166
+ }
167
+ throw pairError(err);
168
+ },
169
+ );
170
+ this.#pairing = { code, promise };
171
+ return promise;
172
+ }
173
+
174
+ /**
175
+ * @param {WebSocket} ws
176
+ * @param {string | null} resumeKey
177
+ */
178
+ #attach(ws, resumeKey) {
179
+ const restored = this.#state === 'lost';
180
+ this.#ws = ws;
181
+ this.#resumeKey = resumeKey;
182
+ this.#state = 'paired';
183
+ this.#attempt = 0;
184
+ if (restored) {
185
+ this.#log(`pairing restored token=${redactToken(this.#code)} after ${Date.now() - this.#lostAt}ms`);
186
+ }
187
+ this.#lostReason = null;
188
+ ws.on('message', (raw) => {
189
+ let msg;
190
+ try {
191
+ msg = JSON.parse(String(raw));
192
+ } catch {
193
+ return;
194
+ }
195
+ if (!msg || typeof msg !== 'object') return;
196
+ if (msg.type === PAIR_MSG.UNPAIRED) {
197
+ this.#lose(ws, typeof msg.detail === 'string' ? `${msg.reason}: ${msg.detail}` : String(msg.reason || 'unpaired'));
198
+ return;
199
+ }
200
+ const id = typeof msg.id === 'string' ? msg.id : null;
201
+ const waiter = id ? this.#pending.get(id) : undefined;
202
+ if (waiter) {
203
+ this.#pending.delete(id);
204
+ if (msg.ok === true) {
205
+ waiter.resolve(msg.result);
206
+ return;
207
+ }
208
+ const error = msg.error && typeof msg.error === 'object'
209
+ ? msg.error
210
+ : { code: 'bridge_error', message: 'Command refused' };
211
+ waiter.reject(Object.assign(new Error(error.message || error.code || 'Bridge call failed'), {
212
+ code: error.code,
213
+ details: error.details,
214
+ }));
215
+ return;
216
+ }
217
+ if (msg.type === PAIR_MSG.ERROR && msg.id == null) {
218
+ this.#lose(ws, `relay_error ${msg.code || 'unknown'}`);
219
+ }
220
+ });
221
+ ws.on('close', () => { this.#lose(ws, 'relay_closed'); });
222
+ ws.on('error', () => { /* `close` follows */ });
223
+ }
224
+
225
+ /**
226
+ * @param {WebSocket} ws
227
+ * @param {string} reason
228
+ */
229
+ #lose(ws, reason) {
230
+ if (this.#ws !== ws) return;
231
+ this.#ws = null;
232
+ try { ws.close(); } catch { /* noop */ }
233
+ this.#state = 'lost';
234
+ this.#lostAt = Date.now();
235
+ this.#lostReason = reason;
236
+ this.#log(`pairing lost token=${redactToken(this.#code)} reason=${reason}; reconnecting`);
237
+ const err = pairingLostError(reason);
238
+ for (const waiter of this.#pending.values()) waiter.reject(err);
239
+ this.#pending.clear();
240
+ this.#scheduleReconnect();
241
+ }
242
+
243
+ #scheduleReconnect() {
244
+ if (this.#timer || this.#state !== 'lost' || this.#pairing) return;
245
+ const delay = this.#delays[Math.min(this.#attempt, this.#delays.length - 1)];
246
+ this.#attempt += 1;
247
+ this.#timer = setTimeout(() => {
248
+ this.#timer = null;
249
+ void this.#reconnectOnce();
250
+ }, delay);
251
+ if (typeof this.#timer.unref === 'function') this.#timer.unref();
252
+ }
253
+
254
+ async #reconnectOnce() {
255
+ if (this.#state !== 'lost' || this.#pairing) return;
82
256
  try {
83
- this.#ws = await connectPeer(this.#url, code);
257
+ await this.#startPairing(this.#code, this.#resumeKey);
84
258
  } catch (err) {
85
- const message = err instanceof Error ? err.message : String(err);
86
- if (/rejected/i.test(message) || message.includes('pair_rejected')) {
87
- throw Object.assign(new Error('Pairing rejected in SurfCAD (user clicked Deny)'), {
88
- code: 'pair_rejected',
89
- });
259
+ if (this.#state !== 'lost') return;
260
+ if (err?.code === 'pair_rejected') {
261
+ this.#log(`pairing denied in SurfCAD token=${redactToken(this.#code)}; stopped reconnecting`);
262
+ this.#state = 'unpaired';
263
+ this.#resumeKey = null;
264
+ this.#clearTimer();
265
+ return;
90
266
  }
91
- if (/unknown_token/i.test(message)) {
92
- throw Object.assign(new Error('No SurfCAD tab is showing this pairing code'), {
93
- code: 'unknown_token',
94
- });
267
+ if (err?.code === 'relay_unreachable' && this.#ensureRelay) {
268
+ await this.#ensureRelay().catch(() => {});
95
269
  }
96
- throw Object.assign(new Error(message), { code: err?.code || 'pair_failed' });
97
270
  }
98
- this.#ws.on('close', () => {
99
- this.#ws = null;
100
- });
101
- return { paired: true, token: code, relay: this.#url };
102
271
  }
103
272
 
104
- async call(command, args = {}) {
105
- if (!this.isPaired()) {
106
- throw Object.assign(new Error('Not paired'), { code: 'not_paired' });
273
+ #clearTimer() {
274
+ if (this.#timer) {
275
+ clearTimeout(this.#timer);
276
+ this.#timer = null;
107
277
  }
108
- return invokeBridge(this.#ws, command, args, `mcp-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`);
109
278
  }
110
279
 
111
- disconnect() {
112
- if (this.#ws) {
113
- try { this.#ws.close(); } catch { /* noop */ }
114
- this.#ws = null;
280
+ /**
281
+ * @param {Error} reason
282
+ * @param {string} code
283
+ */
284
+ #detach(reason, code) {
285
+ this.#generation += 1;
286
+ this.#pairing = null;
287
+ const ws = this.#ws;
288
+ this.#ws = null;
289
+ if (ws) {
290
+ try { ws.close(); } catch { /* noop */ }
115
291
  }
292
+ const err = Object.assign(reason, { code });
293
+ for (const waiter of this.#pending.values()) waiter.reject(err);
294
+ this.#pending.clear();
295
+ }
296
+
297
+ /**
298
+ * Never waits on a dead link: while unpaired or lost this rejects at once.
299
+ *
300
+ * @param {string} command
301
+ * @param {Record<string, unknown>} [args]
302
+ */
303
+ call(command, args = {}) {
304
+ if (this.#state === 'lost') return Promise.reject(pairingLostError(this.#lostReason || undefined));
305
+ if (this.#state === 'pairing') return Promise.reject(pairPendingError());
306
+ if (!this.isPaired()) return Promise.reject(notPaired());
307
+ const ws = /** @type {WebSocket} */ (this.#ws);
308
+ const id = `mcp-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
309
+ return new Promise((resolve, reject) => {
310
+ this.#pending.set(id, { resolve, reject });
311
+ try {
312
+ ws.send(JSON.stringify({ id, command, args }));
313
+ } catch {
314
+ this.#lose(ws, 'send_failed');
315
+ }
316
+ });
317
+ }
318
+
319
+ disconnect() {
320
+ this.#clearTimer();
321
+ this.#detach(new Error('Disconnected'), 'not_paired');
322
+ this.#state = 'unpaired';
323
+ this.#resumeKey = null;
116
324
  }
117
325
  }
118
326
 
package/src/server.mjs CHANGED
@@ -5,13 +5,46 @@ import {
5
5
  ListToolsRequestSchema,
6
6
  } from '@modelcontextprotocol/sdk/types.js';
7
7
  import { bridgeToolDefinitions, loadCommandsCatalog } from './catalog.mjs';
8
- import { formatBridgeError, notPairedError, pairingEnvHint } from './errors.mjs';
8
+ import {
9
+ formatBridgeError,
10
+ notPairedError,
11
+ pairPendingError,
12
+ pairingEnvHint,
13
+ } from './errors.mjs';
9
14
  import { loadPackageVersion } from './packageVersion.mjs';
10
- import { ensureAgentBridgeRelay, stopAgentBridgeRelay } from './bridge/relayServer.mjs';
15
+ import {
16
+ ensureAgentBridgeRelay,
17
+ resetAgentBridgeRelayCache,
18
+ stopAgentBridgeRelay,
19
+ } from './bridge/relayServer.mjs';
11
20
  import { RelaySession } from './relay.mjs';
12
21
 
13
22
  const PAIR_TOOL_NAME = 'pair';
14
23
 
24
+ /** A bridge call that has to pair first waits this long for Allow, then fails. */
25
+ const AUTO_PAIR_WAIT_MS = 1000;
26
+ /** The pair tool returns pair_pending before typical MCP client timeouts (60 s). */
27
+ const PAIR_TOOL_WAIT_MS = 30_000;
28
+
29
+ /**
30
+ * @param {Promise<unknown>} attempt
31
+ * @param {number} waitMs
32
+ */
33
+ async function waitForPairing(attempt, waitMs) {
34
+ attempt.catch(() => {});
35
+ let timer;
36
+ const timeout = new Promise((resolve) => {
37
+ timer = setTimeout(() => resolve(timeout), waitMs);
38
+ });
39
+ try {
40
+ const outcome = await Promise.race([attempt, timeout]);
41
+ if (outcome === timeout) throw pairPendingError();
42
+ return outcome;
43
+ } finally {
44
+ clearTimeout(timer);
45
+ }
46
+ }
47
+
15
48
  function textResult(value, isError = false) {
16
49
  return {
17
50
  content: [{ type: 'text', text: JSON.stringify(value, null, 2) }],
@@ -25,6 +58,8 @@ function toolErrorPayload(err) {
25
58
  code: err.code,
26
59
  message: err.message,
27
60
  details: err.details,
61
+ hint: err.hint,
62
+ retryable: err.retryable,
28
63
  });
29
64
  }
30
65
  return formatBridgeError({ message: String(err?.message || err) });
@@ -80,7 +115,7 @@ export async function createSurfcadMcpServer(options = {}) {
80
115
  }, true);
81
116
  }
82
117
  try {
83
- const result = await session.pair(code);
118
+ const result = await waitForPairing(session.pair(code), PAIR_TOOL_WAIT_MS);
84
119
  return textResult(result);
85
120
  } catch (err) {
86
121
  return textResult(toolErrorPayload(err), true);
@@ -92,15 +127,17 @@ export async function createSurfcadMcpServer(options = {}) {
92
127
  return textResult({ code: 'unknown_tool', message: `Unknown tool: ${name}` }, true);
93
128
  }
94
129
 
95
- if (!session.isPaired()) {
130
+ // A lost session is already re-pairing in the background; session.call
131
+ // fails fast with pairing_lost until it is back.
132
+ if (!session.isPaired() && session.state !== 'lost') {
96
133
  const envCode = (process.env.SURFCAD_PAIRING_CODE || '').trim();
97
134
  if (envCode) {
98
135
  try {
99
- await session.pair(envCode);
136
+ await waitForPairing(session.pair(envCode), AUTO_PAIR_WAIT_MS);
100
137
  } catch (err) {
101
138
  return textResult(toolErrorPayload(err), true);
102
139
  }
103
- } else {
140
+ } else if (session.state !== 'pairing') {
104
141
  return textResult(notPairedError(), true);
105
142
  }
106
143
  }
@@ -110,7 +147,12 @@ export async function createSurfcadMcpServer(options = {}) {
110
147
  return textResult(result);
111
148
  } catch (err) {
112
149
  const code = err?.code;
113
- if (code === 'real_repo_blocked' || code === 'confirm_required' || code === 'pair_rejected') {
150
+ if (
151
+ code === 'real_repo_blocked'
152
+ || code === 'consent_pending'
153
+ || code === 'confirm_required'
154
+ || code === 'pair_rejected'
155
+ ) {
114
156
  return textResult(formatBridgeError({
115
157
  code,
116
158
  message: err.message,
@@ -130,17 +172,34 @@ export async function createSurfcadMcpServer(options = {}) {
130
172
  export async function runSurfcadMcpServer(options = {}) {
131
173
  /** @type {Awaited<ReturnType<typeof ensureAgentBridgeRelay>> | null} */
132
174
  let ownedRelay = null;
133
- if (options.startRelay !== false && process.env.SURFCAD_MCP_START_RELAY !== '0') {
134
- const relay = await ensureAgentBridgeRelay({
135
- onReady: (url) => {
136
- if (process.env.SURFCAD_AGENT_BRIDGE_WS_VERBOSE === '1') {
137
- console.error(`[surfcad-mcp] Agent bridge relay on ${url}`);
138
- }
139
- },
140
- });
175
+ const startRelay = options.startRelay !== false && process.env.SURFCAD_MCP_START_RELAY !== '0';
176
+ const relayOptions = {
177
+ onReady: (url) => {
178
+ if (process.env.SURFCAD_AGENT_BRIDGE_WS_VERBOSE === '1') {
179
+ console.error(`[surfcad-mcp] Agent bridge relay on ${url}`);
180
+ }
181
+ },
182
+ };
183
+ if (startRelay) {
184
+ const relay = await ensureAgentBridgeRelay(relayOptions);
141
185
  if (relay.ownsServer) ownedRelay = relay;
142
186
  }
143
187
 
188
+ // Another surfcad-mcp process may own the relay; when it exits, take over
189
+ // the port so the tab and this session can reconnect.
190
+ const takeOverRelay = async () => {
191
+ if (!startRelay || ownedRelay) return;
192
+ resetAgentBridgeRelayCache();
193
+ const relay = await ensureAgentBridgeRelay(relayOptions);
194
+ if (relay.ownsServer) {
195
+ ownedRelay = relay;
196
+ console.error(`${new Date().toISOString()} [surfcad-mcp] relay owner went away; now serving ${relay.url}`);
197
+ }
198
+ };
199
+
200
+ // Intended MCP stdio lifecycle: when the client closes stdin the process
201
+ // (and the relay it owns) must exit. Playtests that spawn this bin have to
202
+ // keep stdin open; stdio: 'ignore' ends the stream immediately.
144
203
  const onStdinClosed = () => {
145
204
  if (ownedRelay) {
146
205
  const closing = ownedRelay;
@@ -154,7 +213,9 @@ export async function runSurfcadMcpServer(options = {}) {
154
213
  };
155
214
  process.stdin.once('end', onStdinClosed);
156
215
 
157
- const { server, session } = await createSurfcadMcpServer();
216
+ const { server, session } = await createSurfcadMcpServer({
217
+ session: new RelaySession({ ensureRelay: takeOverRelay }),
218
+ });
158
219
  const transport = new StdioServerTransport();
159
220
  await server.connect(transport);
160
221