surfcad-mcp 0.1.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.
@@ -0,0 +1,268 @@
1
+ /**
2
+ * Loopback HTTP/WebSocket server for the M1 agent-bridge relay.
3
+ * Binds 127.0.0.1 only. Handles CORS / Private Network Access preflight for
4
+ * https://surfcad.com → ws://127.0.0.1 upgrades, and serves the `/bridge`
5
+ * popup page for browsers that block that upgrade (Safari).
6
+ */
7
+
8
+ import { createServer } from 'node:http';
9
+ import { WebSocket, WebSocketServer } from 'ws';
10
+ import { createAgentBridgeRelayHub } from './relayHub.mjs';
11
+ import { extraAllowedOrigins, isAllowedHttpOrigin, isLoopbackAddress } from './localAddress.mjs';
12
+ import { handleBridgeRequest } from './bridgePage.mjs';
13
+
14
+ export const DEFAULT_RELAY_PORT = 17341;
15
+
16
+ function parsePort(value) {
17
+ const n = Number(value);
18
+ return Number.isInteger(n) && n > 0 && n < 65536 ? n : DEFAULT_RELAY_PORT;
19
+ }
20
+
21
+ /**
22
+ * @param {string | undefined} origin
23
+ * @returns {Record<string, string>}
24
+ */
25
+ function corsHeadersForOrigin(origin) {
26
+ if (!origin || !isAllowedHttpOrigin(origin)) return {};
27
+ return {
28
+ 'Access-Control-Allow-Origin': origin,
29
+ 'Access-Control-Allow-Private-Network': 'true',
30
+ 'Vary': 'Origin',
31
+ };
32
+ }
33
+
34
+ /**
35
+ * @param {string} url
36
+ * @param {number} [timeoutMs]
37
+ */
38
+ export function probeRelayAtUrl(url, timeoutMs = 1500) {
39
+ return new Promise((resolve) => {
40
+ let settled = false;
41
+ const finish = (ok) => {
42
+ if (settled) return;
43
+ settled = true;
44
+ resolve(ok);
45
+ };
46
+ let ws;
47
+ try {
48
+ ws = new WebSocket(url);
49
+ } catch {
50
+ finish(false);
51
+ return;
52
+ }
53
+ const timer = setTimeout(() => {
54
+ try { ws.close(); } catch { /* noop */ }
55
+ finish(false);
56
+ }, timeoutMs);
57
+ if (typeof timer.unref === 'function') timer.unref();
58
+ ws.once('open', () => {
59
+ clearTimeout(timer);
60
+ try { ws.close(); } catch { /* noop */ }
61
+ finish(true);
62
+ });
63
+ ws.once('error', () => {
64
+ clearTimeout(timer);
65
+ finish(false);
66
+ });
67
+ });
68
+ }
69
+
70
+ export const DEFAULT_HEARTBEAT_MS = 5000;
71
+
72
+ function parseHeartbeatMs(value) {
73
+ const n = Number(value);
74
+ return Number.isFinite(n) && n >= 50 ? n : DEFAULT_HEARTBEAT_MS;
75
+ }
76
+
77
+ /**
78
+ * Drops and heartbeat timeouts always go to stderr (stdout is the MCP stdio
79
+ * channel); routine pairing lines only with SURFCAD_AGENT_BRIDGE_WS_VERBOSE=1.
80
+ *
81
+ * @param {string} line
82
+ * @param {'info' | 'warn'} [level]
83
+ */
84
+ export function defaultRelayLog(line, level = 'info') {
85
+ if (level !== 'warn' && process.env.SURFCAD_AGENT_BRIDGE_WS_VERBOSE !== '1') return;
86
+ console.error(`${new Date().toISOString()} [surfcad-relay] ${level === 'warn' ? 'WARN ' : ''}${line}`);
87
+ }
88
+
89
+ /**
90
+ * @param {{
91
+ * port?: number,
92
+ * host?: string,
93
+ * heartbeatMs?: number,
94
+ * onReady?: (url: string) => void,
95
+ * onLog?: (line: string, level: 'info' | 'warn') => void,
96
+ * }} [options]
97
+ */
98
+ export function startAgentBridgeRelay(options = {}) {
99
+ const host = options.host || '127.0.0.1';
100
+ const port = options.port ?? parsePort(process.env.SURFCAD_AGENT_BRIDGE_WS_PORT);
101
+ const heartbeatMs = options.heartbeatMs ?? parseHeartbeatMs(process.env.SURFCAD_AGENT_BRIDGE_HEARTBEAT_MS);
102
+ const hub = createAgentBridgeRelayHub({ onLog: options.onLog || defaultRelayLog });
103
+
104
+ const server = createServer((req, res) => {
105
+ const origin = req.headers.origin;
106
+ const cors = corsHeadersForOrigin(origin);
107
+
108
+ if (req.method === 'OPTIONS') {
109
+ if (!origin || !isAllowedHttpOrigin(origin)) {
110
+ res.writeHead(403);
111
+ res.end();
112
+ return;
113
+ }
114
+ res.writeHead(204, {
115
+ ...cors,
116
+ 'Access-Control-Allow-Methods': 'GET, OPTIONS',
117
+ 'Access-Control-Allow-Headers': 'Content-Type, Authorization, Sec-WebSocket-Protocol, Sec-WebSocket-Extensions',
118
+ 'Access-Control-Max-Age': '86400',
119
+ });
120
+ res.end();
121
+ return;
122
+ }
123
+
124
+ const bound = server.address();
125
+ const boundPort = bound && typeof bound === 'object' ? bound.port : port;
126
+ if (handleBridgeRequest(req, res, { port: boundPort, extraOrigins: [...extraAllowedOrigins()] })) {
127
+ return;
128
+ }
129
+
130
+ res.writeHead(404, cors);
131
+ res.end();
132
+ });
133
+
134
+ const wss = new WebSocketServer({ noServer: true });
135
+
136
+ wss.on('headers', (headers, req) => {
137
+ const origin = req.headers.origin;
138
+ const cors = corsHeadersForOrigin(origin);
139
+ for (const [key, value] of Object.entries(cors)) {
140
+ headers.push(`${key}: ${value}`);
141
+ }
142
+ });
143
+
144
+ server.on('upgrade', (req, socket, head) => {
145
+ const remote = req.socket.remoteAddress || '';
146
+ if (!isLoopbackAddress(remote)) {
147
+ socket.destroy();
148
+ return;
149
+ }
150
+ const origin = req.headers.origin;
151
+ if (origin && !isAllowedHttpOrigin(origin)) {
152
+ socket.write('HTTP/1.1 403 Forbidden\r\nContent-Type: text/plain\r\n\r\nOrigin not allowed\r\n');
153
+ socket.destroy();
154
+ return;
155
+ }
156
+ wss.handleUpgrade(req, socket, head, (ws) => {
157
+ wss.emit('connection', ws, req);
158
+ hub.attachSocket({
159
+ send: (data) => { ws.send(data); },
160
+ close: () => { ws.close(); },
161
+ ping: () => { ws.ping(); },
162
+ terminate: () => { ws.terminate(); },
163
+ on: (event, cb) => {
164
+ if (event === 'close') {
165
+ ws.on('close', (code, reason) => cb(code, reason?.toString?.() || ''));
166
+ return;
167
+ }
168
+ ws.on(event, cb);
169
+ },
170
+ remoteAddress: remote,
171
+ origin,
172
+ });
173
+ });
174
+ });
175
+
176
+ const heartbeatTimer = setInterval(() => { hub.heartbeat(); }, heartbeatMs);
177
+ if (typeof heartbeatTimer.unref === 'function') heartbeatTimer.unref();
178
+ wss.on('close', () => { clearInterval(heartbeatTimer); });
179
+ server.on('close', () => { clearInterval(heartbeatTimer); });
180
+
181
+ return new Promise((resolve, reject) => {
182
+ server.listen(port, host, () => {
183
+ const bound = server.address();
184
+ const actualPort = bound && typeof bound === 'object' ? bound.port : port;
185
+ const url = `ws://${host}:${actualPort}`;
186
+ options.onReady?.(url);
187
+ resolve({ server, wss, hub, url, port: actualPort, host, ownsServer: true });
188
+ });
189
+ server.on('error', reject);
190
+ });
191
+ }
192
+
193
+ /** @type {Map<number, Promise<unknown>>} */
194
+ const sharedRelayByPort = new Map();
195
+
196
+ /**
197
+ * Start the relay or attach to one already listening on the default loopback port.
198
+ *
199
+ * @param {{ port?: number, onReady?: (url: string) => void }} [options]
200
+ */
201
+ export async function ensureAgentBridgeRelay(options = {}) {
202
+ const host = '127.0.0.1';
203
+ const port = options.port ?? parsePort(process.env.SURFCAD_AGENT_BRIDGE_WS_PORT);
204
+ const url = `ws://${host}:${port}`;
205
+
206
+ const existing = sharedRelayByPort.get(port);
207
+ if (existing) {
208
+ return existing;
209
+ }
210
+
211
+ const promise = (async () => {
212
+ try {
213
+ const started = await startAgentBridgeRelay({ ...options, host, port });
214
+ return started;
215
+ } catch (err) {
216
+ if (err && typeof err === 'object' && err.code === 'EADDRINUSE') {
217
+ const alive = await probeRelayAtUrl(url);
218
+ if (alive) {
219
+ options.onReady?.(url);
220
+ return { url, server: null, wss: null, hub: null, port, host, ownsServer: false, reused: true };
221
+ }
222
+ }
223
+ sharedRelayByPort.delete(port);
224
+ throw err;
225
+ }
226
+ })();
227
+
228
+ sharedRelayByPort.set(port, promise);
229
+ return promise;
230
+ }
231
+
232
+ /**
233
+ * Close relay HTTP/WebSocket listeners started by {@link startAgentBridgeRelay}.
234
+ *
235
+ * @param {{ server?: import('node:http').Server | null, wss?: import('ws').WebSocketServer | null, port?: number, ownsServer?: boolean } | null | undefined} relay
236
+ */
237
+ export function stopAgentBridgeRelay(relay) {
238
+ relay?.hub?.dispose?.();
239
+ if (!relay || !relay.ownsServer) {
240
+ return Promise.resolve();
241
+ }
242
+ return new Promise((resolve) => {
243
+ const finish = () => resolve();
244
+ const wss = relay.wss;
245
+ const server = relay.server;
246
+ if (wss) {
247
+ for (const client of wss.clients) {
248
+ try { client.terminate(); } catch { /* gone */ }
249
+ }
250
+ wss.close(() => {
251
+ if (server) server.close(finish);
252
+ else finish();
253
+ });
254
+ return;
255
+ }
256
+ if (server) server.close(finish);
257
+ else finish();
258
+ });
259
+ }
260
+
261
+ /** @param {number} [port] */
262
+ export function resetAgentBridgeRelayCache(port) {
263
+ if (port == null) {
264
+ sharedRelayByPort.clear();
265
+ return;
266
+ }
267
+ sharedRelayByPort.delete(port);
268
+ }
package/src/errors.mjs CHANGED
@@ -1,10 +1,14 @@
1
+ export const RECONNECT_HINT = 'Open SurfCAD in Chrome and keep the tab open; it will reconnect.';
2
+
1
3
  /**
2
- * @param {{ code?: string, message?: string, details?: unknown }} err
4
+ * @param {{ code?: string, message?: string, details?: unknown, hint?: string, retryable?: boolean }} err
3
5
  */
4
6
  export function formatBridgeError(err) {
5
7
  const code = err?.code || 'bridge_error';
6
8
  const message = err?.message || 'Bridge call failed';
7
9
  const payload = { code, message };
10
+ if (err?.hint) payload.hint = err.hint;
11
+ if (err?.retryable !== undefined) payload.retryable = err.retryable;
8
12
  if (err?.details !== undefined) payload.details = err.details;
9
13
  return payload;
10
14
  }
@@ -13,9 +17,28 @@ export function notPairedError() {
13
17
  return {
14
18
  code: 'not_paired',
15
19
  message: 'Not paired to a SurfCAD tab. Set SURFCAD_PAIRING_CODE or call the pair tool, then click Allow in the app.',
20
+ hint: pairingEnvHint(),
16
21
  };
17
22
  }
18
23
 
24
+ /**
25
+ * @param {string} [reason]
26
+ */
27
+ export function pairingLostError(reason) {
28
+ const why = reason ? ` (${reason})` : '';
29
+ return Object.assign(
30
+ new Error(`Lost the connection to the SurfCAD tab${why}. Reconnecting in the background; retry in a few seconds.`),
31
+ { code: 'pairing_lost', hint: RECONNECT_HINT, retryable: true },
32
+ );
33
+ }
34
+
35
+ export function pairPendingError() {
36
+ return Object.assign(
37
+ new Error('Waiting for Allow in SurfCAD. Click Allow in the app, then retry.'),
38
+ { code: 'pair_pending', hint: 'The pairing request is still open in the SurfCAD tab.', retryable: true },
39
+ );
40
+ }
41
+
19
42
  export function pairingEnvHint() {
20
43
  return 'Copy the 6-character code from SurfCAD → Local agent → Show pairing code.';
21
44
  }
@@ -5,20 +5,30 @@ import { WebSocket } from 'ws';
5
5
  import { PAIR_MSG } from './relayMessages.mjs';
6
6
 
7
7
  /**
8
+ * Resolves once the tab approves. `resume` is the key the tab handed out on
9
+ * the previous approval; the hub matches it for that tabKey and auto-pairs
10
+ * without putting the secret on PAIR_REQUEST.
11
+ *
8
12
  * @param {string} url
9
13
  * @param {string} token
10
- * @returns {Promise<WebSocket>}
14
+ * @param {{ resume?: string | null }} [options]
15
+ * @returns {Promise<{ ws: WebSocket, resumeKey: string | null }>}
11
16
  */
12
- export function connectPeer(url, token) {
17
+ export function connectPeer(url, token, options = {}) {
13
18
  return new Promise((resolve, reject) => {
14
19
  const ws = new WebSocket(url);
20
+ let settled = false;
15
21
  const fail = (err) => {
22
+ if (settled) return;
23
+ settled = true;
16
24
  ws.removeAllListeners('message');
17
25
  try { ws.close(); } catch { /* noop */ }
18
26
  reject(err instanceof Error ? err : new Error(String(err)));
19
27
  };
20
28
  ws.once('open', () => {
21
- ws.send(JSON.stringify({ type: PAIR_MSG.PAIR, token: token.trim().toUpperCase() }));
29
+ const pair = { type: PAIR_MSG.PAIR, token: token.trim().toUpperCase() };
30
+ if (options.resume) pair.resume = options.resume;
31
+ ws.send(JSON.stringify(pair));
22
32
  });
23
33
  ws.on('message', (raw) => {
24
34
  let msg;
@@ -29,14 +39,25 @@ export function connectPeer(url, token) {
29
39
  return;
30
40
  }
31
41
  if (msg?.type === PAIR_MSG.PAIRED) {
42
+ settled = true;
32
43
  ws.removeAllListeners('message');
33
- resolve(ws);
44
+ ws.removeAllListeners('close');
45
+ resolve({ ws, resumeKey: typeof msg.resumeKey === 'string' ? msg.resumeKey : null });
34
46
  return;
35
47
  }
36
48
  if (msg?.type === PAIR_MSG.ERROR || (msg?.code && !msg?.id)) {
37
- fail(new Error(msg.message || msg.code || 'Pairing failed'));
49
+ fail(Object.assign(new Error(msg.message || msg.code || 'Pairing failed'), {
50
+ code: typeof msg.code === 'string' ? msg.code : 'pair_failed',
51
+ }));
38
52
  }
39
53
  });
40
- ws.once('error', fail);
54
+ ws.once('error', (err) => {
55
+ fail(Object.assign(err instanceof Error ? err : new Error(String(err)), {
56
+ code: err?.code === 'ECONNREFUSED' ? 'relay_unreachable' : (err?.code || 'relay_error'),
57
+ }));
58
+ });
59
+ ws.once('close', () => {
60
+ fail(Object.assign(new Error('Relay closed the connection before pairing finished'), { code: 'pair_cancelled' }));
61
+ });
41
62
  });
42
63
  }