surfcad-mcp 0.2.5 → 0.3.1
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 +24 -10
- package/data/commands.json +7877 -1089
- package/data/helpers.json +1765 -0
- package/package.json +1 -1
- package/src/bridge/relayHub.mjs +2 -1
- package/src/helpers.mjs +209 -0
- package/src/prompt/buildGuidance.mjs +27 -0
- package/src/prompt/errorHints.mjs +295 -0
- package/src/prompt/guide.mjs +289 -0
- package/src/prompt/promptSession.mjs +148 -16
- package/src/prompt/promptStall.mjs +6 -0
- package/src/prompt/promptTools.mjs +48 -9
- package/src/relay.mjs +22 -3
- package/src/relayMessages.mjs +2 -0
- package/src/server.mjs +115 -19
|
@@ -7,8 +7,22 @@ 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
|
-
/**
|
|
11
|
-
export const
|
|
10
|
+
/** read_messages { wait_ms } cap: long enough to skip idle polls, short enough for a host tool timeout. */
|
|
11
|
+
export const READ_MESSAGES_MAX_WAIT_MS = 25_000;
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* Closing reply for a task that started in the in-viewer prompt pane.
|
|
15
|
+
* The same sentence is the second sentence of the MCP initialize
|
|
16
|
+
* instructions (hosts keep the start of that field) and the
|
|
17
|
+
* `reply_to_user` description.
|
|
18
|
+
*/
|
|
19
|
+
export const CLOSING_REPLY_GUIDANCE = 'When you finish a task started from the SurfCAD in-viewer prompt pane, send a closing reply with reply_to_user (final: true) summarising what was done, so the user gets confirmation. On failure or partial completion, say what was done, what failed and why, and what is left.';
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* First paragraph of the MCP initialize `instructions`.
|
|
23
|
+
* Goldens pin the webhook sentence as the prefix.
|
|
24
|
+
*/
|
|
25
|
+
export const PROMPT_SERVER_INSTRUCTIONS = `call register_webhook { url, bearer? } if you can receive https webhooks, otherwise poll read_messages. ${CLOSING_REPLY_GUIDANCE}`;
|
|
12
26
|
|
|
13
27
|
/** Exact wording the agent should relay when asking the user for a webhook. */
|
|
14
28
|
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.';
|
|
@@ -73,7 +87,7 @@ export function promptToolDefinitions() {
|
|
|
73
87
|
},
|
|
74
88
|
{
|
|
75
89
|
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. 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
|
|
90
|
+
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. When you finish the task from a prompt you received here, close that chat: ${CLOSING_REPLY_GUIDANCE}`,
|
|
77
91
|
inputSchema: {
|
|
78
92
|
type: 'object',
|
|
79
93
|
additionalProperties: false,
|
|
@@ -84,12 +98,18 @@ export function promptToolDefinitions() {
|
|
|
84
98
|
maximum: 50,
|
|
85
99
|
description: 'How many queued prompts to take, oldest first. Omit to take the whole queue (at most 50).',
|
|
86
100
|
},
|
|
101
|
+
wait_ms: {
|
|
102
|
+
type: 'integer',
|
|
103
|
+
minimum: 0,
|
|
104
|
+
maximum: READ_MESSAGES_MAX_WAIT_MS,
|
|
105
|
+
description: `Long-poll: when the queue is empty, wait up to this many milliseconds (at most ${READ_MESSAGES_MAX_WAIT_MS}) for a prompt or cancel to arrive before answering, instead of returning an empty list at once. Cuts idle polling between steps; omit or 0 to return immediately.`,
|
|
106
|
+
},
|
|
87
107
|
},
|
|
88
108
|
},
|
|
89
109
|
},
|
|
90
110
|
{
|
|
91
111
|
name: 'reply_to_user',
|
|
92
|
-
description:
|
|
112
|
+
description: `${CLOSING_REPLY_GUIDANCE} The final reply is expected: it closes the task in the chat. 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
113
|
inputSchema: {
|
|
94
114
|
type: 'object',
|
|
95
115
|
additionalProperties: false,
|
|
@@ -101,24 +121,36 @@ export function promptToolDefinitions() {
|
|
|
101
121
|
},
|
|
102
122
|
text: {
|
|
103
123
|
type: 'string',
|
|
104
|
-
description: 'Plain text for the user. Not HTML.',
|
|
124
|
+
description: 'Plain text for the user. Not HTML. The closing reply (final: true) summarises what was done, or on failure or partial completion what was done, what failed and why, and what is left.',
|
|
105
125
|
},
|
|
106
126
|
final: {
|
|
107
127
|
type: 'boolean',
|
|
108
|
-
description: 'True
|
|
128
|
+
description: 'True on the closing reply that finishes the prompt. That reply is expected and summarises the result or the failure. Defaults to false.',
|
|
109
129
|
},
|
|
110
130
|
},
|
|
111
131
|
},
|
|
112
132
|
},
|
|
113
133
|
{
|
|
114
134
|
name: 'set_status',
|
|
115
|
-
description:
|
|
135
|
+
description: `Tell the SurfCAD tab what you are doing with the user's prompt: state typing (writing an answer: the chat stays open with typing dots), working (changing the model: the chat collapses and the field shows a spinner), or idle. set_status is for progress and does not close the task. You do not have to call it for working: the first model-changing tool call after a prompt sets working, a streamed reply_to_user (final false) sets typing, and a final reply or 120 seconds without activity sets idle. Set typing before a long answer so the user reads the chat instead of watching the viewport. Without id it targets the latest prompt. A cancelled id returns { ok: false, error: cancelled }. ${CLOSING_REPLY_GUIDANCE}`,
|
|
116
136
|
inputSchema: {
|
|
117
137
|
type: 'object',
|
|
118
138
|
additionalProperties: false,
|
|
119
|
-
required: ['working'],
|
|
120
139
|
properties: {
|
|
121
|
-
|
|
140
|
+
state: {
|
|
141
|
+
type: 'string',
|
|
142
|
+
enum: ['typing', 'working', 'idle'],
|
|
143
|
+
description: 'typing: you are writing an answer (the tab keeps the chat open with typing dots). working: you are changing the model (the tab collapses the chat and shows a spinner). idle: not typing or changing the model. Idle does not close the task; a closing reply_to_user does. Set typing before a long answer; model-changing tool calls set working on their own; a final reply_to_user sets idle.',
|
|
144
|
+
},
|
|
145
|
+
label: {
|
|
146
|
+
type: 'string',
|
|
147
|
+
maxLength: 120,
|
|
148
|
+
description: 'Optional short text for the tab, for example what you are working on.',
|
|
149
|
+
},
|
|
150
|
+
working: {
|
|
151
|
+
type: 'boolean',
|
|
152
|
+
description: 'Legacy form of state: true is working, false is idle. Use state.',
|
|
153
|
+
},
|
|
122
154
|
id: {
|
|
123
155
|
type: 'string',
|
|
124
156
|
description: 'Optional prompt id this status refers to.',
|
|
@@ -143,6 +175,13 @@ export async function callPromptTool(prompts, name, args) {
|
|
|
143
175
|
return { content: [{ type: 'text', text: JSON.stringify(prompts.unregisterWebhook(), null, 2) }] };
|
|
144
176
|
}
|
|
145
177
|
if (name === 'read_messages') {
|
|
178
|
+
if (args.wait_ms != null) {
|
|
179
|
+
const wait = Number(args.wait_ms);
|
|
180
|
+
if (!Number.isInteger(wait) || wait < 0 || wait > READ_MESSAGES_MAX_WAIT_MS) {
|
|
181
|
+
throw Object.assign(new Error(`wait_ms must be an integer from 0 to ${READ_MESSAGES_MAX_WAIT_MS}`), { code: 'bad_args' });
|
|
182
|
+
}
|
|
183
|
+
if (wait > 0 && typeof prompts.waitForMessage === 'function') await prompts.waitForMessage(wait);
|
|
184
|
+
}
|
|
146
185
|
const { messages, images } = prompts.readMessages(args.max);
|
|
147
186
|
if (messages.length === 0) {
|
|
148
187
|
return {
|
package/src/relay.mjs
CHANGED
|
@@ -143,12 +143,27 @@ export class RelaySession {
|
|
|
143
143
|
}
|
|
144
144
|
|
|
145
145
|
/**
|
|
146
|
-
*
|
|
146
|
+
* A tool call after a prompt arrives. A model-changing call (`mutates`)
|
|
147
|
+
* marks the agent working; a read-only call keeps the state alive.
|
|
147
148
|
* Best-effort: a dead socket does not fail the tool call.
|
|
149
|
+
* @param {{ mutates?: boolean }} [info]
|
|
148
150
|
*/
|
|
149
|
-
noteAgentToolCall() {
|
|
151
|
+
noteAgentToolCall(info = {}) {
|
|
150
152
|
try {
|
|
151
|
-
this.#prompts.noteToolCall();
|
|
153
|
+
this.#prompts.noteToolCall(info);
|
|
154
|
+
} catch {
|
|
155
|
+
/* status is advisory */
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
/**
|
|
160
|
+
* Pause the working deadline while a bridge call is in flight, then
|
|
161
|
+
* start it again when the call returns. A long tool call is activity.
|
|
162
|
+
* @param {boolean} held
|
|
163
|
+
*/
|
|
164
|
+
holdAgentWork(held) {
|
|
165
|
+
try {
|
|
166
|
+
this.#prompts.holdWork(held === true);
|
|
152
167
|
} catch {
|
|
153
168
|
/* status is advisory */
|
|
154
169
|
}
|
|
@@ -273,9 +288,13 @@ export class RelaySession {
|
|
|
273
288
|
const error = msg.error && typeof msg.error === 'object'
|
|
274
289
|
? msg.error
|
|
275
290
|
: { code: 'bridge_error', message: 'Command refused' };
|
|
291
|
+
// hint and retryable ride along when the tab sent them (the server
|
|
292
|
+
// fills in a hint from its own table when it did not).
|
|
276
293
|
waiter.reject(Object.assign(new Error(error.message || error.code || 'Bridge call failed'), {
|
|
277
294
|
code: error.code,
|
|
278
295
|
details: error.details,
|
|
296
|
+
...(typeof error.hint === 'string' && error.hint ? { hint: error.hint } : {}),
|
|
297
|
+
...(typeof error.retryable === 'boolean' ? { retryable: error.retryable } : {}),
|
|
279
298
|
}));
|
|
280
299
|
return;
|
|
281
300
|
}
|
package/src/relayMessages.mjs
CHANGED
|
@@ -21,6 +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
|
+
/** Agent → page. Contract v:1. Refreshes the working deadline without changing state. */
|
|
25
|
+
AGENT_ACTIVITY: 'agent.activity',
|
|
24
26
|
/** Page → paired agent. Contract v:1. `{ id }`. */
|
|
25
27
|
AGENT_PROMPT_CANCEL: 'agent.prompt.cancel',
|
|
26
28
|
/** Agent → page. Contract v:1. `{ id, state }`. */
|
package/src/server.mjs
CHANGED
|
@@ -2,7 +2,11 @@ import { Server } from '@modelcontextprotocol/sdk/server/index.js';
|
|
|
2
2
|
import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
|
|
3
3
|
import {
|
|
4
4
|
CallToolRequestSchema,
|
|
5
|
+
ErrorCode,
|
|
6
|
+
ListResourcesRequestSchema,
|
|
5
7
|
ListToolsRequestSchema,
|
|
8
|
+
McpError,
|
|
9
|
+
ReadResourceRequestSchema,
|
|
6
10
|
} from '@modelcontextprotocol/sdk/types.js';
|
|
7
11
|
import { bridgeToolDefinitions, loadCommandsCatalog } from './catalog.mjs';
|
|
8
12
|
import {
|
|
@@ -27,9 +31,22 @@ import {
|
|
|
27
31
|
PROMPT_WEBHOOK_ACTIVE,
|
|
28
32
|
promptToolDefinitions,
|
|
29
33
|
} from './prompt/promptTools.mjs';
|
|
34
|
+
import {
|
|
35
|
+
callGuideTool,
|
|
36
|
+
GUIDE_TOOL_NAME,
|
|
37
|
+
guideResourceContents,
|
|
38
|
+
guideResourceList,
|
|
39
|
+
guideToolDefinition,
|
|
40
|
+
SERVER_INSTRUCTIONS,
|
|
41
|
+
} from './prompt/guide.mjs';
|
|
42
|
+
import { withErrorHint, withRowHints } from './prompt/errorHints.mjs';
|
|
43
|
+
import { callListHelpersTool, LIST_HELPERS_TOOL_NAME, listHelpersToolDefinition } from './helpers.mjs';
|
|
30
44
|
|
|
31
45
|
const PAIR_TOOL_NAME = 'pair';
|
|
32
46
|
|
|
47
|
+
/** One line in the pair result; the guidance itself is guide { topic: "start" }. */
|
|
48
|
+
const PAIR_GUIDE_POINTER = 'Before the first model call read guide { topic: "start" } (how to build in SurfCAD: block out first, features first, hardware as patterned parts); guide {} lists every topic.';
|
|
49
|
+
|
|
33
50
|
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
51
|
|
|
35
52
|
/**
|
|
@@ -68,19 +85,59 @@ async function waitForPairing(attempt, waitMs) {
|
|
|
68
85
|
}
|
|
69
86
|
}
|
|
70
87
|
|
|
88
|
+
/**
|
|
89
|
+
* Compact JSON. Pretty printing put every number of a bbox or a face key on
|
|
90
|
+
* its own line and made each payload about 2.4 times larger (list_commands
|
|
91
|
+
* was 240 KB indented, 99 KB compact).
|
|
92
|
+
*/
|
|
71
93
|
function textResult(value, isError = false) {
|
|
72
94
|
return {
|
|
73
|
-
content: [{ type: 'text', text: JSON.stringify(value
|
|
95
|
+
content: [{ type: 'text', text: JSON.stringify(value) }],
|
|
74
96
|
isError,
|
|
75
97
|
};
|
|
76
98
|
}
|
|
77
99
|
|
|
100
|
+
/**
|
|
101
|
+
* Every error payload leaves with a hint (and a see pointer when the code
|
|
102
|
+
* has an errors.<code> topic); the tool name feeds the fallback hint.
|
|
103
|
+
* @param {unknown} payload
|
|
104
|
+
* @param {string} [tool]
|
|
105
|
+
*/
|
|
106
|
+
function errorResult(payload, tool) {
|
|
107
|
+
return textResult(withErrorHint(payload, { tool }), true);
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/** The `return` default over MCP. The page keeps `full`; an agent reads the script with get_script. */
|
|
111
|
+
const MCP_RETURN_DEFAULT = 'status';
|
|
112
|
+
|
|
113
|
+
/**
|
|
114
|
+
* Tools whose catalog row takes `return` (mutating tools, undo, redo,
|
|
115
|
+
* status) get `return: "status"` when the caller left it out. A catalog
|
|
116
|
+
* row without the property is an older tab contract and is left alone.
|
|
117
|
+
* @param {{ args?: { properties?: Record<string, unknown> } } | undefined} row
|
|
118
|
+
* @param {Record<string, unknown>} args
|
|
119
|
+
*/
|
|
120
|
+
export function withDefaultReturn(row, args) {
|
|
121
|
+
if (!row?.args?.properties || !Object.prototype.hasOwnProperty.call(row.args.properties, 'return')) return args;
|
|
122
|
+
if (Object.prototype.hasOwnProperty.call(args, 'return')) return args;
|
|
123
|
+
return { ...args, return: MCP_RETURN_DEFAULT };
|
|
124
|
+
}
|
|
125
|
+
|
|
78
126
|
/**
|
|
79
127
|
* Pair success is ordinary text content so every MCP client, including Claude Code,
|
|
80
128
|
* shows the note. No structuredContent and no _meta.
|
|
81
129
|
* @param {Record<string, unknown>} result
|
|
82
130
|
* @param {{ webhookRegistered: () => boolean }} prompts
|
|
83
131
|
*/
|
|
132
|
+
/**
|
|
133
|
+
* Does this bridge tool change the model? The catalog row says so
|
|
134
|
+
* (`mutates`); the name is the fallback for a catalog copy that predates it.
|
|
135
|
+
* @param {string} name
|
|
136
|
+
*/
|
|
137
|
+
function mutatingTool(name) {
|
|
138
|
+
return /^(set_script|run|insert_|invoke_helper|confirm_feature|delete_feature|rollback_to|undo|redo|create_|delete_|rename_|part_set_transform|insert_part|open_|paint_confirm|paint$|joint_commit|sheet_commit|sheet_set_params|sheet_edit|sketch_commit|slot_commit|hole_commit|git_|export_|edit_feature|pick_done|select_)/.test(name);
|
|
139
|
+
}
|
|
140
|
+
|
|
84
141
|
function pairToolResult(result, prompts) {
|
|
85
142
|
const webhookRegistered = prompts.webhookRegistered() === true;
|
|
86
143
|
const note = webhookRegistered ? PROMPT_WEBHOOK_ACTIVE : PROMPT_ONBOARDING_NOTE;
|
|
@@ -93,6 +150,8 @@ function pairToolResult(result, prompts) {
|
|
|
93
150
|
content: [
|
|
94
151
|
{ type: 'text', text: JSON.stringify(payload, null, 2) },
|
|
95
152
|
{ type: 'text', text: note },
|
|
153
|
+
// The build guidance lives in the guide tool; one pointer here, for every client.
|
|
154
|
+
{ type: 'text', text: PAIR_GUIDE_POINTER },
|
|
96
155
|
],
|
|
97
156
|
isError: false,
|
|
98
157
|
};
|
|
@@ -119,19 +178,34 @@ export async function createSurfcadMcpServer(options = {}) {
|
|
|
119
178
|
const session = options.session || new RelaySession();
|
|
120
179
|
const bridgeTools = bridgeToolDefinitions(catalog).map((tool) => augmentStatusTool(augmentScreenshotTool(tool)));
|
|
121
180
|
|
|
181
|
+
const version = loadPackageVersion();
|
|
122
182
|
const server = new Server(
|
|
123
|
-
{ name: 'surfcad-mcp', version
|
|
183
|
+
{ name: 'surfcad-mcp', version },
|
|
124
184
|
{
|
|
125
|
-
capabilities: { tools: {} },
|
|
126
|
-
instructions:
|
|
185
|
+
capabilities: { tools: {}, resources: {} },
|
|
186
|
+
instructions: SERVER_INSTRUCTIONS,
|
|
127
187
|
},
|
|
128
188
|
);
|
|
129
189
|
|
|
190
|
+
// The guide topics as resources (surfcad://guide/<topic>), the same text
|
|
191
|
+
// as guide { topic }, versioned with the package for hosts that index them.
|
|
192
|
+
server.setRequestHandler(ListResourcesRequestSchema, async () => ({
|
|
193
|
+
resources: guideResourceList(version),
|
|
194
|
+
}));
|
|
195
|
+
server.setRequestHandler(ReadResourceRequestSchema, async (request) => {
|
|
196
|
+
const uri = request.params.uri;
|
|
197
|
+
const contents = guideResourceContents(uri, version);
|
|
198
|
+
if (!contents) {
|
|
199
|
+
throw new McpError(ErrorCode.InvalidParams, `Unknown resource: ${uri}. resources/list names the surfcad://guide/<topic> resources.`);
|
|
200
|
+
}
|
|
201
|
+
return contents;
|
|
202
|
+
});
|
|
203
|
+
|
|
130
204
|
server.setRequestHandler(ListToolsRequestSchema, async () => ({
|
|
131
205
|
tools: [
|
|
132
206
|
{
|
|
133
207
|
name: PAIR_TOOL_NAME,
|
|
134
|
-
description: `Pair this MCP server to an open SurfCAD tab via the local WebSocket relay. ${pairingEnvHint()} ${PROMPT_SERVER_INSTRUCTIONS}
|
|
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.`,
|
|
135
209
|
inputSchema: {
|
|
136
210
|
type: 'object',
|
|
137
211
|
additionalProperties: false,
|
|
@@ -143,6 +217,8 @@ export async function createSurfcadMcpServer(options = {}) {
|
|
|
143
217
|
},
|
|
144
218
|
},
|
|
145
219
|
},
|
|
220
|
+
guideToolDefinition(),
|
|
221
|
+
listHelpersToolDefinition(),
|
|
146
222
|
...promptToolDefinitions(),
|
|
147
223
|
...bridgeTools,
|
|
148
224
|
],
|
|
@@ -154,14 +230,22 @@ export async function createSurfcadMcpServer(options = {}) {
|
|
|
154
230
|
? request.params.arguments
|
|
155
231
|
: {};
|
|
156
232
|
|
|
233
|
+
if (name === GUIDE_TOOL_NAME) {
|
|
234
|
+
return callGuideTool(args);
|
|
235
|
+
}
|
|
236
|
+
if (name === LIST_HELPERS_TOOL_NAME) {
|
|
237
|
+
const out = callListHelpersTool(args);
|
|
238
|
+
return out.isError ? errorResult(JSON.parse(out.content[0].text), name) : out;
|
|
239
|
+
}
|
|
240
|
+
|
|
157
241
|
if (isPromptTool(name)) {
|
|
158
242
|
if (name !== 'set_status') session.noteAgentToolCall();
|
|
159
243
|
try {
|
|
160
244
|
const out = await callPromptTool(session.prompts, name, args);
|
|
161
|
-
if (out.isError) return
|
|
245
|
+
if (out.isError) return errorResult(out.error, name);
|
|
162
246
|
return { content: out.content, isError: false };
|
|
163
247
|
} catch (err) {
|
|
164
|
-
return
|
|
248
|
+
return errorResult(toolErrorPayload(err), name);
|
|
165
249
|
}
|
|
166
250
|
}
|
|
167
251
|
|
|
@@ -170,22 +254,22 @@ export async function createSurfcadMcpServer(options = {}) {
|
|
|
170
254
|
? args.code.trim()
|
|
171
255
|
: (process.env.SURFCAD_PAIRING_CODE || '').trim();
|
|
172
256
|
if (!code) {
|
|
173
|
-
return
|
|
257
|
+
return errorResult({
|
|
174
258
|
code: 'bad_pairing_code',
|
|
175
259
|
message: `Missing pairing code. Pass { "code": "......" } or set SURFCAD_PAIRING_CODE. ${pairingEnvHint()}`,
|
|
176
|
-
},
|
|
260
|
+
}, name);
|
|
177
261
|
}
|
|
178
262
|
try {
|
|
179
263
|
const result = await waitForPairing(session.pair(code), PAIR_TOOL_WAIT_MS);
|
|
180
264
|
return pairToolResult(result, session.prompts);
|
|
181
265
|
} catch (err) {
|
|
182
|
-
return
|
|
266
|
+
return errorResult(toolErrorPayload(err), name);
|
|
183
267
|
}
|
|
184
268
|
}
|
|
185
269
|
|
|
186
270
|
const known = bridgeTools.some((t) => t.name === name);
|
|
187
271
|
if (!known) {
|
|
188
|
-
return
|
|
272
|
+
return errorResult({ code: 'unknown_tool', message: `Unknown tool: ${name}` });
|
|
189
273
|
}
|
|
190
274
|
|
|
191
275
|
// A lost session is already re-pairing in the background; session.call
|
|
@@ -196,20 +280,32 @@ export async function createSurfcadMcpServer(options = {}) {
|
|
|
196
280
|
try {
|
|
197
281
|
await waitForPairing(session.pair(envCode), AUTO_PAIR_WAIT_MS);
|
|
198
282
|
} catch (err) {
|
|
199
|
-
return
|
|
283
|
+
return errorResult(toolErrorPayload(err), name);
|
|
200
284
|
}
|
|
201
285
|
} else if (session.state !== 'pairing') {
|
|
202
|
-
return
|
|
286
|
+
return errorResult(notPairedError(), name);
|
|
203
287
|
}
|
|
204
288
|
}
|
|
205
289
|
|
|
206
290
|
try {
|
|
207
|
-
|
|
208
|
-
|
|
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.
|
|
294
|
+
const row = catalog.commands.find((c) => c.name === name);
|
|
295
|
+
session.noteAgentToolCall({ mutates: row?.mutates === true || (row?.mutates == null && mutatingTool(name)) });
|
|
296
|
+
session.holdAgentWork(true);
|
|
297
|
+
let out;
|
|
298
|
+
try {
|
|
299
|
+
out = await callPairedBridgeTool(session, name, withDefaultReturn(row, args));
|
|
300
|
+
} finally {
|
|
301
|
+
session.holdAgentWork(false);
|
|
302
|
+
}
|
|
209
303
|
if (name === 'status' && out.isError !== true && out.value && typeof out.value === 'object' && !Array.isArray(out.value)) {
|
|
210
304
|
return textResult({ ...out.value, ...session.prompts.deliveryStatus() });
|
|
211
305
|
}
|
|
212
|
-
|
|
306
|
+
if (out.isError === true) return errorResult(out.value, name);
|
|
307
|
+
// A run that failed answers ok: false with errors rows; those carry hints too.
|
|
308
|
+
return textResult(withRowHints(out.value));
|
|
213
309
|
} catch (err) {
|
|
214
310
|
const code = err?.code;
|
|
215
311
|
if (
|
|
@@ -218,13 +314,13 @@ export async function createSurfcadMcpServer(options = {}) {
|
|
|
218
314
|
|| code === 'confirm_required'
|
|
219
315
|
|| code === 'pair_rejected'
|
|
220
316
|
) {
|
|
221
|
-
return
|
|
317
|
+
return errorResult(formatBridgeError({
|
|
222
318
|
code,
|
|
223
319
|
message: err.message,
|
|
224
320
|
details: err.details,
|
|
225
|
-
}),
|
|
321
|
+
}), name);
|
|
226
322
|
}
|
|
227
|
-
return
|
|
323
|
+
return errorResult(toolErrorPayload(err), name);
|
|
228
324
|
}
|
|
229
325
|
});
|
|
230
326
|
|