surfcad-mcp 0.1.0 → 0.2.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 CHANGED
@@ -8,7 +8,9 @@ Stdio [Model Context Protocol](https://modelcontextprotocol.io/) server for the
8
8
  npx surfcad-mcp
9
9
  ```
10
10
 
11
- The process speaks MCP over **stdio**. Pair it to a running SurfCAD tab (see below), then your MCP client can call bridge tools (`status`, `set_script`, `run`, …) plus a `pair` helper.
11
+ The process speaks MCP over **stdio** and **starts the local relay** on `127.0.0.1:17341` (loopback only). If another process is already listening there (a second MCP client or the SurfCAD dev server), it reuses that relay instead of failing.
12
+
13
+ Pair it to a running SurfCAD tab (see below), then your MCP client can call bridge tools (`status`, `set_script`, `run`, …) plus a `pair` helper.
12
14
 
13
15
  Environment variables:
14
16
 
@@ -16,15 +18,16 @@ Environment variables:
16
18
  | --- | --- |
17
19
  | `SURFCAD_PAIRING_CODE` | 6-character code from the SurfCAD **Local agent** panel (optional if you use the `pair` tool). |
18
20
  | `SURFCAD_AGENT_BRIDGE_WS_URL` | Relay URL (default `ws://127.0.0.1:17341`). |
21
+ | `SURFCAD_MCP_START_RELAY` | Set to `0` to skip starting the relay (tests only). |
19
22
 
20
23
  ## Pair with SurfCAD (Local agent)
21
24
 
22
- 1. Run SurfCAD with the agent bridge on (`npm run dev` in the [SurfCAD repo](https://github.com/artur0x0/surfcad), or open the app with `?agent=1` / `localStorage surfcadAgent=1`).
25
+ 1. Open [https://surfcad.com](https://surfcad.com) (or local dev).
23
26
  2. Open the **profile** menu → **Local agent** → **Show pairing code** and leave the tab open.
24
- 3. Start `surfcad-mcp` with that code in `SURFCAD_PAIRING_CODE`, or call the MCP **`pair`** tool with `{ "code": "ABCDEF" }`.
27
+ 3. Add `surfcad-mcp` to your MCP client (`npx surfcad-mcp`), set `SURFCAD_PAIRING_CODE` to that code, or call the MCP **`pair`** tool with `{ "code": "ABCDEF" }`.
25
28
  4. Click **Allow connection** in SurfCAD when prompted.
26
29
 
27
- The Vite dev/preview server starts the relay automatically. Nothing pairs silently — you must show the code and approve the connection.
30
+ Nothing pairs silently — you must show the code and approve the connection.
28
31
 
29
32
  ## MCP client config (Cursor / Claude Desktop)
30
33
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "surfcad-mcp",
3
- "version": "0.1.0",
3
+ "version": "0.2.0",
4
4
  "description": "SurfCAD agent bridge MCP server (stdio) — pairs to a browser tab via the local WebSocket relay",
5
5
  "license": "Apache-2.0",
6
6
  "author": "artur0x0",
@@ -0,0 +1,55 @@
1
+ /**
2
+ * Localhost binding and browser Origin allowlist for the M1 agent-bridge relay.
3
+ */
4
+
5
+ const LOCAL_HOSTNAMES = new Set(['localhost', '127.0.0.1', '[::1]', '::1']);
6
+
7
+ const PROD_SURFCAD_HOSTS = new Set(['surfcad.com', 'www.surfcad.com']);
8
+
9
+ /**
10
+ * @param {string | undefined | null} address
11
+ */
12
+ export function isLoopbackAddress(address) {
13
+ if (!address || typeof address !== 'string') return false;
14
+ const trimmed = address.trim();
15
+ if (LOCAL_HOSTNAMES.has(trimmed)) return true;
16
+ if (trimmed.startsWith('127.')) return true;
17
+ if (trimmed === '::ffff:127.0.0.1') return true;
18
+ return false;
19
+ }
20
+
21
+ /**
22
+ * Extra origins (full origin strings) allowed in tests via env.
23
+ * @returns {Set<string>}
24
+ */
25
+ function extraAllowedOrigins() {
26
+ const raw = process.env.SURFCAD_AGENT_BRIDGE_EXTRA_ORIGINS || '';
27
+ const set = new Set();
28
+ for (const part of raw.split(',')) {
29
+ const o = part.trim();
30
+ if (o) set.add(o);
31
+ }
32
+ return set;
33
+ }
34
+
35
+ /**
36
+ * Browser tab WebSocket upgrades must come from an allowed https/http origin.
37
+ * Node MCP peers omit Origin and are accepted.
38
+ *
39
+ * @param {string | undefined | null} origin
40
+ */
41
+ export function isAllowedHttpOrigin(origin) {
42
+ if (!origin || typeof origin !== 'string') return true;
43
+ if (extraAllowedOrigins().has(origin.trim())) return true;
44
+ try {
45
+ const url = new URL(origin);
46
+ if (url.protocol !== 'http:' && url.protocol !== 'https:') return false;
47
+ if (LOCAL_HOSTNAMES.has(url.hostname) || url.hostname.startsWith('127.')) return true;
48
+ if (PROD_SURFCAD_HOSTS.has(url.hostname)) return true;
49
+ return false;
50
+ } catch {
51
+ return false;
52
+ }
53
+ }
54
+
55
+ export { PROD_SURFCAD_HOSTS, LOCAL_HOSTNAMES };
@@ -0,0 +1,266 @@
1
+ /**
2
+ * In-memory hub for pairing a browser tab with one local peer over WebSocket.
3
+ * Canonical implementation shared by surfcad-mcp and the SurfCAD dev server.
4
+ */
5
+
6
+ import { PAIR_MSG } from '../relayMessages.mjs';
7
+ import { isAllowedHttpOrigin, isLoopbackAddress } from './localAddress.mjs';
8
+
9
+ /**
10
+ * @typedef {{ send: (data: string) => void, close: () => void, on: (event: string, cb: (...args: unknown[]) => void) => void, remoteAddress?: string, origin?: string }} RelaySocket
11
+ */
12
+
13
+ function sendJson(socket, payload) {
14
+ socket.send(JSON.stringify(payload));
15
+ }
16
+
17
+ function parseMessage(raw) {
18
+ if (typeof raw !== 'string') return null;
19
+ try {
20
+ const msg = JSON.parse(raw);
21
+ if (!msg || typeof msg !== 'object' || Array.isArray(msg)) return null;
22
+ return msg;
23
+ } catch {
24
+ return null;
25
+ }
26
+ }
27
+
28
+ /**
29
+ * @param {RelaySocket} socket
30
+ * @param {string} code
31
+ * @param {string} message
32
+ */
33
+ function refuse(socket, code, message) {
34
+ sendJson(socket, { type: PAIR_MSG.ERROR, code, message });
35
+ try { socket.close(); } catch { /* already closed */ }
36
+ }
37
+
38
+ /**
39
+ * @param {{ onLog?: (line: string) => void }} [opts]
40
+ */
41
+ export function createAgentBridgeRelayHub(opts = {}) {
42
+ const log = (line) => { opts.onLog?.(line); };
43
+
44
+ /** @type {Map<string, { socket: RelaySocket, token: string, pairedPeer: RelaySocket | null, pendingPeer: RelaySocket | null }>} */
45
+ const tabsByToken = new Map();
46
+ /** @type {Map<RelaySocket, { role: 'tab' | 'peer', token: string }>} */
47
+ const socketMeta = new Map();
48
+
49
+ function dropTab(token) {
50
+ const tab = tabsByToken.get(token);
51
+ if (!tab) return;
52
+ tabsByToken.delete(token);
53
+ if (tab.pairedPeer) {
54
+ sendJson(tab.pairedPeer, { type: PAIR_MSG.UNPAIRED, reason: 'tab_disconnected' });
55
+ socketMeta.delete(tab.pairedPeer);
56
+ }
57
+ if (tab.pendingPeer) {
58
+ sendJson(tab.pendingPeer, { type: PAIR_MSG.ERROR, code: 'pair_cancelled', message: 'Tab disconnected' });
59
+ socketMeta.delete(tab.pendingPeer);
60
+ }
61
+ socketMeta.delete(tab.socket);
62
+ }
63
+
64
+ function unpair(token, reason = 'disconnect') {
65
+ const tab = tabsByToken.get(token);
66
+ if (!tab || !tab.pairedPeer) return;
67
+ const peer = tab.pairedPeer;
68
+ tab.pairedPeer = null;
69
+ sendJson(tab.socket, { type: PAIR_MSG.UNPAIRED, reason });
70
+ sendJson(peer, { type: PAIR_MSG.UNPAIRED, reason });
71
+ socketMeta.delete(peer);
72
+ try { peer.close(); } catch { /* gone */ }
73
+ }
74
+
75
+ /**
76
+ * @param {RelaySocket} socket
77
+ */
78
+ function attachSocket(socket) {
79
+ const remote = socket.remoteAddress || '';
80
+ if (!isLoopbackAddress(remote)) {
81
+ refuse(socket, 'remote_blocked', 'Agent bridge relay accepts loopback connections only');
82
+ return;
83
+ }
84
+ if (!isAllowedHttpOrigin(socket.origin)) {
85
+ refuse(socket, 'origin_blocked', 'Origin is not an allowed SurfCAD page (https://surfcad.com or local dev)');
86
+ return;
87
+ }
88
+
89
+ socket.on('message', (raw) => {
90
+ const msg = parseMessage(typeof raw === 'string' ? raw : String(raw));
91
+ if (!msg || typeof msg !== 'object') {
92
+ refuse(socket, 'bad_message', 'Expected JSON object');
93
+ return;
94
+ }
95
+ const meta = socketMeta.get(socket);
96
+
97
+ if (msg.type === PAIR_MSG.REGISTER_TAB) {
98
+ if (meta) {
99
+ refuse(socket, 'already_registered', 'Socket already registered');
100
+ return;
101
+ }
102
+ const token = typeof msg.token === 'string' ? msg.token.trim().toUpperCase() : '';
103
+ if (!token || token.length < 4) {
104
+ refuse(socket, 'bad_token', 'register_tab requires token');
105
+ return;
106
+ }
107
+ const existing = tabsByToken.get(token);
108
+ if (existing) {
109
+ refuse(socket, 'token_in_use', 'Another tab is already advertising this pairing code');
110
+ return;
111
+ }
112
+ tabsByToken.set(token, { socket, token, pairedPeer: null, pendingPeer: null });
113
+ socketMeta.set(socket, { role: 'tab', token });
114
+ log(`tab registered token=${token}`);
115
+ return;
116
+ }
117
+
118
+ if (msg.type === PAIR_MSG.PAIR) {
119
+ if (meta) {
120
+ refuse(socket, 'already_registered', 'Socket already registered');
121
+ return;
122
+ }
123
+ const token = typeof msg.token === 'string' ? msg.token.trim().toUpperCase() : '';
124
+ const tab = tabsByToken.get(token);
125
+ if (!tab) {
126
+ refuse(socket, 'unknown_token', 'No SurfCAD tab is advertising this pairing code');
127
+ return;
128
+ }
129
+ if (tab.pairedPeer) {
130
+ refuse(socket, 'already_paired', 'Tab is already paired with another client');
131
+ return;
132
+ }
133
+ if (tab.pendingPeer && tab.pendingPeer !== socket) {
134
+ refuse(socket, 'pair_pending', 'Tab is already reviewing another pairing request');
135
+ return;
136
+ }
137
+ tab.pendingPeer = socket;
138
+ socketMeta.set(socket, { role: 'peer', token });
139
+ sendJson(tab.socket, { type: PAIR_MSG.PAIR_REQUEST, token });
140
+ log(`pair request token=${token}`);
141
+ return;
142
+ }
143
+
144
+ if (!meta) {
145
+ refuse(socket, 'not_registered', 'Send register_tab or pair first');
146
+ return;
147
+ }
148
+
149
+ const tab = tabsByToken.get(meta.token);
150
+ if (!tab) {
151
+ refuse(socket, 'session_gone', 'Pairing session ended');
152
+ return;
153
+ }
154
+
155
+ if (msg.type === PAIR_MSG.PAIR_APPROVE) {
156
+ if (meta.role !== 'tab') {
157
+ refuse(socket, 'forbidden', 'Only the tab may approve pairing');
158
+ return;
159
+ }
160
+ const peer = tab.pendingPeer;
161
+ if (!peer) {
162
+ sendJson(socket, { type: PAIR_MSG.ERROR, code: 'no_request', message: 'No pairing request to approve' });
163
+ return;
164
+ }
165
+ tab.pendingPeer = null;
166
+ tab.pairedPeer = peer;
167
+ sendJson(socket, { type: PAIR_MSG.PAIRED, token: meta.token });
168
+ sendJson(peer, { type: PAIR_MSG.PAIRED, token: meta.token });
169
+ log(`paired token=${meta.token}`);
170
+ return;
171
+ }
172
+
173
+ if (msg.type === PAIR_MSG.PAIR_REJECT) {
174
+ if (meta.role !== 'tab') {
175
+ refuse(socket, 'forbidden', 'Only the tab may reject pairing');
176
+ return;
177
+ }
178
+ const peer = tab.pendingPeer;
179
+ tab.pendingPeer = null;
180
+ if (peer) {
181
+ sendJson(peer, { type: PAIR_MSG.ERROR, code: 'pair_rejected', message: 'Pairing rejected in SurfCAD' });
182
+ socketMeta.delete(peer);
183
+ try { peer.close(); } catch { /* gone */ }
184
+ }
185
+ return;
186
+ }
187
+
188
+ if (typeof msg.command === 'string' && msg.type !== PAIR_MSG.PAIR) {
189
+ if (meta.role !== 'peer' || tab.pairedPeer !== socket) {
190
+ refuse(socket, 'not_paired', 'Pair before sending bridge commands');
191
+ return;
192
+ }
193
+ if (typeof msg.id !== 'string' && typeof msg.id !== 'number') {
194
+ sendJson(socket, { id: msg.id, ok: false, error: { code: 'bad_call', message: 'call requires id' } });
195
+ return;
196
+ }
197
+ sendJson(tab.socket, {
198
+ id: msg.id,
199
+ command: msg.command,
200
+ args: msg.args == null ? {} : msg.args,
201
+ });
202
+ return;
203
+ }
204
+
205
+ if (Object.prototype.hasOwnProperty.call(msg, 'ok') && msg.type !== PAIR_MSG.PAIR) {
206
+ if (meta.role !== 'tab' || tab.pairedPeer == null) {
207
+ refuse(socket, 'not_paired', 'No paired peer for response');
208
+ return;
209
+ }
210
+ sendJson(tab.pairedPeer, {
211
+ id: msg.id,
212
+ ok: msg.ok === true,
213
+ result: msg.ok === true ? msg.result : undefined,
214
+ error: msg.ok === true ? undefined : msg.error,
215
+ });
216
+ return;
217
+ }
218
+
219
+ refuse(socket, 'unknown_type', `Unknown message type: ${msg.type}`);
220
+ });
221
+
222
+ socket.on('close', () => {
223
+ const m = socketMeta.get(socket);
224
+ if (!m) return;
225
+ const tabEntry = tabsByToken.get(m.token);
226
+ if (!tabEntry) {
227
+ socketMeta.delete(socket);
228
+ return;
229
+ }
230
+ if (m.role === 'tab') {
231
+ dropTab(m.token);
232
+ log(`tab closed token=${m.token}`);
233
+ return;
234
+ }
235
+ if (tabEntry.pendingPeer === socket) {
236
+ tabEntry.pendingPeer = null;
237
+ socketMeta.delete(socket);
238
+ return;
239
+ }
240
+ if (tabEntry.pairedPeer === socket) {
241
+ unpair(m.token, 'peer_disconnected');
242
+ }
243
+ socketMeta.delete(socket);
244
+ });
245
+ }
246
+
247
+ function disconnectToken(token) {
248
+ const tab = tabsByToken.get(token);
249
+ if (!tab) return;
250
+ unpair(token, 'tab_disconnect');
251
+ try { tab.socket.close(); } catch { /* gone */ }
252
+ dropTab(token);
253
+ }
254
+
255
+ return {
256
+ attachSocket,
257
+ disconnectToken,
258
+ /** @param {string} token */
259
+ hasTab(token) {
260
+ return tabsByToken.has(token);
261
+ },
262
+ PAIR_MSG,
263
+ };
264
+ }
265
+
266
+ export { PAIR_MSG };
@@ -0,0 +1,223 @@
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.
5
+ */
6
+
7
+ import { createServer } from 'node:http';
8
+ import { WebSocket, WebSocketServer } from 'ws';
9
+ import { createAgentBridgeRelayHub } from './relayHub.mjs';
10
+ import { isAllowedHttpOrigin, isLoopbackAddress } from './localAddress.mjs';
11
+
12
+ export const DEFAULT_RELAY_PORT = 17341;
13
+
14
+ function parsePort(value) {
15
+ const n = Number(value);
16
+ return Number.isInteger(n) && n > 0 && n < 65536 ? n : DEFAULT_RELAY_PORT;
17
+ }
18
+
19
+ /**
20
+ * @param {string | undefined} origin
21
+ * @returns {Record<string, string>}
22
+ */
23
+ function corsHeadersForOrigin(origin) {
24
+ if (!origin || !isAllowedHttpOrigin(origin)) return {};
25
+ return {
26
+ 'Access-Control-Allow-Origin': origin,
27
+ 'Access-Control-Allow-Private-Network': 'true',
28
+ 'Vary': 'Origin',
29
+ };
30
+ }
31
+
32
+ /**
33
+ * @param {string} url
34
+ * @param {number} [timeoutMs]
35
+ */
36
+ export function probeRelayAtUrl(url, timeoutMs = 1500) {
37
+ return new Promise((resolve) => {
38
+ let settled = false;
39
+ const finish = (ok) => {
40
+ if (settled) return;
41
+ settled = true;
42
+ resolve(ok);
43
+ };
44
+ let ws;
45
+ try {
46
+ ws = new WebSocket(url);
47
+ } catch {
48
+ finish(false);
49
+ return;
50
+ }
51
+ const timer = setTimeout(() => {
52
+ try { ws.close(); } catch { /* noop */ }
53
+ finish(false);
54
+ }, timeoutMs);
55
+ if (typeof timer.unref === 'function') timer.unref();
56
+ ws.once('open', () => {
57
+ clearTimeout(timer);
58
+ try { ws.close(); } catch { /* noop */ }
59
+ finish(true);
60
+ });
61
+ ws.once('error', () => {
62
+ clearTimeout(timer);
63
+ finish(false);
64
+ });
65
+ });
66
+ }
67
+
68
+ /**
69
+ * @param {{ port?: number, host?: string, onReady?: (url: string) => void, onLog?: (line: string) => void }} [options]
70
+ */
71
+ export function startAgentBridgeRelay(options = {}) {
72
+ const host = options.host || '127.0.0.1';
73
+ const port = options.port ?? parsePort(process.env.SURFCAD_AGENT_BRIDGE_WS_PORT);
74
+ const hub = createAgentBridgeRelayHub({
75
+ onLog: options.onLog || ((line) => {
76
+ if (process.env.SURFCAD_AGENT_BRIDGE_WS_VERBOSE === '1') {
77
+ console.log(`[agent-bridge-ws] ${line}`);
78
+ }
79
+ }),
80
+ });
81
+
82
+ const server = createServer((req, res) => {
83
+ const origin = req.headers.origin;
84
+ const cors = corsHeadersForOrigin(origin);
85
+
86
+ if (req.method === 'OPTIONS') {
87
+ if (!origin || !isAllowedHttpOrigin(origin)) {
88
+ res.writeHead(403);
89
+ res.end();
90
+ return;
91
+ }
92
+ res.writeHead(204, {
93
+ ...cors,
94
+ 'Access-Control-Allow-Methods': 'GET, OPTIONS',
95
+ 'Access-Control-Allow-Headers': 'Content-Type, Authorization, Sec-WebSocket-Protocol, Sec-WebSocket-Extensions',
96
+ 'Access-Control-Max-Age': '86400',
97
+ });
98
+ res.end();
99
+ return;
100
+ }
101
+
102
+ res.writeHead(404, cors);
103
+ res.end();
104
+ });
105
+
106
+ const wss = new WebSocketServer({ noServer: true });
107
+
108
+ wss.on('headers', (headers, req) => {
109
+ const origin = req.headers.origin;
110
+ const cors = corsHeadersForOrigin(origin);
111
+ for (const [key, value] of Object.entries(cors)) {
112
+ headers.push(`${key}: ${value}`);
113
+ }
114
+ });
115
+
116
+ server.on('upgrade', (req, socket, head) => {
117
+ const remote = req.socket.remoteAddress || '';
118
+ if (!isLoopbackAddress(remote)) {
119
+ socket.destroy();
120
+ return;
121
+ }
122
+ const origin = req.headers.origin;
123
+ if (origin && !isAllowedHttpOrigin(origin)) {
124
+ socket.write('HTTP/1.1 403 Forbidden\r\nContent-Type: text/plain\r\n\r\nOrigin not allowed\r\n');
125
+ socket.destroy();
126
+ return;
127
+ }
128
+ wss.handleUpgrade(req, socket, head, (ws) => {
129
+ wss.emit('connection', ws, req);
130
+ hub.attachSocket({
131
+ send: (data) => { ws.send(data); },
132
+ close: () => { ws.close(); },
133
+ on: (event, cb) => { ws.on(event, cb); },
134
+ remoteAddress: remote,
135
+ origin,
136
+ });
137
+ });
138
+ });
139
+
140
+ return new Promise((resolve, reject) => {
141
+ server.listen(port, host, () => {
142
+ const bound = server.address();
143
+ const actualPort = bound && typeof bound === 'object' ? bound.port : port;
144
+ const url = `ws://${host}:${actualPort}`;
145
+ options.onReady?.(url);
146
+ resolve({ server, wss, hub, url, port: actualPort, host, ownsServer: true });
147
+ });
148
+ server.on('error', reject);
149
+ });
150
+ }
151
+
152
+ /** @type {Map<number, Promise<unknown>>} */
153
+ const sharedRelayByPort = new Map();
154
+
155
+ /**
156
+ * Start the relay or attach to one already listening on the default loopback port.
157
+ *
158
+ * @param {{ port?: number, onReady?: (url: string) => void }} [options]
159
+ */
160
+ export async function ensureAgentBridgeRelay(options = {}) {
161
+ const host = '127.0.0.1';
162
+ const port = options.port ?? parsePort(process.env.SURFCAD_AGENT_BRIDGE_WS_PORT);
163
+ const url = `ws://${host}:${port}`;
164
+
165
+ const existing = sharedRelayByPort.get(port);
166
+ if (existing) {
167
+ return existing;
168
+ }
169
+
170
+ const promise = (async () => {
171
+ try {
172
+ const started = await startAgentBridgeRelay({ ...options, host, port });
173
+ return started;
174
+ } catch (err) {
175
+ if (err && typeof err === 'object' && err.code === 'EADDRINUSE') {
176
+ const alive = await probeRelayAtUrl(url);
177
+ if (alive) {
178
+ options.onReady?.(url);
179
+ return { url, server: null, wss: null, hub: null, port, host, ownsServer: false, reused: true };
180
+ }
181
+ }
182
+ sharedRelayByPort.delete(port);
183
+ throw err;
184
+ }
185
+ })();
186
+
187
+ sharedRelayByPort.set(port, promise);
188
+ return promise;
189
+ }
190
+
191
+ /**
192
+ * Close relay HTTP/WebSocket listeners started by {@link startAgentBridgeRelay}.
193
+ *
194
+ * @param {{ server?: import('node:http').Server | null, wss?: import('ws').WebSocketServer | null, port?: number, ownsServer?: boolean } | null | undefined} relay
195
+ */
196
+ export function stopAgentBridgeRelay(relay) {
197
+ if (!relay || !relay.ownsServer) {
198
+ return Promise.resolve();
199
+ }
200
+ return new Promise((resolve) => {
201
+ const finish = () => resolve();
202
+ const wss = relay.wss;
203
+ const server = relay.server;
204
+ if (wss) {
205
+ wss.close(() => {
206
+ if (server) server.close(finish);
207
+ else finish();
208
+ });
209
+ return;
210
+ }
211
+ if (server) server.close(finish);
212
+ else finish();
213
+ });
214
+ }
215
+
216
+ /** @param {number} [port] */
217
+ export function resetAgentBridgeRelayCache(port) {
218
+ if (port == null) {
219
+ sharedRelayByPort.clear();
220
+ return;
221
+ }
222
+ sharedRelayByPort.delete(port);
223
+ }
package/src/server.mjs CHANGED
@@ -7,6 +7,7 @@ import {
7
7
  import { bridgeToolDefinitions, loadCommandsCatalog } from './catalog.mjs';
8
8
  import { formatBridgeError, notPairedError, pairingEnvHint } from './errors.mjs';
9
9
  import { loadPackageVersion } from './packageVersion.mjs';
10
+ import { ensureAgentBridgeRelay, stopAgentBridgeRelay } from './bridge/relayServer.mjs';
10
11
  import { RelaySession } from './relay.mjs';
11
12
 
12
13
  const PAIR_TOOL_NAME = 'pair';
@@ -127,6 +128,32 @@ export async function createSurfcadMcpServer(options = {}) {
127
128
  * @param {{ autoPairFromEnv?: boolean }} [options]
128
129
  */
129
130
  export async function runSurfcadMcpServer(options = {}) {
131
+ /** @type {Awaited<ReturnType<typeof ensureAgentBridgeRelay>> | null} */
132
+ 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
+ });
141
+ if (relay.ownsServer) ownedRelay = relay;
142
+ }
143
+
144
+ const onStdinClosed = () => {
145
+ if (ownedRelay) {
146
+ const closing = ownedRelay;
147
+ ownedRelay = null;
148
+ void stopAgentBridgeRelay(closing).finally(() => {
149
+ setTimeout(() => process.exit(0), 0).unref();
150
+ });
151
+ return;
152
+ }
153
+ setTimeout(() => process.exit(0), 0).unref();
154
+ };
155
+ process.stdin.once('end', onStdinClosed);
156
+
130
157
  const { server, session } = await createSurfcadMcpServer();
131
158
  const transport = new StdioServerTransport();
132
159
  await server.connect(transport);