surfcad-mcp 0.2.3 → 0.2.5

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "surfcad-mcp",
3
- "version": "0.2.3",
3
+ "version": "0.2.5",
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",
@@ -360,15 +360,22 @@ export function createAgentBridgeRelayHub(opts = {}) {
360
360
  return;
361
361
  }
362
362
 
363
- if (msg.type === PAIR_MSG.AGENT_PROMPT || msg.type === PAIR_MSG.AGENT_PROMPT_ACK
363
+ if (msg.type === PAIR_MSG.AGENT_PROMPT || msg.type === PAIR_MSG.AGENT_PROMPT_CANCEL
364
+ || msg.type === PAIR_MSG.AGENT_PROMPT_ACK || msg.type === PAIR_MSG.AGENT_PROMPT_CANCEL_RESULT
364
365
  || msg.type === PAIR_MSG.AGENT_REPLY || msg.type === PAIR_MSG.AGENT_STATUS) {
365
- if (msg.type === PAIR_MSG.AGENT_PROMPT) {
366
+ if (msg.type === PAIR_MSG.AGENT_PROMPT || msg.type === PAIR_MSG.AGENT_PROMPT_CANCEL) {
366
367
  if (meta.role !== 'tab') {
367
- sendJson(socket, { type: PAIR_MSG.ERROR, code: 'forbidden', message: 'Only the paired tab sends prompts' });
368
+ sendJson(socket, {
369
+ type: PAIR_MSG.ERROR,
370
+ code: 'forbidden',
371
+ message: msg.type === PAIR_MSG.AGENT_PROMPT_CANCEL
372
+ ? 'Only the paired tab cancels prompts'
373
+ : 'Only the paired tab sends prompts',
374
+ });
368
375
  return;
369
376
  }
370
377
  const promptId = typeof msg.id === 'string' ? msg.id : undefined;
371
- if (rawText.length > maxPromptFrameChars) {
378
+ if (msg.type === PAIR_MSG.AGENT_PROMPT && rawText.length > maxPromptFrameChars) {
372
379
  sendJson(socket, {
373
380
  type: PAIR_MSG.AGENT_PROMPT_ACK,
374
381
  id: promptId,
@@ -378,6 +385,15 @@ export function createAgentBridgeRelayHub(opts = {}) {
378
385
  return;
379
386
  }
380
387
  if (tab.pairedPeer == null) {
388
+ if (msg.type === PAIR_MSG.AGENT_PROMPT_CANCEL) {
389
+ sendJson(socket, {
390
+ type: PAIR_MSG.AGENT_PROMPT_CANCEL_RESULT,
391
+ v: 1,
392
+ id: promptId || '',
393
+ state: 'not_found',
394
+ });
395
+ return;
396
+ }
381
397
  sendJson(socket, {
382
398
  type: PAIR_MSG.AGENT_PROMPT_ACK,
383
399
  id: promptId,
@@ -395,7 +411,7 @@ export function createAgentBridgeRelayHub(opts = {}) {
395
411
  type: PAIR_MSG.ERROR,
396
412
  code: wrongRole ? 'forbidden' : 'not_paired',
397
413
  message: wrongRole
398
- ? 'Only the paired agent sends replies and status'
414
+ ? 'Only the paired agent sends replies, status, and cancel results'
399
415
  : 'Pair before sending agent messages',
400
416
  });
401
417
  return;
@@ -128,8 +128,14 @@ export function createPromptSession(options) {
128
128
  const idleMs = options.idleMs ?? PROMPT_IDLE_MS;
129
129
  const webhookTimeoutMs = options.webhookTimeoutMs ?? WEBHOOK_TIMEOUT_MS;
130
130
 
131
- /** @type {Array<{ id: string, text: string, ts: string, context?: { part_id?: string, assembly_id?: string }, screenshot?: { mime: 'image/png', data: string, width: number, height: number } }>} */
131
+ /**
132
+ * Prompts waiting for `read_messages`, plus cancel notices for prompts
133
+ * that were already delivered. Cancel notices are not prompts.
134
+ * @type {Array<{ kind: 'prompt', id: string, text: string, ts: string, context?: { part_id?: string, assembly_id?: string }, screenshot?: { mime: 'image/png', data: string, width: number, height: number } } | { kind: 'cancel', id: string }>}
135
+ */
132
136
  let queue = [];
137
+ /** @type {Map<string, 'queued' | 'delivered' | 'replied' | 'cancelled'>} */
138
+ const states = new Map();
133
139
  /** @type {string | null} */
134
140
  let webhook = null;
135
141
  /** @type {string | null} Bearer token. Process memory only. Never log or return it. */
@@ -192,6 +198,63 @@ export function createPromptSession(options) {
192
198
  return msg;
193
199
  }
194
200
 
201
+ function promptQueueLength() {
202
+ let count = 0;
203
+ for (const item of queue) {
204
+ if (item.kind !== 'cancel') count += 1;
205
+ }
206
+ return count;
207
+ }
208
+
209
+ /**
210
+ * @param {string} id
211
+ * @param {'queued' | 'delivered' | 'replied' | 'cancelled'} state
212
+ */
213
+ function remember(id, state) {
214
+ states.set(id, state);
215
+ lastId = id;
216
+ }
217
+
218
+ /**
219
+ * POST JSON to the registered webhook. Same https, pin, bearer, and
220
+ * timeout rules as a prompt. Never logs the bearer.
221
+ * @param {string} target
222
+ * @param {object} body
223
+ * @param {number} epoch
224
+ * @returns {Promise<'sent' | 'failed' | 'dead'>}
225
+ */
226
+ async function postJson(target, body, epoch) {
227
+ const verdict = await validateWebhookUrl(target, {
228
+ allowLoopback: testWebhookOverride() === true,
229
+ resolveHost,
230
+ });
231
+ if (epoch !== life) return 'dead';
232
+ if (!(verdict.ok && webhook === target)) return 'failed';
233
+ const insecureTls = testWebhookOverride() === true && isLoopbackHost(verdict.host);
234
+ const pinAddress = verdict.addresses[0];
235
+ const bearer = webhookBearer;
236
+ const authorization = bearer ? `Bearer ${bearer}` : undefined;
237
+ let posted = { ok: false, error: 'webhook_failed' };
238
+ try {
239
+ posted = postWebhook
240
+ ? await postWebhook(target, body, {
241
+ pinAddress,
242
+ insecureTls,
243
+ ...(authorization ? { authorization } : {}),
244
+ })
245
+ : await postPromptWebhook(target, body, {
246
+ timeoutMs: webhookTimeoutMs,
247
+ insecureTls,
248
+ pinAddress,
249
+ ...(bearer ? { bearer } : {}),
250
+ });
251
+ } catch {
252
+ posted = { ok: false, error: 'webhook_failed' };
253
+ }
254
+ if (epoch !== life) return 'dead';
255
+ return posted?.ok === true ? 'sent' : 'failed';
256
+ }
257
+
195
258
  /**
196
259
  * @param {string} id
197
260
  */
@@ -201,16 +264,37 @@ export function createPromptSession(options) {
201
264
  lastAcceptedAt = now();
202
265
  }
203
266
 
267
+ /**
268
+ * @param {{ id: string, text: string, ts: string, context?: object, screenshot?: object }} prompt
269
+ */
204
270
  /**
205
271
  * @param {{ id: string, text: string, ts: string, context?: object, screenshot?: object }} prompt
206
272
  */
207
273
  function enqueue(prompt) {
208
274
  const dropped = [];
209
- while (queue.length >= queueCap) dropped.push(queue.shift());
210
- queue.push(prompt);
275
+ while (promptQueueLength() >= queueCap) {
276
+ const idx = queue.findIndex((item) => item.kind !== 'cancel');
277
+ if (idx < 0) break;
278
+ dropped.push(queue.splice(idx, 1)[0]);
279
+ }
280
+ queue.push({ kind: 'prompt', ...prompt });
211
281
  return dropped;
212
282
  }
213
283
 
284
+ /**
285
+ * @param {string} id
286
+ * @param {number} epoch
287
+ */
288
+ async function notifyCancel(id, epoch) {
289
+ const target = webhook;
290
+ if (target) {
291
+ const posted = await postJson(target, { type: 'cancel', id }, epoch);
292
+ if (posted === 'dead' || posted === 'sent') return;
293
+ }
294
+ if (epoch !== life) return;
295
+ queue.push({ kind: 'cancel', id });
296
+ }
297
+
214
298
  /**
215
299
  * @param {{ id: string, text: string, ts: string, context?: object, screenshot?: object }} prompt
216
300
  * @param {number} epoch
@@ -218,44 +302,19 @@ export function createPromptSession(options) {
218
302
  async function deliver(prompt, epoch) {
219
303
  const target = webhook;
220
304
  if (target) {
221
- const verdict = await validateWebhookUrl(target, {
222
- allowLoopback: testWebhookOverride() === true,
223
- resolveHost,
224
- });
225
- if (epoch !== life) return;
226
- // A unregister or a different URL landed during DNS. Do not POST the old target.
227
- if (verdict.ok && webhook === target) {
228
- const insecureTls = testWebhookOverride() === true && isLoopbackHost(verdict.host);
229
- const pinAddress = verdict.addresses[0];
230
- const bearer = webhookBearer;
231
- const authorization = bearer ? `Bearer ${bearer}` : undefined;
232
- let posted = { ok: false, error: 'webhook_failed' };
233
- try {
234
- posted = postWebhook
235
- ? await postWebhook(target, webhookBody(prompt), {
236
- pinAddress,
237
- insecureTls,
238
- ...(authorization ? { authorization } : {}),
239
- })
240
- : await postPromptWebhook(target, webhookBody(prompt), {
241
- timeoutMs: webhookTimeoutMs,
242
- insecureTls,
243
- pinAddress,
244
- ...(bearer ? { bearer } : {}),
245
- });
246
- } catch {
247
- posted = { ok: false, error: 'webhook_failed' };
248
- }
249
- if (epoch !== life) return;
250
- if (posted?.ok === true) {
251
- emit(ack(prompt.id, 'webhook'));
252
- return;
253
- }
305
+ const posted = await postJson(target, webhookBody(prompt), epoch);
306
+ if (posted === 'dead') return;
307
+ if (posted === 'sent') {
308
+ remember(prompt.id, 'delivered');
309
+ emit(ack(prompt.id, 'webhook'));
310
+ return;
254
311
  }
255
312
  }
256
313
  if (epoch !== life) return;
314
+ remember(prompt.id, 'queued');
257
315
  const dropped = enqueue(prompt);
258
316
  for (const old of dropped) {
317
+ if (old?.id && states.get(old.id) === 'queued') states.delete(old.id);
259
318
  if (old?.id) emit(ack(old.id, 'failed', 'queue_overflow'));
260
319
  }
261
320
  emit(ack(prompt.id, 'queued'));
@@ -322,6 +381,42 @@ export function createPromptSession(options) {
322
381
  return run;
323
382
  }
324
383
 
384
+ /**
385
+ * Cancel one prompt. Queued prompts are dropped. Delivered prompts are
386
+ * marked cancelled and the agent is told (webhook POST, or a later
387
+ * `read_messages` item). Runs after any in-flight accept so a cancel
388
+ * that arrives behind the prompt sees the recorded state.
389
+ * @param {string} rawId
390
+ * @returns {Promise<{ id: string, state: 'cancelled' | 'not_found' | 'already_final' }>}
391
+ */
392
+ function cancel(rawId) {
393
+ const run = chain.then(() => cancelNow(rawId));
394
+ chain = run.then(() => {}, () => {});
395
+ return run;
396
+ }
397
+
398
+ /**
399
+ * @param {string} rawId
400
+ */
401
+ async function cancelNow(rawId) {
402
+ const id = typeof rawId === 'string' ? rawId : '';
403
+ if (!id || !states.has(id)) return { id, state: 'not_found' };
404
+ const state = states.get(id);
405
+ if (state === 'replied') return { id, state: 'already_final' };
406
+ if (state === 'cancelled') return { id, state: 'cancelled' };
407
+ const epoch = life;
408
+ states.set(id, 'cancelled');
409
+ if (state === 'queued') {
410
+ queue = queue.filter((item) => item.kind === 'cancel' || item.id !== id);
411
+ }
412
+ if (id === lastId) {
413
+ workedEpoch = promptEpoch;
414
+ if (working) emitStatus(false, id, true);
415
+ }
416
+ if (state === 'delivered') await notifyCancel(id, epoch);
417
+ return { id, state: 'cancelled' };
418
+ }
419
+
325
420
  /**
326
421
  * @param {number | undefined} max
327
422
  */
@@ -334,8 +429,16 @@ export function createPromptSession(options) {
334
429
  count = Math.min(max, queue.length);
335
430
  }
336
431
  const taken = queue.splice(0, count);
337
- return {
338
- messages: taken.map((item) => ({
432
+ const messages = [];
433
+ const images = [];
434
+ for (const item of taken) {
435
+ if (item.kind === 'cancel') {
436
+ messages.push({ type: 'cancel', id: item.id });
437
+ images.push(null);
438
+ continue;
439
+ }
440
+ if (states.get(item.id) === 'queued') states.set(item.id, 'delivered');
441
+ messages.push({
339
442
  v: 1,
340
443
  id: item.id,
341
444
  text: item.text,
@@ -350,11 +453,12 @@ export function createPromptSession(options) {
350
453
  } : {}),
351
454
  notice: USER_CONTENT_NOTICE,
352
455
  acked: true,
353
- })),
354
- images: taken.map((item) => (item.screenshot
456
+ });
457
+ images.push(item.screenshot
355
458
  ? { data: item.screenshot.data, mimeType: 'image/png' }
356
- : null)),
357
- };
459
+ : null);
460
+ }
461
+ return { messages, images };
358
462
  }
359
463
 
360
464
  /**
@@ -372,6 +476,9 @@ export function createPromptSession(options) {
372
476
  if (text.length > PROMPT_REPLY_MAX) {
373
477
  throw Object.assign(new Error('Reply text is too long'), { code: 'reply_too_long' });
374
478
  }
479
+ if (states.get(inReplyTo) === 'cancelled') {
480
+ return { ok: false, error: 'cancelled' };
481
+ }
375
482
  const isFinal = args.final === true;
376
483
  const sent = emit({
377
484
  type: PAIR_MSG.AGENT_REPLY,
@@ -382,8 +489,11 @@ export function createPromptSession(options) {
382
489
  final: isFinal,
383
490
  });
384
491
  if (!sent) throw Object.assign(new Error('Not paired'), { code: 'not_paired' });
385
- if (isFinal) emitStatus(false, inReplyTo, true);
386
- else if (working) armIdle();
492
+ if (isFinal) {
493
+ queue = queue.filter((item) => item.kind === 'cancel' || item.id !== inReplyTo);
494
+ states.set(inReplyTo, 'replied');
495
+ emitStatus(false, inReplyTo, true);
496
+ } else if (working) armIdle();
387
497
  return { id: inReplyTo, final: isFinal };
388
498
  }
389
499
 
@@ -401,6 +511,10 @@ export function createPromptSession(options) {
401
511
  }
402
512
  id = args.id;
403
513
  }
514
+ const target = id || lastId;
515
+ if (target && states.get(target) === 'cancelled') {
516
+ return { ok: false, error: 'cancelled' };
517
+ }
404
518
  workedEpoch = promptEpoch;
405
519
  const sent = emitStatus(args.working, id || lastId, true);
406
520
  if (!sent) throw Object.assign(new Error('Not paired'), { code: 'not_paired' });
@@ -408,6 +522,10 @@ export function createPromptSession(options) {
408
522
  }
409
523
 
410
524
  function noteToolCall() {
525
+ if (lastId && states.get(lastId) === 'cancelled') {
526
+ if (working) emitStatus(false, lastId, true);
527
+ return;
528
+ }
411
529
  if (promptEpoch > workedEpoch) {
412
530
  workedEpoch = promptEpoch;
413
531
  if (!working) emitStatus(true, lastId, false);
@@ -441,15 +559,24 @@ export function createPromptSession(options) {
441
559
  }
442
560
 
443
561
  function deliveryStatus() {
562
+ const counts = { queued: 0, delivered: 0, replied: 0, cancelled: 0 };
563
+ for (const state of states.values()) {
564
+ if (Object.prototype.hasOwnProperty.call(counts, state)) counts[state] += 1;
565
+ }
566
+ const queued = promptQueueLength();
567
+ counts.queued = queued;
444
568
  return {
445
569
  webhookRegistered: webhook != null,
446
- queued: queue.length,
570
+ queued,
571
+ counts,
572
+ last: lastId && states.has(lastId) ? { id: lastId, state: states.get(lastId) } : null,
447
573
  };
448
574
  }
449
575
 
450
576
  function clear() {
451
577
  life += 1;
452
578
  queue = [];
579
+ states.clear();
453
580
  webhook = null;
454
581
  webhookBearer = null;
455
582
  working = false;
@@ -462,6 +589,7 @@ export function createPromptSession(options) {
462
589
 
463
590
  return {
464
591
  acceptPrompt,
592
+ cancel,
465
593
  readMessages,
466
594
  reply,
467
595
  setStatus,
@@ -474,7 +602,7 @@ export function createPromptSession(options) {
474
602
  return webhook != null;
475
603
  },
476
604
  queuedCount() {
477
- return queue.length;
605
+ return promptQueueLength();
478
606
  },
479
607
  };
480
608
  }
@@ -43,7 +43,7 @@ export function promptToolDefinitions() {
43
43
  return [
44
44
  {
45
45
  name: 'register_webhook',
46
- description: `Register an https webhook that receives user prompts from the paired SurfCAD tab. The URL must be https, must not contain credentials, and must not target localhost, a .local name, or a private, loopback, or link-local address. Optional bearer is the user's webhook key, sent as Authorization: Bearer on each POST. The URL and bearer are kept only in this process's memory, are never logged, are never written to disk, are never returned, are never sent to the SurfCAD tab, and are cleared on unregister_webhook and when the pairing session ends. Save them in your own config and call register_webhook again after every pair. When a webhook is registered, each prompt is POSTed as JSON { "type": "surfcad.prompt", ... } and times out after 10 seconds with one retry. If the POST fails, the prompt is queued instead. ${USER_CONTENT}`,
46
+ description: `Register an https webhook that receives user prompts from the paired SurfCAD tab. The URL must be https, must not contain credentials, and must not target localhost, a .local name, or a private, loopback, or link-local address. Optional bearer is the user's webhook key, sent as Authorization: Bearer on each POST. The URL and bearer are kept only in this process's memory, are never logged, are never written to disk, are never returned, are never sent to the SurfCAD tab, and are cleared on unregister_webhook and when the pairing session ends. Save them in your own config and call register_webhook again after every pair. When a webhook is registered, each prompt is POSTed as JSON { "type": "surfcad.prompt", ... } and times out after 10 seconds with one retry. If the POST fails, the prompt is queued instead. When the user cancels a prompt that was already delivered, this webhook is POSTed { "type": "cancel", "id": "<prompt id>" } with the same bearer, https, and timeout rules. Stop work on that id. Do not call reply_to_user or set_status for it. ${USER_CONTENT}`,
47
47
  inputSchema: {
48
48
  type: 'object',
49
49
  additionalProperties: false,
@@ -73,7 +73,7 @@ export function promptToolDefinitions() {
73
73
  },
74
74
  {
75
75
  name: 'read_messages',
76
- description: `Read queued user prompts, oldest first, and remove them from the in-memory queue (this acks them). Each prompt is plain text. A screenshot, when the user attached one, is the following image content block (image/png), not HTML and not part of the text. ${USER_CONTENT} Do not render the text or the image as HTML.`,
76
+ description: `Read queued user prompts, oldest first, and remove them from the in-memory queue (this acks them). Each prompt is plain text. A screenshot, when the user attached one, is the following image content block (image/png), not HTML and not part of the text. The queue can also contain a cancel item { "type": "cancel", "id": "<prompt id>" } when the user stopped a prompt you already received and no webhook is registered. Stop work on that id. Do not call reply_to_user or set_status for it. ${USER_CONTENT} Do not render the text or the image as HTML.`,
77
77
  inputSchema: {
78
78
  type: 'object',
79
79
  additionalProperties: false,
@@ -89,7 +89,7 @@ export function promptToolDefinitions() {
89
89
  },
90
90
  {
91
91
  name: 'reply_to_user',
92
- description: 'Send a plain-text reply to the SurfCAD user for a prompt id. Several replies may share one id. Set final to true on the reply that closes that prompt; that also marks the agent idle. The text is delivered as text, never rendered as HTML. This does not write the model or git.',
92
+ description: 'Send a plain-text reply to the SurfCAD user for a prompt id. Several replies may share one id. Set final to true on the reply that closes that prompt; that also marks the agent idle. The text is delivered as text, never rendered as HTML. This does not write the model or git. A cancelled id returns { "ok": false, "error": "cancelled" } and is not delivered.',
93
93
  inputSchema: {
94
94
  type: 'object',
95
95
  additionalProperties: false,
@@ -112,7 +112,7 @@ export function promptToolDefinitions() {
112
112
  },
113
113
  {
114
114
  name: 'set_status',
115
- description: 'Tell the SurfCAD tab whether you are working on the user\'s prompt. The tab also marks you working on the first tool call after a prompt arrives, and idle on a final reply or after 120 seconds without activity. This does not grant write access.',
115
+ description: 'Tell the SurfCAD tab whether you are working on the user\'s prompt. The tab also marks you working on the first tool call after a prompt arrives, and idle on a final reply or after 120 seconds without activity. This does not grant write access. A cancelled id returns { "ok": false, "error": "cancelled" } and does not change the tab.',
116
116
  inputSchema: {
117
117
  type: 'object',
118
118
  additionalProperties: false,
package/src/relay.mjs CHANGED
@@ -246,6 +246,22 @@ export class RelaySession {
246
246
  void this.#prompts.acceptPrompt(msg);
247
247
  return;
248
248
  }
249
+ if (msg.type === PAIR_MSG.AGENT_PROMPT_CANCEL) {
250
+ const cancelId = typeof msg.id === 'string' ? msg.id : '';
251
+ void this.#prompts.cancel(cancelId).then((result) => {
252
+ try {
253
+ this.#sendToTab({
254
+ type: PAIR_MSG.AGENT_PROMPT_CANCEL_RESULT,
255
+ v: 1,
256
+ id: result.id,
257
+ state: result.state,
258
+ });
259
+ } catch {
260
+ /* unpaired before the result could be sent */
261
+ }
262
+ }, () => {});
263
+ return;
264
+ }
249
265
  const id = typeof msg.id === 'string' ? msg.id : null;
250
266
  const waiter = id ? this.#pending.get(id) : undefined;
251
267
  if (waiter) {
@@ -21,4 +21,8 @@ export const PAIR_MSG = Object.freeze({
21
21
  AGENT_REPLY: 'agent.reply',
22
22
  /** Agent → page. Contract v:1. */
23
23
  AGENT_STATUS: 'agent.status',
24
+ /** Page → paired agent. Contract v:1. `{ id }`. */
25
+ AGENT_PROMPT_CANCEL: 'agent.prompt.cancel',
26
+ /** Agent → page. Contract v:1. `{ id, state }`. */
27
+ AGENT_PROMPT_CANCEL_RESULT: 'agent.prompt.cancel.result',
24
28
  });
package/src/server.mjs CHANGED
@@ -30,7 +30,7 @@ import {
30
30
 
31
31
  const PAIR_TOOL_NAME = 'pair';
32
32
 
33
- const STATUS_PROMPT_NOTE = ' This process also adds webhookRegistered (true when a prompt webhook is registered; the URL and any bearer are not included) and queued (how many prompt messages are waiting for read_messages).';
33
+ const STATUS_PROMPT_NOTE = ' This process also adds webhookRegistered (true when a prompt webhook is registered; the URL and any bearer are not included), queued (prompt messages waiting for read_messages; cancelled prompts are not counted), counts ({ queued, delivered, replied, cancelled }), and last ({ id, state } of the latest prompt, or null).';
34
34
 
35
35
  /**
36
36
  * MCP-only fields on the bridge status tool. The host command and commands.json stay unchanged.