webiridium-mcp 0.0.0-stage → 0.1.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 (4) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +81 -2
  3. package/package.json +42 -4
  4. package/server.mjs +315 -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
- # Temporary Holding Version
1
+ # webiridium-mcp
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
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.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.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"
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,315 @@
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
+ * 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? } }
15
+ *
16
+ * stdout carries MCP only, so all logging goes to stderr.
17
+ */
18
+
19
+ import { randomBytes, timingSafeEqual } from "node:crypto";
20
+ import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
21
+ import { homedir } from "node:os";
22
+ import { join } from "node:path";
23
+ import { WebSocketServer } from "ws";
24
+ import { Server } from "@modelcontextprotocol/sdk/server/index.js";
25
+ import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
26
+ import {
27
+ CallToolRequestSchema,
28
+ ListToolsRequestSchema,
29
+ } from "@modelcontextprotocol/sdk/types.js";
30
+
31
+ const PORT = Number(process.env.WEBIRIDIUM_BRIDGE_PORT ?? 7323);
32
+ const HOST = "127.0.0.1";
33
+ const HELLO_TIMEOUT_MS = 5_000;
34
+ // Long enough for the user to read and answer the in-app approval dialog
35
+ const CALL_TIMEOUT_MS = 10 * 60_000;
36
+ const STATUS_TOOL = "webiridium_connection_status";
37
+
38
+ const DEFAULT_ORIGINS = ["https://sys-bio.github.io"];
39
+ const extraOrigins = (process.env.WEBIRIDIUM_BRIDGE_ORIGINS ?? "")
40
+ .split(",")
41
+ .map((o) => o.trim())
42
+ .filter(Boolean);
43
+ const allowedOrigins = new Set([...DEFAULT_ORIGINS, ...extraOrigins]);
44
+
45
+ const log = (...args) => console.error("[webiridium-mcp]", ...args);
46
+
47
+ /** Local dev servers (vite) on any port are allowed. */
48
+ const isAllowedOrigin = (origin) => {
49
+ if (!origin) return false;
50
+ if (allowedOrigins.has(origin)) return true;
51
+ try {
52
+ const url = new URL(origin);
53
+ return (
54
+ (url.protocol === "http:" || url.protocol === "https:") &&
55
+ (url.hostname === "localhost" || url.hostname === "127.0.0.1")
56
+ );
57
+ } catch {
58
+ return false;
59
+ }
60
+ };
61
+
62
+ /**
63
+ * The pairing code is kept in ~/.webiridium/bridge-token so the user pastes
64
+ * it into WebIridium once, not every time Claude Code restarts the bridge.
65
+ */
66
+ const loadPairingCode = () => {
67
+ if (process.env.WEBIRIDIUM_BRIDGE_TOKEN) {
68
+ return process.env.WEBIRIDIUM_BRIDGE_TOKEN.trim();
69
+ }
70
+ const dir = join(homedir(), ".webiridium");
71
+ const file = join(dir, "bridge-token");
72
+ try {
73
+ const saved = readFileSync(file, "utf8").trim();
74
+ if (saved) return saved;
75
+ } catch {
76
+ // not created yet
77
+ }
78
+ const code = randomBytes(12).toString("base64url");
79
+ try {
80
+ mkdirSync(dir, { recursive: true });
81
+ writeFileSync(file, code + "\n", { mode: 0o600 });
82
+ } catch (err) {
83
+ log("Could not save pairing code, using a temporary one:", err.message);
84
+ }
85
+ return code;
86
+ };
87
+
88
+ const pairingCode = loadPairingCode();
89
+
90
+ const codesMatch = (given) => {
91
+ if (typeof given !== "string") return false;
92
+ const a = Buffer.from(given.trim());
93
+ const b = Buffer.from(pairingCode);
94
+ return a.length === b.length && timingSafeEqual(a, b);
95
+ };
96
+
97
+ // ---------------------------------------------------------------------------
98
+ // Tab connection state
99
+ // ---------------------------------------------------------------------------
100
+
101
+ /** The one paired tab, or null. A newer paired tab replaces the older one. */
102
+ let tab = null; // { socket, origin, tools }
103
+ let listenError = null;
104
+ let nextCallId = 1;
105
+ const pending = new Map(); // id -> { resolve, timer }
106
+
107
+ const failPending = (message) => {
108
+ for (const [id, p] of pending) {
109
+ clearTimeout(p.timer);
110
+ p.resolve({ success: false, message, error: "BRIDGE_DISCONNECTED" });
111
+ pending.delete(id);
112
+ }
113
+ };
114
+
115
+ const mcp = new Server(
116
+ { name: "webiridium", version: "0.1.0" },
117
+ {
118
+ capabilities: { tools: { listChanged: true } },
119
+ instructions:
120
+ "These tools control the WebIridium simulator open in the user's browser. " +
121
+ `If only ${STATUS_TOOL} is listed, call it to see how to connect the tab. ` +
122
+ "Tools that change the project may show an approval dialog in WebIridium; " +
123
+ "a USER_DECLINED_ACTION result means the user said no there.",
124
+ },
125
+ );
126
+
127
+ const notifyToolsChanged = () => {
128
+ mcp.sendToolListChanged().catch(() => {
129
+ // Client may not be connected yet; it lists tools on connect anyway.
130
+ });
131
+ };
132
+
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
+ },
142
+ });
143
+
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);
148
+ });
149
+
150
+ wss.on("connection", (socket, req) => {
151
+ const origin = req.headers.origin;
152
+ let paired = false;
153
+ const helloTimer = setTimeout(() => {
154
+ if (!paired) socket.close(4001, "No hello received");
155
+ }, HELLO_TIMEOUT_MS);
156
+
157
+ socket.on("message", (raw) => {
158
+ let msg;
159
+ try {
160
+ msg = JSON.parse(raw.toString());
161
+ } catch {
162
+ return;
163
+ }
164
+
165
+ if (!paired) {
166
+ if (msg?.type !== "hello") return;
167
+ clearTimeout(helloTimer);
168
+ if (!codesMatch(msg.token)) {
169
+ socket.send(
170
+ JSON.stringify({ type: "error", message: "Wrong pairing code" }),
171
+ );
172
+ socket.close(4003, "Wrong pairing code");
173
+ return;
174
+ }
175
+ paired = true;
176
+ if (tab && tab.socket !== socket) {
177
+ tab.socket.close(4000, "Replaced by another WebIridium tab");
178
+ }
179
+ tab = {
180
+ socket,
181
+ origin,
182
+ tools: Array.isArray(msg.tools) ? msg.tools : [],
183
+ };
184
+ socket.send(JSON.stringify({ type: "welcome" }));
185
+ log(`Tab paired from ${origin} with ${tab.tools.length} tools`);
186
+ notifyToolsChanged();
187
+ return;
188
+ }
189
+
190
+ if (msg?.type === "tools" && tab?.socket === socket) {
191
+ 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);
199
+ }
200
+ });
201
+
202
+ socket.on("close", () => {
203
+ clearTimeout(helloTimer);
204
+ if (tab?.socket === socket) {
205
+ tab = null;
206
+ failPending("The WebIridium tab disconnected before answering.");
207
+ log("Tab disconnected");
208
+ notifyToolsChanged();
209
+ }
210
+ });
211
+ });
212
+
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
+ });
221
+ return;
222
+ }
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
+ );
236
+ });
237
+
238
+ // ---------------------------------------------------------------------------
239
+ // MCP handlers
240
+ // ---------------------------------------------------------------------------
241
+
242
+ const statusTool = {
243
+ name: STATUS_TOOL,
244
+ 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.",
247
+ inputSchema: { type: "object", properties: {} },
248
+ };
249
+
250
+ const statusText = () => {
251
+ if (listenError) {
252
+ 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."
257
+ );
258
+ }
259
+ if (tab) {
260
+ return `Connected to WebIridium at ${tab.origin}. Tools available: ${tab.tools
261
+ .map((t) => t.name)
262
+ .join(", ")}.`;
263
+ }
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");
272
+ };
273
+
274
+ mcp.setRequestHandler(ListToolsRequestSchema, async () => ({
275
+ tools: [
276
+ statusTool,
277
+ ...(tab?.tools ?? []).filter((t) => t?.name && t.name !== STATUS_TOOL),
278
+ ],
279
+ }));
280
+
281
+ mcp.setRequestHandler(CallToolRequestSchema, async (request) => {
282
+ const { name, arguments: args } = request.params;
283
+ if (name === STATUS_TOOL) {
284
+ return { content: [{ type: "text", text: statusText() }] };
285
+ }
286
+
287
+ const result = await callTab(name, args);
288
+ const parts = [result?.message ?? "(no message)"];
289
+ if (result?.data !== undefined) {
290
+ parts.push("Data:\n" + JSON.stringify(result.data, null, 2));
291
+ }
292
+ if (result?.verifiedPostActionState) {
293
+ parts.push(
294
+ "Application state after this action:\n" + result.verifiedPostActionState,
295
+ );
296
+ }
297
+ // A declined action is the user's answer, not a tool failure
298
+ const declined = result?.error === "USER_DECLINED_ACTION";
299
+ return {
300
+ content: [{ type: "text", text: parts.join("\n\n") }],
301
+ isError: !result?.success && !declined,
302
+ };
303
+ });
304
+
305
+ await mcp.connect(new StdioServerTransport());
306
+ log("MCP server ready on stdio");
307
+
308
+ const shutdown = () => {
309
+ failPending("The bridge is shutting down.");
310
+ wss.close();
311
+ process.exit(0);
312
+ };
313
+ process.stdin.on("close", shutdown);
314
+ process.on("SIGINT", shutdown);
315
+ process.on("SIGTERM", shutdown);