webiridium-mcp 0.0.0-stage → 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.
- package/LICENSE +21 -0
- package/README.md +81 -2
- package/package.json +42 -4
- package/server.mjs +526 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Long Nguyenle
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,82 @@
|
|
|
1
|
-
#
|
|
1
|
+
# webiridium-mcp
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
A local MCP server that lets Claude Code use the tools of a WebIridium tab open
|
|
4
|
+
in your browser: read the model and results, change simulation settings, run
|
|
5
|
+
simulations, edit the Antimony model, and move sliders.
|
|
6
|
+
|
|
7
|
+
WebIridium is a static site, so the model only exists in your browser tab. This
|
|
8
|
+
bridge runs on your computer. Claude Code talks to it over stdio, and the tab
|
|
9
|
+
connects to it over a WebSocket on `127.0.0.1`.
|
|
10
|
+
|
|
11
|
+
```
|
|
12
|
+
Claude Code ──stdio (MCP)──▶ webiridium-mcp ◀──ws://127.0.0.1:7323── WebIridium tab
|
|
13
|
+
```
|
|
14
|
+
|
|
15
|
+
## Setup
|
|
16
|
+
|
|
17
|
+
You need [Node.js](https://nodejs.org) 18 or newer and
|
|
18
|
+
[Claude Code](https://claude.com/claude-code).
|
|
19
|
+
|
|
20
|
+
1. Add the server to Claude Code. `npx` downloads it the first time it runs:
|
|
21
|
+
|
|
22
|
+
```
|
|
23
|
+
claude mcp add webiridium --scope user -- npx -y webiridium-mcp
|
|
24
|
+
```
|
|
25
|
+
|
|
26
|
+
2. In Claude Code, ask it to connect to WebIridium. It calls
|
|
27
|
+
`webiridium_connection_status`, which gives you a pairing code.
|
|
28
|
+
3. In WebIridium, open **Chat → Settings → Connect to Claude Code**, paste the
|
|
29
|
+
code and click **Connect**.
|
|
30
|
+
|
|
31
|
+
The WebIridium tools appear in Claude Code once the tab connects. The tab
|
|
32
|
+
reconnects by itself after a reload or a Claude Code restart.
|
|
33
|
+
|
|
34
|
+
## Safety
|
|
35
|
+
|
|
36
|
+
- The bridge listens on `127.0.0.1` only.
|
|
37
|
+
- It only accepts connections from `https://sys-bio.github.io` and local dev
|
|
38
|
+
servers (`localhost` / `127.0.0.1` on any port). Add more with
|
|
39
|
+
`WEBIRIDIUM_BRIDGE_ORIGINS` (comma-separated).
|
|
40
|
+
- A tab must send the pairing code before it can receive calls. The code is
|
|
41
|
+
saved in `~/.webiridium/bridge-token`. Delete that file to get a new one.
|
|
42
|
+
- Changes to the project still show WebIridium's approval dialog, unless
|
|
43
|
+
"Ask for user confirmation" is turned off in chat settings.
|
|
44
|
+
- Only one tab is connected at a time. A newly paired tab replaces the old one.
|
|
45
|
+
|
|
46
|
+
## Options
|
|
47
|
+
|
|
48
|
+
| Variable | Default | Meaning |
|
|
49
|
+
| --------------------------- | --------------------------- | ----------------------------------------- |
|
|
50
|
+
| `WEBIRIDIUM_BRIDGE_PORT` | `7323` | WebSocket port (set the same port in-app) |
|
|
51
|
+
| `WEBIRIDIUM_BRIDGE_TOKEN` | saved random code | Use a fixed pairing code instead |
|
|
52
|
+
| `WEBIRIDIUM_BRIDGE_ORIGINS` | `https://sys-bio.github.io` | Extra page origins allowed to connect |
|
|
53
|
+
|
|
54
|
+
## Protocol
|
|
55
|
+
|
|
56
|
+
JSON messages over the WebSocket:
|
|
57
|
+
|
|
58
|
+
| Direction | Message |
|
|
59
|
+
| ------------ | ----------------------------------------------------------------------- |
|
|
60
|
+
| tab → bridge | `{ type: "hello", token, tools: [{ name, description, inputSchema }] }` |
|
|
61
|
+
| bridge → tab | `{ type: "welcome" }` or `{ type: "error", message }` |
|
|
62
|
+
| bridge → tab | `{ type: "call", id, name, arguments }` |
|
|
63
|
+
| tab → bridge | `{ type: "result", id, result }` (a `ToolExecutionResult`) |
|
|
64
|
+
|
|
65
|
+
## Development
|
|
66
|
+
|
|
67
|
+
```
|
|
68
|
+
npm install
|
|
69
|
+
npm test
|
|
70
|
+
```
|
|
71
|
+
|
|
72
|
+
To try a local copy with Claude Code:
|
|
73
|
+
|
|
74
|
+
```
|
|
75
|
+
claude mcp add webiridium-dev -- node /path/to/webiridium-mcp/server.mjs
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
See [RELEASING.md](./RELEASING.md) for publishing to npm.
|
|
79
|
+
|
|
80
|
+
## License
|
|
81
|
+
|
|
82
|
+
MIT
|
package/package.json
CHANGED
|
@@ -1,6 +1,44 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "webiridium-mcp",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.2.0",
|
|
4
|
+
"description": "MCP server that lets Claude Code drive the WebIridium simulator open in your browser",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"bin": {
|
|
7
|
+
"webiridium-mcp": "server.mjs"
|
|
8
|
+
},
|
|
9
|
+
"files": [
|
|
10
|
+
"server.mjs",
|
|
11
|
+
"README.md",
|
|
12
|
+
"LICENSE"
|
|
13
|
+
],
|
|
14
|
+
"scripts": {
|
|
15
|
+
"start": "node server.mjs",
|
|
16
|
+
"test": "node --test test/bridge.test.mjs"
|
|
17
|
+
},
|
|
18
|
+
"engines": {
|
|
19
|
+
"node": ">=18"
|
|
20
|
+
},
|
|
21
|
+
"dependencies": {
|
|
22
|
+
"@modelcontextprotocol/sdk": "^1.11.1",
|
|
23
|
+
"ws": "^8.18.2"
|
|
24
|
+
},
|
|
25
|
+
"keywords": [
|
|
26
|
+
"mcp",
|
|
27
|
+
"model-context-protocol",
|
|
28
|
+
"claude",
|
|
29
|
+
"claude-code",
|
|
30
|
+
"webiridium",
|
|
31
|
+
"antimony",
|
|
32
|
+
"systems-biology"
|
|
33
|
+
],
|
|
34
|
+
"author": "Long Nguyenle",
|
|
35
|
+
"license": "MIT",
|
|
36
|
+
"repository": {
|
|
37
|
+
"type": "git",
|
|
38
|
+
"url": "git+https://github.com/lognguyenle/webiridium-mcp.git"
|
|
39
|
+
},
|
|
40
|
+
"homepage": "https://github.com/lognguyenle/webiridium-mcp#readme",
|
|
41
|
+
"bugs": {
|
|
42
|
+
"url": "https://github.com/lognguyenle/webiridium-mcp/issues"
|
|
43
|
+
}
|
|
44
|
+
}
|
package/server.mjs
ADDED
|
@@ -0,0 +1,526 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/**
|
|
3
|
+
* WebIridium MCP bridge.
|
|
4
|
+
*
|
|
5
|
+
* Claude Code starts this process and talks MCP to it over stdio. The open
|
|
6
|
+
* WebIridium tab connects to it over a WebSocket on 127.0.0.1, sends the list
|
|
7
|
+
* of tools it offers, and runs each tool call it receives in the page (with
|
|
8
|
+
* the in-app approval dialog for anything that changes the project).
|
|
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
|
+
*
|
|
13
|
+
* Wire protocol (JSON messages over the WebSocket):
|
|
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 }
|
|
20
|
+
*
|
|
21
|
+
* stdout carries MCP only, so all logging goes to stderr.
|
|
22
|
+
*/
|
|
23
|
+
|
|
24
|
+
import { randomBytes, timingSafeEqual } from "node:crypto";
|
|
25
|
+
import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
|
26
|
+
import { homedir } from "node:os";
|
|
27
|
+
import { join } from "node:path";
|
|
28
|
+
import { WebSocket, WebSocketServer } from "ws";
|
|
29
|
+
import { Server } from "@modelcontextprotocol/sdk/server/index.js";
|
|
30
|
+
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
|
|
31
|
+
import {
|
|
32
|
+
CallToolRequestSchema,
|
|
33
|
+
ListToolsRequestSchema,
|
|
34
|
+
} from "@modelcontextprotocol/sdk/types.js";
|
|
35
|
+
|
|
36
|
+
const VERSION = JSON.parse(
|
|
37
|
+
readFileSync(new URL("./package.json", import.meta.url), "utf8"),
|
|
38
|
+
).version;
|
|
39
|
+
const PORT = Number(process.env.WEBIRIDIUM_BRIDGE_PORT ?? 7323);
|
|
40
|
+
const HOST = "127.0.0.1";
|
|
41
|
+
const HELLO_TIMEOUT_MS = 5_000;
|
|
42
|
+
// Long enough for the user to read and answer the in-app approval dialog
|
|
43
|
+
const CALL_TIMEOUT_MS = 10 * 60_000;
|
|
44
|
+
const STATUS_TOOL = "webiridium_connection_status";
|
|
45
|
+
|
|
46
|
+
const DEFAULT_ORIGINS = ["https://sys-bio.github.io"];
|
|
47
|
+
const extraOrigins = (process.env.WEBIRIDIUM_BRIDGE_ORIGINS ?? "")
|
|
48
|
+
.split(",")
|
|
49
|
+
.map((o) => o.trim())
|
|
50
|
+
.filter(Boolean);
|
|
51
|
+
const allowedOrigins = new Set([...DEFAULT_ORIGINS, ...extraOrigins]);
|
|
52
|
+
|
|
53
|
+
const log = (...args) => console.error("[webiridium-mcp]", ...args);
|
|
54
|
+
|
|
55
|
+
/** Local dev servers (vite) on any port are allowed. */
|
|
56
|
+
const isAllowedOrigin = (origin) => {
|
|
57
|
+
if (!origin) return false;
|
|
58
|
+
if (allowedOrigins.has(origin)) return true;
|
|
59
|
+
try {
|
|
60
|
+
const url = new URL(origin);
|
|
61
|
+
return (
|
|
62
|
+
(url.protocol === "http:" || url.protocol === "https:") &&
|
|
63
|
+
(url.hostname === "localhost" || url.hostname === "127.0.0.1")
|
|
64
|
+
);
|
|
65
|
+
} catch {
|
|
66
|
+
return false;
|
|
67
|
+
}
|
|
68
|
+
};
|
|
69
|
+
|
|
70
|
+
/**
|
|
71
|
+
* The pairing code is kept in ~/.webiridium/bridge-token so the user pastes
|
|
72
|
+
* it into WebIridium once, not every time Claude Code restarts the bridge.
|
|
73
|
+
*/
|
|
74
|
+
const loadPairingCode = () => {
|
|
75
|
+
if (process.env.WEBIRIDIUM_BRIDGE_TOKEN) {
|
|
76
|
+
return process.env.WEBIRIDIUM_BRIDGE_TOKEN.trim();
|
|
77
|
+
}
|
|
78
|
+
const dir = join(homedir(), ".webiridium");
|
|
79
|
+
const file = join(dir, "bridge-token");
|
|
80
|
+
try {
|
|
81
|
+
const saved = readFileSync(file, "utf8").trim();
|
|
82
|
+
if (saved) return saved;
|
|
83
|
+
} catch {
|
|
84
|
+
// not created yet
|
|
85
|
+
}
|
|
86
|
+
const code = randomBytes(12).toString("base64url");
|
|
87
|
+
try {
|
|
88
|
+
mkdirSync(dir, { recursive: true });
|
|
89
|
+
writeFileSync(file, code + "\n", { mode: 0o600 });
|
|
90
|
+
} catch (err) {
|
|
91
|
+
log("Could not save pairing code, using a temporary one:", err.message);
|
|
92
|
+
}
|
|
93
|
+
return code;
|
|
94
|
+
};
|
|
95
|
+
|
|
96
|
+
const pairingCode = loadPairingCode();
|
|
97
|
+
|
|
98
|
+
const codesMatch = (given) => {
|
|
99
|
+
if (typeof given !== "string") return false;
|
|
100
|
+
const a = Buffer.from(given.trim());
|
|
101
|
+
const b = Buffer.from(pairingCode);
|
|
102
|
+
return a.length === b.length && timingSafeEqual(a, b);
|
|
103
|
+
};
|
|
104
|
+
|
|
105
|
+
// ---------------------------------------------------------------------------
|
|
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.
|
|
115
|
+
// ---------------------------------------------------------------------------
|
|
116
|
+
|
|
117
|
+
/** "starting" | "hub" | "peer" */
|
|
118
|
+
let role = "starting";
|
|
119
|
+
/** Hub: the one paired tab, or null. A newer paired tab replaces the older one. */
|
|
120
|
+
let tab = null; // { socket, origin, tools }
|
|
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
|
+
|
|
133
|
+
let nextCallId = 1;
|
|
134
|
+
const pending = new Map(); // id -> { resolve, timer }
|
|
135
|
+
|
|
136
|
+
const failPending = (message) => {
|
|
137
|
+
for (const [id, p] of pending) {
|
|
138
|
+
clearTimeout(p.timer);
|
|
139
|
+
p.resolve({ success: false, message, error: "BRIDGE_DISCONNECTED" });
|
|
140
|
+
pending.delete(id);
|
|
141
|
+
}
|
|
142
|
+
};
|
|
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
|
+
|
|
152
|
+
const mcp = new Server(
|
|
153
|
+
{ name: "webiridium", version: VERSION },
|
|
154
|
+
{
|
|
155
|
+
capabilities: { tools: { listChanged: true } },
|
|
156
|
+
instructions:
|
|
157
|
+
"These tools control the WebIridium simulator open in the user's browser. " +
|
|
158
|
+
`If only ${STATUS_TOOL} is listed, call it to see how to connect the tab. ` +
|
|
159
|
+
"Tools that change the project may show an approval dialog in WebIridium; " +
|
|
160
|
+
"a USER_DECLINED_ACTION result means the user said no there.",
|
|
161
|
+
},
|
|
162
|
+
);
|
|
163
|
+
|
|
164
|
+
const notifyToolsChanged = () => {
|
|
165
|
+
mcp.sendToolListChanged().catch(() => {
|
|
166
|
+
// Client may not be connected yet; it lists tools on connect anyway.
|
|
167
|
+
});
|
|
168
|
+
};
|
|
169
|
+
|
|
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",
|
|
195
|
+
});
|
|
196
|
+
|
|
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,
|
|
219
|
+
});
|
|
220
|
+
|
|
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.
|
|
244
|
+
const origin = req.headers.origin;
|
|
245
|
+
const isPeer = !origin;
|
|
246
|
+
let paired = false;
|
|
247
|
+
const helloTimer = setTimeout(() => {
|
|
248
|
+
if (!paired) socket.close(4001, "No hello received");
|
|
249
|
+
}, HELLO_TIMEOUT_MS);
|
|
250
|
+
|
|
251
|
+
socket.on("message", (raw) => {
|
|
252
|
+
const msg = parse(raw);
|
|
253
|
+
if (!msg) return;
|
|
254
|
+
|
|
255
|
+
if (!paired) {
|
|
256
|
+
if (msg.type !== (isPeer ? "peer-hello" : "hello")) return;
|
|
257
|
+
clearTimeout(helloTimer);
|
|
258
|
+
if (!codesMatch(msg.token)) {
|
|
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
|
+
}
|
|
268
|
+
socket.close(4003, "Wrong pairing code");
|
|
269
|
+
return;
|
|
270
|
+
}
|
|
271
|
+
paired = true;
|
|
272
|
+
if (isPeer) {
|
|
273
|
+
peers.add(socket);
|
|
274
|
+
send(socket, { type: "welcome" });
|
|
275
|
+
send(socket, hubState());
|
|
276
|
+
return;
|
|
277
|
+
}
|
|
278
|
+
if (tab && tab.socket !== socket) {
|
|
279
|
+
tab.socket.close(4000, "Replaced by another WebIridium tab");
|
|
280
|
+
}
|
|
281
|
+
tab = {
|
|
282
|
+
socket,
|
|
283
|
+
origin,
|
|
284
|
+
tools: Array.isArray(msg.tools) ? msg.tools : [],
|
|
285
|
+
};
|
|
286
|
+
lastRejection = null;
|
|
287
|
+
send(socket, { type: "welcome" });
|
|
288
|
+
log(`Tab paired from ${origin} with ${tab.tools.length} tools`);
|
|
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
|
+
}
|
|
299
|
+
return;
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
if (msg.type === "tools" && tab?.socket === socket) {
|
|
303
|
+
tab.tools = Array.isArray(msg.tools) ? msg.tools : [];
|
|
304
|
+
broadcastState();
|
|
305
|
+
} else if (msg.type === "result") {
|
|
306
|
+
settle(msg);
|
|
307
|
+
}
|
|
308
|
+
});
|
|
309
|
+
|
|
310
|
+
socket.on("close", () => {
|
|
311
|
+
clearTimeout(helloTimer);
|
|
312
|
+
peers.delete(socket);
|
|
313
|
+
if (tab?.socket === socket) {
|
|
314
|
+
tab = null;
|
|
315
|
+
failPending("The WebIridium tab disconnected before answering.");
|
|
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;
|
|
345
|
+
notifyToolsChanged();
|
|
346
|
+
} else if (msg.type === "result") {
|
|
347
|
+
settle(msg);
|
|
348
|
+
}
|
|
349
|
+
});
|
|
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
|
+
};
|
|
369
|
+
|
|
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);
|
|
404
|
+
return;
|
|
405
|
+
}
|
|
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
|
+
}
|
|
413
|
+
});
|
|
414
|
+
}
|
|
415
|
+
|
|
416
|
+
// ---------------------------------------------------------------------------
|
|
417
|
+
// MCP handlers
|
|
418
|
+
// ---------------------------------------------------------------------------
|
|
419
|
+
|
|
420
|
+
const statusTool = {
|
|
421
|
+
name: STATUS_TOOL,
|
|
422
|
+
description:
|
|
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.",
|
|
425
|
+
inputSchema: { type: "object", properties: {} },
|
|
426
|
+
};
|
|
427
|
+
|
|
428
|
+
const describeRejection = () => {
|
|
429
|
+
if (!lastRejection) return null;
|
|
430
|
+
const { reason, origin, at } = lastRejection;
|
|
431
|
+
if (reason === "website not allowed") {
|
|
432
|
+
return (
|
|
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."
|
|
437
|
+
);
|
|
438
|
+
}
|
|
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
|
+
);
|
|
471
|
+
}
|
|
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");
|
|
478
|
+
};
|
|
479
|
+
|
|
480
|
+
mcp.setRequestHandler(ListToolsRequestSchema, async () => ({
|
|
481
|
+
tools: [
|
|
482
|
+
statusTool,
|
|
483
|
+
...(currentTab()?.tools ?? []).filter(
|
|
484
|
+
(t) => t?.name && t.name !== STATUS_TOOL,
|
|
485
|
+
),
|
|
486
|
+
],
|
|
487
|
+
}));
|
|
488
|
+
|
|
489
|
+
mcp.setRequestHandler(CallToolRequestSchema, async (request) => {
|
|
490
|
+
const { name, arguments: args } = request.params;
|
|
491
|
+
if (name === STATUS_TOOL) {
|
|
492
|
+
return { content: [{ type: "text", text: statusText() }] };
|
|
493
|
+
}
|
|
494
|
+
|
|
495
|
+
const result = await callTab(name, args);
|
|
496
|
+
const parts = [result?.message ?? "(no message)"];
|
|
497
|
+
if (result?.data !== undefined) {
|
|
498
|
+
parts.push("Data:\n" + JSON.stringify(result.data, null, 2));
|
|
499
|
+
}
|
|
500
|
+
if (result?.verifiedPostActionState) {
|
|
501
|
+
parts.push(
|
|
502
|
+
"Application state after this action:\n" + result.verifiedPostActionState,
|
|
503
|
+
);
|
|
504
|
+
}
|
|
505
|
+
// A declined action is the user's answer, not a tool failure
|
|
506
|
+
const declined = result?.error === "USER_DECLINED_ACTION";
|
|
507
|
+
return {
|
|
508
|
+
content: [{ type: "text", text: parts.join("\n\n") }],
|
|
509
|
+
isError: !result?.success && !declined,
|
|
510
|
+
};
|
|
511
|
+
});
|
|
512
|
+
|
|
513
|
+
await mcp.connect(new StdioServerTransport());
|
|
514
|
+
log("MCP server ready on stdio");
|
|
515
|
+
start();
|
|
516
|
+
|
|
517
|
+
const shutdown = () => {
|
|
518
|
+
stopping = true;
|
|
519
|
+
failPending("The bridge is shutting down.");
|
|
520
|
+
hubSocket?.close();
|
|
521
|
+
wss?.close();
|
|
522
|
+
process.exit(0);
|
|
523
|
+
};
|
|
524
|
+
process.stdin.on("close", shutdown);
|
|
525
|
+
process.on("SIGINT", shutdown);
|
|
526
|
+
process.on("SIGTERM", shutdown);
|