surfcad-mcp 0.2.2 → 0.2.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/README.md +17 -3
- package/package.json +1 -1
- package/src/prompt/promptSession.mjs +53 -8
- package/src/prompt/promptTools.mjs +25 -4
- package/src/prompt/webhookPost.mjs +18 -6
- package/src/relay.mjs +1 -1
- package/src/server.mjs +55 -5
package/README.md
CHANGED
|
@@ -27,6 +27,10 @@ Environment variables:
|
|
|
27
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" }`.
|
|
28
28
|
4. Click **Allow** (the green check) in SurfCAD when prompted.
|
|
29
29
|
|
|
30
|
+
The MCP server instructions are: `call register_webhook { url, bearer? } if you can receive https webhooks, otherwise poll read_messages.`
|
|
31
|
+
|
|
32
|
+
A successful `pair`, when no webhook is registered yet, returns an onboarding note as text content (a `type: "text"` block, not only `structuredContent` or `_meta`). The note asks the agent to request a webhook URL and key from the user. The key is the `bearer` argument. Suggested wording to relay: "To get SurfCAD messages instantly, send me your webhook URL and key. This only needs to be done once. Otherwise I'll check for SurfCAD messages between steps, so replies may lag." If the user declines, the agent polls `read_messages`. This process holds the URL and bearer in memory only, so the agent should save them in its own config or memory and call `register_webhook` again after every pair. If a webhook is already registered when `pair` succeeds, the result omits that note and says the webhook is active.
|
|
33
|
+
|
|
30
34
|
Nothing pairs without your approval.
|
|
31
35
|
|
|
32
36
|
### Safari
|
|
@@ -51,6 +55,14 @@ Safari on a Mac blocks https pages from opening `ws://127.0.0.1` directly. In Sa
|
|
|
51
55
|
|
|
52
56
|
In Cursor, add the same block under **Settings → MCP** or your project `.cursor/mcp.json`.
|
|
53
57
|
|
|
58
|
+
## Claude Code
|
|
59
|
+
|
|
60
|
+
```bash
|
|
61
|
+
claude mcp add surfcad -- npx surfcad-mcp
|
|
62
|
+
```
|
|
63
|
+
|
|
64
|
+
A local CLI session usually has no public https endpoint, so polling `read_messages` is the normal path there. Webhooks apply when the user runs a receiver that can take https POSTs. The key they send is the `bearer` argument of `register_webhook`.
|
|
65
|
+
|
|
54
66
|
## Tools
|
|
55
67
|
|
|
56
68
|
Every command in `data/commands.json` is one MCP tool with the same name and argument schema, plus `pair` and five in-process prompt tools. `GET /tools` on the loopback relay, `list_commands`, and that file list the same bridge tools. Prefer `insert_*` feature tools. `set_script` is the freehand fallback and requires `part_id`.
|
|
@@ -90,13 +102,15 @@ These five tools stay inside the local `surfcad-mcp` process. They are not SurfC
|
|
|
90
102
|
|
|
91
103
|
| Tool | Args | What it does |
|
|
92
104
|
| --- | --- | --- |
|
|
93
|
-
| `register_webhook` | `{ url }` | Remember an https URL that receives each user prompt as `POST` JSON `{ "type": "surfcad.prompt", ... }`. Rejects `http`, credentials in the URL, localhost, `.local` names, and private or loopback addresses. The URL
|
|
94
|
-
| `unregister_webhook` | `{}` | Drop that URL. Later prompts are queued. |
|
|
105
|
+
| `register_webhook` | `{ url, bearer? }` | Remember an https URL that receives each user prompt as `POST` JSON `{ "type": "surfcad.prompt", ... }`. Optional `bearer` is sent as `Authorization: Bearer <bearer>` (non-empty, at most 4096 characters, no CR or LF). Rejects `http`, credentials in the URL, localhost, `.local` names, and private or loopback addresses. The URL and bearer are held only in memory, are never logged, are never written to disk, are never returned or put in status, are never sent to the SurfCAD tab, and are cleared on `unregister_webhook` and when the pairing session ends. |
|
|
106
|
+
| `unregister_webhook` | `{}` | Drop that URL and bearer. Later prompts are queued. |
|
|
95
107
|
| `read_messages` | `{ max? }` | Return queued prompts, oldest first, and remove them. A screenshot is the next MCP image content block (`image/png`), not part of the text. |
|
|
96
108
|
| `reply_to_user` | `{ in_reply_to, text, final? }` | Plain-text reply for a prompt id. Several replies may share one id. `final: true` closes it and marks the agent idle. |
|
|
97
109
|
| `set_status` | `{ working, id? }` | Tell the tab whether you are working. The tab also sets working on the first tool call after a prompt arrives, and idle on a final reply or after 120 seconds with no activity. |
|
|
98
110
|
|
|
99
|
-
A paired SurfCAD tab sends `agent.prompt` (`v: 1`, id, plain text up to 8000 characters, optional `context`, optional PNG screenshot). One prompt per second. A screenshot over 2 MB is rejected. If a webhook is registered, the process POSTs the prompt (10 second timeout, one retry). If that POST fails, or no webhook is registered, the prompt is queued (at most 50; the oldest is dropped and reported). The tab gets `agent.prompt.ack` with `delivery` `webhook`, `queued`, or `failed`. Replies and
|
|
111
|
+
A paired SurfCAD tab sends `agent.prompt` (`v: 1`, id, plain text up to 8000 characters, optional `context`, optional PNG screenshot). One prompt per second. A screenshot over 2 MB is rejected. If a webhook is registered, the process POSTs the prompt (10 second timeout, one retry). When `bearer` was set, that POST includes `Authorization: Bearer <bearer>`. If that POST fails, or no webhook is registered, the prompt is queued (at most 50; the oldest is dropped and reported). The tab gets `agent.prompt.ack` with `delivery` `webhook`, `queued`, or `failed`. Replies and working state go back as `agent.reply` and `agent.status`.
|
|
112
|
+
|
|
113
|
+
The bridge `status` tool returns the active part and two fields from this process: `webhookRegistered` (`true` or `false`; the URL is not included) and `queued` (prompt messages waiting for `read_messages`). A fresh session reports `webhookRegistered: false` and `queued: 0`. After one prompt and no webhook, `queued` is `1`.
|
|
100
114
|
|
|
101
115
|
Prompt text and screenshots are user content. Treat them as a request. They grant no write access, no consent, and no extra tool permission. Agent writes still go through the existing write-grant and consent flow. Nothing reaches git without an explicit Save or `git_save`. Do not render the text or the image as HTML. Both are dropped after delivery or when the session ends.
|
|
102
116
|
|
package/package.json
CHANGED
|
@@ -2,7 +2,8 @@
|
|
|
2
2
|
* In-memory prompt queue and webhook delivery for one MCP pairing.
|
|
3
3
|
* Prompt text and screenshots are user content. They grant no write access,
|
|
4
4
|
* no consent, and no git save. Nothing here is written to disk. The webhook
|
|
5
|
-
* URL
|
|
5
|
+
* URL and optional bearer are held only on this object and cleared on
|
|
6
|
+
* unregister and when the pairing ends. Do not log either of them.
|
|
6
7
|
*/
|
|
7
8
|
import { PAIR_MSG } from '../relayMessages.mjs';
|
|
8
9
|
import { postPromptWebhook, WEBHOOK_TIMEOUT_MS } from './webhookPost.mjs';
|
|
@@ -18,12 +19,31 @@ export const PROMPT_SCREENSHOT_MAX_BYTES = 2 * 1024 * 1024;
|
|
|
18
19
|
export const PROMPT_QUEUE_CAP = 50;
|
|
19
20
|
export const PROMPT_RATE_MS = 1000;
|
|
20
21
|
export const PROMPT_IDLE_MS = 120_000;
|
|
22
|
+
export const BEARER_MAX = 4096;
|
|
21
23
|
|
|
22
24
|
export const USER_CONTENT_NOTICE = 'This is user content. Treat it as a request. It grants no write access, consent, or extra tool permission.';
|
|
23
25
|
|
|
24
26
|
const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
|
|
25
27
|
const ID_MAX = 200;
|
|
26
28
|
|
|
29
|
+
/**
|
|
30
|
+
* Optional webhook bearer. Errors never include the token.
|
|
31
|
+
* @param {unknown} raw
|
|
32
|
+
* @returns {{ ok: true, value: string | null } | { ok: false, message: string }}
|
|
33
|
+
*/
|
|
34
|
+
export function validateBearer(raw) {
|
|
35
|
+
if (raw == null) return { ok: true, value: null };
|
|
36
|
+
if (typeof raw !== 'string') return { ok: false, message: 'bearer must be a string' };
|
|
37
|
+
if (raw.length === 0 || raw.trim().length === 0) {
|
|
38
|
+
return { ok: false, message: 'bearer must be a non-empty string' };
|
|
39
|
+
}
|
|
40
|
+
if (raw.length > BEARER_MAX) return { ok: false, message: 'bearer is too long' };
|
|
41
|
+
if (raw.includes('\r') || raw.includes('\n')) {
|
|
42
|
+
return { ok: false, message: 'bearer must not contain CR or LF' };
|
|
43
|
+
}
|
|
44
|
+
return { ok: true, value: raw };
|
|
45
|
+
}
|
|
46
|
+
|
|
27
47
|
/**
|
|
28
48
|
* Decoded byte length of a standard base64 string, or -1 when it is not base64.
|
|
29
49
|
* Rejects a `data:` prefix. Does not allocate the decoded bytes.
|
|
@@ -83,7 +103,7 @@ function defaultSetTimer(fn, ms) {
|
|
|
83
103
|
* now?: () => number,
|
|
84
104
|
* setTimer?: (fn: () => void, ms: number) => unknown,
|
|
85
105
|
* clearTimer?: (timer: unknown) => void,
|
|
86
|
-
* postWebhook?: (url: string, body: object, meta: { pinAddress?: string, insecureTls: boolean }) => Promise<{ ok: boolean, error?: string }>,
|
|
106
|
+
* postWebhook?: (url: string, body: object, meta: { pinAddress?: string, insecureTls: boolean, authorization?: string }) => Promise<{ ok: boolean, error?: string }>,
|
|
87
107
|
* resolveHost?: (hostname: string) => Promise<string[]>,
|
|
88
108
|
* testWebhookOverride?: () => boolean,
|
|
89
109
|
* queueCap?: number,
|
|
@@ -112,6 +132,8 @@ export function createPromptSession(options) {
|
|
|
112
132
|
let queue = [];
|
|
113
133
|
/** @type {string | null} */
|
|
114
134
|
let webhook = null;
|
|
135
|
+
/** @type {string | null} Bearer token. Process memory only. Never log or return it. */
|
|
136
|
+
let webhookBearer = null;
|
|
115
137
|
let working = false;
|
|
116
138
|
let promptEpoch = 0;
|
|
117
139
|
let workedEpoch = 0;
|
|
@@ -194,23 +216,32 @@ export function createPromptSession(options) {
|
|
|
194
216
|
* @param {number} epoch
|
|
195
217
|
*/
|
|
196
218
|
async function deliver(prompt, epoch) {
|
|
197
|
-
|
|
198
|
-
|
|
219
|
+
const target = webhook;
|
|
220
|
+
if (target) {
|
|
221
|
+
const verdict = await validateWebhookUrl(target, {
|
|
199
222
|
allowLoopback: testWebhookOverride() === true,
|
|
200
223
|
resolveHost,
|
|
201
224
|
});
|
|
202
225
|
if (epoch !== life) return;
|
|
203
|
-
|
|
226
|
+
// A unregister or a different URL landed during DNS. Do not POST the old target.
|
|
227
|
+
if (verdict.ok && webhook === target) {
|
|
204
228
|
const insecureTls = testWebhookOverride() === true && isLoopbackHost(verdict.host);
|
|
205
229
|
const pinAddress = verdict.addresses[0];
|
|
230
|
+
const bearer = webhookBearer;
|
|
231
|
+
const authorization = bearer ? `Bearer ${bearer}` : undefined;
|
|
206
232
|
let posted = { ok: false, error: 'webhook_failed' };
|
|
207
233
|
try {
|
|
208
234
|
posted = postWebhook
|
|
209
|
-
? await postWebhook(
|
|
210
|
-
|
|
235
|
+
? await postWebhook(target, webhookBody(prompt), {
|
|
236
|
+
pinAddress,
|
|
237
|
+
insecureTls,
|
|
238
|
+
...(authorization ? { authorization } : {}),
|
|
239
|
+
})
|
|
240
|
+
: await postPromptWebhook(target, webhookBody(prompt), {
|
|
211
241
|
timeoutMs: webhookTimeoutMs,
|
|
212
242
|
insecureTls,
|
|
213
243
|
pinAddress,
|
|
244
|
+
...(bearer ? { bearer } : {}),
|
|
214
245
|
});
|
|
215
246
|
} catch {
|
|
216
247
|
posted = { ok: false, error: 'webhook_failed' };
|
|
@@ -388,26 +419,39 @@ export function createPromptSession(options) {
|
|
|
388
419
|
|
|
389
420
|
/**
|
|
390
421
|
* @param {unknown} url
|
|
422
|
+
* @param {unknown} [bearer]
|
|
391
423
|
*/
|
|
392
|
-
async function registerWebhook(url) {
|
|
424
|
+
async function registerWebhook(url, bearer) {
|
|
425
|
+
const token = validateBearer(bearer);
|
|
426
|
+
if (!token.ok) throw Object.assign(new Error(token.message), { code: 'bad_args' });
|
|
393
427
|
const verdict = await validateWebhookUrl(url, {
|
|
394
428
|
allowLoopback: testWebhookOverride() === true,
|
|
395
429
|
resolveHost,
|
|
396
430
|
});
|
|
397
431
|
if (!verdict.ok) throw Object.assign(new Error(verdict.message), { code: verdict.code });
|
|
398
432
|
webhook = typeof url === 'string' ? url.trim() : null;
|
|
433
|
+
webhookBearer = token.value;
|
|
399
434
|
return { registered: true };
|
|
400
435
|
}
|
|
401
436
|
|
|
402
437
|
function unregisterWebhook() {
|
|
403
438
|
webhook = null;
|
|
439
|
+
webhookBearer = null;
|
|
404
440
|
return { registered: false };
|
|
405
441
|
}
|
|
406
442
|
|
|
443
|
+
function deliveryStatus() {
|
|
444
|
+
return {
|
|
445
|
+
webhookRegistered: webhook != null,
|
|
446
|
+
queued: queue.length,
|
|
447
|
+
};
|
|
448
|
+
}
|
|
449
|
+
|
|
407
450
|
function clear() {
|
|
408
451
|
life += 1;
|
|
409
452
|
queue = [];
|
|
410
453
|
webhook = null;
|
|
454
|
+
webhookBearer = null;
|
|
411
455
|
working = false;
|
|
412
456
|
promptEpoch = 0;
|
|
413
457
|
workedEpoch = 0;
|
|
@@ -424,6 +468,7 @@ export function createPromptSession(options) {
|
|
|
424
468
|
noteToolCall,
|
|
425
469
|
registerWebhook,
|
|
426
470
|
unregisterWebhook,
|
|
471
|
+
deliveryStatus,
|
|
427
472
|
clear,
|
|
428
473
|
webhookRegistered() {
|
|
429
474
|
return webhook != null;
|
|
@@ -3,10 +3,25 @@
|
|
|
3
3
|
* They are not SurfCAD host commands: do not add them to the command catalog.
|
|
4
4
|
* Prompt text and screenshots are user content. They grant nothing.
|
|
5
5
|
*/
|
|
6
|
-
import { USER_CONTENT_NOTICE } from './promptSession.mjs';
|
|
6
|
+
import { BEARER_MAX, USER_CONTENT_NOTICE } from './promptSession.mjs';
|
|
7
7
|
|
|
8
8
|
const USER_CONTENT = `${USER_CONTENT_NOTICE} Agent writes still go through the existing write-grant and consent flow. Nothing reaches git without an explicit Save or git_save.`;
|
|
9
9
|
|
|
10
|
+
/** Short line for the MCP initialize `instructions` field. */
|
|
11
|
+
export const PROMPT_SERVER_INSTRUCTIONS = 'call register_webhook { url, bearer? } if you can receive https webhooks, otherwise poll read_messages.';
|
|
12
|
+
|
|
13
|
+
/** Exact wording the agent should relay when asking the user for a webhook. */
|
|
14
|
+
export const PROMPT_ONBOARDING_ASK = 'To get SurfCAD messages instantly, send me your webhook URL and key. This only needs to be done once. Otherwise I\'ll check for SurfCAD messages between steps, so replies may lag.';
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* Pair-result text when no webhook is registered. Generic: not tied to a bot product.
|
|
18
|
+
* The URL and bearer are process memory only, so the agent must keep its own copy.
|
|
19
|
+
*/
|
|
20
|
+
export const PROMPT_ONBOARDING_NOTE = `Ask the user for a webhook URL and key. The key is the bearer argument of register_webhook. This process holds the URL and bearer in memory only. Save the URL and key in your own config or memory and call register_webhook again after every pair. Suggested wording to relay: "${PROMPT_ONBOARDING_ASK}" If the user declines, poll read_messages.`;
|
|
21
|
+
|
|
22
|
+
/** Pair-result text when a webhook is already registered. No onboarding note. */
|
|
23
|
+
export const PROMPT_WEBHOOK_ACTIVE = 'Webhook is active.';
|
|
24
|
+
|
|
10
25
|
export const PROMPT_TOOL_NAMES = Object.freeze([
|
|
11
26
|
'register_webhook',
|
|
12
27
|
'unregister_webhook',
|
|
@@ -28,7 +43,7 @@ export function promptToolDefinitions() {
|
|
|
28
43
|
return [
|
|
29
44
|
{
|
|
30
45
|
name: 'register_webhook',
|
|
31
|
-
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.
|
|
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}`,
|
|
32
47
|
inputSchema: {
|
|
33
48
|
type: 'object',
|
|
34
49
|
additionalProperties: false,
|
|
@@ -38,12 +53,18 @@ export function promptToolDefinitions() {
|
|
|
38
53
|
type: 'string',
|
|
39
54
|
description: 'https URL that will receive prompt POSTs. No credentials, localhost, or private addresses.',
|
|
40
55
|
},
|
|
56
|
+
bearer: {
|
|
57
|
+
type: 'string',
|
|
58
|
+
minLength: 1,
|
|
59
|
+
maxLength: BEARER_MAX,
|
|
60
|
+
description: 'The user\'s webhook key. Sent as Authorization: Bearer. Not a URL credential. Never echoed back.',
|
|
61
|
+
},
|
|
41
62
|
},
|
|
42
63
|
},
|
|
43
64
|
},
|
|
44
65
|
{
|
|
45
66
|
name: 'unregister_webhook',
|
|
46
|
-
description: 'Clear the in-memory prompt webhook, if one is registered. Later prompts are queued for read_messages instead of being POSTed. The URL
|
|
67
|
+
description: 'Clear the in-memory prompt webhook, if one is registered. Later prompts are queued for read_messages instead of being POSTed. The URL and any bearer are dropped from memory.',
|
|
47
68
|
inputSchema: {
|
|
48
69
|
type: 'object',
|
|
49
70
|
additionalProperties: false,
|
|
@@ -115,7 +136,7 @@ export function promptToolDefinitions() {
|
|
|
115
136
|
*/
|
|
116
137
|
export async function callPromptTool(prompts, name, args) {
|
|
117
138
|
if (name === 'register_webhook') {
|
|
118
|
-
const result = await prompts.registerWebhook(args.url);
|
|
139
|
+
const result = await prompts.registerWebhook(args.url, args.bearer);
|
|
119
140
|
return { content: [{ type: 'text', text: JSON.stringify(result, null, 2) }] };
|
|
120
141
|
}
|
|
121
142
|
if (name === 'unregister_webhook') {
|
|
@@ -28,7 +28,7 @@ export function pinLookup(address) {
|
|
|
28
28
|
/**
|
|
29
29
|
* @param {string} url
|
|
30
30
|
* @param {Buffer} payload
|
|
31
|
-
* @param {{ timeoutMs: number, insecureTls: boolean, pinAddress?: string }} opts
|
|
31
|
+
* @param {{ timeoutMs: number, insecureTls: boolean, pinAddress?: string, bearer?: string }} opts
|
|
32
32
|
*/
|
|
33
33
|
function defaultHttpsPost(url, payload, opts) {
|
|
34
34
|
return new Promise((resolve, reject) => {
|
|
@@ -43,17 +43,25 @@ function defaultHttpsPost(url, payload, opts) {
|
|
|
43
43
|
reject(new Error('https required'));
|
|
44
44
|
return;
|
|
45
45
|
}
|
|
46
|
+
const headers = {
|
|
47
|
+
'content-type': 'application/json',
|
|
48
|
+
'content-length': String(payload.length),
|
|
49
|
+
accept: 'application/json',
|
|
50
|
+
};
|
|
51
|
+
if (typeof opts.bearer === 'string' && opts.bearer.length > 0) {
|
|
52
|
+
if (opts.bearer.includes('\r') || opts.bearer.includes('\n')) {
|
|
53
|
+
reject(new Error('webhook_failed'));
|
|
54
|
+
return;
|
|
55
|
+
}
|
|
56
|
+
headers.authorization = `Bearer ${opts.bearer}`;
|
|
57
|
+
}
|
|
46
58
|
const requestOptions = {
|
|
47
59
|
protocol: 'https:',
|
|
48
60
|
hostname: parsed.hostname,
|
|
49
61
|
port: parsed.port || 443,
|
|
50
62
|
path: `${parsed.pathname}${parsed.search}`,
|
|
51
63
|
method: 'POST',
|
|
52
|
-
headers
|
|
53
|
-
'content-type': 'application/json',
|
|
54
|
-
'content-length': String(payload.length),
|
|
55
|
-
accept: 'application/json',
|
|
56
|
-
},
|
|
64
|
+
headers,
|
|
57
65
|
rejectUnauthorized: opts.insecureTls !== true,
|
|
58
66
|
servername: parsed.hostname,
|
|
59
67
|
timeout: opts.timeoutMs,
|
|
@@ -84,6 +92,7 @@ function defaultHttpsPost(url, payload, opts) {
|
|
|
84
92
|
* attempts?: number,
|
|
85
93
|
* insecureTls?: boolean,
|
|
86
94
|
* pinAddress?: string,
|
|
95
|
+
* bearer?: string,
|
|
87
96
|
* request?: typeof defaultHttpsPost,
|
|
88
97
|
* }} [options]
|
|
89
98
|
*/
|
|
@@ -97,6 +106,9 @@ export async function postPromptWebhook(url, body, options = {}) {
|
|
|
97
106
|
insecureTls: options.insecureTls === true,
|
|
98
107
|
pinAddress: options.pinAddress,
|
|
99
108
|
};
|
|
109
|
+
if (typeof options.bearer === 'string' && options.bearer.length > 0) {
|
|
110
|
+
opts.bearer = options.bearer;
|
|
111
|
+
}
|
|
100
112
|
let lastError = 'webhook_failed';
|
|
101
113
|
for (let i = 0; i < attempts; i += 1) {
|
|
102
114
|
try {
|
package/src/relay.mjs
CHANGED
|
@@ -88,7 +88,7 @@ export class RelaySession {
|
|
|
88
88
|
* ensureRelay?: () => Promise<unknown>,
|
|
89
89
|
* onLog?: (line: string) => void,
|
|
90
90
|
* promptSession?: ReturnType<typeof createPromptSession>,
|
|
91
|
-
* postWebhook?: (url: string, body: object, meta: { pinAddress?: string, insecureTls: boolean }) => Promise<{ ok: boolean, error?: string }>,
|
|
91
|
+
* postWebhook?: (url: string, body: object, meta: { pinAddress?: string, insecureTls: boolean, authorization?: string }) => Promise<{ ok: boolean, error?: string }>,
|
|
92
92
|
* testWebhookOverride?: () => boolean,
|
|
93
93
|
* resolveHost?: (hostname: string) => Promise<string[]>,
|
|
94
94
|
* now?: () => number,
|
package/src/server.mjs
CHANGED
|
@@ -19,10 +19,31 @@ import {
|
|
|
19
19
|
} from './bridge/relayServer.mjs';
|
|
20
20
|
import { RelaySession } from './relay.mjs';
|
|
21
21
|
import { augmentScreenshotTool, callPairedBridgeTool } from './screenshotFile.mjs';
|
|
22
|
-
import {
|
|
22
|
+
import {
|
|
23
|
+
callPromptTool,
|
|
24
|
+
isPromptTool,
|
|
25
|
+
PROMPT_ONBOARDING_NOTE,
|
|
26
|
+
PROMPT_SERVER_INSTRUCTIONS,
|
|
27
|
+
PROMPT_WEBHOOK_ACTIVE,
|
|
28
|
+
promptToolDefinitions,
|
|
29
|
+
} from './prompt/promptTools.mjs';
|
|
23
30
|
|
|
24
31
|
const PAIR_TOOL_NAME = 'pair';
|
|
25
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).';
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* MCP-only fields on the bridge status tool. The host command and commands.json stay unchanged.
|
|
37
|
+
* @param {{ name: string, description?: string }} tool
|
|
38
|
+
*/
|
|
39
|
+
function augmentStatusTool(tool) {
|
|
40
|
+
if (!tool || tool.name !== 'status') return tool;
|
|
41
|
+
return {
|
|
42
|
+
...tool,
|
|
43
|
+
description: `${tool.description || ''}${STATUS_PROMPT_NOTE}`,
|
|
44
|
+
};
|
|
45
|
+
}
|
|
46
|
+
|
|
26
47
|
/** A bridge call that has to pair first waits this long for Allow, then fails. */
|
|
27
48
|
const AUTO_PAIR_WAIT_MS = 1000;
|
|
28
49
|
/** The pair tool returns pair_pending before typical MCP client timeouts (60 s). */
|
|
@@ -54,6 +75,29 @@ function textResult(value, isError = false) {
|
|
|
54
75
|
};
|
|
55
76
|
}
|
|
56
77
|
|
|
78
|
+
/**
|
|
79
|
+
* Pair success is ordinary text content so every MCP client, including Claude Code,
|
|
80
|
+
* shows the note. No structuredContent and no _meta.
|
|
81
|
+
* @param {Record<string, unknown>} result
|
|
82
|
+
* @param {{ webhookRegistered: () => boolean }} prompts
|
|
83
|
+
*/
|
|
84
|
+
function pairToolResult(result, prompts) {
|
|
85
|
+
const webhookRegistered = prompts.webhookRegistered() === true;
|
|
86
|
+
const note = webhookRegistered ? PROMPT_WEBHOOK_ACTIVE : PROMPT_ONBOARDING_NOTE;
|
|
87
|
+
const payload = {
|
|
88
|
+
...(result && typeof result === 'object' ? result : {}),
|
|
89
|
+
webhookRegistered,
|
|
90
|
+
note,
|
|
91
|
+
};
|
|
92
|
+
return {
|
|
93
|
+
content: [
|
|
94
|
+
{ type: 'text', text: JSON.stringify(payload, null, 2) },
|
|
95
|
+
{ type: 'text', text: note },
|
|
96
|
+
],
|
|
97
|
+
isError: false,
|
|
98
|
+
};
|
|
99
|
+
}
|
|
100
|
+
|
|
57
101
|
function toolErrorPayload(err) {
|
|
58
102
|
if (err && typeof err === 'object' && err.code) {
|
|
59
103
|
return formatBridgeError({
|
|
@@ -73,18 +117,21 @@ function toolErrorPayload(err) {
|
|
|
73
117
|
export async function createSurfcadMcpServer(options = {}) {
|
|
74
118
|
const catalog = options.catalog || loadCommandsCatalog();
|
|
75
119
|
const session = options.session || new RelaySession();
|
|
76
|
-
const bridgeTools = bridgeToolDefinitions(catalog).map((tool) => augmentScreenshotTool(tool));
|
|
120
|
+
const bridgeTools = bridgeToolDefinitions(catalog).map((tool) => augmentStatusTool(augmentScreenshotTool(tool)));
|
|
77
121
|
|
|
78
122
|
const server = new Server(
|
|
79
123
|
{ name: 'surfcad-mcp', version: loadPackageVersion() },
|
|
80
|
-
{
|
|
124
|
+
{
|
|
125
|
+
capabilities: { tools: {} },
|
|
126
|
+
instructions: PROMPT_SERVER_INSTRUCTIONS,
|
|
127
|
+
},
|
|
81
128
|
);
|
|
82
129
|
|
|
83
130
|
server.setRequestHandler(ListToolsRequestSchema, async () => ({
|
|
84
131
|
tools: [
|
|
85
132
|
{
|
|
86
133
|
name: PAIR_TOOL_NAME,
|
|
87
|
-
description: `Pair this MCP server to an open SurfCAD tab via the local WebSocket relay. ${pairingEnvHint()}`,
|
|
134
|
+
description: `Pair this MCP server to an open SurfCAD tab via the local WebSocket relay. ${pairingEnvHint()} ${PROMPT_SERVER_INSTRUCTIONS}`,
|
|
88
135
|
inputSchema: {
|
|
89
136
|
type: 'object',
|
|
90
137
|
additionalProperties: false,
|
|
@@ -130,7 +177,7 @@ export async function createSurfcadMcpServer(options = {}) {
|
|
|
130
177
|
}
|
|
131
178
|
try {
|
|
132
179
|
const result = await waitForPairing(session.pair(code), PAIR_TOOL_WAIT_MS);
|
|
133
|
-
return
|
|
180
|
+
return pairToolResult(result, session.prompts);
|
|
134
181
|
} catch (err) {
|
|
135
182
|
return textResult(toolErrorPayload(err), true);
|
|
136
183
|
}
|
|
@@ -159,6 +206,9 @@ export async function createSurfcadMcpServer(options = {}) {
|
|
|
159
206
|
try {
|
|
160
207
|
session.noteAgentToolCall();
|
|
161
208
|
const out = await callPairedBridgeTool(session, name, args);
|
|
209
|
+
if (name === 'status' && out.isError !== true && out.value && typeof out.value === 'object' && !Array.isArray(out.value)) {
|
|
210
|
+
return textResult({ ...out.value, ...session.prompts.deliveryStatus() });
|
|
211
|
+
}
|
|
162
212
|
return textResult(out.value, out.isError === true);
|
|
163
213
|
} catch (err) {
|
|
164
214
|
const code = err?.code;
|