surfcad-mcp 0.3.2 → 0.3.4

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,178 @@
1
+ /**
2
+ * Remote relay address, agent name, and local-vs-remote selection.
3
+ * The token never appears in these helpers.
4
+ */
5
+
6
+ import { homedir } from 'node:os';
7
+ import { join } from 'node:path';
8
+
9
+ export const DEFAULT_AGENT_SERVER = 'https://surfcad.com';
10
+
11
+ /**
12
+ * Per-user directory for the saved login. Override with
13
+ * SURFCAD_MCP_CONFIG_DIR (tests and unusual installs). Otherwise
14
+ * $XDG_CONFIG_HOME/surfcad-mcp, or ~/.config/surfcad-mcp.
15
+ * @param {NodeJS.ProcessEnv} [env]
16
+ */
17
+ export function configDir(env = process.env) {
18
+ const override = env.SURFCAD_MCP_CONFIG_DIR;
19
+ if (typeof override === 'string' && override.trim()) return override.trim();
20
+ const xdg = env.XDG_CONFIG_HOME;
21
+ if (typeof xdg === 'string' && xdg.trim()) return join(xdg.trim(), 'surfcad-mcp');
22
+ const home = typeof env.HOME === 'string' && env.HOME.trim() ? env.HOME.trim() : homedir();
23
+ return join(home, '.config', 'surfcad-mcp');
24
+ }
25
+
26
+ /**
27
+ * @param {NodeJS.ProcessEnv} [env]
28
+ */
29
+ export function tokenPath(env = process.env) {
30
+ return join(configDir(env), 'token.json');
31
+ }
32
+
33
+ /**
34
+ * Cleartext is only for a loopback dev server. Every other host must be https.
35
+ * @param {string} hostname URL.hostname (IPv6 has no brackets)
36
+ */
37
+ function isCleartextLoopback(hostname) {
38
+ const host = hostname.toLowerCase().replace(/^\[|\]$/g, '');
39
+ return host === 'localhost' || host === '127.0.0.1' || host === '::1';
40
+ }
41
+
42
+ /**
43
+ * Accept https, http, wss, or ws. Return the origin only (`https://host`).
44
+ * A path such as `/agent` is dropped; callers add it.
45
+ * `http://` and `ws://` are accepted only for localhost, 127.0.0.1, and ::1.
46
+ * @param {unknown} input
47
+ */
48
+ export function normalizeServer(input) {
49
+ let text = String(input ?? '').trim();
50
+ if (!text) {
51
+ throw Object.assign(new Error('Server URL is empty.'), { code: 'bad_server' });
52
+ }
53
+ if (text.startsWith('wss://')) text = `https://${text.slice('wss://'.length)}`;
54
+ else if (text.startsWith('ws://')) text = `http://${text.slice('ws://'.length)}`;
55
+ else if (!/^https?:\/\//i.test(text)) text = `https://${text}`;
56
+ let url;
57
+ try {
58
+ url = new URL(text);
59
+ } catch {
60
+ throw Object.assign(new Error('Server URL is not a valid http(s) URL.'), { code: 'bad_server' });
61
+ }
62
+ if (url.protocol !== 'https:' && url.protocol !== 'http:') {
63
+ throw Object.assign(new Error('Server URL must be http or https.'), { code: 'bad_server' });
64
+ }
65
+ if (!url.host) {
66
+ throw Object.assign(new Error('Server URL is missing a host.'), { code: 'bad_server' });
67
+ }
68
+ if (url.protocol === 'http:' && !isCleartextLoopback(url.hostname)) {
69
+ throw Object.assign(
70
+ new Error(`Cleartext is only allowed for localhost, 127.0.0.1, and ::1. Use https for ${url.host}.`),
71
+ { code: 'bad_server' },
72
+ );
73
+ }
74
+ return `${url.protocol}//${url.host}`;
75
+ }
76
+
77
+ /**
78
+ * `--server` wins, then SURFCAD_AGENT_SERVER, then the server stored with
79
+ * the login, then https://surfcad.com.
80
+ * @param {{ flag?: string, env?: NodeJS.ProcessEnv, saved?: { server?: string } | null }} [options]
81
+ */
82
+ export function resolveServerUrl(options = {}) {
83
+ const env = options.env || process.env;
84
+ const flag = typeof options.flag === 'string' ? options.flag.trim() : '';
85
+ if (flag) return normalizeServer(flag);
86
+ const fromEnv = typeof env.SURFCAD_AGENT_SERVER === 'string' ? env.SURFCAD_AGENT_SERVER.trim() : '';
87
+ if (fromEnv) return normalizeServer(fromEnv);
88
+ const saved = options.saved && typeof options.saved.server === 'string' ? options.saved.server.trim() : '';
89
+ if (saved) return normalizeServer(saved);
90
+ return DEFAULT_AGENT_SERVER;
91
+ }
92
+
93
+ /**
94
+ * @param {string} origin http(s) origin, no path
95
+ */
96
+ export function agentUrls(origin) {
97
+ const base = normalizeServer(origin);
98
+ const url = new URL(base);
99
+ const wsProtocol = url.protocol === 'https:' ? 'wss:' : 'ws:';
100
+ return {
101
+ origin: base,
102
+ approvalUrl: `${base}/agent`,
103
+ wsUrl: `${wsProtocol}//${url.host}/agent`,
104
+ pairUrl: `${base}/agent/pair`,
105
+ pollUrl: `${base}/agent/pair/poll`,
106
+ joinUrl: `${base}/agent/join/redeem`,
107
+ commandsUrl: `${base}/agent/commands`,
108
+ promptsUrl: `${base}/agent/prompts`,
109
+ };
110
+ }
111
+
112
+ /**
113
+ * Name sent at login and on the hello frame.
114
+ * `--name`, then SURFCAD_AGENT_NAME, then the name stored at login, then
115
+ * the MCP client's `clientInfo.name`. Empty means the server says "an agent".
116
+ * `login` has no MCP client, so it never sees clientInfo.
117
+ * @param {{
118
+ * name?: string,
119
+ * savedName?: string,
120
+ * clientInfo?: { name?: string } | null,
121
+ * env?: NodeJS.ProcessEnv,
122
+ * }} [options]
123
+ */
124
+ export function resolveAgentName(options = {}) {
125
+ const env = options.env || process.env;
126
+ const flag = typeof options.name === 'string' ? options.name.trim() : '';
127
+ if (flag) return flag;
128
+ const fromEnv = typeof env.SURFCAD_AGENT_NAME === 'string' ? env.SURFCAD_AGENT_NAME.trim() : '';
129
+ if (fromEnv) return fromEnv;
130
+ const saved = typeof options.savedName === 'string' ? options.savedName.trim() : '';
131
+ if (saved) return saved;
132
+ const fromClient = options.clientInfo && typeof options.clientInfo.name === 'string'
133
+ ? options.clientInfo.name.trim()
134
+ : '';
135
+ return fromClient;
136
+ }
137
+
138
+ /**
139
+ * Loopback settings that must keep the local relay even after a login,
140
+ * so goldens and an existing local MCP config are not taken over.
141
+ * @param {NodeJS.ProcessEnv} env
142
+ */
143
+ function explicitLocalRelay(env) {
144
+ const url = env.SURFCAD_AGENT_BRIDGE_WS_URL;
145
+ if (typeof url === 'string' && url.trim()) return true;
146
+ const port = env.SURFCAD_AGENT_BRIDGE_WS_PORT;
147
+ if (typeof port === 'string' && port.trim()) return true;
148
+ const code = env.SURFCAD_PAIRING_CODE;
149
+ if (typeof code === 'string' && code.trim()) return true;
150
+ return false;
151
+ }
152
+
153
+ /**
154
+ * First match wins:
155
+ * 1. `--remote` → remote
156
+ * 2. `--local` → local
157
+ * 3. an explicit loopback URL, port, or pairing code → local
158
+ * 4. a saved login → remote
159
+ * 5. local
160
+ * @param {{
161
+ * remote?: boolean,
162
+ * local?: boolean,
163
+ * loggedIn?: boolean,
164
+ * env?: NodeJS.ProcessEnv,
165
+ * }} [options]
166
+ * @returns {{ ok: true, mode: 'local' | 'remote' } | { ok: false, error: string }}
167
+ */
168
+ export function selectRelayMode(options = {}) {
169
+ const env = options.env || process.env;
170
+ if (options.remote && options.local) {
171
+ return { ok: false, error: 'Pass either --remote or --local, not both.' };
172
+ }
173
+ if (options.remote) return { ok: true, mode: 'remote' };
174
+ if (options.local) return { ok: true, mode: 'local' };
175
+ if (explicitLocalRelay(env)) return { ok: true, mode: 'local' };
176
+ if (options.loggedIn) return { ok: true, mode: 'remote' };
177
+ return { ok: true, mode: 'local' };
178
+ }
@@ -0,0 +1,289 @@
1
+ /**
2
+ * Command path used when the agent WebSocket cannot be opened.
3
+ * POST /agent/commands, then SSE, then long-poll. The bearer token is sent
4
+ * on the request and is never written into an error or a log line.
5
+ */
6
+
7
+ import { readCommandResponse } from '../commandProtocol.mjs';
8
+ import { asRemoteError, tokenRevokedError } from '../errors.mjs';
9
+
10
+ /** How long a command may sit unanswered, on the WebSocket and on HTTPS. */
11
+ export const COMMAND_WAIT_MS = 10 * 60 * 1000;
12
+ const STEP_TIMEOUT_MS = 30_000;
13
+
14
+ /** Same error for a WebSocket command and for the HTTPS wait. */
15
+ export function commandWaitTimeout() {
16
+ return Object.assign(new Error('Timed out waiting for the SurfCAD tab.'), {
17
+ code: 'bridge_error',
18
+ retryable: true,
19
+ });
20
+ }
21
+
22
+ /**
23
+ * @param {number} status
24
+ * @param {any} json
25
+ */
26
+ function httpFailure(status, json) {
27
+ if (status === 401) return tokenRevokedError();
28
+ const code = typeof json?.error === 'string' ? json.error : '';
29
+ const message = typeof json?.message === 'string' ? json.message : '';
30
+ return asRemoteError({ code, message: message || code });
31
+ }
32
+
33
+ /**
34
+ * @param {unknown} response
35
+ */
36
+ export function resultFromCommandResponse(response) {
37
+ const parsed = readCommandResponse(response);
38
+ if (!parsed) {
39
+ return {
40
+ ok: false,
41
+ error: Object.assign(new Error('Bad command response'), { code: 'bridge_error' }),
42
+ };
43
+ }
44
+ if (parsed.ok === true) return { ok: true, result: parsed.result };
45
+ return { ok: false, error: asRemoteError(parsed.error) };
46
+ }
47
+
48
+ /**
49
+ * @param {string} raw
50
+ */
51
+ export function parseSseBlock(raw) {
52
+ let event = 'message';
53
+ /** @type {string[]} */
54
+ const data = [];
55
+ for (const line of raw.split('\n')) {
56
+ if (line.startsWith('event:')) event = line.slice('event:'.length).trim();
57
+ else if (line.startsWith('data:')) data.push(line.slice('data:'.length).trim());
58
+ }
59
+ /** @type {unknown} */
60
+ let json = null;
61
+ if (data.length) {
62
+ try {
63
+ json = JSON.parse(data.join('\n'));
64
+ } catch {
65
+ json = null;
66
+ }
67
+ }
68
+ return { event, data: json };
69
+ }
70
+
71
+ /**
72
+ * @param {string} buffer
73
+ * @param {{ event: string, data: unknown }[]} events
74
+ */
75
+ function drainSse(buffer, events) {
76
+ let rest = buffer.replace(/\r\n/g, '\n');
77
+ let idx = rest.indexOf('\n\n');
78
+ while (idx !== -1) {
79
+ const raw = rest.slice(0, idx);
80
+ rest = rest.slice(idx + 2);
81
+ if (raw.trim()) events.push(parseSseBlock(raw));
82
+ idx = rest.indexOf('\n\n');
83
+ }
84
+ return rest;
85
+ }
86
+
87
+ /**
88
+ * @param {Response} res
89
+ */
90
+ async function readSseEvents(res) {
91
+ /** @type {{ event: string, data: unknown }[]} */
92
+ const events = [];
93
+ const reader = res.body?.getReader?.();
94
+ if (!reader) {
95
+ const text = await res.text();
96
+ drainSse(`${text.replace(/\r\n/g, '\n')}\n\n`, events);
97
+ return events;
98
+ }
99
+ const decoder = new TextDecoder();
100
+ let buffer = '';
101
+ let done = false;
102
+ try {
103
+ while (!done) {
104
+ const next = await reader.read();
105
+ done = next.done === true;
106
+ if (done) break;
107
+ buffer += decoder.decode(next.value, { stream: true });
108
+ buffer = drainSse(buffer, events);
109
+ }
110
+ buffer += decoder.decode();
111
+ drainSse(`${buffer}\n\n`, events);
112
+ } finally {
113
+ try { reader.releaseLock(); } catch { /* already released */ }
114
+ }
115
+ return events;
116
+ }
117
+
118
+ /**
119
+ * @param {{ event: string, data: unknown }[]} events
120
+ * @returns {'pending' | { ok: true, result: unknown } | { ok: false, error: Error }}
121
+ */
122
+ function interpretSse(events) {
123
+ for (const event of events) {
124
+ if (event.event === 'error') {
125
+ const code = event.data && typeof event.data === 'object'
126
+ ? /** @type {{ error?: string }} */ (event.data).error
127
+ : '';
128
+ if (code === 'not_found') {
129
+ return {
130
+ ok: false,
131
+ error: Object.assign(new Error('That command is no longer waiting.'), { code: 'not_found' }),
132
+ };
133
+ }
134
+ return { ok: false, error: asRemoteError({ code: code || 'bridge_error', message: 'Command failed' }) };
135
+ }
136
+ if (event.event === 'pending') return 'pending';
137
+ if (event.event === 'result') {
138
+ const outcome = resultFromCommandResponse(event.data);
139
+ if (!outcome.ok) return { ok: false, error: outcome.error };
140
+ return { ok: true, result: outcome.result };
141
+ }
142
+ }
143
+ return 'pending';
144
+ }
145
+
146
+ /**
147
+ * @param {string} url
148
+ * @param {string} token
149
+ * @param {typeof fetch} fetchImpl
150
+ * @param {AbortSignal} signal
151
+ */
152
+ async function fetchAuthed(url, token, fetchImpl, signal) {
153
+ return fetchImpl(url, {
154
+ method: 'GET',
155
+ headers: {
156
+ Authorization: `Bearer ${token}`,
157
+ Accept: 'application/json',
158
+ },
159
+ signal,
160
+ });
161
+ }
162
+
163
+ /**
164
+ * @param {{
165
+ * commandsUrl: string,
166
+ * token: string,
167
+ * frame: { v: number, id: string | number, command: string, args: unknown },
168
+ * fetch?: typeof fetch,
169
+ * now?: () => number,
170
+ * }} options
171
+ */
172
+ export async function callOverHttp(options) {
173
+ const fetchImpl = options.fetch || fetch;
174
+ const now = options.now || Date.now;
175
+ const frame = options.frame;
176
+ const post = await fetchImpl(options.commandsUrl, {
177
+ method: 'POST',
178
+ headers: {
179
+ Authorization: `Bearer ${options.token}`,
180
+ 'Content-Type': 'application/json',
181
+ Accept: 'application/json',
182
+ },
183
+ body: JSON.stringify(frame),
184
+ });
185
+ /** @type {any} */
186
+ let posted = null;
187
+ try {
188
+ posted = await post.json();
189
+ } catch {
190
+ posted = null;
191
+ }
192
+ if (post.status === 401) throw tokenRevokedError();
193
+ if (post.status !== 202) throw httpFailure(post.status, posted);
194
+
195
+ const deadline = now() + COMMAND_WAIT_MS;
196
+ let sseFailed = false;
197
+ while (now() < deadline) {
198
+ const signal = AbortSignal.timeout(STEP_TIMEOUT_MS + 5000);
199
+ if (!sseFailed) {
200
+ try {
201
+ const outcome = await waitViaSse(options, fetchImpl, signal);
202
+ if (outcome === 'pending') continue;
203
+ if (!outcome.ok) throw outcome.error;
204
+ return outcome.result;
205
+ } catch (err) {
206
+ if (isTerminal(err)) throw err;
207
+ sseFailed = true;
208
+ }
209
+ }
210
+ const polled = await waitViaPoll(options, fetchImpl, signal);
211
+ if (polled === 'pending') continue;
212
+ if (!polled.ok) throw polled.error;
213
+ return polled.result;
214
+ }
215
+ throw commandWaitTimeout();
216
+ }
217
+
218
+ /**
219
+ * @param {unknown} err
220
+ */
221
+ function isTerminal(err) {
222
+ const code = err && typeof err === 'object' ? /** @type {{ code?: string }} */ (err).code : '';
223
+ return code === 'tab_asleep'
224
+ || code === 'too_many_pending'
225
+ || code === 'token_revoked'
226
+ || code === 'client_update_required'
227
+ || code === 'not_found';
228
+ }
229
+
230
+ /**
231
+ * @param {{ commandsUrl: string, token: string, frame: { id: string | number } }} options
232
+ * @param {typeof fetch} fetchImpl
233
+ * @param {AbortSignal} signal
234
+ */
235
+ async function waitViaSse(options, fetchImpl, signal) {
236
+ const url = `${options.commandsUrl}/${encodeURIComponent(String(options.frame.id))}/events?timeout=${STEP_TIMEOUT_MS}`;
237
+ const res = await fetchImpl(url, {
238
+ method: 'GET',
239
+ headers: {
240
+ Authorization: `Bearer ${options.token}`,
241
+ Accept: 'text/event-stream',
242
+ },
243
+ signal,
244
+ });
245
+ if (res.status === 401) throw tokenRevokedError();
246
+ if (!res.ok) {
247
+ try { await res.body?.cancel?.(); } catch { /* noop */ }
248
+ throw Object.assign(new Error(`Event stream failed (${res.status})`), { code: 'sse_failed' });
249
+ }
250
+ const type = res.headers.get('content-type') || '';
251
+ if (type.includes('application/json')) {
252
+ try { await res.body?.cancel?.(); } catch { /* noop */ }
253
+ throw Object.assign(new Error('Event stream was not available'), { code: 'sse_failed' });
254
+ }
255
+ const events = await readSseEvents(res);
256
+ if (!events.length) {
257
+ throw Object.assign(new Error('Event stream was empty'), { code: 'sse_failed' });
258
+ }
259
+ return interpretSse(events);
260
+ }
261
+
262
+ /**
263
+ * @param {{ commandsUrl: string, token: string, frame: { id: string | number } }} options
264
+ * @param {typeof fetch} fetchImpl
265
+ * @param {AbortSignal} signal
266
+ */
267
+ async function waitViaPoll(options, fetchImpl, signal) {
268
+ const url = `${options.commandsUrl}/${encodeURIComponent(String(options.frame.id))}?timeout=${STEP_TIMEOUT_MS}`;
269
+ const res = await fetchAuthed(url, options.token, fetchImpl, signal);
270
+ /** @type {any} */
271
+ let json = null;
272
+ try {
273
+ json = await res.json();
274
+ } catch {
275
+ json = null;
276
+ }
277
+ if (res.status === 401) throw tokenRevokedError();
278
+ if (res.status === 404) {
279
+ throw Object.assign(new Error('That command is no longer waiting.'), { code: 'not_found' });
280
+ }
281
+ if (!res.ok) throw httpFailure(res.status, json);
282
+ if (json?.status === 'pending') return 'pending';
283
+ if (json?.status === 'done') {
284
+ const outcome = resultFromCommandResponse(json.response);
285
+ if (!outcome.ok) return { ok: false, error: outcome.error };
286
+ return { ok: true, result: outcome.result };
287
+ }
288
+ throw Object.assign(new Error('Bad command response'), { code: 'bridge_error' });
289
+ }