surfcad-mcp 0.3.1 → 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.
package/src/server.mjs CHANGED
@@ -12,7 +12,6 @@ import { bridgeToolDefinitions, loadCommandsCatalog } from './catalog.mjs';
12
12
  import {
13
13
  formatBridgeError,
14
14
  notPairedError,
15
- pairPendingError,
16
15
  pairingEnvHint,
17
16
  } from './errors.mjs';
18
17
  import { loadPackageVersion } from './packageVersion.mjs';
@@ -22,6 +21,10 @@ import {
22
21
  stopAgentBridgeRelay,
23
22
  } from './bridge/relayServer.mjs';
24
23
  import { RelaySession } from './relay.mjs';
24
+ import { resolveAgentName, resolveServerUrl } from './remote/config.mjs';
25
+ import { RemoteSession } from './remote/session.mjs';
26
+ import { readSavedLogin } from './remote/tokenStore.mjs';
27
+ import { waitForPairing } from './pairWait.mjs';
25
28
  import { augmentScreenshotTool, callPairedBridgeTool } from './screenshotFile.mjs';
26
29
  import {
27
30
  callPromptTool,
@@ -41,6 +44,7 @@ import {
41
44
  } from './prompt/guide.mjs';
42
45
  import { withErrorHint, withRowHints } from './prompt/errorHints.mjs';
43
46
  import { callListHelpersTool, LIST_HELPERS_TOOL_NAME, listHelpersToolDefinition } from './helpers.mjs';
47
+ import { mergeRegisteredIntoListCommands } from './listCommandsMerge.mjs';
44
48
 
45
49
  const PAIR_TOOL_NAME = 'pair';
46
50
 
@@ -61,30 +65,51 @@ function augmentStatusTool(tool) {
61
65
  };
62
66
  }
63
67
 
64
- /** A bridge call that has to pair first waits this long for Allow, then fails. */
65
- const AUTO_PAIR_WAIT_MS = 1000;
66
- /** The pair tool returns pair_pending before typical MCP client timeouts (60 s). */
67
- const PAIR_TOOL_WAIT_MS = 30_000;
68
+ /**
69
+ * One list for tools/list and for the rows list_commands adds. MCP-only
70
+ * tools are whatever this returns that is not a bridge command.
71
+ * @param {Array<{ name: string, description?: string, inputSchema?: object }>} bridgeTools
72
+ */
73
+ function registeredToolDefinitions(bridgeTools) {
74
+ return [
75
+ {
76
+ name: PAIR_TOOL_NAME,
77
+ description: `Pair this MCP server to an open SurfCAD tab via the local WebSocket relay. ${pairingEnvHint()} ${PROMPT_SERVER_INSTRUCTIONS} After pairing call guide { topic: "start" } (How to build in SurfCAD: block out first, features first, hardware as patterned parts) before the first model call.`,
78
+ inputSchema: {
79
+ type: 'object',
80
+ additionalProperties: false,
81
+ properties: {
82
+ code: {
83
+ type: 'string',
84
+ description: '8-character pairing code from the SurfCAD Local agent panel',
85
+ },
86
+ },
87
+ },
88
+ },
89
+ guideToolDefinition(),
90
+ listHelpersToolDefinition(),
91
+ ...promptToolDefinitions(),
92
+ ...bridgeTools,
93
+ ];
94
+ }
68
95
 
69
96
  /**
70
- * @param {Promise<unknown>} attempt
71
- * @param {number} waitMs
97
+ * @param {{ name: string, description?: string }} tool
98
+ * @param {string[]} extraNames
72
99
  */
73
- async function waitForPairing(attempt, waitMs) {
74
- attempt.catch(() => {});
75
- let timer;
76
- const timeout = new Promise((resolve) => {
77
- timer = setTimeout(() => resolve(timeout), waitMs);
78
- });
79
- try {
80
- const outcome = await Promise.race([attempt, timeout]);
81
- if (outcome === timeout) throw pairPendingError();
82
- return outcome;
83
- } finally {
84
- clearTimeout(timer);
85
- }
100
+ function augmentListCommandsTool(tool, extraNames) {
101
+ if (!tool || tool.name !== 'list_commands' || extraNames.length === 0) return tool;
102
+ return {
103
+ ...tool,
104
+ description: `${tool.description || ''} Also lists the MCP-only tools this server registers (${extraNames.join(', ')}), in the agent group. They are not bridge commands.`,
105
+ };
86
106
  }
87
107
 
108
+ /** A bridge call that has to pair first waits this long for Allow, then fails. */
109
+ const AUTO_PAIR_WAIT_MS = 1000;
110
+ /** The pair tool returns pair_pending before typical MCP client timeouts (60 s). */
111
+ const PAIR_TOOL_WAIT_MS = 30_000;
112
+
88
113
  /**
89
114
  * Compact JSON. Pretty printing put every number of a bbox or a face key on
90
115
  * its own line and made each payload about 2.4 times larger (list_commands
@@ -176,7 +201,15 @@ function toolErrorPayload(err) {
176
201
  export async function createSurfcadMcpServer(options = {}) {
177
202
  const catalog = options.catalog || loadCommandsCatalog();
178
203
  const session = options.session || new RelaySession();
204
+ const bridgeNames = new Set(catalog.commands.map((command) => command.name));
179
205
  const bridgeTools = bridgeToolDefinitions(catalog).map((tool) => augmentStatusTool(augmentScreenshotTool(tool)));
206
+ const mcpOnlyNames = registeredToolDefinitions(bridgeTools)
207
+ .map((tool) => tool.name)
208
+ .filter((name) => !bridgeNames.has(name));
209
+ for (let i = 0; i < bridgeTools.length; i += 1) {
210
+ bridgeTools[i] = augmentListCommandsTool(bridgeTools[i], mcpOnlyNames);
211
+ }
212
+ const registeredTools = registeredToolDefinitions(bridgeTools);
180
213
 
181
214
  const version = loadPackageVersion();
182
215
  const server = new Server(
@@ -202,26 +235,7 @@ export async function createSurfcadMcpServer(options = {}) {
202
235
  });
203
236
 
204
237
  server.setRequestHandler(ListToolsRequestSchema, async () => ({
205
- tools: [
206
- {
207
- name: PAIR_TOOL_NAME,
208
- description: `Pair this MCP server to an open SurfCAD tab via the local WebSocket relay. ${pairingEnvHint()} ${PROMPT_SERVER_INSTRUCTIONS} After pairing call guide { topic: "start" } (How to build in SurfCAD: block out first, features first, hardware as patterned parts) before the first model call.`,
209
- inputSchema: {
210
- type: 'object',
211
- additionalProperties: false,
212
- properties: {
213
- code: {
214
- type: 'string',
215
- description: '6-character pairing code from the SurfCAD Local agent panel',
216
- },
217
- },
218
- },
219
- },
220
- guideToolDefinition(),
221
- listHelpersToolDefinition(),
222
- ...promptToolDefinitions(),
223
- ...bridgeTools,
224
- ],
238
+ tools: registeredTools,
225
239
  }));
226
240
 
227
241
  server.setRequestHandler(CallToolRequestSchema, async (request) => {
@@ -256,7 +270,7 @@ export async function createSurfcadMcpServer(options = {}) {
256
270
  if (!code) {
257
271
  return errorResult({
258
272
  code: 'bad_pairing_code',
259
- message: `Missing pairing code. Pass { "code": "......" } or set SURFCAD_PAIRING_CODE. ${pairingEnvHint()}`,
273
+ message: `Missing pairing code. Pass { "code": "........" } or set SURFCAD_PAIRING_CODE. ${pairingEnvHint()}`,
260
274
  }, name);
261
275
  }
262
276
  try {
@@ -288,9 +302,9 @@ export async function createSurfcadMcpServer(options = {}) {
288
302
  }
289
303
 
290
304
  try {
291
- // A model-changing tool switches the tab to working on its own.
292
- // The call holds the idle window until it returns: a long tool call
293
- // is the agent working, not a stall.
305
+ // A model-changing tool enters building if set_status has not already.
306
+ // A read never does. The call holds the idle window until it returns:
307
+ // a long tool call is the agent working, not a stall.
294
308
  const row = catalog.commands.find((c) => c.name === name);
295
309
  session.noteAgentToolCall({ mutates: row?.mutates === true || (row?.mutates == null && mutatingTool(name)) });
296
310
  session.holdAgentWork(true);
@@ -303,6 +317,12 @@ export async function createSurfcadMcpServer(options = {}) {
303
317
  if (name === 'status' && out.isError !== true && out.value && typeof out.value === 'object' && !Array.isArray(out.value)) {
304
318
  return textResult({ ...out.value, ...session.prompts.deliveryStatus() });
305
319
  }
320
+ if (name === 'list_commands' && out.isError !== true) {
321
+ out = {
322
+ ...out,
323
+ value: mergeRegisteredIntoListCommands(out.value, { registered: registeredTools, bridgeNames, args }),
324
+ };
325
+ }
306
326
  if (out.isError === true) return errorResult(out.value, name);
307
327
  // A run that failed answers ok: false with errors rows; those carry hints too.
308
328
  return textResult(withRowHints(out.value));
@@ -328,9 +348,11 @@ export async function createSurfcadMcpServer(options = {}) {
328
348
  }
329
349
 
330
350
  /**
331
- * @param {{ autoPairFromEnv?: boolean }} [options]
351
+ * @param {{ autoPairFromEnv?: boolean, startRelay?: boolean, mode?: 'local' | 'remote', server?: string, name?: string, env?: NodeJS.ProcessEnv }} [options]
332
352
  */
333
353
  export async function runSurfcadMcpServer(options = {}) {
354
+ if (options.mode === 'remote') return runRemoteMcpServer(options);
355
+
334
356
  /** @type {Awaited<ReturnType<typeof ensureAgentBridgeRelay>> | null} */
335
357
  let ownedRelay = null;
336
358
  const startRelay = options.startRelay !== false && process.env.SURFCAD_MCP_START_RELAY !== '0';
@@ -389,3 +411,46 @@ export async function runSurfcadMcpServer(options = {}) {
389
411
 
390
412
  return { server, session, transport };
391
413
  }
414
+
415
+ /**
416
+ * Logged-in (or `--remote`) stdio server. Does not start the loopback relay.
417
+ * The bearer token is never logged.
418
+ * @param {{ server?: string, name?: string, env?: NodeJS.ProcessEnv }} options
419
+ */
420
+ async function runRemoteMcpServer(options) {
421
+ const env = options.env || process.env;
422
+ const saved = await readSavedLogin(env);
423
+ if (!saved?.token) {
424
+ throw Object.assign(new Error('No saved login. Run npx surfcad-mcp login.'), { code: 'not_logged_in' });
425
+ }
426
+ const serverUrl = resolveServerUrl({ flag: options.server, env, saved });
427
+ const pinned = resolveAgentName({ name: options.name, savedName: saved.name, env });
428
+ const remote = new RemoteSession({
429
+ serverUrl,
430
+ token: saved.token,
431
+ name: pinned,
432
+ fillNameFromClient: !pinned,
433
+ });
434
+ const { server, session } = await createSurfcadMcpServer({ session: remote });
435
+ server.oninitialized = () => {
436
+ remote.applyClientInfo(server.getClientVersion());
437
+ void remote.connect().catch((err) => {
438
+ console.error(`${new Date().toISOString()} [surfcad-mcp] ${err?.message || 'remote connect failed'}`);
439
+ });
440
+ };
441
+ if (!remote.needsClientName()) {
442
+ void remote.connect().catch((err) => {
443
+ console.error(`${new Date().toISOString()} [surfcad-mcp] ${err?.message || 'remote connect failed'}`);
444
+ });
445
+ }
446
+
447
+ const onStdinClosed = () => {
448
+ remote.disconnect();
449
+ setTimeout(() => process.exit(0), 0).unref();
450
+ };
451
+ process.stdin.once('end', onStdinClosed);
452
+
453
+ const transport = new StdioServerTransport();
454
+ await server.connect(transport);
455
+ return { server, session, transport };
456
+ }