Spaces:
Running
Running
File size: 6,710 Bytes
7c91152 8ff66cf 7c91152 8ff66cf 7c91152 935600d 7c91152 935600d 7c91152 8ff66cf 7c91152 935600d 7c91152 935600d 7c91152 8ff66cf 7c91152 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 | // The page's end of the MCP bridge. tools/mcp/server.mjs, which Claude Code (or another MCP client) runs on
// this computer, serves a WebSocket on 127.0.0.1; this page connects to it when asked to: ?bridge (or
// ?bridge=PORT) in its URL, or the Agent tab's Connect button. The server sends the client's tool calls; the
// page runs them one at a time, with the tools its own agent uses, and sends each result back.
//
// Messages, as JSON:
// page -> server: {type: "hello", version, tools, guide, info}, {type: "result", id, result}, {type: "progress", id, message}
// server -> page: {type: "call", id, name, args}, {type: "cancel", id}, {type: "client", name} (the MCP
// client's), {type: "tick"} (while a call runs, so that a hidden tab, which gets no animation frames, still
// steps the physics), {type: "replaced"} (another tab connected to the server instead of this one),
// {type: "perception", gemini_key} (the server's GEMINI_API_KEY, for locate: kept in memory while connected).
export const DEFAULT_PORT = 8770;
export class Bridge {
/**
* `handlers`: hello() -> {tools, guide, info}; call(name, args) -> Promise of a result; cancel() stops the running
* skill; activity() -> what the robot is doing, for progress; pump() steps the physics of a hidden tab.
* `on` tells the panel: status(state) ("off", "connecting", "waiting", "connected", "replaced"),
* call(name, args), result(name, result).
*/
constructor(handlers, on = {}) {
this.handlers = handlers;
this.on = on;
this.port = DEFAULT_PORT;
this.ws = null;
this.state = "off";
this.wanted = false; // connect, and connect again after the server goes away
this.replaced = false;
this.tries = 0;
this.retry = null;
this.queue = Promise.resolve(); // one call at a time: two skills at once would cancel each other
this.current = null; // the id of the call running
this.cancelled = new Set(); // calls cancelled while they waited their turn
}
get connected() {
return this.ws?.readyState === WebSocket.OPEN;
}
/** Connect to the server on `port`, and keep trying until it answers. */
connect(port = this.port) {
this.port = port;
this.wanted = true;
this.replaced = false;
this.tries = 0;
clearTimeout(this.retry);
if (this.ws) return; // connecting or connected already
this.#open();
}
disconnect() {
this.wanted = false;
this.geminiKey = null;
clearTimeout(this.retry);
const ws = this.ws;
this.ws = null;
ws?.close();
if (this.current !== null) this.handlers.cancel();
this.#status("off");
}
#status(state) {
this.state = state;
this.on.status?.(state);
}
#open() {
const ws = new WebSocket(`ws://127.0.0.1:${this.port}`);
let opened = false;
this.ws = ws;
this.#status(this.tries ? "waiting" : "connecting");
ws.onopen = () => {
opened = true;
this.tries = 0;
ws.send(JSON.stringify({ type: "hello", version: 1, ...this.handlers.hello() }));
this.#status("connected");
};
ws.onmessage = (event) => {
let message;
try {
message = JSON.parse(event.data);
} catch {
return;
}
this.#message(ws, message);
};
ws.onerror = () => {}; // onclose follows
ws.onclose = () => {
if (this.ws !== ws) return; // disconnected on purpose
this.ws = null;
this.geminiKey = null;
if (this.current !== null) this.handlers.cancel(); // nobody waits for it any more
if (!this.wanted || this.replaced) return this.#status(this.replaced ? "replaced" : "off");
this.tries++;
this.#status("waiting");
if (!opened) this.#checkAccess();
this.retry = setTimeout(() => this.#open(), Math.min(5000, 1000 * this.tries));
};
}
/**
* A page from another site than this computer reaches 127.0.0.1 only if the person lets it (Chrome's local
* network access checks): `access` is "granted", "prompt" or "denied" where the browser says.
*/
async #checkAccess() {
if (["127.0.0.1", "localhost", "[::1]"].includes(location.hostname)) return;
for (const name of ["loopback-network", "local-network-access"]) {
try {
const { state } = await navigator.permissions.query({ name });
if (state !== this.access) {
this.access = state;
this.on.status?.(this.state);
}
return;
} catch {
// not this browser's name for it
}
}
}
#message(ws, message) {
if (message.type === "tick") return void this.handlers.pump();
if (message.type === "replaced") {
this.replaced = true;
return;
}
if (message.type === "cancel") {
if (this.current === message.id) this.handlers.cancel();
else this.cancelled.add(message.id);
return;
}
if (message.type === "client") {
this.client = message.name; // the MCP client's name, as it gave it to the server
return void this.on.status?.(this.state);
}
if (message.type === "perception") {
this.geminiKey = typeof message.gemini_key === "string" && message.gemini_key ? message.gemini_key : null;
return void this.on.status?.(this.state);
}
if (message.type === "call") this.queue = this.queue.then(() => this.#run(ws, message)).catch((error) => console.error(error));
}
async #run(ws, { id, name, args }) {
if (this.cancelled.delete(id) || ws !== this.ws) return this.#send(ws, { type: "result", id, result: { ok: false, message: "cancelled before it started" } });
this.current = id;
this.on.call?.(name, args ?? {});
let said = null;
const progress = setInterval(() => {
const message = this.handlers.activity();
if (message && message !== said) this.#send(ws, { type: "progress", id, message: (said = message) });
}, 1000);
let result;
try {
result = await this.handlers.call(name, args ?? {});
} catch (error) {
result = { ok: false, message: error.message };
} finally {
clearInterval(progress);
this.current = null;
}
this.on.result?.(name, result ?? {});
this.#send(ws, { type: "result", id, result: result ?? {} });
}
#send(ws, message) {
if (ws.readyState === WebSocket.OPEN) ws.send(JSON.stringify(message));
}
}
/** The port to connect to when the page's URL asks for the bridge (?bridge or ?bridge=PORT), else null. */
export function bridgeRequested(url = location.href) {
const params = new URL(url).searchParams;
if (!params.has("bridge")) return null;
const port = Number(params.get("bridge"));
return Number.isInteger(port) && port > 0 && port < 65536 ? port : DEFAULT_PORT;
}
|