webiridium-mcp 0.1.0 → 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.
Files changed (2) hide show
  1. package/package.json +2 -2
  2. package/server.mjs +298 -87
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "webiridium-mcp",
3
- "version": "0.1.0",
3
+ "version": "0.2.0",
4
4
  "description": "MCP server that lets Claude Code drive the WebIridium simulator open in your browser",
5
5
  "type": "module",
6
6
  "bin": {
@@ -13,7 +13,7 @@
13
13
  ],
14
14
  "scripts": {
15
15
  "start": "node server.mjs",
16
- "test": "node --test"
16
+ "test": "node --test test/bridge.test.mjs"
17
17
  },
18
18
  "engines": {
19
19
  "node": ">=18"
package/server.mjs CHANGED
@@ -7,11 +7,16 @@
7
7
  * of tools it offers, and runs each tool call it receives in the page (with
8
8
  * the in-app approval dialog for anything that changes the project).
9
9
  *
10
+ * Several copies can run at once (one per Claude Code session): the first
11
+ * one listens and the rest relay through it. See "Hub / peer roles" below.
12
+ *
10
13
  * Wire protocol (JSON messages over the WebSocket):
11
- * tab -> bridge { type: "hello", token, tools: [{ name, description, inputSchema }] }
12
- * bridge -> tab { type: "welcome" } | { type: "error", message }
13
- * bridge -> tab { type: "call", id, name, arguments }
14
- * tab -> bridge { type: "result", id, result: { success, message, data?, error?, verifiedPostActionState? } }
14
+ * tab -> hub { type: "hello", token, tools: [{ name, description, inputSchema }] }
15
+ * hub -> tab { type: "welcome" } | { type: "error", message }
16
+ * hub -> tab { type: "call", id, name, arguments }
17
+ * tab -> hub { type: "result", id, result: { success, message, data?, error?, verifiedPostActionState? } }
18
+ * peer -> hub { type: "peer-hello", token } then { type: "call", id, name, arguments }
19
+ * hub -> peer { type: "welcome" } | { type: "state", tab, lastRejection } | { type: "result", id, result }
15
20
  *
16
21
  * stdout carries MCP only, so all logging goes to stderr.
17
22
  */
@@ -20,7 +25,7 @@ import { randomBytes, timingSafeEqual } from "node:crypto";
20
25
  import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
21
26
  import { homedir } from "node:os";
22
27
  import { join } from "node:path";
23
- import { WebSocketServer } from "ws";
28
+ import { WebSocket, WebSocketServer } from "ws";
24
29
  import { Server } from "@modelcontextprotocol/sdk/server/index.js";
25
30
  import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
26
31
  import {
@@ -28,6 +33,9 @@ import {
28
33
  ListToolsRequestSchema,
29
34
  } from "@modelcontextprotocol/sdk/types.js";
30
35
 
36
+ const VERSION = JSON.parse(
37
+ readFileSync(new URL("./package.json", import.meta.url), "utf8"),
38
+ ).version;
31
39
  const PORT = Number(process.env.WEBIRIDIUM_BRIDGE_PORT ?? 7323);
32
40
  const HOST = "127.0.0.1";
33
41
  const HELLO_TIMEOUT_MS = 5_000;
@@ -95,12 +103,33 @@ const codesMatch = (given) => {
95
103
  };
96
104
 
97
105
  // ---------------------------------------------------------------------------
98
- // Tab connection state
106
+ // Hub / peer roles
107
+ //
108
+ // Every Claude Code session (and every `claude mcp list` health check) starts
109
+ // its own copy of this server, but only one process can listen on the port.
110
+ // That process is the hub: the tab connects to it. Every other copy connects
111
+ // to the hub as a peer and sends its tool calls through it. When the hub
112
+ // exits, the peers race to take over the port, and the tab reconnects to the
113
+ // new hub by itself. So any number of sessions can use the same tab, and no
114
+ // copy is ever left without a connection.
99
115
  // ---------------------------------------------------------------------------
100
116
 
101
- /** The one paired tab, or null. A newer paired tab replaces the older one. */
117
+ /** "starting" | "hub" | "peer" */
118
+ let role = "starting";
119
+ /** Hub: the one paired tab, or null. A newer paired tab replaces the older one. */
102
120
  let tab = null; // { socket, origin, tools }
103
- let listenError = null;
121
+ /** Hub: connected peer sockets. */
122
+ const peers = new Set();
123
+ /** Peer: the hub socket, and the tab state the hub last reported. */
124
+ let hubSocket = null;
125
+ let remoteTab = null; // { origin, tools } | null
126
+ /** Why the last connection attempt was turned away, for the status tool. */
127
+ let lastRejection = null; // { reason, origin, at }
128
+ /** Peer: the hub refused this process (pairing codes differ). */
129
+ let peerRejected = null;
130
+ let wss = null;
131
+ let stopping = false;
132
+
104
133
  let nextCallId = 1;
105
134
  const pending = new Map(); // id -> { resolve, timer }
106
135
 
@@ -112,8 +141,16 @@ const failPending = (message) => {
112
141
  }
113
142
  };
114
143
 
144
+ const settle = (msg) => {
145
+ const p = pending.get(msg.id);
146
+ if (!p) return;
147
+ clearTimeout(p.timer);
148
+ pending.delete(msg.id);
149
+ p.resolve(msg.result);
150
+ };
151
+
115
152
  const mcp = new Server(
116
- { name: "webiridium", version: "0.1.0" },
153
+ { name: "webiridium", version: VERSION },
117
154
  {
118
155
  capabilities: { tools: { listChanged: true } },
119
156
  instructions:
@@ -130,49 +167,114 @@ const notifyToolsChanged = () => {
130
167
  });
131
168
  };
132
169
 
133
- const wss = new WebSocketServer({
134
- host: HOST,
135
- port: PORT,
136
- maxPayload: 16 * 1024 * 1024,
137
- verifyClient: ({ origin }, done) => {
138
- if (isAllowedOrigin(origin)) return done(true);
139
- log("Rejected connection from origin", origin);
140
- done(false, 403, "Origin not allowed");
141
- },
170
+ /** The tab as this process sees it, whichever role it has. */
171
+ const currentTab = () => {
172
+ if (role === "hub") {
173
+ return tab ? { origin: tab.origin, tools: tab.tools } : null;
174
+ }
175
+ if (role === "peer") return remoteTab;
176
+ return null;
177
+ };
178
+
179
+ const send = (socket, msg) => {
180
+ if (socket.readyState === WebSocket.OPEN) socket.send(JSON.stringify(msg));
181
+ };
182
+
183
+ const parse = (raw) => {
184
+ try {
185
+ return JSON.parse(raw.toString());
186
+ } catch {
187
+ return null;
188
+ }
189
+ };
190
+
191
+ const notConnected = () => ({
192
+ success: false,
193
+ message: `WebIridium is not connected. Call ${STATUS_TOOL} for setup steps.`,
194
+ error: "BRIDGE_DISCONNECTED",
142
195
  });
143
196
 
144
- wss.on("listening", () => log(`Listening on ws://${HOST}:${PORT}`));
145
- wss.on("error", (err) => {
146
- listenError = err;
147
- log("WebSocket server error:", err.message);
197
+ /** Sends a call over `socket` and resolves with the result message. */
198
+ const sendCall = (socket, name, args, timeoutMs) =>
199
+ new Promise((resolve) => {
200
+ const id = nextCallId++;
201
+ const timer = setTimeout(() => {
202
+ pending.delete(id);
203
+ resolve({
204
+ success: false,
205
+ message: "WebIridium did not answer in time.",
206
+ error: "BRIDGE_TIMEOUT",
207
+ });
208
+ }, timeoutMs);
209
+ pending.set(id, { resolve, timer });
210
+ send(socket, { type: "call", id, name, arguments: args ?? {} });
211
+ });
212
+
213
+ // ----- Hub -----------------------------------------------------------------
214
+
215
+ const hubState = () => ({
216
+ type: "state",
217
+ tab: tab ? { origin: tab.origin, tools: tab.tools } : null,
218
+ lastRejection,
148
219
  });
149
220
 
150
- wss.on("connection", (socket, req) => {
221
+ const broadcastState = () => {
222
+ for (const peer of peers) send(peer, hubState());
223
+ notifyToolsChanged();
224
+ };
225
+
226
+ const reject = (reason, origin) => {
227
+ lastRejection = {
228
+ reason,
229
+ origin: origin ?? null,
230
+ at: new Date().toISOString(),
231
+ };
232
+ log(`Rejected connection (${reason})`, origin ?? "");
233
+ for (const peer of peers) send(peer, hubState());
234
+ };
235
+
236
+ const tabCall = (name, args) =>
237
+ tab
238
+ ? sendCall(tab.socket, name, args, CALL_TIMEOUT_MS)
239
+ : Promise.resolve(notConnected());
240
+
241
+ const handleConnection = (socket, req) => {
242
+ // Browsers always send Origin, so a connection without one is a local
243
+ // process: another copy of this server. Pages can never pose as a peer.
151
244
  const origin = req.headers.origin;
245
+ const isPeer = !origin;
152
246
  let paired = false;
153
247
  const helloTimer = setTimeout(() => {
154
248
  if (!paired) socket.close(4001, "No hello received");
155
249
  }, HELLO_TIMEOUT_MS);
156
250
 
157
251
  socket.on("message", (raw) => {
158
- let msg;
159
- try {
160
- msg = JSON.parse(raw.toString());
161
- } catch {
162
- return;
163
- }
252
+ const msg = parse(raw);
253
+ if (!msg) return;
164
254
 
165
255
  if (!paired) {
166
- if (msg?.type !== "hello") return;
256
+ if (msg.type !== (isPeer ? "peer-hello" : "hello")) return;
167
257
  clearTimeout(helloTimer);
168
258
  if (!codesMatch(msg.token)) {
169
- socket.send(
170
- JSON.stringify({ type: "error", message: "Wrong pairing code" }),
171
- );
259
+ if (isPeer) {
260
+ send(socket, {
261
+ type: "error",
262
+ message: "the running copy has a different pairing code",
263
+ });
264
+ } else {
265
+ reject("wrong pairing code", origin);
266
+ send(socket, { type: "error", message: "Wrong pairing code" });
267
+ }
172
268
  socket.close(4003, "Wrong pairing code");
173
269
  return;
174
270
  }
175
271
  paired = true;
272
+ if (isPeer) {
273
+ peers.add(socket);
274
+ send(socket, { type: "welcome" });
275
+ send(socket, hubState());
276
+ return;
277
+ }
176
278
  if (tab && tab.socket !== socket) {
177
279
  tab.socket.close(4000, "Replaced by another WebIridium tab");
178
280
  }
@@ -181,59 +283,135 @@ wss.on("connection", (socket, req) => {
181
283
  origin,
182
284
  tools: Array.isArray(msg.tools) ? msg.tools : [],
183
285
  };
184
- socket.send(JSON.stringify({ type: "welcome" }));
286
+ lastRejection = null;
287
+ send(socket, { type: "welcome" });
185
288
  log(`Tab paired from ${origin} with ${tab.tools.length} tools`);
186
- notifyToolsChanged();
289
+ broadcastState();
290
+ return;
291
+ }
292
+
293
+ if (isPeer) {
294
+ if (msg.type === "call") {
295
+ tabCall(String(msg.name), msg.arguments).then((result) =>
296
+ send(socket, { type: "result", id: msg.id, result }),
297
+ );
298
+ }
187
299
  return;
188
300
  }
189
301
 
190
- if (msg?.type === "tools" && tab?.socket === socket) {
302
+ if (msg.type === "tools" && tab?.socket === socket) {
191
303
  tab.tools = Array.isArray(msg.tools) ? msg.tools : [];
192
- notifyToolsChanged();
193
- } else if (msg?.type === "result") {
194
- const p = pending.get(msg.id);
195
- if (!p) return;
196
- clearTimeout(p.timer);
197
- pending.delete(msg.id);
198
- p.resolve(msg.result);
304
+ broadcastState();
305
+ } else if (msg.type === "result") {
306
+ settle(msg);
199
307
  }
200
308
  });
201
309
 
202
310
  socket.on("close", () => {
203
311
  clearTimeout(helloTimer);
312
+ peers.delete(socket);
204
313
  if (tab?.socket === socket) {
205
314
  tab = null;
206
315
  failPending("The WebIridium tab disconnected before answering.");
207
316
  log("Tab disconnected");
317
+ broadcastState();
318
+ }
319
+ });
320
+ };
321
+
322
+ // ----- Peer ----------------------------------------------------------------
323
+
324
+ const connectAsPeer = () => {
325
+ const socket = new WebSocket(`ws://${HOST}:${PORT}`);
326
+ hubSocket = socket;
327
+ let welcomed = false;
328
+
329
+ socket.on("open", () =>
330
+ send(socket, { type: "peer-hello", token: pairingCode }),
331
+ );
332
+ socket.on("message", (raw) => {
333
+ const msg = parse(raw);
334
+ if (!msg) return;
335
+ if (msg.type === "welcome") {
336
+ welcomed = true;
337
+ role = "peer";
338
+ peerRejected = null;
339
+ log("Connected to the running webiridium-mcp as a peer");
340
+ } else if (msg.type === "error") {
341
+ peerRejected = String(msg.message);
342
+ } else if (msg.type === "state") {
343
+ remoteTab = msg.tab ?? null;
344
+ lastRejection = msg.lastRejection ?? null;
208
345
  notifyToolsChanged();
346
+ } else if (msg.type === "result") {
347
+ settle(msg);
209
348
  }
210
349
  });
211
- });
350
+ // An error is always followed by "close", which retries
351
+ socket.on("error", () => {});
352
+ socket.on("close", () => {
353
+ if (hubSocket !== socket) return;
354
+ hubSocket = null;
355
+ const hadTab = Boolean(remoteTab);
356
+ remoteTab = null;
357
+ role = "starting";
358
+ failPending(
359
+ "The connection to WebIridium was handed to another Claude Code session before it answered, so it may or may not have run. Check with get_application_state, then try again.",
360
+ );
361
+ if (hadTab) notifyToolsChanged();
362
+ if (stopping) return;
363
+ if (welcomed) log("The running copy went away; taking over");
364
+ // A rejected peer would be rejected again, so retry slowly in case the
365
+ // other copy exits. Otherwise race the other peers to become the hub.
366
+ setTimeout(start, peerRejected ? 5_000 : 50 + Math.random() * 300);
367
+ });
368
+ };
212
369
 
213
- const callTab = (name, args) =>
214
- new Promise((resolve) => {
215
- if (!tab) {
216
- resolve({
217
- success: false,
218
- message: `WebIridium is not connected. Call ${STATUS_TOOL} for setup steps.`,
219
- error: "BRIDGE_DISCONNECTED",
220
- });
370
+ const callTab = (name, args) => {
371
+ if (role === "hub") return tabCall(name, args);
372
+ if (role === "peer" && hubSocket && remoteTab) {
373
+ // The hub applies its own timeout; this one only guards a silent hub
374
+ return sendCall(hubSocket, name, args, CALL_TIMEOUT_MS + 5_000);
375
+ }
376
+ return Promise.resolve(notConnected());
377
+ };
378
+
379
+ // ----- Start ---------------------------------------------------------------
380
+
381
+ /** Try to become the hub; if the port is taken, join the hub as a peer. */
382
+ function start() {
383
+ if (stopping) return;
384
+ const server = new WebSocketServer({
385
+ host: HOST,
386
+ port: PORT,
387
+ maxPayload: 16 * 1024 * 1024,
388
+ verifyClient: ({ origin }, done) => {
389
+ if (!origin || isAllowedOrigin(origin)) return done(true);
390
+ reject("website not allowed", origin);
391
+ done(false, 403, "Origin not allowed");
392
+ },
393
+ });
394
+ server.on("listening", () => {
395
+ wss = server;
396
+ role = "hub";
397
+ peerRejected = null;
398
+ log(`Listening on ws://${HOST}:${PORT}`);
399
+ });
400
+ server.on("connection", handleConnection);
401
+ server.on("error", (err) => {
402
+ if (wss === server) {
403
+ log("WebSocket server error:", err.message);
221
404
  return;
222
405
  }
223
- const id = nextCallId++;
224
- const timer = setTimeout(() => {
225
- pending.delete(id);
226
- resolve({
227
- success: false,
228
- message: "WebIridium did not answer in time.",
229
- error: "BRIDGE_TIMEOUT",
230
- });
231
- }, CALL_TIMEOUT_MS);
232
- pending.set(id, { resolve, timer });
233
- tab.socket.send(
234
- JSON.stringify({ type: "call", id, name, arguments: args ?? {} }),
235
- );
406
+ server.close();
407
+ if (err.code === "EADDRINUSE") {
408
+ connectAsPeer();
409
+ } else {
410
+ log(`Could not listen on ${HOST}:${PORT}:`, err.message);
411
+ setTimeout(start, 5_000);
412
+ }
236
413
  });
414
+ }
237
415
 
238
416
  // ---------------------------------------------------------------------------
239
417
  // MCP handlers
@@ -242,39 +420,69 @@ const callTab = (name, args) =>
242
420
  const statusTool = {
243
421
  name: STATUS_TOOL,
244
422
  description:
245
- "Reports whether a WebIridium browser tab is connected to this bridge, and if not, " +
246
- "the pairing code and steps the user needs to connect it.",
423
+ "Reports whether a WebIridium browser tab is connected, and if not, why, plus the " +
424
+ "pairing code and steps the user needs to connect it.",
247
425
  inputSchema: { type: "object", properties: {} },
248
426
  };
249
427
 
250
- const statusText = () => {
251
- if (listenError) {
428
+ const describeRejection = () => {
429
+ if (!lastRejection) return null;
430
+ const { reason, origin, at } = lastRejection;
431
+ if (reason === "website not allowed") {
252
432
  return (
253
- `The bridge could not listen on ${HOST}:${PORT} (${listenError.message}). ` +
254
- "Another Claude Code session may already be running it. Close that session, " +
255
- "or set WEBIRIDIUM_BRIDGE_PORT to a different port in this MCP server's config " +
256
- "and use the same port in WebIridium."
433
+ `A page at ${origin} tried to connect at ${at} and was turned away: only ` +
434
+ "https://sys-bio.github.io and localhost / 127.0.0.1 pages are allowed. If that " +
435
+ "was WebIridium opened through a network address, open it at localhost instead, " +
436
+ "or add the origin to WEBIRIDIUM_BRIDGE_ORIGINS in this server's config."
257
437
  );
258
438
  }
259
- if (tab) {
260
- return `Connected to WebIridium at ${tab.origin}. Tools available: ${tab.tools
261
- .map((t) => t.name)
262
- .join(", ")}.`;
439
+ return (
440
+ `A WebIridium tab at ${origin} tried to connect at ${at} with the wrong pairing ` +
441
+ `code. In WebIridium, click Disconnect, paste the code ${pairingCode} and click Connect.`
442
+ );
443
+ };
444
+
445
+ const statusText = () => {
446
+ const lines = [];
447
+ const current = currentTab();
448
+ if (current) {
449
+ lines.push(
450
+ `Connected to WebIridium at ${current.origin}. Tools available: ${current.tools
451
+ .map((t) => t.name)
452
+ .join(", ")}.`,
453
+ );
454
+ } else if (peerRejected) {
455
+ lines.push(
456
+ "Another copy of webiridium-mcp is already running with a different pairing " +
457
+ "code. Make sure every Claude Code config for webiridium uses the same " +
458
+ "WEBIRIDIUM_BRIDGE_TOKEN, or none.",
459
+ );
460
+ } else if (role === "starting") {
461
+ lines.push("The connector is reconnecting; try again in a second.");
462
+ } else {
463
+ lines.push(
464
+ "No WebIridium tab is connected. Ask the user to:",
465
+ "1. Open WebIridium (https://sys-bio.github.io/WebIridium/ or a local dev server at localhost).",
466
+ "2. Open the Chat panel, then Settings, and find 'Connect to Claude Code'.",
467
+ `3. Paste this pairing code: ${pairingCode}`,
468
+ `4. Leave the port as ${PORT} and click Connect.`,
469
+ "The tab connects within a few seconds, and the WebIridium tools then appear.",
470
+ );
263
471
  }
264
- return [
265
- "No WebIridium tab is connected. Ask the user to:",
266
- "1. Open WebIridium (https://sys-bio.github.io/WebIridium/ or their local dev server).",
267
- "2. Open the Chat panel, then Settings, and find 'Connect to Claude Code'.",
268
- `3. Paste this pairing code: ${pairingCode}`,
269
- `4. Leave the port as ${PORT} and click Connect.`,
270
- "The WebIridium tools will appear once the tab connects.",
271
- ].join("\n");
472
+ const rejection = describeRejection();
473
+ if (rejection && !current) lines.push("", rejection);
474
+ const how =
475
+ role === "hub" ? "listening" : "relaying through the running copy";
476
+ lines.push("", `(webiridium-mcp ${VERSION}, ${how} on ${HOST}:${PORT})`);
477
+ return lines.join("\n");
272
478
  };
273
479
 
274
480
  mcp.setRequestHandler(ListToolsRequestSchema, async () => ({
275
481
  tools: [
276
482
  statusTool,
277
- ...(tab?.tools ?? []).filter((t) => t?.name && t.name !== STATUS_TOOL),
483
+ ...(currentTab()?.tools ?? []).filter(
484
+ (t) => t?.name && t.name !== STATUS_TOOL,
485
+ ),
278
486
  ],
279
487
  }));
280
488
 
@@ -304,10 +512,13 @@ mcp.setRequestHandler(CallToolRequestSchema, async (request) => {
304
512
 
305
513
  await mcp.connect(new StdioServerTransport());
306
514
  log("MCP server ready on stdio");
515
+ start();
307
516
 
308
517
  const shutdown = () => {
518
+ stopping = true;
309
519
  failPending("The bridge is shutting down.");
310
- wss.close();
520
+ hubSocket?.close();
521
+ wss?.close();
311
522
  process.exit(0);
312
523
  };
313
524
  process.stdin.on("close", shutdown);