surfcad-mcp 0.0.1 → 0.2.0

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,16 @@
1
+ import { readFileSync } from 'node:fs';
2
+ import { dirname, join } from 'node:path';
3
+ import { fileURLToPath } from 'node:url';
4
+
5
+ const PKG_ROOT = join(dirname(fileURLToPath(import.meta.url)), '..');
6
+
7
+ /** @returns {string} Semver from packages/surfcad-mcp/package.json */
8
+ export function loadPackageVersion() {
9
+ const raw = readFileSync(join(PKG_ROOT, 'package.json'), 'utf8');
10
+ const doc = JSON.parse(raw);
11
+ const version = doc?.version;
12
+ if (typeof version !== 'string' || !version.trim()) {
13
+ throw new Error('package.json is missing a version field');
14
+ }
15
+ return version.trim();
16
+ }
package/src/relay.mjs ADDED
@@ -0,0 +1,119 @@
1
+ import { WebSocket } from 'ws';
2
+ import { connectPeer } from './nodeClient.mjs';
3
+ import { PAIR_MSG } from './relayMessages.mjs';
4
+
5
+ const DEFAULT_WS_URL = 'ws://127.0.0.1:17341';
6
+
7
+ export function defaultRelayUrl() {
8
+ const fromEnv = process.env.SURFCAD_AGENT_BRIDGE_WS_URL;
9
+ if (typeof fromEnv === 'string' && fromEnv.trim()) return fromEnv.trim();
10
+ return DEFAULT_WS_URL;
11
+ }
12
+
13
+ /**
14
+ * @param {WebSocket} ws
15
+ * @param {string} command
16
+ * @param {Record<string, unknown>} args
17
+ * @param {string | number} id
18
+ */
19
+ export function invokeBridge(ws, command, args = {}, id = '1') {
20
+ return new Promise((resolve, reject) => {
21
+ const onMessage = (raw) => {
22
+ let msg;
23
+ try {
24
+ msg = JSON.parse(String(raw));
25
+ } catch {
26
+ return;
27
+ }
28
+ if (msg?.id !== id) return;
29
+ ws.off('message', onMessage);
30
+ if (msg.ok === true) {
31
+ resolve(msg.result);
32
+ return;
33
+ }
34
+ const error = msg.error && typeof msg.error === 'object'
35
+ ? msg.error
36
+ : { code: 'bridge_error', message: 'Command refused' };
37
+ reject(Object.assign(new Error(error.message || error.code || 'Bridge call failed'), {
38
+ code: error.code,
39
+ details: error.details,
40
+ }));
41
+ };
42
+ ws.on('message', onMessage);
43
+ ws.send(JSON.stringify({ id, command, args }));
44
+ });
45
+ }
46
+
47
+ export class RelaySession {
48
+ /** @type {WebSocket | null} */
49
+ #ws = null;
50
+ #url;
51
+ #code = '';
52
+
53
+ constructor(options = {}) {
54
+ this.#url = options.url || defaultRelayUrl();
55
+ }
56
+
57
+ get url() {
58
+ return this.#url;
59
+ }
60
+
61
+ get pairingCode() {
62
+ return this.#code;
63
+ }
64
+
65
+ isPaired() {
66
+ return this.#ws != null && this.#ws.readyState === WebSocket.OPEN;
67
+ }
68
+
69
+ /**
70
+ * @param {string} token
71
+ */
72
+ async pair(token) {
73
+ const code = String(token || '').trim().toUpperCase();
74
+ if (!code) {
75
+ throw Object.assign(new Error('Pairing code is required'), { code: 'bad_pairing_code' });
76
+ }
77
+ if (this.#ws) {
78
+ try { this.#ws.close(); } catch { /* noop */ }
79
+ this.#ws = null;
80
+ }
81
+ this.#code = code;
82
+ try {
83
+ this.#ws = await connectPeer(this.#url, code);
84
+ } catch (err) {
85
+ const message = err instanceof Error ? err.message : String(err);
86
+ if (/rejected/i.test(message) || message.includes('pair_rejected')) {
87
+ throw Object.assign(new Error('Pairing rejected in SurfCAD (user clicked Deny)'), {
88
+ code: 'pair_rejected',
89
+ });
90
+ }
91
+ if (/unknown_token/i.test(message)) {
92
+ throw Object.assign(new Error('No SurfCAD tab is showing this pairing code'), {
93
+ code: 'unknown_token',
94
+ });
95
+ }
96
+ throw Object.assign(new Error(message), { code: err?.code || 'pair_failed' });
97
+ }
98
+ this.#ws.on('close', () => {
99
+ this.#ws = null;
100
+ });
101
+ return { paired: true, token: code, relay: this.#url };
102
+ }
103
+
104
+ async call(command, args = {}) {
105
+ if (!this.isPaired()) {
106
+ throw Object.assign(new Error('Not paired'), { code: 'not_paired' });
107
+ }
108
+ return invokeBridge(this.#ws, command, args, `mcp-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`);
109
+ }
110
+
111
+ disconnect() {
112
+ if (this.#ws) {
113
+ try { this.#ws.close(); } catch { /* noop */ }
114
+ this.#ws = null;
115
+ }
116
+ }
117
+ }
118
+
119
+ export { PAIR_MSG };
@@ -0,0 +1,16 @@
1
+ /**
2
+ * Wire message types for the SurfCAD M1 agent-bridge relay (browser tab ↔ local peer).
3
+ * Kept in sync with `src/agent/ws/relayHub.js` in the SurfCAD monorepo.
4
+ */
5
+ export const PAIR_MSG = Object.freeze({
6
+ ERROR: 'error',
7
+ REGISTER_TAB: 'register_tab',
8
+ PAIR: 'pair',
9
+ PAIR_REQUEST: 'pair_request',
10
+ PAIR_APPROVE: 'pair_approve',
11
+ PAIR_REJECT: 'pair_reject',
12
+ PAIRED: 'paired',
13
+ UNPAIRED: 'unpaired',
14
+ CALL: 'call',
15
+ RESPONSE: 'response',
16
+ });
package/src/server.mjs ADDED
@@ -0,0 +1,169 @@
1
+ import { Server } from '@modelcontextprotocol/sdk/server/index.js';
2
+ import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
3
+ import {
4
+ CallToolRequestSchema,
5
+ ListToolsRequestSchema,
6
+ } from '@modelcontextprotocol/sdk/types.js';
7
+ import { bridgeToolDefinitions, loadCommandsCatalog } from './catalog.mjs';
8
+ import { formatBridgeError, notPairedError, pairingEnvHint } from './errors.mjs';
9
+ import { loadPackageVersion } from './packageVersion.mjs';
10
+ import { ensureAgentBridgeRelay, stopAgentBridgeRelay } from './bridge/relayServer.mjs';
11
+ import { RelaySession } from './relay.mjs';
12
+
13
+ const PAIR_TOOL_NAME = 'pair';
14
+
15
+ function textResult(value, isError = false) {
16
+ return {
17
+ content: [{ type: 'text', text: JSON.stringify(value, null, 2) }],
18
+ isError,
19
+ };
20
+ }
21
+
22
+ function toolErrorPayload(err) {
23
+ if (err && typeof err === 'object' && err.code) {
24
+ return formatBridgeError({
25
+ code: err.code,
26
+ message: err.message,
27
+ details: err.details,
28
+ });
29
+ }
30
+ return formatBridgeError({ message: String(err?.message || err) });
31
+ }
32
+
33
+ /**
34
+ * @param {{ catalog?: ReturnType<typeof loadCommandsCatalog>, session?: RelaySession, autoPair?: boolean }} [options]
35
+ */
36
+ export async function createSurfcadMcpServer(options = {}) {
37
+ const catalog = options.catalog || loadCommandsCatalog();
38
+ const session = options.session || new RelaySession();
39
+ const bridgeTools = bridgeToolDefinitions(catalog);
40
+
41
+ const server = new Server(
42
+ { name: 'surfcad-mcp', version: loadPackageVersion() },
43
+ { capabilities: { tools: {} } },
44
+ );
45
+
46
+ server.setRequestHandler(ListToolsRequestSchema, async () => ({
47
+ tools: [
48
+ {
49
+ name: PAIR_TOOL_NAME,
50
+ description: `Pair this MCP server to an open SurfCAD tab via the local WebSocket relay. ${pairingEnvHint()}`,
51
+ inputSchema: {
52
+ type: 'object',
53
+ additionalProperties: false,
54
+ properties: {
55
+ code: {
56
+ type: 'string',
57
+ description: '6-character pairing code from the SurfCAD Local agent panel',
58
+ },
59
+ },
60
+ },
61
+ },
62
+ ...bridgeTools,
63
+ ],
64
+ }));
65
+
66
+ server.setRequestHandler(CallToolRequestSchema, async (request) => {
67
+ const name = request.params.name;
68
+ const args = request.params.arguments && typeof request.params.arguments === 'object'
69
+ ? request.params.arguments
70
+ : {};
71
+
72
+ if (name === PAIR_TOOL_NAME) {
73
+ const code = typeof args.code === 'string' && args.code.trim()
74
+ ? args.code.trim()
75
+ : (process.env.SURFCAD_PAIRING_CODE || '').trim();
76
+ if (!code) {
77
+ return textResult({
78
+ code: 'bad_pairing_code',
79
+ message: `Missing pairing code. Pass { "code": "......" } or set SURFCAD_PAIRING_CODE. ${pairingEnvHint()}`,
80
+ }, true);
81
+ }
82
+ try {
83
+ const result = await session.pair(code);
84
+ return textResult(result);
85
+ } catch (err) {
86
+ return textResult(toolErrorPayload(err), true);
87
+ }
88
+ }
89
+
90
+ const known = bridgeTools.some((t) => t.name === name);
91
+ if (!known) {
92
+ return textResult({ code: 'unknown_tool', message: `Unknown tool: ${name}` }, true);
93
+ }
94
+
95
+ if (!session.isPaired()) {
96
+ const envCode = (process.env.SURFCAD_PAIRING_CODE || '').trim();
97
+ if (envCode) {
98
+ try {
99
+ await session.pair(envCode);
100
+ } catch (err) {
101
+ return textResult(toolErrorPayload(err), true);
102
+ }
103
+ } else {
104
+ return textResult(notPairedError(), true);
105
+ }
106
+ }
107
+
108
+ try {
109
+ const result = await session.call(name, args);
110
+ return textResult(result);
111
+ } catch (err) {
112
+ const code = err?.code;
113
+ if (code === 'real_repo_blocked' || code === 'confirm_required' || code === 'pair_rejected') {
114
+ return textResult(formatBridgeError({
115
+ code,
116
+ message: err.message,
117
+ details: err.details,
118
+ }), true);
119
+ }
120
+ return textResult(toolErrorPayload(err), true);
121
+ }
122
+ });
123
+
124
+ return { server, session, catalog, bridgeTools };
125
+ }
126
+
127
+ /**
128
+ * @param {{ autoPairFromEnv?: boolean }} [options]
129
+ */
130
+ export async function runSurfcadMcpServer(options = {}) {
131
+ /** @type {Awaited<ReturnType<typeof ensureAgentBridgeRelay>> | null} */
132
+ let ownedRelay = null;
133
+ if (options.startRelay !== false && process.env.SURFCAD_MCP_START_RELAY !== '0') {
134
+ const relay = await ensureAgentBridgeRelay({
135
+ onReady: (url) => {
136
+ if (process.env.SURFCAD_AGENT_BRIDGE_WS_VERBOSE === '1') {
137
+ console.error(`[surfcad-mcp] Agent bridge relay on ${url}`);
138
+ }
139
+ },
140
+ });
141
+ if (relay.ownsServer) ownedRelay = relay;
142
+ }
143
+
144
+ const onStdinClosed = () => {
145
+ if (ownedRelay) {
146
+ const closing = ownedRelay;
147
+ ownedRelay = null;
148
+ void stopAgentBridgeRelay(closing).finally(() => {
149
+ setTimeout(() => process.exit(0), 0).unref();
150
+ });
151
+ return;
152
+ }
153
+ setTimeout(() => process.exit(0), 0).unref();
154
+ };
155
+ process.stdin.once('end', onStdinClosed);
156
+
157
+ const { server, session } = await createSurfcadMcpServer();
158
+ const transport = new StdioServerTransport();
159
+ await server.connect(transport);
160
+
161
+ const envCode = (process.env.SURFCAD_PAIRING_CODE || '').trim();
162
+ if (options.autoPairFromEnv !== false && envCode) {
163
+ session.pair(envCode).catch(() => {
164
+ /* user may approve later; tools will retry */
165
+ });
166
+ }
167
+
168
+ return { server, session, transport };
169
+ }